22. Qu’est-ce qui est cool dans .NET 3.5?? Linq Linq to objects Linq to xml Linq to Sql Linq to dataset LinqLinqDataSource in ASP.NET Linq support in WPF databinding Linq Linq, Linq, …
23. Qu’est-ce qui est cool dans .NET 3.5?? Web applications ASP.NET AJAX built in Application Services Exposed ListView control Service Applications Syndication object model WCF support for REST and JSON services WCF & WF integration Client Application Excellent tooling support! UIElement3D Managed Add-in framework (System.AddIn) XBAP support for Firefox
24. Vue d’ensemble des évolutions de C# 3.0 / VB 9.0 Nouveautés des langages
26. C# 3.0, ses objectifs de conception ! Intégration d’objets, des données relationnelles et du XML LINQ Enrichissement du langage (C# v1.0, v2.0) Basésur la .NET CLR 2.0 Ajout de nouvellesfonctionnalités Lambda expressions Détachement du langage des APIs spécifiques 100% compatible avec les versions précédentes C# 3.0 peutêtrecomplètementtraduit en C# 2.0
27. C# 3.0, ses Innovations ! Query expressions var contacts = from c in customers where c.State == "WA" select new { c.Name, c.Phone }; Expression trees Local variable type inference Automatic properties Lambda expressions var contacts = customers .Where(c => c.State == "WA") .Select(c => new { c.Name, c.Phone }); Partial methods Extension methods Object initializers Anonymous types
35. Types implicites / Inférence de types « Var » Déclaration de variable ou Array sans spécifier de type Déclaration fortement typée Doit être directement initialisée Variables locales uniquement
36. Initialisation d’objets simplifiée Déclaration avec unesyntaxesimplifiée. Initialisationd’objettypé Person p = new Person {Name = "Chris Smith", Age = 31}; Initialisationd’objet avec type anonyme var productInfos = from p in products select new {p.ProductName, p.UnitPrice}; foreach(var p in productInfos){...} Initialisation d’objet avec un type nullable : compile time error !
37. … Initialisation de collections simplifiée Uniquement pour les collection de classes implémentant “IEnumerable” List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List<Test> list = new List<Test> { new Test{ num = 1, s = "Hello"}, new Test{ num = 2, s = "World"}, new Test{ num = 3, s = "From C#"} };
38. … Propriétés automatiques Déclaration avec unesyntaxesimplifiée. Attributs non permis (utiliseralors la méthoderégulière)
39. Types anonymes Types automatiquement générés à la compilationvar v = new { Amount = 108, Message = "Hello" }; Non disponible dans le code source Intellisence disponible Typiquementutilisédans la clause select des query expression Repose surl’initialisationd’objet et collections var query = fromprod in Products select new { prod.Color, prod.Price}; foreach(var v in query) { Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price); }
40. Méthodes d’extension Ajout “Virtuel” d’une méthode à un type Méthode Static : premier paramètre “this” Étend, ne modifie pas le type, override Définition du scope par “using namespaces”
41. Expressions Lambda Ecriture inline de méthodes Lambda opérateur « => » (se dit « conduit à ») Simplifications d'écriture des entêtes d'une méthode anonyme delegate int D1(int i); D1 myDelegate1 = x => x + 1; int j = myDelegate1(5); //j = 6 Permet d’écrire une fonction dans une expression et de récupérer un pointeur vers la fonction Possibilité de récupérer un arbre d’expression
42. Expressions Lambda Exemplesd’expressions lambda x => x + 1 // Implicitly typed, expression body x => { return x + 1; } // Implicitly typed, statement body (int x) => x + 1 // Explicitly typed, expression body (int x) => { return x + 1; } // Explicitly typed, statement body (x, y) => x * y // Multiple parameters () => Console.WriteLine() // No parameters
43. Expressions Lambda Inférence de type dans une Lambda customers.Where(c => c.City == "London"); Opérateurs de vérification Func<int, bool> myFunc = x => x == 5; bool result = myFunc(4); // returns false of course int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int oddNumbers = numbers.Count(n => n % 2 == 1); Ne pas confondre avec l’opérateur “>=“ var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index);
44. Méthodes Partielles Les types partiels peuvent maintenant contenir des méthodes partielles partial class Customer { partial void OnCreated() { Console.WriteLine(“Welcome new customer”); } }
45. Et là … « LINQ » ! Des nouveautés à LINQ (.NET Language-IntegratedQuery) : un pas ? http://msdn2.microsoft.com/fr-fr/netframework/aa904594.aspx
46. LINQ : Définition Linq = LanguageINtegratedQuery Exemples DLinq = Database + Linq Appelé maintenant Linq to Data Xlinq = XML + Linq Appelé maintenant Linq to XML
47. LINQ : Concepts Linq = innovation de VS2008 et .NET 3.5 Change radicalement le travail de données Avantages Simplifie l’écriture des requêtes Unifie la syntaxe de requêtes pour tout type de source de données Renforce la connection entre les données relationnelles et le monde de l’OO Accélère les développements Gestion des erreurs à la compilation Intellisense et debugging
48. LINQ : Fondations C# v3.0 – VB v9.0 Query expressions var contacts = from c in customers where c.State == "WA" select new { c.Name, c.Phone }; Expression trees Local variable type inference Automatic properties Lambda expressions var contacts = customers .Where(c => c.State == "WA") .Select(c => new { c.Name, c.Phone }); Partial methods Extension methods Object initializers Anonymous types
49. LINQ : Architecture Others… VB C# Sources de données LINQ .NET Language Integrated Query (LINQ) Linqsur des sources ADO.NET LINQ To XML LINQ To Entities LINQ To SQL LINQ To Datasets LINQ To Objects Provider <book> <title/> <author/> <price/> </book> XML Relationnel Objets
51. LINQ : 3 parties de toute requête Touterequête LINQ consiste en 3 actions essentielles : Obtention de la source de données(xml, db, Objects) Création de la requête Exécution de la requête
52. LINQ : Framework L’architecture à la base de Linq est constituée de deux parties LINQ Language Extensions Un langage de programmation implémentant les extensions de langage LINQ C# et VB implémentés au sein de VS2008 LINQ Providers Provider LINQ implémentant les Standard QueryOperator méthodes pour chaque source de données spéficique.
53. LINQ : Requête de base IEnumerable<Customer> customerQuery = from cust in customers //... Exemple : List<int> numberList = new List<int> { 1, 2, 3, 4 }; var query = from i in numberList where i < 4 select i;
54. Query Expressions Vs LINQ var locals = from c in customers Wherec.ZipCode==91822 select (new {FullName=c.FirstName + “ “ + c.LastName, HomeAdresse=c.Address}); var locals = customers .Where(c => c.ZipCode == 91822) .Select(c => new { FullName = c.FirstName + “ “ + c.LastName, HomeAddress = c.Address });
55. Linq or not : Différence ? C#2 List<City> returnCities = new List<City>(); Foreach (city c in cities) { If (c.Name==« London ») returnCities.Add(c); } C#3 / LINQ var query= from c in cities Where c. Name==« London » Select c;
57. LINQ : Projections - SELECT Utilisation du Keyword “Select” Nécessité de modifier, transformer les donnéesretournées par unerequête LINQ LINQ permet des scénariosavancés de mise en forme de données = “Projections” Exploitation des type anonymesproposés par le compilateur
58. LINQ : Projections + Types Anonymes List<City> cities = CityUtilityHelper.GetCities(); var places = from city in cities where city.DistanceFromSeattle > 1000 select new { City = city.Name, Country = city.Country, DistInKm = city.DistFromSeattle * 1.61 }; GridView1.DataSource = places; GridView1.DataBind(); Type anonymeutilisé pour forger un type de retour personnalisé!Application d’une conversion Miles/Kms
59. LINQ : Query Operators C# 3.0 VB 9.0 from .. in .. where .. select .. [into ..] group .. by .. [into ..] orderby .. [descending] join .. in .. on .. equals .. let .. = .. From .. [As ..] In .. Where .. Select .. [,..]* Group .. By .. Into .. Group Join .. [As ..] In .. On ..Equals .. [...] Into .. Order By ... [Descending] Join .. In .. On ..Equals .. [...] Let .. = ... Others: Skip, Skip While, Take, Take While Aggregates: All, Any, Average, [Long]Count, Max, Min, Sum Les opérateurs sont implémentés via des méthodes d’extensions
65. Firstname Lastname Title of the Presenter Goes Here Presentation title{with sample bracket usage}
Notas do Editor
The main points are that the CLR engine is the same version (so no need to retest your apps) and that the headline feature is the language enhancements (C#3 & VB9 compilers) and LINQ.
The main points are that the CLR engine is the same version (so no need to retest your apps) and that the headline feature is the language enhancements (C#3 & VB9 compilers) and LINQ.
Time: 4 minDiscussion Points:How do the new 3.5 SP1 technologies relate to previous versions of the framework?First, let’s talk about how these new SP1 enhancements relate to the 3.5, 3.0, and 2.0 versions of the framework.The .NET Framework 3.5 SP1 will add these technologies on top of the framework 3.5 that just shipped in November.In addition, the current plan of record is that there will be updated service packs for both the 3.0 assemblies and the 2.0 framework and CLRSo to be clear, the .NET Framework 3.5 SP1 will depend on the .NET Framework 3.5, 3.0 with SP2, and 2.0 with SP2 to be installed on a users machine.
C# - started as “the (first) language for CLR”; emphasize the pragmatic approach (cf. Anders Hejlsberg) = be explicit about language features like properties, events, etc. developer confidence2.0 = generics wave (impact on CLR) + additional useful things (that do require generics on their own + that are useful on their own)3.0 = LINQ + making the language more concise, more productive, more powerful, ...
LINQ: tell the story of Reflex 2.0, Dbase III+, ... where data and code were close together structured + distributed programming changed this = layered approach result: data and code on two islands with a huge gap between the two need for O/R mapping tools etcWith LINQ: data becomes a first-class citizen of the languageReduce “language noise” (e.g. tiresome repetitive code etc)API independent you can reimplement stuff on your own, the language doesn’t care about it (e.g. extension methods on Ienumerable<T>, don’t mention the word yet)Backward compat: refer to MSR paper on formal proof of the possibility for translation of every C# 3.0 program to an equivalent C# 2.0 program (semantically)
Build up the slide and introduce “syntactical sugar”. Story telling approach referring back to the gap between data and code and the LINQ solution using Language Integrated queries requires glue: functional style programming concepts, introduction of concepts from the relational world (e.g. projection clauses require anonymous types) and language simplification (e.g. object initializers).Use the words:-Different compilation stages (front-end query syntax is translated into “pure” C# into ..., e.g. resolution of query expressions to chains of method calls)-Method call chain (can still be instance methods or extension methods)
VB = longer history (up to 9.0)Refer to huge transition from 6.0 to .NET which implied the creation of a runtime library for bw compat: play the rules of the CLS (OO for example) and remain consistent with VB pre-.NETVB 8.0 = GenericsVB 9.0 = LINQ + XML (difference with C#)
When used with local variables, the var keyword instructs the compiler to infer the type of the variable or the array elements from the expression on the right side of the initialization statement.Indispensable pour les types anonymeshttp://msdn2.microsoft.com/fr-fr/library/bb384061(VS.90).aspx
Collection initializers provide a way to specify one or more object intializers when initializing any collection class that implements IEnumerable. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls2ème exemple :The following collection initializer uses object initializers to initialize objects of the Test class defined in an earlier example. Note that the individual object initializers are enclosed in braces and separated by commas.