43
Object Oriented Programming Introduction to .NET Dr. Mike Spann Dr. Mike Spann [email protected] [email protected]

Object Oriented Programming Introduction to.NET Dr. Mike Spann [email protected]

Embed Size (px)

Citation preview

Page 1: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Object Oriented Programming

Introduction to .NET

Dr. Mike SpannDr. Mike Spann

[email protected]@bham.ac.uk

Page 2: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Contents OverviewOverview What is .NET?What is .NET? .NET – the big picture.NET – the big picture The Common Language RuntimeThe Common Language Runtime Common Intermediate Language, Metadata and JIT Common Intermediate Language, Metadata and JIT

CompilationCompilation Managed modules and assembliesManaged modules and assemblies Framework Class Library Framework Class Library Visual Studio.NETVisual Studio.NET .NET application scenarios.NET application scenarios

Page 3: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Overview

In this lecture, we will introduce the .NET In this lecture, we will introduce the .NET programming environment in preparation for the programming environment in preparation for the course on the object oriented programming using C#course on the object oriented programming using C# .NET is a multi-language programming platform .NET is a multi-language programming platform

but C# targets but C# targets onlyonly .NET .NET

Page 4: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

What is .NET? This is a tough question!This is a tough question! .NET is a complex software environment for .NET is a complex software environment for

providing servicesproviding services From enabling the development of simple From enabling the development of simple

standalone (maybe Windows-based) standalone (maybe Windows-based) applications running locallyapplications running locally

To complex Web services distributed across To complex Web services distributed across the internet perhaps using mobile devicesthe internet perhaps using mobile devices

Page 5: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

What is .NET? We live in a distributed world where services are no We live in a distributed world where services are no

longer just provided locallylonger just provided locally .NET can be used to develop robust software at any .NET can be used to develop robust software at any

point in a distributed application environmentpoint in a distributed application environment In the past different technologies and maybe even In the past different technologies and maybe even

different programming languages were necessary at different programming languages were necessary at different parts of the application different parts of the application (client/server/database.....)(client/server/database.....)

.NET is a common framework for all software .NET is a common framework for all software development and executiondevelopment and execution

Page 6: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

What is .NET?

Web Server

Client

Second-Tier(database or other server)

Second-Tier

Peer to peer Client

Page 7: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

.NET – the big picture

.NET has a number of distinct features :.NET has a number of distinct features : CLR (Common Language Runtime)CLR (Common Language Runtime) FCL (Framework Class Library)FCL (Framework Class Library) MetadataMetadata CIL (Common Intermediate Language)CIL (Common Intermediate Language)

The first two are the most important from a The first two are the most important from a programmers point of viewprogrammers point of view Any application that runs under the supervision of Any application that runs under the supervision of

the CLR is known as a the CLR is known as a managed applicationmanaged application

Page 8: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

.NET – the big picture

using System.Windows.Forms;using System.Drawing;

class MyForm:Form{public static void Main(){

Application.Run(new MyForm());

}

protected override void OnPaint(PaintEventArgse){e.Graphics.DrawString(

"Hello World!", new Font("Arial", 35),Brushes.Blue, 10, 100);

SomeSource.csSomeSource.cs

C# Compileror Visual Studio.NET

.EXE

IL

Meta-data

Windows (or other operating system )

Framework Class Library(a huge reusable collection of types) Common Language Runtime

Managed Application (at runtime)

JIT Compiler10010100 1011000010000000 1011101011011011 1101011111000010 01110110

Machine Language(Executed by CPU)

Page 9: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

The Common Language Runtime (CLR) ..NET code runs under the supervision of the CLRNET code runs under the supervision of the CLR

For this reason such code is called For this reason such code is called Managed CodeManaged Code The CLR supplies memory management, type safety, The CLR supplies memory management, type safety,

code verifiability, thread management and securitycode verifiability, thread management and security These are complex issues, especially securityThese are complex issues, especially security However, the key point is we can safely plug in However, the key point is we can safely plug in

software components into our application from software components into our application from diverse and un-trusted sourcesdiverse and un-trusted sources

Page 10: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

The Common Language Runtime (CLR) The CLR manages memory for managed codeThe CLR manages memory for managed code

All allocations of objects and buffers made from a All allocations of objects and buffers made from a Managed HeapManaged Heap

Unused objects and buffers are cleaned up Unused objects and buffers are cleaned up automatically through automatically through Garbage CollectionGarbage Collection

Some of the worst bugs in software development are Some of the worst bugs in software development are not possible with managed codenot possible with managed code

Leaked memory or objectsLeaked memory or objects References to freed or non-existent objectsReferences to freed or non-existent objects Reading of uninitialized variablesReading of uninitialized variables

Page 11: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

The Common Language Runtime (CLR) All programs running under CLR allocate memory All programs running under CLR allocate memory

from a managed heap from a managed heap The managed heap is maintained by the CLR The managed heap is maintained by the CLR

It is used for all memory resources, such as data It is used for all memory resources, such as data buffers, strings, collections, stacks and cachesbuffers, strings, collections, stacks and caches

Enables automatic garbage collection to be Enables automatic garbage collection to be efficient as the CLR can keep a track of unused efficient as the CLR can keep a track of unused memorymemory

Page 12: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

The Common Language Runtime (CLR)

A

B

E

D

C

The Managed Heap

= Object or buffer in memory

class MyClass{void Method(){

Variable v1;Variable v2;

do{...

If a garbage collection occurs during the execution of

Method(), then objects A and D will be cleaned up because

neither is directly or indirectly referenced by code

Page 13: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Common Intermediate Language, Metadata and JIT Compilation A managed executable comprises instructions expressed in the A managed executable comprises instructions expressed in the

common intermediate language (CIL) plus metadatacommon intermediate language (CIL) plus metadata

The key point is that the CIL is completely language independent The key point is that the CIL is completely language independent (C#, C++, Java, Perl ....)(C#, C++, Java, Perl ....)

Metadata describes high level features of the CIL instructions, Metadata describes high level features of the CIL instructions, for examplefor example Method argument types, return valuesMethod argument types, return values Class definitionsClass definitions Provides type information and binding rulesProvides type information and binding rules

.EXE = CIL + Metadata

Page 14: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Common Intermediate Language, Metadata and JIT Compilation

using System.Windows.Forms;using System.Drawing;

class MyForm:Form{public static void Main(){

Application.Run(new MyForm());

}

protected override void OnPaint(PaintEventArgs e){e.Graphics.DrawString(

"Hello World!", new Font("Arial",35),Brushes.Blue, 10, 100);

SomeSource.csSomeSource.cs

C# Compiler

SomeSources.exe

CIL

Metadata

A Managed Application

Page 15: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Common Intermediate Language, Metadata and JIT Compilation

For a simple ‘Hello World’ program, the CIL looks like For a simple ‘Hello World’ program, the CIL looks like ‘high level’ assembler :‘high level’ assembler :

.method private hidebysig static void Main() cil .method private hidebysig static void Main() cil managedmanaged

{{ .entrypoint.entrypoint // Code size 11 (0xb)// Code size 11 (0xb) .maxstack 8.maxstack 8 IL_0000: ldstr "Hello, world!"IL_0000: ldstr "Hello, world!" IL_0005: call void IL_0005: call void

[mscorlib]System.Console::WriteLine(string)[mscorlib]System.Console::WriteLine(string) IL_000a: retIL_000a: ret} // end of method HelloWorld::Main} // end of method HelloWorld::Main

Page 16: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Common Intermediate Language, Metadata and JIT Compilation

The Just in Time (JIT) compiler is part of The Just in Time (JIT) compiler is part of the CLRthe CLR

The JIT compiler uses both the metadata The JIT compiler uses both the metadata and the IL from a managed executable to and the IL from a managed executable to create machine language instructions at create machine language instructions at runtime runtime

These machine language instructions are These machine language instructions are executed nativelyexecuted natively

Page 17: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Common Intermediate Language, Metadata and JIT Compilation

Running Process’ Memory

SomeSources.exe

IL

Metadata

JIT Compiler

10010100 10110000 10000000 1011101011011011 11010111 11000010 01110110

Native Machine Language

The CPU executes the JIT-compiled machine code directly

At execution time the IL and Metadata are JIT compiled

Page 18: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Common Intermediate Language, Metadata and JIT Compilation

For efficiency, the JIT compiler is only invoked For efficiency, the JIT compiler is only invoked the first time an object method is calledthe first time an object method is called Subsequently execution jumps straight into Subsequently execution jumps straight into

native codenative code The system never wastes time JIT compiling The system never wastes time JIT compiling

methods that won’t be called by this run of your methods that won’t be called by this run of your applicationapplication

Page 19: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Common Intermediate Language, Metadata and JIT Compilation

AssemblyAssemblySource Source CodeCode

Language Language CompilerCompiler

CompilationCompilation

At installation or At installation or the first time the first time

each method is each method is calledcalled

ExecutionExecution

JIT CompilerJIT CompilerNativeNative

CodeCode

Code (IL)Code (IL)

MetadataMetadata

Page 20: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Common Intermediate Language, Metadata and JIT Compilation However, in the process of JIT compiling the code some very However, in the process of JIT compiling the code some very

important things happen.important things happen. Type-safety and security are verifiedType-safety and security are verified Code correctness is verified (no dangling memory references, or Code correctness is verified (no dangling memory references, or

referencing unassigned data)referencing unassigned data) Code executes at native speed Code executes at native speed

In short, the combination of CLR verification and JIT compilation In short, the combination of CLR verification and JIT compilation will increase the functionality and robustness traditional console or will increase the functionality and robustness traditional console or GUI applicationsGUI applications

However, for widely distributed applications that make use of However, for widely distributed applications that make use of components from many sources, the advantages of managed code are components from many sources, the advantages of managed code are a necessitya necessity

Page 21: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Managed modules and assemblies

.NET refers to the combination of the CIL and .NET refers to the combination of the CIL and metadata as a metadata as a managed modulemanaged module

However, the CLR However, the CLR cannotcannot execute a managed execute a managed modulemodule The smallest unit of executable code is referred The smallest unit of executable code is referred

to as an to as an assemblyassembly

Page 22: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Managed modules and assemblies A managed module is made up of only a single file A managed module is made up of only a single file However, a managed assembly can be made up of However, a managed assembly can be made up of

one or more files one or more files These files can be any number of managed These files can be any number of managed

modules modules Also assemblies can also include resource files Also assemblies can also include resource files

(which can be any kind of file, including .jpg and (which can be any kind of file, including .jpg and .xml files, for example).xml files, for example)

Assemblies also contain a Assemblies also contain a manifestmanifestDescribes the files that make up the assemblyDescribes the files that make up the assembly

Page 23: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Managed modules and assemblies

Managed Module IL and Metadata

Managed Module IL and Metadata

Managed Module IL and Metadata

Resource File(.jpg, .html, etc.)

AssemblyContains Manifest of files

Page 24: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Managed modules and assemblies

Typically re-useable components Typically re-useable components exist in exist in assemblies external of the main executable assemblies external of the main executable assemblyassembly Pretty much the same as linking in external Pretty much the same as linking in external

librarieslibraries A A .dll .dll file is created instead of a file is created instead of a .exe .exe file and file and

no no mainmain method is required method is required More of this when we look at developing C# More of this when we look at developing C#

programsprograms

Page 25: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Framework Class Library (FCL) The FCL is a massive collection of classes, structures, The FCL is a massive collection of classes, structures,

enumerated types and interfaces defined and implemented enumerated types and interfaces defined and implemented for reusefor reuse

For example, with the FCL we can use it toFor example, with the FCL we can use it to Display windowsDisplay windows Manipulate filesManipulate files Create container objects (such as arrays)Create container objects (such as arrays) Do mathsDo maths The FCL also has advanced classes for creating web and The FCL also has advanced classes for creating web and

distributed applicationsdistributed applications

Page 26: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Framework Class Library (FCL)

The various classes and types are grouped into a The various classes and types are grouped into a hierarchy of hierarchy of namespacesnamespaces Similar to the package/sub-package arrangement of Similar to the package/sub-package arrangement of

Java API’sJava API’s Helps find specific classes for your applicationHelps find specific classes for your application For example the For example the System.IOSystem.IO namespace is a good place namespace is a good place

to look in the documentation for classes related to to look in the documentation for classes related to input/outputinput/output

The The System.Windows.Forms System.Windows.Forms namespace contains namespace contains classes for manipulating top level windowsclasses for manipulating top level windows

Page 27: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Framework Class Library (FCL)

Some Important .NET NamespacesSome Important .NET Namespaces System System Core data/auxiliary classesCore data/auxiliary classes System.Collections System.Collections Resizable arrays + other containersResizable arrays + other containers System.Data System.Data ADO.NET database access classesADO.NET database access classes System.Drawing System.Drawing Graphical Output classesGraphical Output classes System.IO System.IO Classes for file/stream I/OClasses for file/stream I/O System.Net System.Net Classes to wrap network protocolsClasses to wrap network protocols System.Web System.Web HTTP support classesHTTP support classes System.Web.Services System.Web.Services Classes for writing web servicesClasses for writing web services System.Web.UI System.Web.UI Core classes used by ASP.NETCore classes used by ASP.NET System.Threading System.Threading Classes to create/manage threadsClasses to create/manage threads System.Windows.Forms System.Windows.Forms Classes for Windows GUI appsClasses for Windows GUI apps

Page 28: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Framework Class Library (FCL)

It’s important to be able to efficiently use the FCL It’s important to be able to efficiently use the FCL documentation which comes with Visual Studio or documentation which comes with Visual Studio or the .NET SDK the .NET SDK

We can access the documentation from the Visual We can access the documentation from the Visual Studio homepageStudio homepage Each FCL class has its own page with a lot of Each FCL class has its own page with a lot of

informationinformation The most useful is some example codeThe most useful is some example code Code can be language filtered Code can be language filtered

Page 29: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk
Page 30: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk
Page 31: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Framework Class Library (FCL)

Programming using FCL classes is much Programming using FCL classes is much simpler than ‘traditional’ windows simpler than ‘traditional’ windows programmingprogramming Very intuitiveVery intuitive Equivalent simplicity to Java graphics Equivalent simplicity to Java graphics

((SwingSwing) programming) programming

Page 32: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Framework Class Library (FCL)

HWND hwndMain = CreateWindowEx(HWND hwndMain = CreateWindowEx( 0, "MainWClass", "Main Window",0, "MainWClass", "Main Window", WS_OVERLAPPEDWINDOW | WS_HSCROLL | WS_OVERLAPPEDWINDOW | WS_HSCROLL | WS_VSCROLL,WS_VSCROLL, CW_USEDEFAULT, CW_USEDEFAULT,CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,CW_USEDEFAULT, CW_USEDEFAULT, (HWND)NULL, (HMENU)NULL, hInstance, (HWND)NULL, (HMENU)NULL, hInstance, NULL); NULL); ShowWindow(hwndMain, SW_SHOWDEFAULT); ShowWindow(hwndMain, SW_SHOWDEFAULT); UpdateWindow(hwndMain);UpdateWindow(hwndMain);

Dim Dim form form As NewAs New Form() Form()form.Text = "Main Window"form.Text = "Main Window"form.Show()form.Show()

Displaying a window using the Windows API

Displaying a window using FCL(VB)

Page 33: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio.NET

Visual Studio .NET is Visual Studio .NET is notnot part of the .NET Framework! part of the .NET Framework! Visual Studio is an integrated development Visual Studio is an integrated development

environment published by Microsoft for writing environment published by Microsoft for writing Windows programsWindows programs But .NET applications can be developed with a But .NET applications can be developed with a

simple text editor and compiled and run with simple text editor and compiled and run with command line instructions!command line instructions!

Obviously VS requires the .NET framework to be Obviously VS requires the .NET framework to be installedinstalled

Page 34: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio.NET

Page 35: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio.NET

We will look in more detail at how to We will look in more detail at how to develop projects using VS in the next develop projects using VS in the next lecturelecture However, it’s important to emphasise that However, it’s important to emphasise that

for simple programs, its sometimes easier for simple programs, its sometimes easier to use the command based compilerto use the command based compiler

Even for developing Windows Even for developing Windows applications!applications!

Page 36: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio.NET

using System.Windows.Forms;using System.Drawing; class MyForm:Form{

public static void Main(){

Application.Run(new MyForm()); } protected override void OnPaint(PaintEventArgs e)

{ e.Graphics.DrawString("Hello World!", new Font("Arial", 35), Brushes.Blue, 10, 100); }}

Page 37: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio.NET

We can use the command line compiler to We can use the command line compiler to compile this program and create an .exe file:compile this program and create an .exe file:

/Target:winexe /Target:winexe means create a GUI means create a GUI (Windows) application(Windows) application

We run the program by just typing the We run the program by just typing the name of the .exe file (HelloGui)name of the .exe file (HelloGui)

C:\>csc /Target:winexe HelloGui.cs

Page 38: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio.NET

Page 39: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

.NET application scenarios

Applications can be developed in .NET for the Applications can be developed in .NET for the following scenariosfollowing scenarios Standalone applicationsStandalone applications

ConsoleConsoleWindowsWindows

Active Web ApplicationsActive Web Applications Web formsWeb formsServer side processingServer side processing

Page 40: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

.NET application scenarios

Typically Typically an active web-page would involve the an active web-page would involve the interaction between a browser, a web server and a interaction between a browser, a web server and a databasedatabase

IE

Client user interface (Web form) Web server

ASP.NETXHTML

Database

ADO.NET

Page 41: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

.NET application scenarios Web service applications Web service applications

Software components that perform a task in a Software components that perform a task in a distributed manner across the internetdistributed manner across the internet

Web services use standard protocols such as SOAP Web services use standard protocols such as SOAP and XML to communicate data between machines and XML to communicate data between machines across the internet across the internet

The .NET Framework can easily be used to create The .NET Framework can easily be used to create and expose web service applications on the Internet and expose web service applications on the Internet

It is also very easy to create web-service client It is also very easy to create web-service client software using C# (or any other .NET Language)software using C# (or any other .NET Language)

Page 42: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

.NET application scenarios A web service is similar to an active web page A web service is similar to an active web page but but

the client is another piece of software, rather than the client is another piece of software, rather than a human user using a browsera human user using a browser

}}

Client

SOAP/xml

Web server

using System;class App{ public static void Main(){ DateService webObj = new DateService(); webObj.Url = "http://www.wintellect.com/Services/DateService.asmx"; String dateString = webObj.GetDateString(); Console.WriteLine(dateString); }}

<%@ WebService Language="C#" Class="DateService" %>using System;using System.Web.Services;public class DateService:WebService{ [WebMethod] public String GetDateString() { return DateTime.Now.ToString("D");

Page 43: Object Oriented Programming Introduction to.NET Dr. Mike Spann m.spann@bham.ac.uk

Summary

We have seen a fairly detailed overview of the .NET We have seen a fairly detailed overview of the .NET frameworkframework

We have seen that it’s a robust environment for We have seen that it’s a robust environment for application program development and execution application program development and execution

It’s language neutral although C# only targets .NETIt’s language neutral although C# only targets .NET It removes many of the programmer headaches for the It removes many of the programmer headaches for the

development of windows (component-based) development of windows (component-based) applications as well as distributed applicationsapplications as well as distributed applications Much of the technicalities we have discussed are Much of the technicalities we have discussed are

transparent to the programmertransparent to the programmer