Beruflich Dokumente
Kultur Dokumente
MCA 512
Syllabus
Unit-1: The .Net framework: Introduction, The Origin of .Net Technology, Common Language Runtime (CLR), Common Type System (CTS), Common Language Specification (CLS), Microsoft Intermediate Language (MSIL), Just-In Time Compilation, Framework Base Classes. Unit-II: C -Sharp Language (C#): Introduction, Data Types, Identifiers, Variables, Constants, Literals,Array and Strings, Object and Classes, Inheritance and Polymorphism, Operator Overloading, Interfaces, Delegates and Events. Type conversion. Unit-III : C# Using Libraries: Namespace- System, Input-Output, MultiThreading, Networking and sockets, Managing Console I/O Operations, Windows Forms, Error Handling.
Unit-IV: Advanced Features Using C#: Web Services, Window Services, Asp.net Web Form Controls, ADO.Net. Distributed Application in C#, Unsafe Mode, Graphical Device interface with C#. Unit-V : .Net Assemblies and Attribute: .Net Assemblies features and structure, private and share assemblies, Built-In attribute and custom attribute. Introduction about generic..
References
1. Wiley, Beginning Visual C# 2008,Wrox
2. Fergal Grimes, Microsoft .Net for Programmers. (SPI) 3. Balagurusamy, Programming with C#, (TMH) 4. Mark Michaelis, Essential C# 3.0: For .NET Framework 3.5, 2/e, Pearson Education 5. Shibi Parikkar, C# with .Net Frame Work , Firewall Media.
COM+ Services improve reliability, scalability and manageability. IE provides D/HTML for better interactivity Combination of stateless Web protocols with DNS and IP routing have enabled mass-scale GeoScalability
Separation of data and business logic provide greater scalability and performance while accessing enterprise and legacy data
Smarter Clients Standard Browsers Smarter Devices Richer, More Productive User Experience
OS OS Services Services Open Internet Communications Protocols (HTTP, SMTP, XML, SOAP)
.NET Framework
Operations
Visual Studio.NET
Application
Before COM, applications were completely separate entities with little or no integration
COM provides a way for components to integrate. However, each component must provide the plumbing and objects cannot directly interact.
With the .NET Framework common language runtime, components are built on a common substrate. No plumbing is needed and objects can directly interact
The .NET infrastructure is the part of .NET that most developers are referring to when they refer to .NET. The .NET infrastructure refers to all the technologies that make up the new environment for creating and running robust, scalable, distributed applications. The part of .NET that lets us develop these applications is the .NET Framework.
The .NET Framework consists of the Common Language Runtime (CLR) .NET Framework class libraries( Base Class Library (BCL)).
(Note: If you're familiar with either the Microsoft Foundation Classes (MFC) or Borland's Object Windows Library (OWL), you're already familiar with class libraries. The .NET Framework class libraries include support for everything from file I/O and database I/O to XML and SOAP. In fact, the .NET Framework class libraries are so vast that it would easily take a book just to give a superficial overview of all the supported classes. )
VB VB
C++ C++
C# C#
JScript JScript
Common Language Specification Common Language Specification Common LanguageSpecification Windows Windows ASP.NET: Web Services Forms and Web Forms Forms ADO.NET: Data and XML ADO.NET: Data and XML Base Class Library Base Class Library Common Language Runtime Common Language Runtime
CLR
Components of CLR
Class Loader: This loads classes into the runtime. MSIL to native code compiler: This converts MSIL code into native code. Code manager: This manager the code during execution i.e provides code check, the resources it needs during execution. Garbage Collector: provide automatic memory management and avoid memory leaks. Security Engine: This enforces security restrictions and CAS. Type Checker: This enforces strict type checking.
Components of CLR(continued..)
Thread Support: This provides multithreading support to applications. Exception Manager : This provides a mechanism to handle the run-time exceptions. Debug Engine : Allow you to debug different type of applications. COM marshaler : This allows .net application to exchange data with COM applications. BASE Class library : This provides the types the applications needed at runtime.
You write source code in C# and compile it using the C# compiler (csc.exe) into an EXE. The C# compiler outputs the MSIL code and a manifest into a read-only part of the EXE that has a standard PE (Win32-portable executable) header. When the compiler creates the output, it also imports a function named _ CorExeMain from the .NET runtime. When the application is executed, the operating system loads the PE, as well as any dependent dynamic-link libraries (DLLs), such as the one that exports the _ CorExeMain function (mscoree.dll), just as it does with any valid PE. The operating system loader then jumps to the entry point inside the PE, which is put there by the C# compiler. However, since the operating system obviously can't execute the MSIL code, the entry point is just a small stub that jumps to the _ CorExeMain function in mscoree.dll. The _ CorExeMain function starts the execution of the MSIL code that was placed in the PE. Since MSIL code cannot be executed directlybecause it's not in a machine-executable formatthe CLR compiles the MSIL by using a just-in-time (JIT) compiler (or JITter) into native CPU instructions as it processes the MSIL. JIT compiling occurs only as methods in the program are called. The compiled executable code is cached on the machine and is recompiled only if there's some change to the source code.
Three different JITters can be used to convert the MSIL into native code, depending on the circumstances:
1. Install-time code generation Install-time code generation will compile an entire assembly into CPU-specific binary code, just as a C++ compiler does. An assembly is the code package that's sent to the compiler. This compilation is done at install time, when the end user is least likely to notice that the assembly is being JIT-compiled. The advantage of install-time code generation is that it allows you to compile the entire assembly just once before you run it. Because the entire assembly is compiled, you don't have to worry about intermittent performance issues every time a method in your code is executed the first time. When and if you use this utility depends on the size of your specific system and your deployment environment. Typically, if you're going to create an installation application for your system, you should go ahead and use this JITter so that the user has a fully optimized version of the system "out of the box."
2. JIT The default JITter is called at run timein the manner it is described in the preceding numbered listeach time a method is invoked for the first time. This is akin to a "pay-as-you-go" plan and is the default if you don't explicitly run the PreJIT compiler. 3. EconoJIT Another run-time JITter, the EconoJIT is specifically designed for systems that have limited resourcesfor example, handheld devices with small amounts of memory. The major difference between this JITter and the regular JITter is the incorporation of something called code pitching. Code pitching allows the EconoJIT to discard the generated, or compiled, code if the system begins to run out of memory. The benefit is that the memory is reclaimed. However, the disadvantage is that if the code being pitched is invoked again, it must be compiled again as though it had never been called.
Metadata and Reflection In addition to mapping source code to MSIL instruction sequences, CLScompliant compilers have another equally important task: embedding metadata into the resulting EXE. Metadata is data that describes data. In this context, metadata is the collection of programmatic items that constitute the EXE, such as the types declared and the methods implemented.This metadata is similar to the type libraries (typelibs) generated with Component Object Model (COM) components. Not only is the metadata output from a .NET compiler substantially more expressive and complete than the COM typelibs we're accustomed to, but the metadata is also always embedded in the EXE. This way, there's no chance of losing the application's metadata or having a mismatched pair of files.
The reason for using metadata. It allows the .NET runtime to know at run time what types will be allocated and what methods will be called. This enables the runtime to properly set up its environment to more efficiently run the application. The means by which this metadata is queried is called reflection. The .NET Framework class libraries provide an entire set of reflection methods that enable any applicationnot just the CLRto query another application's metadata. Tools such as Visual Studio.NET use these reflection methods to implement features such as IntelliSense. With IntelliSense, as you type in a method name, that method's arguments pop up in a list box on the screen. Visual Studio.NET takes that functionality even further, showing all the members of a type. Another incredibly useful .NET tool that takes advantage of reflection is the Microsoft .NET Framework IL Disassembler (ILDASM). This powerful utility parses the target application's metadata and then displays information about the application in a treelike hierarchy.
Security
The most important facet of any distributed application development environment is how it handles security. Thankfully for those of us who have long complained that Microsoft would never be taken seriously in the server-side enterprise solutions space without a completely new approach to security, .NET brings many concepts to the table. In fact, security begins as soon as a class is loaded by the CLR because the class loader is a part of the .NET security scheme. For example, when a class is loaded in the .NET runtime, security-related factors such as accessibility rules and self-consistency requirements are verified. In addition, security checks ensure that a piece of code has the proper credentials to access certain resources. Security code ensures role determination and identity information. These security checks even span process and machine boundaries to ensure that sensitive data is not compromised in distributed computing environments.
Deployment
Deployment case dealing with the different binary files, Registry issues, COM components, and support library installation of products such as open database connectivity (ODBC) and Data Access Objects (DAO) is difficult. The key to .NET application deployment is the concept of assemblies. Assemblies are simply packages of semantically related behaviour that are built as either single-file or multiple-file entities. The specifics of how you deploy your application will vary based on whether you're developing a Web server application or a traditional desktop application for Windows. However, with the introduction of the assembly as a fully encapsulated set of functionality, deployment can be as simple as copying the necessary assemblies to a target location.
Deployment( Continue)
Many of the problems that caused so much trouble for programmers prior to the .NET Framework have now been eliminated. For example, there's no need to register components,as you do with COM components and Microsoft ActiveX controlsbecause with metadata and reflection, all components are self-describing. The .NET run time also keeps track of the files, and the versions of the files, associated with an application. Therefore, any application that is installed is automatically associated with the files that are part of its assembly. If a setup application attempts to overwrite a file needed by another application, the .NET runtime is smart enough to allow the setup application to install the needed file, but the CLR doesn't delete the previous version of the file because it's still required by the first application.
Unmanaged code is code that isn't controlled by the .NET runtime. However, unmanaged code doesn't have the advantages that managed code has, such as garbage collection, a unified type system, and metadata. Here are some situations Managed code calling unmanaged DLL functions Let's say your application needs to interface to a C-like DLL and the company that wrote the DLL isn't adopting .NET as quickly as your company is. In this case, you still need to call into that DLL from a .NET application. Managed code using COM components You might also need to continue supporting COM components. You do this by creating a .NET wrapper for the COM component so that the managed client thinks it's working with a .NET class. Unmanaged code using .NET services You want to access .NET from unmanaged code. It's solved using a reciprocal approach: a COM client is fooled into thinking it's using a COM server, which is actually a .NET service of some sort.
The source code gets compiled to IL and the same time metadata information is created using the meta data engine. These are optionally linked with other code compiled by different compilers and the result is an EXE or DLL containing the IL code, which is saved to disk. The compilers work is now done. Then on execution, the IL code and any functionality from the .NET base class library is brought together using class loader. The combined code is optionally tested for type safety using the verifier before the JIT (Just in time) compiler comes into play. The JIT compiler processes the IL creating managed native code which is passed on the .NET runtime manager.
Garbage Collection
Process of automatically freeing up memory when an object it been allocated to is no longer being used Prevents the following errors: Forgetting to destroy objects Attempting to destroy the same object more than once Destroying an active object
Type
Methods Properties Fields
Assemblies
ParcelTracker.DLL Metadata IL/native code Resources myAssembly.DLL Assembly Metadata Type Metadata IL Code Graphic.BMP Resources Single Module Multiple Modules Util.DLL Type Metadata IL Code
Serialization
(e.g. SOAP)
Metadata
(and code)
Profiler
Schema Generator
VC VB IL ... Script
Native Code
EconoEcono-JIT Compiler
CPU
Value Types
Represent primitive types in an efficient way Extensible Boxing and unboxing
Verification
IL is verified by a verifier and guaranteed to be type safe Checks for type casts, memory initialization, array bounds Checks stack operations
Security System
Permissions
Grant Demand (minimal, optional, refuse) Stack walk
Policy Set of permissions Evidence Input to policy Zones Cryptography Signed XML IETF/W3C XMLDSIG Fully extensible
Versioning
Multiple versions of component can be installed on machine A single process can use different version of component at same time Zero-impact installation and uninstallation (copy)
Instantiation
A term unique to object-oriented programming, instantiation is simply the act of creating an instance of a class. That instance is an object. In the following example, all we're doing is creating a class, or specification, for an object. In other words, no memory has been allocated at this time because we have only the blueprint for an object, not an actual object itself.
Designing Abstractions
Inheritance
Inheritance relates to the programmer's ability to specify that one class has a kind-of relationship with another class. Through inheritance, you can create (or derive) a new class that's based on an existing class. You can then modify the class the way that you want and create new objects of the derived type. This ability is the essence of creating a class hierarchy. Outside of abstraction, inheritance is the most significant part of a system's overall design. A derived class is the new class being created, and the base class is the one from which the new class is derived. The newly derived class inherits all the members of the base class, thereby enabling you to reuse previous work. Substitutability.Substitutability means that the advertised behavior of the derived class is substitutable for the base class. Another rule of thumb to keep in mind when creating your class hierarchies is that a derived class should require no more and promise no less than its base class on any inherited interfaces. Not adhering to this rule breaks existing code. A class's interface is a binding contract between itself and programmers using the class.
Polymorphism
The definition for polymorphism is that it is functionality that allows old code to call new code. This is arguably the biggest benefit of object-oriented programming because it allows you to extend or enhance your system without modifying or breaking existing code.
Two benefits.
First, it gives you the ability to group objects that have a common base class and treat them consistently I have three different object types SalariedEmployee, ContractorEmployee,and HourlyEmployeeI can treat them all as Employee objects because they all derive from the Employee base class. This is how I can stuff them in an array that is defined as an array of Employee objects. Because of polymorphism, when I call one of those object's methods, the runtime will ensure that the correct derived object's method is called. The second advantage is that old code can use new code
C#
Built on top of CLR Was designed from ground up to make use of CLR services Component Oriented
Properties are first class Events are first class
Hello World
using System; class Hello { static void Main() { Console.WriteLine(Hello word); } }
ASP.NET ADO.NET
Windows XML
System.Web Services Description Discovery Protocols Caching Configuration Security SessionState UI HtmlControls WebControls Design
System.Windows.Forms ComponentModel
System.Drawing Drawing2D Imaging System.Xml SQL SQLTypes System XSLT XPath Serialization Printing Text
3. Data Types
Objectives
.NET is designed around the CTS, or Common Type System.
The CTS is what allows assemblies, written in different languages, to work together. To ensure interoperability across languages, Microsoft has also defined the CLS, or Common Language Specification, a subset of the CTS that all languages support. Otherwise, the types in C# are what you would expect from a modern OOPL The Common Type System Value vs. reference types Arrays Namespaces
The Common Type System (CTS) CTS is based on a hierarchy of classes defined in FCL all types inherit from Object (all except interface types)
St r i ng
Ar r ay
Val ueTy pe
Ex c ept i on
Del egat e
Cl as s 1
Pr i m t i v e t y pes i Bool ean By t e I nt 16 I nt 32 I nt 64 Char Si ngl e Doubl e Dec i m al Dat eTi m e Ti m eSpan G d ui
Enum
St r uc t ur e1
M t i c as t ul Del egat e
Cl as s 2
Enum 1
Del egat e1
Cl as s 3
Mapping C# to CTS
Language keywords map to common CTS classes:
Keyword
bool char sbyte byte short ushort int uint long ulong float double decimal string
Description
Boolean 16 bit Unicode character 8 bit signed integer 8 bit unsigned integer 16 bit signed integer 16 bit unsigned integer 32 bit signed integer 32 bit unsigned integer 64 bit signed integer 64 bit unsigned integer 32 bit floating point 64 bit floating point 128 bit high precision character sequence
Example
An example of using types in C#
declare before you use (compiler enforced) initialize before you public class App use (compiler enforced)
{ public static void Main() { int width, height; width = 2; height = 4; int area = width * height; int x; int y = x * 2; ... } }
declarations
decl + initializer
Type conversion
Some automatic type conversions available
from smaller to larger types
d = i; i = (int) d; i = System.Convert.ToInt32(s);
Value vs. reference types C# separates data types into two categories Value types:
variable represents a value ("bits")
int i; i = 10;
10
Reference types:
variable represents a reference to a heap-based object actual data resides in the object
"calico" string s; s = "calico";
s = j.ToString(); s = 99.ToString();
public Customer(string name, int id) { this.Name = name; this.ID = id; } public override string ToString() { return "Customer: " + this.Name; } }
// constructor
// method
if (c1 == null) ... if (c1 == c2) ... if (c1.Equals(c2)) ... if (s1 == s2) ...
Defining equality
Classes should override Equals
public class Customer { . . . public override bool Equals(object obj) { Customer other; if ((obj == null) || (!(obj is Customer))) return false; // definitely not equal other = (Customer) obj; return this.ID == other.ID; } // typecast to access // equal if same id...
GetHashCode
If you override Equals, must also override GetHashCode:
public class Customer { . . . public override int GetHashCode() { return this.id.GetHashCode(); }
Arrays
Arrays are reference types
based on Array class in FCL must be created using new 0-based indexing assigned default values (0 for numeric, null for references, create etc.)
element access
int[] a; a = new int[5]; a[0] = 17; a[1] = 32; int x = a[0] + a[1] + a[4]; int l = a.Length;
number of elements
Multi-dimensional arrays
C# supports arrays as a single object OR array of arrays
latter allows you to implement jagged arrays
Customer[,] int[][] twoD; jagged2D;
twoD = new Customer[10, 100]; twoD[0, 0] = new Customer(); twoD[9, 99] = new Customer();
// 2D array as array of arrays
jagged2D = new int[10][]; jagged2D[0] = new int[10]; jagged2D[1] = new int[20]; jagged2D[9] = new int[100]; jagged2D[0][0] = 1; jagged2D[9][99] = 100;
Namespace != Assembly
Orthogonal concepts:
namespace for organization assembly for packaging
One namespace could be spread across multiple assemblies One assembly may contain multiple namesspaces
e.g. mscorlib.dll