Title: 'NET 3'xx
1.NET 3.xx .NET 4.0 CTP
Slides before 1st Section Divider
.NET 3.X
Linq
.NET 4.0 CTP
2Features in .NET 3.XNew Features in .NET 4.0
3.NET 3.X
pptPlex Section Divider
The slides after this divider will be grouped
into a section and given the label you type
above. Feel free to move this slide to any
position in the deck.
4C 3.0 Language features
Implicitly Typed Local Variables and Arrays
var int_var 5 var string_var "text" var
array new ArrayList() Anonymous classclass
created on the fly to store a set of values
5C 3.0 Language features
Object initializers (requires public default
constructor) private class Person //
Auto-implemented properties public int Age
get set public string Name get set
static void Test() // Object initializer
Person per new Person Age 22, Name
"Mony" Similarly can be initialized nested
objects and collections
6C 3.0 Language features
Extension methodsExtending type with new methods
without altering the definition of the original
type.
7C 3.0 Language features
- Partial methodMethod with optional
implementation (in partial class)
8C 3.0 Language features
- Lambda ExpressionsUnnamed method written in
place of a delegate instance and converted by
compiler to - A delegate instance
- An expression tree
- Building expression tree at runtime and
compilation to delegate
9Anonymous delegate (c2.0)
int GetNumber(Listltintgt numbers) //gets the
first number smaller than 10 // in the list
return numbers.Find( delegate(int n)
return nlt10 ) Lambda
Expression return numbers.Find( n gt nlt10)
10Anonymous delegate (c2.0)
numbers.Sort( delegate(int x, int y) return
y-x ) Lambda Expression numbers.Sort((x,y)
gt y-x) Another example Listltintgt numbers
GetNumbers() int match numbers.Find(ngt
nlt10) numbers.ForEach(n gt Console.WriteLine(n))
Listltfloatgt floatNumbers numbers.ConvertAlllt
floatgt(n gt (float)n) numbers.Sort((x,y)gt var
w y-x return z ) numbers.RemoveAll(n gt
n2!0)
11C 3.0 Language features
Lambda Expression Tree
12Lambda Expression Tree
ExpressionltPredicateltintgtgt expression
Expression.LambdaltPredicateltintgtgt(
Expression.LT( Expression.Parameter(typeof(int
), "n"), Expression.Constant(10) ),
Expression.Parameter(typeof(int), "n")
) //Get a compiled version of the expression
Predicateltintgt predicateexpression.Compile() /
/use the compiled expression bool
isMatchpredicate(8)
13NET 3.0 and LINQ
- Language features
- Linq to Objects
- Linq to SQL
- Linq to XML
14Linq
pptPlex Section Divider
The slides after this divider will be grouped
into a section and given the label you type
above. Feel free to move this slide to any
position in the deck.
15LINQ - introduction
- LINQ is a general-purpose language-integrated
querying toolset. - Unified way to access data from differen sources
(in-memory objects -LINQ to Objects, databases -
LINQ to SQL, XML documents - LINQ to XML a
file-system, or any other source). - Problem specific language for building structured
type-safe queries. - Query comprehension syntax.
- ORM - object relational mapping.
- Declarative approach
- Functional construction.
- Deffered execution.
16LINQ to Objects
- Quering all collections which expose IEnumerable
or IQuerable. - Assembly line
- Query operators doesn't modify original data
sequence. - Query operators types Filtering, Projection,
Partitioning, Join, Concatenation, Ordering,
Grouping, Conversion, Equality, Element,
Generation, Quantifiers, Aggregation.
17Some examples
Base layout for presentation
18Functional construction
Base layout for presentation
19LINQ to SQL
- LINQ as ORM - supports mapping between object and
tables, inheritance mapping, database
relationships and objects references mapping,
stored procedurs provides implementation of
following patterns optimistic concurrency, data
access object, unit of work, identity map and
change register optimizes the database
interaction based on object changes tracking.
Light and highly configurable. - LINQ as problem specific language - comfortable
toolset for expression INSERTION, DELETION,
SELECTION and MODIFICATION operation capability
of dynamical construction strongly typed queries
directly within the language based on Linq
operations compile-time type checking and
Intellisense. - The intended usage for LINQ to SQL is as the
following pattern Query Report Edit Submit
Dispose. - Strong support for rapid development object
relational designer, code immersing attributes,
database creation.
20LINQ to SQL vs. LINQ to
21When you should consider using LINQ to SQL
- Use an ORM solution when database is 11 with my
object model (one class - one table) - Use an ORM solution with inheritance hierarchies
that are stored in a single table - Use my own plain classes instead of using
generated classes or deriving from a base class
or implementing an interface - Leverage LINQ as the way I write queries (LINQ as
a type safe problem specific language for queries
building) - I want develop code (prototype) in quick and easy
way - I need something with high efficiency and where I
can optimize performance through stored
procedures and compiled queries
22When you should consider using Linq to Entity
- Write applications that can target different
database engines in addition to Microsoft SQL
Server - Define domain models for my application and use
these as the basis for my persistence layer. - Use an ORM solution where my classes may be 11
with the database or may have a very different
structure from the database schema - Use an ORM solution with inheritance hierarchies
that may have alternative storage schemes (single
table for the hierarchy, single table for each
class, single table for all data related to
specific type) - Leverage LINQ as the way I write queries and have
the query work in a database vendor agnostic
manner. - I need something with high efficiency and where I
can optimize performance through stored
procedures and compiled queries
23Linq to SQL table mapping
Przyklady -klasa/tablica -relacje -procedury -zap
ytania -konfigurowalnosc -optymistyczna
wspolbieznosc/rozwiazywanie konfliktow podczas
commita
24Linq to SQL DataContext and Table
- DataContext provide
- Connection management
- Query translation and execution
- Object identity
- Change trackingDataContext is intended as a
short living object. - TableltTEntitygtRepresents a table for a
particular type in the underlying database.
TableltTEntitygt enables - Querying over the table
- Adding objects
- Removing objects
- Attaching objects
25Linq to SQL database access
- InsertOnSubmint
- DeleteOnSubmit
- Attach
- SubmitChanges
26Linq to SQL optymistics concurency, conflict
resolving
- Optymistics concurency
- Check if other application have changed values in
a row - If there is no conflicts, submit changes
transactionally - If conflict was detected, report rows and values
in conflict (CurrentValue, OriginalValue,
DatabaseValue) and allow user to resolve
conflict (KeepChanges,KeepCurrentValues,OverwriteC
urrentValues) - Suitable for case when chance of conflict is low.
- We can exclude field from update check and
conflict detection.
27Linq to SQL mapping relationships
- One-to-one and one-to-many relationships
- We express relationships by Association
attribute with following parameters - Storage internal field used to track the
related object - ThisKey members of the entity class to
represent the key values on this side of the
association - OtherKey members of the target entity class to
represent the key values on the other side of the
association - Relationships are stored as a predefined query,
with a built-in Where clause that extracts
related entities. - Relationships are stored in field one of
following type EntityRefltTEntitygt,
EntitySetltTEntitygt. EntitySet express many and
EntityRef express one side of relationships. - We can use Storage field in query building,
entity insertion and entity access.
28Linq to SQL mapping relationships
29Linq to SQL mapping inheritance hierarchy
- All classes in hierarchy are mapped into single
database table. - In root class we add field with attribute
Column(IsDiscriminator true) to distinguish
between class in hierarchy. - Root class is decorated by attributes
InheritanceMapping(Code sucClassId, Type
typeof(sucClass)) for all mapped classes in
hierarchy. Code is an identifier which designates
that row belongs to Type class. - In quering over class hierarchy we can filter
over object type.
30Linq to SQL mapping procedures
- Support for mapping and calling of stored
procedures and user-defined functions via methods
defined in object model that represents the
stored procedures/ user-defined functions. - Linq may be configured to use stored procedures
to perform update, insert or delete. - User-defined functions may be used in building
queries.
31Linq to SQL optimisation
- Using DataLoadOptions we can choose between two
approaches to load entities from database - Load data from database as they are needed.
- Load details immidiately.
- LoadWith immediate loading of data related to
the main target. - AssociateWith immediate loading related
entities with filtering. - Loading related entities is performed in the same
query as loading main target entities.
32LINQ to XML key concepts
Functional construction - creating a complete XML
tree in a single statement structure of code
used reflects structure of document. Context-free
XML creation Simplified names Text as value
casting elements and attributes values to the
type that they contain.
33Linq to XML common scenarios
- Building objects from XML
- Creating XML from object graphs
- Creating XML with data from a database
- Filtering and mixing data from a database with
XML data - Reading XML and updating a database
- Transforming text files into XML
34Linq to XML example
Base layout for presentation
35Linq to XML example
Rapid development
36Linq - Conclusions
- Strong support for rapid development.
- Declarative approach and functional construction.
- Unified way to access data from different sources
(in-memory objects -LINQ to Objects, databases -
LINQ to SQL, XML documents - LINQ to XML a
file-system, or any other source). - Problem specific language for building structured
type-safe queries.
37.NET 4.0 CTP
pptPlex Section Divider
The slides after this divider will be grouped
into a section and given the label you type
above. Feel free to move this slide to any
position in the deck.
38Whats new in the .NET 4?
New types Dynamic Lookup Named and Optional
Parameters COM Specific Interop
Features Variance
39C 4 New types
Numerics BigInteger Complex Data
Structures Tuple SortedSetltTgt, ISetltTgt I/O Memory
-Mapped File Unified Cancellation Model
40Dynamic Lookup
- DLR Dynamic Language Runtime
- New API in .NET 4
- Provides infrastructure with common dynamic tools
- Used by C, VB.NET, IronPython, IronRuby
- The Dynamic Type
- New static type called dynamic
- Call a method with any name and any arguments
- Dynamic Operations
- Method calls // d.M(7)
- Field and Property accesses // d.f d.P
- Indexer and Operator calls // done
dtwo 3 - Delegate invocations // string s d(5,7)
41Dynamic Lookup
- Dynamic Lookup
- Resolve names at runtime instead of compile time
- Was already available in VB.NET as late binding
- Useful Scenarios
- Office automation and other COM Interop scenarios
- Consuming types written in dynamic languages
- Enhanced support for reflection
42Named and Optional Parameters
- Optional Parameters allow to omit the arguments
- Named Parameters allow to pass the arguments by
name
public void M(int x, int y 5, int z 7) M(1,
2, 3) // ordinary call of MM(1, 2) //
omitting z equivalent to M(1, 2, 7)M(1)
// omitting both y and z equivalent to M(1, 5,
7)
M(1, z 3) // passing z by name M(x 1, z 3)
// passing both x and z by name M(z 3, x 1)
// reversing the order of arguments
43Overload Resolution
- A signature is applicable if
- All parameters are optional
- All parameters have exactly 1 corresponding
argument (name/position) - Convertible to the parameter type
- Conversion rules applied only on explicit
arguments - Omitted optional arguments are ignored
- The signature without omitted optional attributes
is preferred
M(string s, int i 1)M(object o)M(int i,
string s Hello)M(int i) M(5)
44COM Specific Interop Features
- Dynamic Import
- Many COM methods use variant type ? object in
PIAs - In majority of cases the static type is known
- Before Explicit cast was necessary
- Now COM signatures use dynamic instead of
object - Omitting Ref
- Many COM APIs contain reference parameters
- Not meant to mutate the argument another way to
pass value params - Before Manually created temporary variables
- Now Compiler generated temporary variables
Before ((Excel.Range)excel.Cells1, 1).Value2
"Hello" Excel.Range range (Excel.Range)excel.Ce
lls1, 1
Now excel.Cells1, 1.Value "Hello" Excel.Range
range excel.Cells1, 1
45Variance
- It is often surprising that this is illegal
- However there are interfaces where this cannot
occur - Like IEnumerableltTgt
- There is no method that takes an element in
IListltstringgt strings new Listltstringgt()IListlt
objectgt objects strings
objects0 5string s strings0
IEnumerableltobjectgt objects strings
46Generic Co- Contravariance
- If T appears only as an output, its safe to
passXltTDerivedgt for XltTgt ? Covariance - If T appears only as an input, its safe to pass
XltTBasegt for XltTgt ? Contravariance
public interface IEnumerableltout Tgt
IEnumerable IEnumeratorltTgt
GetEnumerator()
var result strings.Union(objects) // succeeds
with an IEnumerableltobjectgt
public interface IComparerltin Tgt public int
Compare(T left, T right)
47Variance Limitations
- Can only be declared on
- Interfaces
- Delegates
- Only applies for reference conversion (not boxing
conversion) - IEnumerableltintgt is not an IEnumerableltobjectgt
48MS Parallel Computing Initiative
pptPlex Section Divider
The slides after this divider will be grouped
into a section and given the label you type
above. Feel free to move this slide to any
position in the deck.
49MS Parallel Computing Initiative
- Letting the developers solve business problems,
- not concurrency problems
- Concurrency for the mainstream
- Simplicity, Productivity, Safety
50Concurrency Landscape in VS 2010 .NET 4
System.Threading
Parallel Extensions
Unified Cancellation Model
51New System.Threading Primitives
- A Barrier is a synchronization primitive that
enforces the stopping of execution between a
number of threads or processes at a given point
and prevents further execution until all threads
or processors have reached the given point. - A CountdownEvent is a synchronization primitive
that enables ongoing tracking of a given workload
in order to determine if processing of that
workload is finished or not.
52Barrier
Dennis
Mac
Charlie
Gas Station Barrier
Boston
53Barrier - Code
54CountdownEvent
55CountdownEvent - Code
56Unified Cancellation Model
CancellationTokenSource
Cancel()
OP2
OP3
OP1
57Unified Cancellation Model - Code
58Parallel Extensions
- .NET Library
- Can be used by all .NET Languages
- Contains 3 different pieces
- Parallel LINQ (PLINQ)
- Task Parallel Library (TPL)
- Coordination Data Structures (CDS)
59From Threads To Tasks (1)
60From Threads To Tasks (2)
61Task Scheduler
Local Queue
Local Queue
Global Queue
Worker Thread 1
Worker Thread p
Program Thread
Task 3
Task 1
Task 4
Task 5
Task 2
62Rich API
System.Threading.Tasks
Starting
Parent/Child
Task.Factory.StartNew()
var p new Task(() gt var t new
Task())
63Parallel Static Class
- When program statements are independent they can
be parallelized
64Parallel.For Example
65Parallel LINQ-to-Objects (PLINQ)
- Built on top of Tasks
- Enables LINQ developers to leverage multiple
cores - Fully supports all .NET standard query operators
- Minimal impact to existing LINQ model
var q from p in people where p.Name
queryInfo.Name p.State
queryInfo.State p.Year gt
yearStart p.Year lt
yearEnd orderby p.Year ascending
select p
.AsParallel()
66System.Collections.Concurrent
- Provides several thread-safe collection classes
- ConcurrentStackltTgt
- ConcurrentQueueltTgt
- ConcurrentLinkedListltTgt
- ConcurrentDictionaryltTKey,TValuegt
- ConcurrentBagltTKey,TValuegt
- BlockingCollectionltTgt
- IProducerConsumerCollectionltTgt
- Partitioner, PartitionerltTgt, OrderablePartitionerlt
Tgt - Should be used in multi-threaded scenarios
instead of - System.Collections
- System.Collections.Generic