1 / 55

.NET Framework 4.0 and C# 4.0

.NET Framework 4.0 and C# 4.0. Development Platform for Modern Applications. Jürg Jucker Microsoft Innovation Center Rapperswil juerg.jucker@msic.ch. Agenda. Supported Plattforms for the .NET Framework Idea/Concepts of the .NET Framework Introduction to C# and differences to Java

jun
Télécharger la présentation

.NET Framework 4.0 and C# 4.0

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. .NET Framework 4.0 and C# 4.0 Development Platform for Modern Applications JürgJucker Microsoft Innovation Center Rapperswil juerg.jucker@msic.ch

  2. Agenda • Supported Plattforms for the .NET Framework • Idea/Concepts of the .NET Framework • Introduction to C# and differences to Java • New Features with .NET FW 4.0 / C# 4.0 • Parallel Computing • MultiTouch / Surface Table • ... • .NET Development Environment

  3. Supported Plattforms for the .NET Framework

  4. PC / Server / Cloud(on other OS than Windows you can use Mono) Mobile Devices(Smart Phone / PDA) Microcontroller(Embedded Systems) Supported Plattforms for .NET Framework .NET Framework 4.0 • .NET Compact Framework • only a subset of the .NET Framework .NET Micro Framework

  5. Rich Client Windows Forms (based on Windows API) Windows Presentation Foundation (Direct3D) Webapplication ASP.NET ASP.NET MVC Rich Internet Application Silverlight Services (Webservices / Cloud Services) Windows Communication Foundation (Webservices and more...) Windows Azure Plattform (Cloud Services) Supportet Client Technologies

  6. Implementation ofMicrosoft’s New Vision Client Phone PC TV Tools and Cross-Platform Support Server Cloud

  7. Idea/Concepts of the .NET Framework

  8. .NET Initiative Microsoft is creating an advanced new generation of software that will drive the Next Generation Internet. We call this initiative Microsoft® .NET, and its purpose is to make information available any time, any place, on any device. Microsoft October 16, 2000

  9. A new software platform for the desktop and the Web What is .NET? Unmanaged Applications Operating System (Windows, Linux, Unix, ...)

  10. A new software platform for the desktop and the Web What is .NET? Unmanaged Applications Managed Applications Class Library Common Language Runtime Operating System (Windows, Linux, Unix, ...) Common Language Runtime interoperability, security, garbage collection, versioning, ... Class Library GUI, collections, threads, networking, reflection, XML, ...

  11. A new software platform for the desktop and the Web What is .NET? Unmanaged Applications Managed Applications Web Applications Web Forms Web Services Class Library ASP.NET Common Language Runtime Web Server (IIS) Operating System (Windows, Linux, Unix, ...) ASP.NET, Web Forms Web GUI (object-oriented, event-based, browser-independent) Web Services distributed services over RPC (SOAP, HTTP)

  12. Uniform model for desktop and Web programming Under .NET Desktop and Web programming object-oriented (even ASP.NET) compiled (C#, C++, VB.NET, Fortran, ...) uniform class library Goals of .NET So far Desktop programming Web programming object-oriented compiled (C/C++, Fortran, ...) extensive class libraries ASP (not object-oriented) interpreted (VBScript, Javascript, PHP, ...) specialized libraries

  13. Interoperability between programming languages • Under .NET • binary compatibility between more than 20 languges (C#, C++, VB.NET, Java, • Eiffel, Fortran, Cobol, ML, Haskell, Pascal, Oberon, Perl, Python, ...) class in VB.NET subclass in C# used in Eiffel Public Class A Public x As Integer Public Sub Foo() ... End Class class B : A { public string s; public void Bar() {...} } class Client feature obj: B; ... create obj; obj.Bar; ... end Goals of .NET • So far • - millions of lines of code in C++, Fortran, Visual Basic, ... • - very limited interoperability

  14. Simpler programming of dynamic Web pages • Under .NET • - ASP.NET (clean separation of HTML and script code) object-oriented event-based rapid application development (RAD) allows user-written GUI elements efficient (compiled server scripts) automatic state management authorisation / authentication ... Goals of .NET • So far • - ASP (mixture of HTML and VBScript or Javascript)

  15. More quality and convenience - Security • strong static typing • run-time type checks (no more buffer overruns!) • garbage collection • CIL code verifier • public key signatures of code • role-based access rights • code-based access rights - Side by Side Execution • versioning • end of "DLL hell" - Simpler Software Installation • no more registry entries • clean and simple de-installation Goals of .NET

  16. Interoperability C# if (a > b) max = a; else max = b; C# C++ VB ... CIL compiler compiler compiler compiler IL_0004: ldloc.0 IL_0005: ldloc.1 IL_0006: ble.s IL_000c IL_0008: ldloc.0 IL_0009: stloc.2 IL_000a: br.s IL_000e IL_000c: ldloc.1 IL_000d: stloc.2 CIL code (+ metadata) loader Intel code verifier mov ebx,[-4] mov edx,[-8] cmp ebx,edx jle 17 mov ebx,[-4] mov [-12],ebx ... JIT compiler machine code

  17. Introduction to C# and differences to Java

  18. As in C++ • Struct types • Operator overloading • Pointer arithmetic in unsafe code • Some syntactic details Features of C# Very similar to Java 70% Java, 10% C++, 5% Visual Basic, 15% new • As in Java • Object-orientation (single inheritance) • Interfaces • Generics (more powerful than in Java) • Exceptions • Threads • Namespaces (similar to Java packages) • Strong typing • Garbage collection • Reflection • Dynamic loading of code • ...

  19. "Syntactic Sugar" • Component-based programming • - Properties • - Events • Delegates • Indexers • foreach loop • Boxing / unboxing • Linq • ... New Features in C# • Really new (compared to Java) • Call-by-reference parameters • Stack-allocated objects (structs) • Block matrices • Uniform type system • goto statement • Attributes • System-level programming • Versioning

  20. using System; class Hello { static void Main() { Console.WriteLine("Hello World"); } } Compilation (from the Console window; produces Hello.exe) csc Hello.cs Execution Hello Hello World Program File Hello.cs • imports the namespace System • entry point must be called Main • prints to the console • file name and class nameneed not be identical.

  21. If no namespace is specified => anonymous default namespace Namespaces may also contain structs, interfaces, delegates and enums Namespace may be "reopened" in other files Simplest case: single class, single file, default namespace Structure of C# Programs Programm File1.cs File2.cs File3.cs namespace A {...} namespace B {...} namespace C {...} class X {...} class Y {...} class Z {...}

  22. class C { ... fields, constants ... // for object-oriented programming ... methods ... ... constructors, destructors ... ... properties ... // for component-based programming ... events ... ... indexers ... // for convenience ... overloaded operators ... ... nested types (classes, interfaces, structs, enums, delegates) ... } Objects are allocated on the heap (classes are reference types) Objects must be created with new Stack s = new Stack(100); Classes can inherit from one other class (single code inheritance) Classes can implement multiple interfaces (multiple type inheritance) Contents of Classes

  23. Syntactic sugar for get/set methods class Data { FileStream s; public stringFileName { set{ s = new FileStream(value, FileMode.Create); } get{ return s.Name; } } } Used as "smart fields" Data d = new Data(); d.FileName = "myFile.txt"; // calls set("myFile.txt") string s = d.FileName; // calls get() JIT compilers often inline get/set methods  no efficiency penalty. Properties property type property name "input parameter" of the set method

  24. get or set can be omitted class Account { long balance; public long Balance { get { return balance; } } } x = account.Balance; // ok account.Balance= ...; // compiler reports an error Properties • Why are properties a good idea? • Allow read-only and write-only fields. • Can validate a field when it is accessed. • Interface and implementation of the data can differ. • Substitute for fields in interfaces.

  25. Static method for implementing a certain operator struct Fraction { int x, y; public Fraction (int x, int y) {this.x = x; this.y = y; } public static Fraction operator + (Fraction a, Fraction b) { return new Fraction(a.x * b.y + b.x * a.y, a.y * b.y); } } Usage Fraction a = new Fraction(1, 2); Fraction b = new Fraction(3, 4); Fraction c = a + b; // c.x == 10, c.y == 8 The following operators can be overloaded: arithmetic: +, - (unary and binary), *, /, %, ++, -- relational: ==, !=, <, >, <=, >= bit operators: &, |, ^ others: !, ~, >>, <<, true, false Must always return a function result If == (<, <=, true) is overloaded,!= (>=, >, false) must be overloaded as well. Operator Overloading

  26. No anonymous types like in Java Different default visibility for membersC#: privateJava: package Different default visibility for typesC#: internalJava: package Differences to Java

  27. Declaration of a delegate type delegate void Notifier (string sender); // ordinary method signature // with the keyword delegate Delegate = Method Type Declaration of a delegate variable Notifier greetings; Assigning a method to a delegate variable void SayHello(string sender) { Console.WriteLine("Hello from " + sender); } greetings = new Notifier(SayHello); // or just: greetings = SayHello; // in C# 2.0 Calling a delegate variable greetings("John");// invokes SayHello("John") => "Hello from John"

  28. A delegate variable can hold multiple methods at the same time Notifier greetings; greetings = SayHello; greetings +=SayGoodBye; greetings("John"); // "Hello from John" // "Good bye from John" greetings -=SayHello; greetings("John"); // "Good bye from John" Multicast Delegates • Note • If the multicast delegate is a function, the value of the last call is returned • If the multicast delegate has an out parameter, the parameter of the last call is returned. ref parameters are passed through all methods.

  29. IEnumerable<string> result = from c in cities where c.StartsWith("L") orderby c select c.ToUpper(); LINZ LONDON Query Expressions SQL-like queries on arbitrary collections (IEnumerable<T>) Sample collection string[] cities = {"London", "Vienna", "Paris", "Linz", "Brussels"}; Query IEnumerable<string> result = from c in cities select c; Result foreach (string s in result) Console.WriteLine(s); London Vienna Paris Linz Brussels Query expressions are translated into lambda expressions and extension methods

  30. C# 2.0 f = delegate (int x) { return x * x; } ... f(3) ... // 9 f = delegate (int x) { return x + 1; } ... f(3) ... // 4 C# 3.0 f = x => x * x; ... f(3) ... // 9 f = x => x + 1; ... f(3) ... // 4 Lambda Expressions Short form for delegate values delegate intFunction(int x); intSquare(int x) { return x * x; } intInc(int x) { return x + 1; } C# 1.0 Function f; f = new Function(Square); ... f(3) ... // 9 f = new Function(Inc); ... f(3) ... // 4

  31. int[] values = Apply (i => 2 * i + 1, new int[] {2, 4, 6, 8}); => 5, 9, 13, 17 Example for Lambda Expressions Applying a function to a sequence of integers int[] Apply (Function f, int[] data) { int[] result = new int[data.Length]; for (int i = 0; i < data.Length; i++) { result[i] = f(data[i]); } return result; } delegate int Function (int x);

  32. Usage Fraction f = new Fraction(1, 2); f = f.Inverse(); // f = FractionUtils.Inverse(f); f.Add(2); // FractionUtils.Add(f, 2); • Can be called like instance methods of Fraction • However, can only access public members of Fraction Extension Methods Add functionality to an existing class Existing class Fraction Extension methods for class Fraction class Fraction { public int z, n; public Fraction (int z, int n) {...} ... } static class FractionUtils { public static Fraction Inverse (this Fraction f) { return new Fraction(f.n, f.z); } public static void Add (this Fraction f, int x) { f.z += x * f.n; } } • must be declared in a static class • must be static methods • first parameter must be declared with thisand must denote the class, to which themethod should be added

  33. for declaring variables of an anonymous type Even simpler, if the values are composed from fields of existing objects class Person { public string Name; public string Address; public int Id; } ... Person p = new Person(...), anonymous type with fields Name and Id var obj = new { p.Name, p.Id }; Anonymous Types For creating structured values of an anonymous (i.e. nameless) type var obj = new { Name = "John", Id = 100 }; class ??? { public string Name; public int Id; } creates an object of a new type with the fields Name and Id ??? obj = new ???(); obj.Name = "John"; obj.Id = 100;

  34. Translation lambda expressions var result = from c in customers where c.City == "Vienna" orderby c.Name select new {c.Name, c.Phone}; var result = customers .Where( c => c.City == "Vienna") .OrderBy( c=> c.Name) .Select(c => new {c.Name, c.Phone}); anonymous type extension methods Translation of Query Expressions Example: assume the following declarations List<Customer> customers = ...; class Customer { public string Name; public string City; public int Phone; } foreach (var c in result) Console.WriteLine(c.Name + " " + c.Phone);

  35. The Windows Presentation Foundation (WPF) is the new GUI Framework from Microsoft Included in the .Net Framework since Version 3.0 Not available on the .Net Compact Framework Enables to deliver rich user experience Full media support Allows better designer/developer collaboration Separation of design and behavior Uses XAML to describe the visual aspects of the UI Standalone/Smart Clients or Browser based Applications WPF Overview

  36. XAML example <StackPanel> <TextBlock>User</TextBlock> <TextBox /> <TextBlock>Pwd</TextBlock> <TextBox /> <Button Content=„Login“ Click=„Login_Click“/> </StackPanel> Result Code Behind/Behavior void Login_Click(object sender,RoutedEventArgs e) { // Implement logic here… } WPF UI: XAML and Code Behind

  37. Integrated Architectural foundation for interoperability with apps on other plattforms and on other Windows’ distributed stacks such as support for WS-* protocols WCF supports diverse (communication) technologies HTTP, native TCP, SOAP, Named-Pipes, MSMQ, COM+ Web-style services (.NET 3.5) Workflow Services (.NET 3.5) Distributed durable workflows WCF replaces the distributed technologies of the .Net 1.1/2.0-Framework WCF – Why Yet Another Technology?

  38. Concepts and Architecture C C C B B B A A A Address, Binding, Contract Caller Service Message Address Binding Contract (Where) (How) (What)

  39. Service Contract Example TimeService using System; using System.ServiceModel; namespaceTimeService { [ServiceContract(Namespace = "http://www.hsr.ch/time")] publicinterfaceITimeService { [OperationContract] stringGetTime(); [OperationContract] TimeDescData GetTimeDesc(); } • WCF-Namesepace • Service-Interface • Service-Methode • Service-Methode

  40. Service Implementation Example TimeService using System; namespace TimeService { publicclass TimeService : ITimeService { publicstring GetTime() { return DateTime.Now.ToString(); } public TimeDescData GetTimeDesc() { returnnew TimeDescData(); } } }

  41. Example TimeService Console Host using System; using System.ServiceModel; class MyServiceHost { staticServiceHost myServiceHost = null; static void StartService() { myServiceHost = new ServiceHost(typeof(TimeService); myServiceHost.Open(); } staticvoid StopService() { if (myServiceHost.State != CommunicationState.Closed) myServiceHost.Close(); } staticvoid Main() { StartService(); Console.WriteLine("Service gestartet... "); Console.ReadLine(); StopService(); } } ServiceHost provides Host-functionaliy for publishing a WCF-Service

  42. Client Build a Proxy for the Client Side Visual Studio Add Service Reference

  43. New Features with .NET FW 4.0 / C# 4.0

  44. Parallel Extensions is a .NET Library that supports declarative and imperative data parallelism, imperative task parallelism, and a set of data structures that make coordination easier. Parallel LINQ (PLINQ) Task Parallel Library (TPL) Coordination Data Structures (CDS) Parallel Programming

  45. XAML-only workflows are the new default Unified model between WF, WCF, and WPF Extended base activity library More activities will be present on CodePlex WF 4.0 simplifies data flow by adding: Arguments, variables, and expressions Significant improvements in performance and scalability New FlowChart Workflow Improved WF 4.0 designer / Designer Rehosting Workflow Foundation 4.0

  46. Entity Data Model Define your application model Map it to a persistence store (Database) Comprised of 3 layers Conceptual (Object Model) Mapping Storage (Database Model) Databaseagnostic Databasevendors are developing providers …Microsoft SQL Server, Oracle, IBM DB2 supportet Twoquery options: Entity SQL LINQ To Entities ADO.NET Entity Framework Object-Relational Mapping Entity Data Model Conceptual Mapping Storage

  47. LINQ TO ENTITIES Application from c in db.Customers where c.City == "London" select c.CompanyName db.Customers.Add(c1); c2.City = "Barcelona"; db.Customers.Remove(c3); LINQ Query Objects SaveChanges() Entity Data Model SQL Query Rows DML or SProcs SELECT CompanyName FROM Cust WHERE City = 'London' INSERT INTO Cust … UPDATE Cust …DELETE FROM Cust … DB (for instance SQL Server)

  48. Next Release: H1 2010 as part of .NET Framework 4 and Visual Studio 2010 Key Features: Windows 7 Integration Support for Multitouch Taskbar Integration Controls for Building Rich Clients DataGrid, DatePicker, Calendar, Windows 7 & Office Ribbon Control Windows Presentation Foundation

  49. …creates new opportunities. Software that is intuitive to use Software that is collaborative with multiple users …is not new. Researchers have been exploring this stuff for decades …is now going mainstream. Hardware: Robust touch-capable hardwarefrom Microsoft and OEMs OS: Windows 7 has great touch support SDKs: Microsoft is making touch easy to leverage You: Partners creating innovative apps Multitouch

  50. Development Environment

More Related