57
Carnegie Mellon Universit y MSCF 1 C#/.NET Basics

Carnegie Mellon University MSCF1 C#/.NET Basics. Carnegie Mellon University MSCF2.NET Runtime environment called the Common Language Runtime (CLR) Class

  • View
    219

  • Download
    2

Embed Size (px)

Citation preview

Carnegie Mellon University MSCF 1

C#/.NET

Basics

Carnegie Mellon University MSCF 2

.NET

• Runtime environment called the Common Language Runtime (CLR)

• Class library called the Framework Class Library (FCL)

Carnegie Mellon University MSCF 3

Common Language Runtime

• Modern runtime environment• .NET compilers do not target a specific

processor • The CLR must be present on the target

machine• Safely manages code execution• JIT compilation from MSIL to machine

executable• Security and Permission management

Carnegie Mellon University MSCF 4

Framework Class Library

• Object oriented• Collections, console, network and file I/O• Database and XML support• Rich server side event model• Rich client side support for GUI construction• Support for building SOAP based web services• More than 3,500 classes

Carnegie Mellon University MSCF 5

C# Overview

• C# is type safe (hard to access objects in inappropriate ways)

• Automatic memory management

• Exception handling

• Array bounds checking

• Support for checked arithmetic

Carnegie Mellon University MSCF 6

// Hello World 1 in C#

class MyApp {

public static void Main() {

System.String x = "World"; System.Console.WriteLine("Hello " + x); }}

Compile withcsc -t:exe -out:HelloUser.exe -r:MSCorLib.dll HelloUser.csExecute MSIL Managed Code withHelloUserThe code runs within the Common Language Runtime (CLR)

MSCorLib.dll is oneamong many assemblieswe can include. The Basic Class Library isspread over a couple of assemblies.

MyApp is in theglobal namespace

Hello World 1 Full Namespaces

The .exe file has bootstrap code to runthe .NET run time.

Carnegie Mellon University MSCF 7

// Hello World 2 in C#using System;

class MyApp {

public static void Main() {

String x = "World 2"; Console.WriteLine("Hello " + x); }}

Compile Withcsc HelloUser.csExecute The MS Intermediate Language .exe file withHelloUser

Hello World 2 Using System

Carnegie Mellon University MSCF 8

// Hello World 3 in C#class MyApp {

public static void Main() {

String x = "World 3"; Console.WriteLine("Hello " + x); }}

HelloUser.cs(9,7): error CS0246: The type or namespace name 'String' could not be found (are you missing a using directive or an assembly reference?)And more errors…

Hello World 3 Without System

Carnegie Mellon University MSCF 9

Code May Come From A Network

• Has it been tampered with?

• Who wrote it?

• What permissions does it require?

• What permissions should we grant it?

• A major advantage of .NET over traditional

Windows applications is fined-grained control over security.

Carnegie Mellon University MSCF 10

Signing Hello World 4 (1) My Path Variable:

C:\WINDOWS\system32;C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705;C:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Bin

(1)Generate 128-byte public/private key pair and place in a file sn.exe –k PublicPrivate.snk

(2) Add an attribute to the source so that the compiler places the public key in the executable, generates a hash and signs it.

(3) Signature verification is automatic but may be done manually with - sn.exe -v MyApp.exe

(4) Verification is done against the public key in the executable and not against the public key in PublicPrivate.snk

Carnegie Mellon University MSCF 11

Signing Hello World 4 (2) // Hello World 4 in C# (with a signature)

using System.Reflection;

// Tell the compiler where the public/private key pair reside[assembly:AssemblyKeyFile("PublicPrivate.snk")]

class MyApp {

public static void Main() {

System.String x = "World"; System.Console.WriteLine("Hello " + x); }}

Carnegie Mellon University MSCF 12

Signing Hello World 4 (3) Create the keys

D:\McCarthy\www\46-690\SignAnAssembly>sn.exe -k PublicPrivate.snk

Key pair written to PublicPrivate.snk

Compile code

D:\McCarthy\www\46-690\SignAnAssembly>csc MyApp.cs

Verification is automatic but here we force it

D:\McCarthy\www\46-690\SignAnAssembly>sn.exe -v MyApp.exe

Assembly 'MyApp.exe' is valid

Carnegie Mellon University MSCF 13

Type System Unification 0

• The object class is the ultimate base class for both reference types and value types

• Simple types in C# alias structs found in System

• So, Simple types have methods int i = 3; string s = i.ToString();• But follow the same semantics as simple

types of old, e.g., i = 3; j = i; j = 2; // i still 3

Carnegie Mellon University MSCF 14

class MyMathApp {

public static void Main() {

float x = 2.3F; // Semantics are the same System.Single y = 1.0F; // Only the syntax differs

float z = x + y;

System.Console.WriteLine("Result = " + z); }}

Type System Unification 1

Carnegie Mellon University MSCF 15

// All types derive from System.Object (which corresponds to the primitive object// type.)class MyMathApp {

public static void Main() {

float x = 2.3F; // 2.3 is a double so use 'F' for float System.Single y = 1.0F; float z = x + y; object o = z; // object is part of C#, Object is in System System.Console.WriteLine("Object Result = " + o); }}

Object Result = 3.3

Type System Unification 2

Carnegie Mellon University MSCF 16

Exception Handling (1)// Exception Handling - loops foreverusing System;class CatchExceptionExample { public static void Main() { int result = 1; try { while(true) { result = result * 2; } } catch(Exception e) { Console.WriteLine("Exception caught"); Console.WriteLine(e.Message); } Console.WriteLine("Graceful termination"); }}

Carnegie Mellon University MSCF 17

Exception Handling (2)// Exception Handling - Graceful terminationusing System;class CatchExceptionExample { public static void Main() { int result = 1; try { while(true) { result = checked(result * 2); } } catch(Exception e) { Console.WriteLine("Exception caught"); Console.WriteLine(e.Message); } Console.WriteLine("Graceful termination"); }}

Carnegie Mellon University MSCF 18

Exception Handling (3)

D:>CatchExceptionExample.exe

Exception caught

Arithmetic operation resulted in an overflow.

Graceful termination

Carnegie Mellon University MSCF 19

Parameters1 Pass By Value// C# Parameters

using System; public class Parameter1 {

static void inc(int x) { ++x; }

public static void Main() {

int a = 30; inc(a); Console.WriteLine(a); // 30 is displayed } }

Carnegie Mellon University MSCF 20

Parameters 2 Pass by Reference

// C# Parameters 2

using System; public class Parameter2 {

static void inc(ref int x) { ++x; }

public static void Main() {

int a = 30; inc(ref a); Console.WriteLine(a); // 31 is displayed } }

Carnegie Mellon University MSCF 21

Parameters 3 Passing Objects// C# Parameters

using System;

public class Student { public int age;} public class Parameter3 {

static void swap(Student x, Student y) { Student t = x; x = y; y = t; }

Carnegie Mellon University MSCF 22

public static void Main() {

Student a = new Student(); a.age = 34; Student b = new Student(); b.age = 65; swap(a,b); Console.WriteLine(a.age +" " +b.age); // 34 65 } }

Carnegie Mellon University MSCF 23

Parameter 4 Passing Objects// C# Parametersusing System;

public class Student { public int age;} public class Parameter4 {

static void swap(ref Student x, ref Student y) { Student t = x; x = y; y = t; }

Carnegie Mellon University MSCF 24

public static void Main() {

Student a = new Student(); a.age = 34; Student b = new Student(); b.age = 65; swap(ref a,ref b); Console.WriteLine(a.age +" " +b.age); // 65 34 } }

Carnegie Mellon University MSCF 25

Parameters 5 Out Parameters// C# Parameters

using System;

public class Student { public int age;} public class Parameter5 {

static void MakeAStudent(out Student x) { x = new Student(); // assignment is required }

Carnegie Mellon University MSCF 26

public static void Main() {

Student a; MakeAStudent(out a); a.age = 34; Console.WriteLine(a.age); // 35 is displayed } }

Carnegie Mellon University MSCF 27

Parameter 6 Passing Arrays// C# Parameters

using System; public class Parameter6 {

static decimal Multiply(params decimal[] a) { decimal amt = 0.0m; foreach(decimal i in a) amt += i; return amt; }

Carnegie Mellon University MSCF 28

public static void Main() {

decimal[] x = { 2.0m, 3.0m, 1.0m }; Console.WriteLine(Multiply(x)); // 6.0 is displayed } }

Carnegie Mellon University MSCF 29

// Classes may have members with protection levels// The default is private.class Student { public string name; int age;

public Student(string n, int a) { name = n; age = a; }}class MyClassApp {

public static void Main() { Student s = new Student("Mike",23); System.Console.WriteLine("Student " + s.name); // illegal to try to display the age from here }}

Classes 1

Carnegie Mellon University MSCF 30

internal class Student {

public string name; int age; public Student(string n, int a) { // Classes default to 'internal' visibility. name = n; // MyClassApp is public and therefore age = a; // visible to external // assemblies. }}public class MyClassApp {

public static void Main() { Student s = new Student("Mike",23); System.Console.WriteLine("Student " + s); }}

Student Student

Classes 2

Carnegie Mellon University MSCF 31

using System;

class Student {

private string name; private int age;

public String StudentName { set { name = value; } get { return name; } }

Classes 3 Properties

Carnegie Mellon University MSCF 32

public int StudentAge { set { age = value; } get { return age; } }} public class MyClassApp {

public static void Main() {

Student s = new Student(); s.StudentName = "Mike"; // calls set s.StudentAge = 23; // calls set // call get Console.WriteLine(s.StudentName + ":" + s.StudentAge); }}Mike:23

Carnegie Mellon University MSCF 33

Classes 4 Inheritance// C# Classes and Inheritance

using System;

class Student {

private string name; private int age;

public String StudentName { set { name = value; } get { return name; } }

Carnegie Mellon University MSCF 34

public int StudentAge { set { age = value; } get { return age; } } }

Carnegie Mellon University MSCF 35

class GradStudent : Student {

private String underGraduateDegree; public String Degree { set { underGraduateDegree = value; } get { return underGraduateDegree; } }}

Carnegie Mellon University MSCF 36

public class DemoInheritance {

public static void Main() {

GradStudent s = new GradStudent(); s.StudentName = "Mike"; s.StudentAge = 23; s.Degree = "Philosophy";

Console.WriteLine(s.StudentName + ":" + s.StudentAge + ":" + s.Degree); }}

Mike:23:Philosophy

Carnegie Mellon University MSCF 37

Classes 5 Polymorphism// C# Classes and Polymorphism

using System;

public class Student {

private string name; private int age;

public String StudentName { set { name = value; } get { return name; } }

Carnegie Mellon University MSCF 38

public int StudentAge { set { age = value; } get { return age; } } }

Carnegie Mellon University MSCF 39

public class GradStudent : Student {

private String underGraduateDegree; public String Degree { set { underGraduateDegree = value; } get { return underGraduateDegree; } }}

Carnegie Mellon University MSCF 40

public class DoctoralStudent : GradStudent {

private String thesisTitle; public String ThesisTitle { get { return thesisTitle; } }

public DoctoralStudent(string thesis) { thesisTitle = thesis; }}

Carnegie Mellon University MSCF 41

public class DemoInheritance {

public static void Main() {

GradStudent s = new GradStudent(); DoctoralStudent d = new DoctoralStudent("The Semantic Web"); s.StudentName = "Mike"; s.StudentAge = 23; d.StudentName = "Sue"; d.StudentAge = 25; Console.WriteLine(s.StudentName + ":" + s.StudentAge); Console.WriteLine(d.StudentName + ":" + d.StudentAge);

Display(s); Display(d); } public static void Display(Student x) { // Method takes any Student Console.WriteLine(x.StudentName + ":" + x.StudentAge); } }

Carnegie Mellon University MSCF 42

// Classes may have "Type Constructors"

internal class Student {

public static int numberOfStudentsCreated;

static Student() { // must take no args numberOfStudentsCreated = 0; }

public string name; int age;

public Student(string n, int a) { name = n; age = a; numberOfStudentsCreated++; }}

Type Constructors 1

Carnegie Mellon University MSCF 43

public class MyClassApp {

public static void Main() {

Student s = new Student("Mike",23); Student t = new Student("Sue",23);

System.Console.WriteLine("Student's created = " + Student.numberOfStudentsCreated);

}}

HelloUserStudent's created = 2

Carnegie Mellon University MSCF 44

GUI Programming (1)using System;

using System.Windows.Forms;

public class WindowGreeting {

private String m_userName; public String UserName {

set { m_userName = value; } get { return m_userName; } }

Carnegie Mellon University MSCF 45

public void Greet() {

MessageBox.Show("Hello " + m_userName); }

public static void Main(String[] a) {

WindowGreeting wg = new WindowGreeting(); wg.UserName = "Mike"; wg.Greet(); }}

Carnegie Mellon University MSCF 46

Carnegie Mellon University MSCF 47

GUI Programming (2)

csc -r:System.Windows.Forms.dll NewOne.cs

NewOne

The escape key works too.

Carnegie Mellon University MSCF 48

GUI Programming (2)using System;using System.Drawing;using System.Windows.Forms;

// Inherit from Form to control window

public class WindowGreeting : Form {

private String m_userName; private Button m_btnClose; private Label m_label;

public WindowGreeting() {

Console.WriteLine("constructing"); m_label = new Label(); m_label.Location = new Point(16,16); m_label.Size = new Size(136,24); m_label.Text = "";

Carnegie Mellon University MSCF 49

m_btnClose = new Button(); m_btnClose.Location = new Point(48,50); m_btnClose.Size = new Size(56,24); m_btnClose.Text = "Discard"; m_btnClose.Click += new EventHandler(CloseButton_Click); this.Controls.Add(m_label); this.Controls.Add(m_btnClose);

this.ClientSize = new Size(150, 90);

this.CancelButton = m_btnClose;

}

Carnegie Mellon University MSCF 50

void CloseButton_Click(Object sender, EventArgs e) { this.Close(); }

public String UserName {

set { m_userName = value; } get { return m_userName; } } public static void Main(String[] a) { WindowGreeting wg = new WindowGreeting(); wg.ShowDialog(); }}

Carnegie Mellon University MSCF 51

Networking 1 Visit a Web Site// Snarf.cs from C# in a Nutshell// Snarf.exe http://www.oreilly.com/catalog/csharpnut

using System;using System.IO;using System.Net;using System.Text;

class Snarf {

static void Main(String[] args) {

// args[0] holds a URL from the command line WebRequest req = WebRequest.Create(args[0]); WebResponse resp = req.GetResponse();

Carnegie Mellon University MSCF 52

// read the data from the URL Stream s = resp.GetResponseStream(); StreamReader sr = new StreamReader(s,Encoding.ASCII); String doc = sr.ReadToEnd();

Console.WriteLine(doc); }}

Suppose IIS is running with a virtual directory called MyNewWebAppsSnarf http://localhost/MyNewWebApps/Index.htmlDisplays the HTML code on the DOS Screen

Carnegie Mellon University MSCF 53

Distributed Objects using System.Runtime.Remoting.Channels.Tcp;using System.Runtime.Remoting.Channels;using System.Runtime.Remoting;using System;

class MyClient {

public static void Main() {

ChannelServices.RegisterChannel(new TcpClientChannel());

RemoteStudent r = (RemoteStudent) Activator.GetObject( typeof(RemoteStudent), "tcp://localhost:6502/somestudent");

This clientassumes the server isrunning.

Carnegie Mellon University MSCF 54

String name = r.getName(); int age = r.getAge();

Console.WriteLine("Student Name: " + name + " Age: " + age); }

}

Directory before compilationMyClient.cs Student.dll Student.cs Server.csCompile with

csc -t:exe -r:Student.dll MyClient.cs

Run withMyClientStudent Name: Mike Age: 23

Carnegie Mellon University MSCF 55

The Remote Object

// A Remote Student Object saved in Student.csusing System;

public class RemoteStudent : MarshalByRefObject {

private int age = 23; private String name = "Mike";

public int getAge() { return age; } public String getName() { return name; }

}Compile with csc -t:library Student.csProduces a DLL file Student.dll

Carnegie Mellon University MSCF 56

Publish the Object with Server.cs

using System.Runtime.Remoting.Channels.Tcp;using System.Runtime.Remoting.Channels;using System.Runtime.Remoting;using System;

class MyApp {

public static void Main() {

ChannelServices.RegisterChannel( new TcpServerChannel(6502)); RemotingConfiguration.RegisterWellKnownServiceType( Type.GetType("RemoteStudent, Student"), "SomeStudent", WellKnownObjectMode.SingleCall);

Carnegie Mellon University MSCF 57

Console.WriteLine("Press a key to exit server"); Console.Read(); }}

Compile with csc Server.csExecute with ServerPress a key to exit server