Think Think Smart Smart
Jan 19, 2016
Think Think SmartSmart
.Net Framework.Net Framework
Er.Ashish pandeyEr.Ashish pandeyNew Horizon IndiaNew Horizon India
(9871682886)(9871682886)
AgendaAgenda What is .Net FrameworkWhat is .Net Framework Common Language RuntimeCommon Language Runtime
Assemblies(Modules,CTS/CLS)Assemblies(Modules,CTS/CLS) Memory management in .NetMemory management in .Net Execution ModelExecution Model .Net security Model.Net security Model
ASP.NETASP.NET ADO.NETADO.NET
Development ChallengesDevelopment Challenges
Software IntegrationSoftware Integration Language silo problem Language silo problem Development and deployment complexityDevelopment and deployment complexity Multiple programming modelsMultiple programming models Security not inherentSecurity not inherent
The .NET FrameworkThe .NET FrameworkWhat Is the .NET Framework?What Is the .NET Framework?
A set of technologies that:A set of technologies that: unite today’s isolated Web applicationsunite today’s isolated Web applications make information available make information available
anytime, anywhereanytime, anywhere simplify development and deploymentsimplify development and deployment
How does .NET achieve the above?How does .NET achieve the above? Web servicesWeb services ADO.NET DataSets and XML support ADO.NET DataSets and XML support
throughout the platform throughout the platform rich tools, runtime services, and rich tools, runtime services, and
XCOPY deploymentXCOPY deployment
.Net Framework.Net Framework
Common Language Runtime (CLR)Common Language Runtime (CLR)
Base Class LibraryBase Class Library
Visual BasicVisual BasicSource Source codecode
CompilerCompiler
C++C++C#C#
CompilerCompilerCompilerCompiler
AssemblyAssemblyIL codeIL code
AssemblyAssemblyIL codeIL code
AssemblyAssemblyIL codeIL code
Operating system servicesOperating system services
Common language runtimeCommon language runtime
JIT compilerJIT compiler
Native codeNative code
ManagedManagedcodecode
UnmanagedUnmanagedcomponentcomponent
Common Language RuntimeCommon Language RuntimeExecution ModelExecution Model
The CLRThe CLR
Base Class Library SupportBase Class Library Support
Thread SupportThread Support COM MarshalerCOM Marshaler
Type CheckerType Checker Exception ManagerException Manager
MSIL to NativeMSIL to NativeCompilersCompilers
CodeCodeManagerManager
GarbageGarbageCollectorCollector
Security EngineSecurity Engine Debug EngineDebug Engine
Class LoaderClass Loader
System
System.Data (ADO .NET) System.XML
System.Web (ASP .NET)
Globalization
Diagnostics
Configuration
Collections
Resources
Reflection
Net
IO
Threading
Text
ServiceProcess
Security
Design
ADO
SQLTypes
SQL
XPath
XSLT
RuntimeInteropServices
Remoting
Serialization
Serialization
Configuration SessionState
Caching Security
ServicesDescription
Discovery
Protocols
UIHTMLControls
WebControls
System.Drawing
Imaging
Drawing2D
Text
Printing
System.WinForms
Design ComponentModel
.Net Framework Classes.Net Framework Classes
Common Language RuntimeCommon Language Runtime Execution engine for .NET framework Execution engine for .NET framework
applications.applications. Services provided.Services provided.
Code management (loading and execution).Code management (loading and execution). Application memory isolation.Application memory isolation. Verification of type safety.Verification of type safety. Conversion of IL to native code.Conversion of IL to native code. Enforcement of code access security Enforcement of code access security Exception handling, including cross-language Exception handling, including cross-language
exceptions exceptions Interoperation between managed code, COM Interoperation between managed code, COM
objects, and pre-existing DLLs (unmanaged objects, and pre-existing DLLs (unmanaged code and data)code and data)
… …..
Common Language RuntimeCommon Language RuntimeGoalsGoals
DevelopmentDevelopment standard class frameworkstandard class framework automatic memory managementautomatic memory management consistent error handlingconsistent error handling mixed-language applicationsmixed-language applications multiple platformsmultiple platforms safer executionsafer execution
DeploymentDeployment removal on registration dependencyremoval on registration dependency safety: fewer versioning problemssafety: fewer versioning problems the end of “DLL Hell”the end of “DLL Hell”
Common Language RuntimeCommon Language RuntimeMultiple Language SupportMultiple Language Support
Common Type System (CTS)Common Type System (CTS)
Common Language Specification (CLS)Common Language Specification (CLS)
Common Language Common Language SpecificationSpecification CTS defines a complex set of types CTS defines a complex set of types
So a compromise the CLSSo a compromise the CLS Must implement BOOL, Byte, Char, Must implement BOOL, Byte, Char,
Integers etcIntegers etc Need not implement UintegersNeed not implement Uintegers
Arrays in all languages must have zero as Arrays in all languages must have zero as the lower bound.the lower bound.
All Languages support the same sub set.All Languages support the same sub set.
Types Types Unified Type SystemUnified Type System
Value typesValue types Directly contain dataDirectly contain data Cannot be nullCannot be null
Reference typesReference types Contain references to objectsContain references to objects May be nullMay be null
int i = 123;string s = "Hello world";
123i
s "Hello world"
Types Types Unified Type SystemUnified Type System
Value typesValue types PrimitivesPrimitives int i; float x;int i; float x; EnumsEnums enum State { Off, On }enum State { Off, On } StructsStructs struct Point {int x,y;}struct Point {int x,y;}
Reference typesReference types RootRoot objectobject StringString stringstring ClassesClasses class Foo: Bar, IFoo {...}class Foo: Bar, IFoo {...} InterfacesInterfaces interface IFoo: IBar {...}interface IFoo: IBar {...} ArraysArrays string[] a = new string[] a = new string[10];string[10];
DelegatesDelegates delegate void Empty();delegate void Empty();
Types Types Unified Type SystemUnified Type System
Value (Struct)Value (Struct) Reference Reference (Class)(Class)
Variable holdsVariable holds Actual valueActual value Memory locationMemory location
Allocated onAllocated on Stack, memberStack, member HeapHeap
NullabilityNullability Always has valueAlways has value May be nullMay be null
Default valueDefault value 00 nullnull
Assignment Assignment meansmeans Copy dataCopy data Copy referenceCopy reference
Types Types Unified Type SystemUnified Type SystemBenefits of value typesBenefits of value types
No heap allocation, less GC pressureNo heap allocation, less GC pressure More efficient use of memoryMore efficient use of memory Less reference indirectionLess reference indirection Unified type systemUnified type system
No primitive/object dichotomyNo primitive/object dichotomy
TypesTypesUnified Type SystemUnified Type SystemEverything is an objectEverything is an object
All types ultimately inherit from objectAll types ultimately inherit from object Any piece of data can be stored, Any piece of data can be stored,
transported, and manipulated with no extra transported, and manipulated with no extra workwork
MemoryStream FileStream
Stream Hashtable int double
object
ARRAYARRAY
MyClass[] objMyClass= new MyClass[6];MyClass[] objMyClass= new MyClass[6];
Myclass objMyClass[6];Myclass objMyClass[6];
Which One is Better and WHY?Which One is Better and WHY?
Source codeSource codeSource codeSource code
C++, C#, Visual C++, C#, Visual Basic or Basic or any .NET any .NET languagelanguage
Csc.exe or Vbc.exeCsc.exe or Vbc.exeCompilerCompiler
AssemblyAssemblyAssemblyAssembly
DLL or EXEDLL or EXE
Common Language RuntimeCommon Language RuntimeCompilationCompilation
csc /out:myAssembly.dll /debug+ /target:library parceltracker.cscsc /out:myAssembly.dll /debug+ /target:library parceltracker.cs
AgendaAgenda
What is .Net FrameworkWhat is .Net Framework Common Language RuntimeCommon Language Runtime
AssembliesAssemblies Memory management in .NetMemory management in .Net Execution ModelExecution Model .Net security Model.Net security Model
ASP.NETASP.NET ADO.NETADO.NET
AgendaAgenda
What is .Net FrameworkWhat is .Net Framework Common Language RuntimeCommon Language Runtime
AssembliesAssemblies Memory management in .NetMemory management in .Net Execution ModelExecution Model .Net security Model.Net security Model
ASP.NETASP.NET ADO.NETADO.NET
MetadataMetadataMetadataMetadata
IL IL Managed Managed
codecode
IL IL Managed Managed
codecode
ResourcesResourcesResourcesResources
myAssembly.dllmyAssembly.dll
Common Language RuntimeCommon Language RuntimeAssembliesAssemblies
Inside an AssemblyInside an Assembly
Single File AssemblySingle File Assembly
What are Assemblies ?What are Assemblies ?
Assemblies are the smallest unit of code Assemblies are the smallest unit of code distribution, deployment and versioningdistribution, deployment and versioning
ResourcesResources
MSILMSIL
MetaDataMetaData
ManifestManifest
ThisAssembly.dllThisAssembly.dll
ResourcesResources
MSILMSIL
MetaDataMetaData
ManifestManifest
ThisAssembly.dllThisAssembly.dll
MSILMSIL
MetadataMetadata
A.netmoduleA.netmodule
B.netmoduleB.netmodule
ManifestManifest(No Assembly Metadata)(No Assembly Metadata)
MSILMSIL
MetadataMetadata
ManifestManifest(No Assembly Metadata)(No Assembly Metadata)
Multi File AssemblyMulti File Assembly
Common Language RuntimeCommon Language RuntimeMetadataMetadata
Type informationType information more complete than IDL / TLBmore complete than IDL / TLB automatically bound into assemblyautomatically bound into assembly
inseparableinseparable stored in binary formatstored in binary format
describes every class typedescribes every class type
Type DescriptionsType Descriptions
ClassesClassesBase classesBase classesImplemented interfacesImplemented interfacesData membersData membersMethodsMethods
ClassesClassesBase classesBase classesImplemented interfacesImplemented interfacesData membersData membersMethodsMethods
NameNameVersionVersionCultureCulture
NameNameVersionVersionCultureCulture
Assembly ManifestAssembly Manifest
Other assembliesOther assembliesSecurity permissionsSecurity permissionsExported typesExported types
Other assembliesOther assembliesSecurity permissionsSecurity permissionsExported typesExported types
Common Language RuntimeCommon Language RuntimeMetadata in an AssemblyMetadata in an Assembly
AssemblyAssemblyHeadersHeaders
•PE PE
•CLRCLR
•Metadata (idata,text,etc)Metadata (idata,text,etc)
•ILIL
Common Language RuntimeCommon Language RuntimeApplicationsApplications
One or more assembliesOne or more assemblies Types Of AssembliesTypes Of Assemblies
PrivatePrivate Shared (placed in GAC)Shared (placed in GAC)
Different applications may use different versions of Different applications may use different versions of an assemblyan assembly easier software updateseasier software updates easier software removaleasier software removal
Assembly Assembly ProbingProbingWorking Directory(c:\…)Working Directory(c:\…)
Sub directory(C:\Assembly\…)Sub directory(C:\Assembly\…)
Named path(c:\path\..)Named path(c:\path\..)
Named Path SubdirectoryNamed Path Subdirectory
GACGAC
Registry IssuesRegistry Issues
•Versioning ?Versioning ?•DLL HELL ?DLL HELL ?•Side By Side Execution ?Side By Side Execution ?•InstallationInstallation•UninstallUninstall
GACGAC
AgendaAgenda
What is .Net FrameworkWhat is .Net Framework Common Language RuntimeCommon Language Runtime
AssembliesAssemblies Execution ModelExecution Model Memory management in .NetMemory management in .Net
ASP.NETASP.NET ADO.NETADO.NET
Automatic Memory Automatic Memory ManagementManagement
Garbage collection mechanismGarbage collection mechanism
Implicit Garbage collectionImplicit Garbage collection Explicit Garbage collectionExplicit Garbage collection
{Idispose Interface}{Idispose Interface}
Garbage collection mechanism Implicit Garbage collection Explicit Garbage collection
{Idispose Interface}
Memory ManagementMemory Management
MethodsMethodsFinalizeFinalizeCloseCloseDisposeDispose
Data structureData structureFinalizer ListFinalizer ListFreacheableFreacheable
GenerationGenerationssMax 3(0,1,2)Max 3(0,1,2)Weak refWeak refStrong RefStrong Ref
Refresher of Classic ASPRefresher of Classic ASP
•Server Side Pages containing HTML
•Dynamic Pages
•HTML Editors
<body bgColor="#00ff00">
<form id="Form1" method="post">
</form>
</body>
Refresher of Classic ASPRefresher of Classic ASP
Client Side Scripting (VB Script/Java Script) Validations Checks Range Checking Date Display
Blend of HTML (Design) and script (Logic)
Object Oriented Robust / Reusability Problem Redundancy
Problems with Classic ASPProblems with Classic ASP
Architecture of ASP.NETArchitecture of ASP.NET
Extension is *.aspx Is Represented by a unique C#
class (Code behind) <%@ Page Language =“C#”
Codebehind=“WebForm1.aspx.cs” ……. %>
Architecture of ASP.NETArchitecture of ASP.NET
Architecture of ASP.NETArchitecture of ASP.NET
Architecture of ASP.NETArchitecture of ASP.NET
Architecture of ASP.NETArchitecture of ASP.NET
Page_Load
YYY_Clicked
Page_Unload
ProcessRequestProcessRequest
XXX_Changed
Runtime CompilationRuntime Compilation
ASPXASPXFileFile
Request
ASPXASPX
EngineEngine
ParseParse
Gen’dGen’dPagePageClassClass
Generate
ResponseResponse
RequestRequest
InstantiateInstantiate
ResponseResponse
Code-Code-behindbehindclassclass
PagePage
ClassClass Instantiate, Instantiate, Process and Process and
RenderRender
CompileCompile
ASPNET_STATE
INETINFO
ASPNET_WP
Caching
HttpHandlersHttpHandlers
PagesPages Services Services
ASP.NET Modular ArchitectureASP.NET Modular Architecture
ASPNET_ISAPIASPNET_ISAPI
Authent Sessions SessionSessionStateStateHTTP RuntimeHTTP Runtime
HttpModulesHttpModules
1. Intrinsic Controls HTML controls’ counterparts
[Buttons, Textbox, List] 2. Rich Controls [AdRotator, Calendar] 3. Data-centril Controls [DataGrid: DataBindings]
Categories of WebForm ControlsCategories of WebForm Controls
Categories of WebForm ControlsCategories of WebForm Controls
Validation Controls CompareValidator CustomValidator RangeValidator RegularExpressionValidator RequiredFieldValidator ValidationSummary
ASP.Net Object ModelASP.Net Object Model
Request
Server
Application Session
HttpContext
Response
Environment in whichthe request is resolved
ASP.Net Object ModelASP.Net Object Model
Request
Server
Application
HttpContext
Response Session
Abstract version of the HTTP request made
by the client
ASP.Net Object ModelASP.Net Object Model
Request
Server
Application Session
HttpContext
Response
Various methods for convenience
ASP.Net Object ModelASP.Net Object Model
Request
Server
Application Session
HttpContext
Response
Stores variables with application scope (multiple requests from a single user)
ASP.Net Object ModelASP.Net Object Model
Request
Server
Application Session
HttpContext
Response
Stores variables with application scope (multiple
requests from multiple users)
ASP.Net Object ModelASP.Net Object Model
Request
Server
Application Session
HttpContext
Response
Stores variables with application scope (multiple
requests from multiple users)
ADO.NETADO.NET
Why ADO.NET?Why ADO.NET?
ADO works great, butADO works great, but Requires COM and WindowsRequires COM and Windows®®
Recordsets don’t travel well across the Recordsets don’t travel well across the InternetInternet
Connected behavior is hard to work withConnected behavior is hard to work with ADO.NET solves these problemsADO.NET solves these problems
Uses XML under the covers for all data Uses XML under the covers for all data transporttransport
XML has no runtime/transport requirementsXML has no runtime/transport requirements No special code required to marshal across the No special code required to marshal across the
InternetInternet ADO.NET requires new mindsetADO.NET requires new mindset
All data access disconnectedAll data access disconnected All data transport uses XMLAll data transport uses XML
Connected Or Disconnected?Connected Or Disconnected?
System.Data namespace contains System.Data namespace contains disconnected set of objectsdisconnected set of objects DataSet, DataTable, DataRow, and so onDataSet, DataTable, DataRow, and so on
Specific namespaces Specific namespaces (System.Data.OleDb and (System.Data.OleDb and System.Data.SqlClient) contain System.Data.SqlClient) contain connected objectsconnected objects SqlDataAdapter/OleDbDataAdapterSqlDataAdapter/OleDbDataAdapter SqlConnection/OleDbConnectionSqlConnection/OleDbConnection SqlDataReader/OleDbDataReaderSqlDataReader/OleDbDataReader
Connected Or Disconnected?Connected Or Disconnected?
With ADO, a fundamental question is:With ADO, a fundamental question is:Where is the data managed?Where is the data managed?
On the client?On the client? On the server?On the server? A mixture of the two?A mixture of the two?
The answer in ADO The answer in ADO … …it depends on the cursor you are it depends on the cursor you are
using.using. With ADO.NET:With ADO.NET:
Data is always on the client (via Data is always on the client (via DataSet) or on its way to the client (via DataSet) or on its way to the client (via IDataReader)IDataReader)
ADO.NET ArchitectureADO.NET Architecture
Business TierBusiness Tier Data TierData Tier
Presentation TierPresentation Tier
Windows Forms
Web Forms
Business to Business
Data Object (Class)
DataSet
DataSetDataSet
InternetInternetIntranetIntranet
Data AdapterData Adapter
Data AdapterData Adapter
(BizTalk, for example)
XML
MyApp.Exe
IE
ADO.NETADO.NETA
pp
lica
tio
nA
pp
lica
tio
n
OD
BC
Dri
ver
OD
BC
Dri
ver
ODBCODBCRDBMSRDBMSO
DB
CO
DB
COLE DBOLE DBRDBMSRDBMS
.NET Data Provider.NET Data Provider
ConnectionConnection
CommandCommand
Data ReaderData Reader
Data AdapterData Adapter
OL
E D
BO
LE
DB
OL
E D
B P
rovi
der
OL
E D
B P
rovi
der
SQL ServerSQL Server
ADO.NET ObjectsADO.NET Objects
ConnectionConnection Connects to data sourceConnects to data source
CommandCommand Executes SELECT, INSERT, UPDATE Executes SELECT, INSERT, UPDATE
and DELETE commandsand DELETE commands Data ReaderData Reader
Forward-only, read-only stream of Forward-only, read-only stream of datadata
Data AdapterData Adapter Connects a DataSet to a data sourceConnects a DataSet to a data source
XML SUPPORT
WHYWHY MICROSOFTMICROSOFT70M Systems are installed with .NET70M Systems are installed with .NET
IExplorer IExplorer NetscapeNetscape
SeacrhSeacrh
(Index 6 M)(Index 6 M)
GoogleGoogle
(Index 8M)(Index 8M)
Media PlayerMedia Player JetAudio, Real JetAudio, Real PlayerPlayer
XBOXXBOX PlaystationPlaystation
MS CRMMS CRM SiebelSiebel
MicrosoftMicrosoft DepartmentDepartment OthersOthers
Contact DetailContact Detail
Email : Email :
IM:IM:[email protected]
Group:Group:Groups.msn.com/InnoventorsGroups.msn.com/Innoventors