NET Framework 4.0 and C# 4.0 - Center

advertisement

Development Platform for Modern Applications

Jürg Jucker

Microsoft Innovation Center Rapperswil juerg.jucker@msic.ch

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

for the .NET Framework

PC / Server / Cloud

(on other OS than Windows you can use Mono)

.NET Framework 4.0

Mobile Devices

(Smart Phone / PDA) .NET Compact Framework only a subset of the

.NET Framework

Microcontroller

(Embedded Systems)

.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)

Client

PC Phone TV

Server Cloud

of the .NET Framework

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

Unmanaged

Applications

Operating System (Windows, Linux, Unix, ...)

A new software platform for the desktop and the Web

Unmanaged

Applications

Managed Applications

Class Library

Common Language Runtime

Operating System (Windows, Linux, Unix, ...)

Common Language

Runtime

Class Library interoperability, security, garbage collection, versioning, ...

GUI, collections, threads, networking, reflection, XML, ...

A new software platform for the desktop and the Web

Unmanaged

Applications

Managed Applications

Class Library

Web Applications

Web Forms Web Services

ASP.NET

ASP.NET,

Web Forms

Web Services

Common Language Runtime

Web Server (IIS)

Operating System (Windows, Linux, Unix, ...)

Web GUI (object-oriented, event-based, browser-independent) distributed services over RPC (SOAP, HTTP)

Uniform model for desktop and Web programming

So far

Desktop programming object-oriented compiled (C/C++, Fortran, ...) extensive class libraries

Web programming

ASP (not object-oriented) interpreted (VBScript, Javascript, PHP, ...) specialized libraries

Under .NET

Desktop and Web programming object-oriented (even ASP.NET) compiled (C#, C++, VB.NET, Fortran, ...) uniform class library

Interoperability between programming languages

So far

- millions of lines of code in C++, Fortran, Visual Basic, ...

- very limited interoperability

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

Public Class A

Public x As Integer

Public Sub Foo() ...

End Class subclass in C# class B : A { public string s; public void Bar() {...}

} used in Eiffel class Client feature obj: B;

...

create obj; obj.Bar;

...

end

13

Simpler programming of dynamic Web pages

So far

- ASP (mixture of HTML and VBScript or Javascript)

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

...

14

More quality and convenience

-

Security

Side by Side Execution

• 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

• versioning

• end of "DLL hell"

Simpler Software Installation • no more registry entries

• clean and simple de-installation

15

C# C++ VB ...

compiler compiler compiler compiler

CIL code

(+ metadata) loader verifier

JIT compiler machine code

C# if (a > b) max = a; else max = b;

CIL

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

Intel code mov ebx,[-4] mov edx,[-8] cmp ebx,edx jle 17 mov ebx,[-4] mov [-12],ebx

...

16

and differences to Java

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

• ...

As in C++

• Struct types

• Operator overloading

• Pointer arithmetic in unsafe code

• Some syntactic details

18

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

"Syntactic Sugar"

• Component-based programming

- Properties

- Events

• Delegates

• Indexers

• foreach loop

• Boxing / unboxing

• Linq

• ...

19

}

File Hello.cs

using System; class Hello {

} static void Main() {

Console.WriteLine("Hello World");

• imports the namespace

System

• entry point must be called

Main

• prints to the console

• file name and class name need not be identical.

Compilation (from the Console window; produces Hello.exe) csc Hello.cs

Execution

Hello

20

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

File1.cs

Programm

File2.cs

File3.cs

namespace A {...} namespace B {...} namespace C {...} class X {...} class Y {...} class Z {...}

21

class C {

... fields, constants ...

... methods ...

... constructors, destructors ...

... properties ...

... events ...

... indexers ...

... overloaded operators ...

// for object-oriented programming

// for component-based programming

// for convenience

}

... 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)

22

Syntactic sugar for get/set methods class Data {

FileStream s; property type property name

}

} public string FileName { set { s = new FileStream( value , FileMode.Create);

} get {

} return s.Name; "input parameter" of the set method

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.

23

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

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.

24

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: relational:

+, - (unary and binary), *, /, %, ++, --

==, !=, <, >, <=, >= bit operators: &, |, ^ others: !, ~, >>, <<, true, false

Must always return a function result

If == (<, <=, true) is overloaded,!= (>=, >, false ) must be overloaded as well.

25

No anonymous types like in Java

Different default visibility for members

C#:

Java: private package

Different default visibility for types

C#:

Java: internal package

26

Declaration of a delegate type delegate void Notifier (string sender); // ordinary method signature

// with the keyword delegate

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:

// in C# 2.0

greetings = SayHello;

Calling a delegate variable greetings("John"); // invokes SayHello("John") => "Hello from John"

27

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"

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.

28

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;

IEnumerable<string> result = from c in cities where c.StartsWith("L") orderby c select c.ToUpper();

Result foreach (string s in result) Console.WriteLine(s);

London

Vienna

Paris

Linz

Brussels

LINZ

LONDON

Query expressions are translated into lambda expressions and extension methods

29

Short form for delegate values delegate int Function (int x); int Square (int x) { return x * x; } int Inc (int x) { return x + 1; }

C# 1.0

Function f; f = new Function(Square); f = new Function(Inc);

C# 2.0

f = delegate (int x) { return x * x; } f = delegate (int x) { return x + 1; }

... f(3) ...

... f(3) ...

... f(3) ...

... f(3) ...

// 9

// 4

// 9

// 4

C# 3.0

f = x => x * x ; f = x => x + 1 ;

... f(3) ...

... f(3) ...

// 9

// 4

30

Applying a function to a sequence of integers delegate int Function (int x);

} 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; int[] values = Apply ( i => 2 * i + 1 , new int[] {2, 4, 6, 8});

=> 5, 9, 13, 17

31

Add functionality to an existing class

Existing class Fraction

} class Fraction { public int z, n; public Fraction (int z, int n) {...}

...

Usage

Fraction f = new Fraction(1, 2); f = f.Inverse() ;

// f = FractionUtils.Inverse(f);

Extension methods for class Fraction

} 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 this and must denote the class, to which the method should be added f.Add(2) ;

// FractionUtils.Add(f, 2);

• Can be called like instance methods of

Fraction

• However, can only access public members of

Fraction

32

For creating structured values of an anonymous (i.e. nameless) type var obj = new { Name = "John", Id = 100 }; creates an object of a new type with the fields Name and Id for declaring variables of an anonymous type

} class ??? { public string Name; public int Id;

??? obj = new ???(); obj.Name = "John"; obj.Id = 100;

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(...), var obj = new { p.Name, p.Id }; anonymous type with fields Name and Id

34

Example : assume the following declarations

List<Customer> customers = ...;

} class Customer { public string Name; public string City; public int Phone;

Translation var result = from c in customers where c.City == "Vienna" orderby c.Name

select new {c.Name, c.Phone}; foreach (var c in result)

Console.WriteLine(c.Name + " " + c.Phone); lambda expressions var result = customers

.Where( c => c.City == "Vienna" )

.OrderBy( c=> c.Name

)

.Select( c => new {c.Name, c.Phone} ) ; extension methods anonymous type

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

Result

XAML example

<StackPanel>

<TextBlock>User</TextBlock>

<TextBox />

<TextBlock>Pwd</TextBlock>

<TextBox />

<Button Content=„Login“

Click=„Login_Click“/>

</StackPanel>

Code Behind/Behavior

} void Login_Click( object sender,

RoutedEventArgs e) {

// Implement logic here…

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

Concepts and Architecture

Caller

C B A Message

A B C

A B C

Service

Address Binding Contract

(Where) (How) (What)

Service Contract

using System; using System.ServiceModel; namespace TimeService {

[ServiceContract(Namespace = "http://www.hsr.ch/time")] public interface ITimeService {

• WCF-Namesepace

• Service-Interface

[OperationContract] string GetTime();

• Service-Methode

[OperationContract]

TimeDescData GetTimeDesc();

• Service-Methode

}

Service Implementation

using System; namespace TimeService

{ public class TimeService : ITimeService

{ public string GetTime()

{ return DateTime.Now.ToString();

} public TimeDescData GetTimeDesc()

{ return new TimeDescData();

}

}

}

using System; using System.ServiceModel; class MyServiceHost { static ServiceHost myServiceHost = null ;

ServiceHost

} static void StartService() { myServiceHost = new ServiceHost(typeof(TimeService); myServiceHost.Open();

} static void StopService() { if (myServiceHost.State != CommunicationState.Closed) myServiceHost.Close();

}

} static void Main() {

StartService();

Console.WriteLine("Service gestartet... ");

Console.ReadLine();

StopService(); provides Host-functionaliy for publishing a WCF-Service

42

Client

Visual Studio Add Service Reference

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)

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

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)

Database agnostic

Database vendors are developing providers …

Microsoft SQL Server, Oracle, IBM DB2 supportet

Two query options:

Entity SQL

LINQ To Entities

Entity Data Model

Conceptual

Mapping

Storage

from c in db.Customers

where c.City == "London" select c.CompanyName

LINQ Query

Application db.Customers.Add(c1); c2.City = "Barcelona"; db.Customers.Remove(c3);

Objects SaveChanges()

Entity Data Model

SQL Query

SELECT CompanyName

FROM Cust

WHERE City = 'London'

Rows

DB (for instance

SQL Server)

DML or SProcs

INSERT INTO Cust …

UPDATE Cust …

DELETE FROM Cust …

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

…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.

1. Hardware: Robust touch-capable hardware from Microsoft and OEMs

2. OS: Windows 7 has great touch support

3. SDKs: Microsoft is making touch easy to leverage

4. You: Partners creating innovative apps

Office Clients

Excel

Project

WSS/MOSS

Outlook

(Provided by 3 rd

Parties)

Includes Client Access License

Non-Windows

Eclipse

MacOS

Linux

Unix

Host (Java)

(Provided by TeamPrise client in 2008, Microsoft

Client in 2010)

Web

Legacy Clients

VB6

VC++ 6

FoxPro 9

Access 2003

VS.NET 2003

Powerbuilder

Sparx EA

Oracle App. Developer

SQL Management Studio

SQL Enterprise Manager

(Other VSS/MSSCCI compatible)

Additional Client Access License MAY be required

Visual

Studio

2005 – 2008

Clients

Visual Studio Developer

Visual Studio Tester

Visual Studio Architect

Visual Studio Database

Visual Studio Professional

Visual Studio Standard

Business Intelligence

Studio

Visual Studio

2010 Clients

Visual Studio Ultimate

Visual Studio Premium

Visual Studio Professional

Microsoft Test Elements

Microsoft Lab Manager

Microsoft Expression Web

Microsoft Expression Blend

Document/Portal Services

Reporting Services

Test Case Management

Version Control

Team Foundation Server Standard

Build Workflow Services

Project Management

Lab Management Services

List Item Tracking

Other Systems

(Quality Center)

Conversion/Migration Custom Integrations Extensibility

55

For more Information please contact

Jürg Jucker

Dipl. Ing. Inf. FH / Head .NET CC HSR jjucker@hsr.ch

Microsoft Innovation Center Rapperswil

Oberseestrasse 10

CH-8640 Rapperswil

Download