600 likes | 831 Views
.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
E N D
.NET Framework 4.0 and C# 4.0 Development Platform for Modern Applications JürgJucker 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 • New Features with .NET FW 4.0 / C# 4.0 • Parallel Computing • MultiTouch / Surface Table • ... • .NET Development Environment
Supported Plattforms for the .NET Framework
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
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
Implementation ofMicrosoft’s New Vision Client Phone PC TV Tools and Cross-Platform Support Server Cloud
Idea/Concepts of the .NET Framework
.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
A new software platform for the desktop and the Web What is .NET? Unmanaged Applications Operating System (Windows, Linux, Unix, ...)
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, ...
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)
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
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
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)
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
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
Introduction to C# and differences to Java
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 • ...
"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
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.
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 {...}
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
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
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.
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
No anonymous types like in Java Different default visibility for membersC#: privateJava: package Different default visibility for typesC#: internalJava: package Differences to Java
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"
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.
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
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
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);
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
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;
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);
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
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
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?
Concepts and Architecture C C C B B B A A A Address, Binding, Contract Caller Service Message Address Binding Contract (Where) (How) (What)
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
Service Implementation Example TimeService using System; namespace TimeService { publicclass TimeService : ITimeService { publicstring GetTime() { return DateTime.Now.ToString(); } public TimeDescData GetTimeDesc() { returnnew TimeDescData(); } } }
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
Client Build a Proxy for the Client Side Visual Studio Add Service Reference
New Features with .NET FW 4.0 / C# 4.0
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
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
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
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)
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
…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