Upload
clarence-clark
View
216
Download
0
Tags:
Embed Size (px)
Citation preview
An Introduction An Introduction to .NETto .NETKeith MulkeyKeith Mulkey
Senior Software EngineerSenior Software Engineer
SFA, Inc.SFA, Inc.
AgendaAgendaWhat is .NET?What is .NET?
What is the Common Language Runtime (CLR)?What is the Common Language Runtime (CLR)?Introduction to Visual Studio 2005 and the IDEIntroduction to Visual Studio 2005 and the IDE
Introduction to C#Introduction to C#
What is .NET?What is .NET?
According to Microsoft, .NET is According to Microsoft, .NET is ““the Microsoft Web services strategy to the Microsoft Web services strategy to
connect information, people, systems, and connect information, people, systems, and devices through software”devices through software”
What does this mean to the average What does this mean to the average developer?developer?ABSOLUTELY NOTHING!ABSOLUTELY NOTHING!
What is .NET to the average What is .NET to the average developer?developer?
A Framework that provides:A Framework that provides:an easy to use development environmentan easy to use development environmenta multitude of libraries that make our job a multitude of libraries that make our job easier including distributed processingeasier including distributed processingcross-language interoperabilitycross-language interoperabilitya runtime environment that will manage a runtime environment that will manage resources with no assistance from usresources with no assistance from ustight integration with the operating systemtight integration with the operating systemeasy integration of third party librarieseasy integration of third party libraries
.NET Framework Design Features.NET Framework Design Features
Component (Assembly) InfrastructureComponent (Assembly) Infrastructure
Language IntegrationLanguage Integration
Distributed ComputingDistributed Computing
Simplified DevelopmentSimplified Development
Simplified DeploymentSimplified Deployment
ReliabilityReliability
SecuritySecurity
Component InfrastructureComponent Infrastructure
.NET classes are ready to be used at the .NET classes are ready to be used at the binary levelbinary level
.NET assemblies do not have to be .NET assemblies do not have to be registered in the Windows registryregistered in the Windows registry
No special “plumbing” code is required No special “plumbing” code is required for component registration, class for component registration, class factories, component lifetime or dynamic factories, component lifetime or dynamic bindingbinding
Language IntegrationLanguage Integration
Language Independence vs. Language Language Independence vs. Language IntegrationIntegration
COM supported language independenceCOM supported language independenceComponent can be written in any languageComponent can be written in any languageComponent must meet COM specification rulesComponent must meet COM specification rulesSupports binary reuseSupports binary reuseDOES NOT allow COM component code reuseDOES NOT allow COM component code reuseDOES NOT support COM component class DOES NOT support COM component class extensionextensionDOES NOT allow catching exceptions thrown by DOES NOT allow catching exceptions thrown by COM componentCOM component
Language IntegrationLanguage Integration
Language Independence vs. Language Language Independence vs. Language IntegrationIntegration
COM supported language independenceCOM supported language independence.NET supports language integration.NET supports language integration
Components can be written in any supported Components can be written in any supported language (C#, VB, Managed C++, J#)language (C#, VB, Managed C++, J#)The adherence to a common specification is The adherence to a common specification is taken care of by .NETtaken care of by .NETDOES allow .NET component code reuseDOES allow .NET component code reuseDOES support .NET component class extensionDOES support .NET component class extensionDOES allow catching exceptions thrown by .NET DOES allow catching exceptions thrown by .NET componentscomponents
Language IntegrationLanguage Integration
Language Independence vs. Language Language Independence vs. Language IntegrationIntegration
COM supported language independenceCOM supported language independence.NET supports language integration.NET supports language integration
Made possible by the Common Type System Made possible by the Common Type System (CTS)(CTS)Everything in CTS derives from System.ObjectEverything in CTS derives from System.ObjectCTS supports concepts of classes, interfaces, CTS supports concepts of classes, interfaces, delegates, reference types, and value typesdelegates, reference types, and value typesCTS supports base system types such as CTS supports base system types such as integer, double, string, file manipulationinteger, double, string, file manipulation
Language IntegrationLanguage Integration
Language Independence vs. Language Language Independence vs. Language IntegrationIntegration
COM supported language independenceCOM supported language independence.NET supports language integration.NET supports language integration
Common Language Specification (CLS) Common Language Specification (CLS) provides minimum set of rulesprovides minimum set of rulesAll .NET language compilers must meet CLS All .NET language compilers must meet CLS and generate code that conforms to CTSand generate code that conforms to CTSThis allows different .NET languages to be used This allows different .NET languages to be used in the same applicatonin the same applicaton
Distributed ComputingDistributed Computing
COM supported distributed computing COM supported distributed computing using DCOMusing DCOM
Due to embedded IP address, DCOM Due to embedded IP address, DCOM would not work through firewalls and would not work through firewalls and NATNAT
.NET uses industry standard SOAP to .NET uses industry standard SOAP to interoperate on the Internetinteroperate on the Internet
.NET Remoting uses a CORBA-like .NET Remoting uses a CORBA-like approach for distributed computingapproach for distributed computing
Simplified DevelopmentSimplified Development
Every .NET language uses the same Every .NET language uses the same library of .NET componentslibrary of .NET componentsThe API to the .NET library of The API to the .NET library of components is always the samecomponents is always the sameIntegrating with .NET components is Integrating with .NET components is always the samealways the sameThe same IDE is used for all languagesThe same IDE is used for all languagesIntellisenseIntellisense®® works the same for all works the same for all languageslanguagesThe build process is always the sameThe build process is always the same
Simplified DeploymentSimplified Deployment
No more “DLL Hell”No more “DLL Hell”Shared DLLs are registered with the Global Shared DLLs are registered with the Global Assembly Cache (GAC)Assembly Cache (GAC)
Multiple versions of the same DLL can co-Multiple versions of the same DLL can co-existexist
Applications are tightly bound to a particular Applications are tightly bound to a particular DLL versionDLL version
Simplified DeploymentSimplified Deployment
No more “DLL Hell”No more “DLL Hell”
DLL Registry entries eliminatedDLL Registry entries eliminatedReferences and dependencies stored in References and dependencies stored in DLL manifestDLL manifest
Private DLLs are found using logical paths Private DLLs are found using logical paths or XML based configuration filesor XML based configuration files
Shared (public) DLLs are found using the Shared (public) DLLs are found using the GACGAC
Both are found at runtimeBoth are found at runtime
Simplified DeploymentSimplified Deployment
No more “DLL Hell”No more “DLL Hell”
DLL Registry entries eliminatedDLL Registry entries eliminated
““Zero-Impact” installation and removalZero-Impact” installation and removal.NET DLLs are not entered into registry .NET DLLs are not entered into registry upon installationupon installation
Hence no need to remove from registry Hence no need to remove from registry upon uninstallupon uninstall
Installation and removal can be Installation and removal can be accomplished with copy and delete accomplished with copy and delete
Simplified DeploymentSimplified Deployment
No more “DLL Hell”No more “DLL Hell”
DLL Registry entries eliminatedDLL Registry entries eliminated
““Zero-Impact” installation and removalZero-Impact” installation and removal
Web, network, and CD deployment all Web, network, and CD deployment all supported within Visual Studio 2005supported within Visual Studio 2005
ReliabilityReliability
Type safetyType safetyCLR must recognize and verify types CLR must recognize and verify types before they are loaded and executedbefore they are loaded and executed
Helps prevent buffer overruns which can be Helps prevent buffer overruns which can be a source of program errors and security a source of program errors and security weaknessesweaknesses
ReliabilityReliability
Type safetyType safety
Common error handlingCommon error handling
Automatic memory managementAutomatic memory management
SecuritySecurity
.NET can protect access to specific parts .NET can protect access to specific parts of executable codeof executable code.NET supports strong naming of .NET supports strong naming of assemblies to help prevent pirating and assemblies to help prevent pirating and tamperingtampering.NET has extensive support for all of the .NET has extensive support for all of the major security algorithms and practices major security algorithms and practices in use todayin use today.NET can be tightly integrated with the .NET can be tightly integrated with the Windows Active DirectoryWindows Active Directory
.NET Framework Architecture.NET Framework Architecture
Common Language Runtime(debug, exception, type checking, garbage collection, JIT compilation, etc.)
Framework Base Classes(IO, string, net, security, threading, text, reflection, collections, etc.)
Data and XML Classes(ADO.NET, SQL, XSLT, Xpath, XML, etc)
Web Services Web Forms Windows Forms
Windows Platform
.NET Framework
VEGAApplication
What is the CLR?What is the CLR?
The CLR is the heart and soul of The CLR is the heart and soul of the .NET architecturethe .NET architecture
Analogous to Java’s JVMAnalogous to Java’s JVM
The CLR activates objects and:The CLR activates objects and:performs security checks on themperforms security checks on them
lays them out in memorylays them out in memory
executes themexecutes them
garbage collects themgarbage collects them
The CLR vs. the JVMThe CLR vs. the JVM
Both are runtime infrastructures that Both are runtime infrastructures that abstract the underlying platformabstract the underlying platform
JVM supports any language that can be JVM supports any language that can be represented in its bytecoderepresented in its bytecode
JavaJava
The CLR vs. the JVMThe CLR vs. the JVM
Both are runtime infrastructures that Both are runtime infrastructures that abstract the underlying platformabstract the underlying platform
JVM supports any language that can be JVM supports any language that can be represented in its bytecoderepresented in its bytecode
CLR supports any language that can be CLR supports any language that can be represented in its Common Intermediate represented in its Common Intermediate Language (CIL)Language (CIL)
C#, VB.NET, Managed C++, J#C#, VB.NET, Managed C++, J#
Which is better, CLR or JVM?Which is better, CLR or JVM?
Depends on who you askDepends on who you ask
The CLR is not and never has been an The CLR is not and never has been an interpreterinterpreter
In April 2003, a subset of the CLR known In April 2003, a subset of the CLR known as the Common Language Interface as the Common Language Interface (CLI) became an international standard(CLI) became an international standard
Projects are underway to develop CLRs Projects are underway to develop CLRs for Linux and Unix and possibly even for Linux and Unix and possibly even Mac OS XMac OS X
Back to the CLRBack to the CLR
The CLR manages the execution of code The CLR manages the execution of code in the .NET environmentin the .NET environmentThe CLR:The CLR:
loads required classesloads required classesperforms Just-In-Time (JIT) compilationperforms Just-In-Time (JIT) compilationenforces securityenforces securityand much more…and much more…
Units of deployment are Portable Units of deployment are Portable Executables (PEs) aka assembliesExecutables (PEs) aka assembliesPEs can be DLLs or EXEsPEs can be DLLs or EXEs
What is a .NET Assembly?What is a .NET Assembly?
Assemblies consist of code and Assemblies consist of code and metadatametadata
Code in an assembly is in the form of the Code in an assembly is in the form of the Common Intermediate Language (CIL)Common Intermediate Language (CIL)
Metadata makes it all work togetherMetadata makes it all work together
.NET Assembly.NET Assembly
Cobol .NETSource Code
Perl .NETSource Code
Managed C++Source Code
J#Source Code
VB .NETSource Code
Cobol .NETCompiler
Perl .NETCompiler
Managed C++Compiler
J#Compiler
VB .NETCompiler
C#Compiler
C#Source Code
.NETAssembly
(DLL or EXE)
CILand
Metadata
Compilation
.NET Metadata.NET Metadata
In .NET, metadata includes:In .NET, metadata includes:type definitionstype definitions
version informationversion information
external assembly referencesexternal assembly references
other standardized informationother standardized information
.NET Metadata.NET Metadata
In .NET, metadata includes:In .NET, metadata includes:
.NET uses metadata to describe an .NET uses metadata to describe an assembly in detail, including:assembly in detail, including:
identity descriptionidentity description
types that it referencestypes that it references
types that it exportstypes that it exports
security requirements for executionsecurity requirements for execution
.NET Metadata.NET Metadata
In .NET, metadata includes:In .NET, metadata includes:
.NET uses metadata to describe an .NET uses metadata to describe an assembly in detail, including:assembly in detail, including:
Metadata provides enough information Metadata provides enough information for any runtime tool or program to find for any runtime tool or program to find out everything that is needed for out everything that is needed for component integrationcomponent integration
.NET Consumers of Metadata.NET Consumers of Metadata
CLR relies on metadata to support CLR relies on metadata to support runtime featuresruntime features
verificationverification
security enforcementsecurity enforcement
cross-context marshallingcross-context marshalling
memory layoutmemory layout
executionexecution
.NET Consumers of Metadata.NET Consumers of Metadata
CLR relies on metadata to support CLR relies on metadata to support runtime featuresruntime features
Class Loader of CLR uses metadata to Class Loader of CLR uses metadata to find and load .NET classesfind and load .NET classes
JIT compiler uses metadata to compile JIT compiler uses metadata to compile CIL codeCIL code
Various tools use metadata to support Various tools use metadata to support integration (e.g., Intellisenseintegration (e.g., Intellisense®®))
Type Libraries on SteroidsType Libraries on Steroids
Any application, tool, or utility that can Any application, tool, or utility that can read metadata from a .NET assembly read metadata from a .NET assembly can make use of that assembly.can make use of that assembly.
Metadata ensures language Metadata ensures language interoperabilityinteroperability
Single-File & Multi-File AssembliesSingle-File & Multi-File Assemblies
Assemblies composed of a single *.dll or *.exe Assemblies composed of a single *.dll or *.exe are single-file assembliesare single-file assemblies
Multi-file assemblies are composed of Multi-file assemblies are composed of numerous .NET *.dlls or *.exes termed numerous .NET *.dlls or *.exes termed modulesmodules
Primary module contains the assembly Primary module contains the assembly manifestmanifest
Other modules contain module-level manifestOther modules contain module-level manifest
Primary module documents the set of Primary module documents the set of “secondary” modules within the assembly“secondary” modules within the assembly
The .NET Runtime EnvironmentThe .NET Runtime Environment
The term runtime can be understood as The term runtime can be understood as a collection of external services that are a collection of external services that are required to execute a given compiled required to execute a given compiled unit of code.unit of code.
MFC requires mfc42.dllMFC requires mfc42.dll
VB6 requires msvbvm60.dllVB6 requires msvbvm60.dll
Java requires the JVMJava requires the JVM
.NET requires the CLR.NET requires the CLR
The .NET CLRThe .NET CLR
Crux of the CLR is the Common Object Crux of the CLR is the Common Object Runtime Execution Engine (mscoree.dll)Runtime Execution Engine (mscoree.dll)
f
Cobol .NETSource Code
Perl .NETSource Code
Managed C++Source Code
J#Source Code
VB .NETSource Code
Cobol .NETCompiler
Perl .NETCompiler
Managed C++Compiler
J#Compiler
VB .NETCompiler
C#Compiler
C#Source Code
.NETAssembly
(DLL or EXE)
CILand
Metadata
CLR
ClassLoader
JITCompiler
PlatformDependentExecutableInstructions
Compilation Runtime – mscoree.dll
CLR ExecutionCLR ExecutionVEGA
Class Loader(Locates class & entry point, caches type information,
allocates memory, initializes statics, instantiates object)
CLR’s Common Object Runtime Execution Engine
Verifier(Verifies that metadata is well formed, CIL code is type safe, caches verified status)
JIT Compilation
Me
tho
dIn
vo
ca
tio
n
JIT Compiler(Occurs on a method by method basis, is optimized for host platform,
occurs on first method invocation only)
Execution Support and Management(Garbage Collector, Security Engine, Code Manager
Exception Manager, Thread Support, etc)
Visual Studio 2005 & Visual Studio 2005 & the IDEthe IDE
Visual Studio 2005 & the IDEVisual Studio 2005 & the IDE
Solution ExplorerSolution Explorer
Class ViewClass View
Object BrowserObject Browser
Code Definition WindowCode Definition Window
Code RefactoringCode Refactoring
IntellisenseIntellisense®®
ToolbarsToolbars
DebuggingDebugging
What is C#What is C#
New programming language developed New programming language developed by Microsoft for .NETby Microsoft for .NET
Syntax is very similar to JavaSyntax is very similar to Java
Just as Java is in many ways a cleaned-Just as Java is in many ways a cleaned-up version of C++, C# can be viewed as up version of C++, C# can be viewed as a cleaned-up version of Java a cleaned-up version of Java
C# is managed codeC# is managed code
Anatomy of a C# ProgramAnatomy of a C# Program
A C# application must have one PE that A C# application must have one PE that is an .exe; it can have any number of is an .exe; it can have any number of PEs that are .dllsPEs that are .dlls
By convention, C# source code files By convention, C# source code files have a .cs extensionhave a .cs extension
All program logic must be contained All program logic must be contained within a type definitionwithin a type definition
Anatomy of a C# ProgramAnatomy of a C# Program
Every C# application must contain a Every C# application must contain a class defining a Main() methodclass defining a Main() method
Main() must be public and staticMain() must be public and static
Main() typically does very little other than Main() typically does very little other than start things upstart things up
Rules of the RoadRules of the Road
Everything must exist within a Everything must exist within a namespacenamespace
“ “enum”s and “struct”s can be defined enum”s and “struct”s can be defined outside of a class but must be scoped within outside of a class but must be scoped within a namespacea namespace
Object visibility should always be Object visibility should always be specified. If one is not provided the specified. If one is not provided the compiler will assign a defaultcompiler will assign a default
Data in C#Data in C#
There are NO POINTERs in C# (per se)There are NO POINTERs in C# (per se)ALL reference type objects must be “new”ed ALL reference type objects must be “new”ed and are allocated on the managed heapand are allocated on the managed heap
Objects are NEVER “delete”ed; the garbage Objects are NEVER “delete”ed; the garbage collector will take care of thatcollector will take care of that
Scope resolution operator is always a Scope resolution operator is always a period (“.”) irrespective of the object’s period (“.”) irrespective of the object’s location (stack or heap)location (stack or heap)
Pointers can be used in “unsafe” code Pointers can be used in “unsafe” code sections -- but let’s not go there!sections -- but let’s not go there!
Data in C#Data in C#
Class attributes are always initialized to Class attributes are always initialized to a safe default valuea safe default value
Local variables within a member scope Local variables within a member scope are not initializedare not initialized
the compiler will force assignment before the compiler will force assignment before they can be usedthey can be used
there is one exception to thisthere is one exception to this
The Mother of All ObjectsThe Mother of All Objects
When you create a class that does not When you create a class that does not explicitly specify a base class, you explicitly specify a base class, you implicitly derive from System.Objectimplicitly derive from System.ObjectSystem.Object provides some basic System.Object provides some basic functionality for all C# classesfunctionality for all C# classes
Example: ToString() returns a string Example: ToString() returns a string representation of the given objectrepresentation of the given object
Some functionality can be overridden: Some functionality can be overridden: Equals, GetHashCode, ToString, and Equals, GetHashCode, ToString, and FinalizeFinalize
Class Objects in C#Class Objects in C#
Class objects are either “public” or Class objects are either “public” or “internal”“internal”
Every C# class gets a “free” default Every C# class gets a “free” default constructorconstructor
ensures that all member data is set to an ensures that all member data is set to an appropriate default valueappropriate default value
value-type data are initialized with a default, value-type data are initialized with a default, safe value (e.g., int and doubles are safe value (e.g., int and doubles are initialized to 0)initialized to 0)
reference-type data are initialized to nullreference-type data are initialized to null
Class Objects in C#Class Objects in C#
As soon as you define a custom constructor, As soon as you define a custom constructor, the default constructor is removedthe default constructor is removed
class loader however still initializes attributes to class loader however still initializes attributes to default valuesdefault values
if a default constructor is still needed, you will have if a default constructor is still needed, you will have to provide it.to provide it.
There are no “friend” classes. Visibility There are no “friend” classes. Visibility modifier “internal” is similar but not the samemodifier “internal” is similar but not the same
Class attributes can be initialized by Class attributes can be initialized by assignment when declaredassignment when declared
Class Objects in C#Class Objects in C#
A class can be declared as “static”A class can be declared as “static”In fact the class that contains Main() must In fact the class that contains Main() must be declared staticbe declared static
Typically one .cs file contains the Typically one .cs file contains the declaration of one C# classdeclaration of one C# class
C# classes can span multiple files using C# classes can span multiple files using the “partial” modifierthe “partial” modifier
Inheritance in C#Inheritance in C#
Much the same as in C++Much the same as in C++
Multiple inheritance is not supportedMultiple inheritance is not supported
You can however implement as many You can however implement as many interfaces as you likeinterfaces as you like
Abstract methods and classes must be Abstract methods and classes must be marked as such using the keyword marked as such using the keyword “abstract”“abstract”
Loops and Branching in C#Loops and Branching in C#
““for”, “while”, “do … while”, “if … else” all for”, “while”, “do … while”, “if … else” all work as in C/C++work as in C/C++
““foreach” is new to C#foreach” is new to C#Allows interation over items in a collection Allows interation over items in a collection or arrayor array
No need to test for upper and lower limitsNo need to test for upper and lower limits
Example:Example:string[] colorSchemes = { “Day”, “Dusk”, “Night” };foreach (string s in colorSchemes { … }
Loops and Branching in C#Loops and Branching in C#
““switch” works as in C/C++ with a couple switch” works as in C/C++ with a couple of exceptions…of exceptions…
each “case” must have a terminating “break” each “case” must have a terminating “break” unless there is no code between “case”sunless there is no code between “case”s
the “switch” statement can evaluate stringsthe “switch” statement can evaluate strings
Accessors and MutatorsAccessors and Mutators
Object oriented encapsulation Object oriented encapsulation Attributes should not be directly accessibleAttributes should not be directly accessible
Accessors should be provided to retrieve Accessors should be provided to retrieve statestate
Mutators should be provided to set stateMutators should be provided to set state
Traditional approach:Traditional approach:GetXXX() or get_XXX()GetXXX() or get_XXX()
SetXXX() or set_XXX()SetXXX() or set_XXX()
C# uses propertiesC# uses properties
C# PropertiesC# Properties
Example:Example:
““value” is value” is notnot a keyword but rather a a keyword but rather a contentual keywordcontentual keyword
Properties feel more “natural”Properties feel more “natural”Instead of: Instead of:
We use: We use:
private double lat;public double Lat {get{return lat;} set{lat=value;}}
double myLat = gsoPoint.get_Lat();
double myLat = gsoPoint.Lat;
C# PropertiesC# Properties
Accessors and mutators can have Accessors and mutators can have different visibility:different visibility:
How would you make a property read or How would you make a property read or write only?write only?
Properties can be “static”Properties can be “static”
private double lat;public double Lat {get{return lat;} protected set{lat=value;}}
C# Casting RulesC# Casting Rules
Any data type can be stored in an Any data type can be stored in an “object” variable:“object” variable:
Any subclass object can be stored in a Any subclass object can be stored in a superclass object variable:superclass object variable:
object shape = new GSOLine();
GSOShape shape = new GSOLine();
C# Casting RulesC# Casting Rules
How do we get it back?How do we get it back?
What if “shape” is not a “GSOLine”?What if “shape” is not a “GSOLine”?InvalidCastException is thrown at runtimeInvalidCastException is thrown at runtime
GSOLine line = (GSOLine)shape;
C# Casting RulesC# Casting Rules
Is there another way?Is there another way?
What if “shape” is not a “GSOLine”?What if “shape” is not a “GSOLine”?The “as” operation will return nullThe “as” operation will return null
GSOLine line = shape as GSOLine;
C# Casting RulesC# Casting Rules
Which is better?Which is better?Exceptions are expensiveExceptions are expensive
Can we tell before we cast?Can we tell before we cast?if (shape is GSOLine)
Anatomy of a C# Anatomy of a C# Source Code FileSource Code File
Building a Simple GUI Building a Simple GUI in Visual Studio 2005in Visual Studio 2005