July 2007 - Posts
-
Definition The command design pattern is used when one object needs to execute an action on another object. The action that needs to be executed is defined as a command object which also includes all its parameters. What is it supposed to solve In business applications there are many uses for command patterns, listed below - Multi-level undo and redo.
- Transactional processing.
- Thread pools
- Macro recordings
- Command Queuing
- Gaming
UML Diagram Particpants | Command | Declares an abstract interface for the command that needs to be executed. | | ConcreteCommand | The concrete command defines the binding between the receiver and the command. | | Client | The client creates the concrete command and and sets the receiver. | | Invoker | The invoker simply uses the command to carry out the request on. | | Receiver | The receiver implements the logic of performing actions. The detailed code of what needs to be done is implemented in the Receiver. | Sample C# code The sample code below simply defines a structural application for the command pattern. The code creates concrete command that will prerform a specific task. The command is is instantiated and added to a Receiver that will be the target of the command where the command will be executed on. An invoker will be created that will accept the concrete command and execute the command. namespace Brett.Patterns.GangOfFour.Command.Structural
{
using System;
/// <summary>
/// Declares an abstract interface for the command that needs to be executed.
/// </summary>
/// <remarks>
/// This abstract defines the constructor and an abstract Execute method.
/// </remarks>
abstract class Command
{
protected Receiver _receiver;
/// <summary>
/// The receiver constructor which identifies the reciever that
/// will execute the command.
/// </summary>
/// <param name="receiver"></param>
public Command(Receiver receiver)
{
_receiver = receiver;
}
/// <summary>
/// The abastract method which is overridden in a concrete command.
/// </summary>
public abstract void Execute();
}
/// <summary>
/// The concrete command defines the binding between the receiver and the command.
/// </summary>
class ConcreteCommand : Command
{
/// <summary>
/// The concrete constructor simple calls the base class (Command).
/// </summary>
/// <param name="receiver"></param>
public ConcreteCommand(Receiver receiver)
: base(receiver)
{
}
/// <summary>
/// Calls the recievers action method to perform the task.
/// </summary>
public override void Execute()
{
_receiver.Action();
}
}
/// <summary>
/// The receiver implements the logic of performing actions. The detailed code of what needs to be done is implemented in the Receiver.
/// </summary>
class Receiver
{
/// <summary>
/// The reciever does the work for performing the action.
/// </summary>
public void Action()
{
Console.WriteLine("Receiver.Action() called");
}
}
/// <summary>
/// The invoker simply uses the command to carry out the request on.
/// </summary>
class Invoker
{
private Command _command;
/// <summary>
/// Identifies the command the invoker needs to execute.
/// </summary>
/// <param name="command"></param>
public void SetCommand(Command command)
{
_command = command;
}
/// <summary>
/// Executes the command, which in turn executes the recievers action.
/// </summary>
public void ExecuteCommand()
{
_command.Execute();
}
}
/// <summary>
/// The client creates the concrete command and and sets the receiver.
/// </summary>
class Client
{
/// <summary>
///
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//Create a receiver, command and invoker
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
Invoker invoker = new Invoker();
//Define the command that needs to be executed
invoker.SetCommand(command);
//Invoke the command
invoker.ExecuteCommand();
}
}
}
|
-
IntelliSense code snippets are used for auto writing code within visual studio and are explained in my blog post Improving your productivity in Visual Studio using Code Snippets. This post discusses how to make your own snippets. Creating a .snippet file A visual studio .snippet file is actually a .xml file with a defined schema. Firstly create an XML file -
On the File menu, click New and then click File. -
Click XML File and then click Open. -
On the File menu, click Save <XMLFileName>. -
In the Save as type box, select All Files (*.*). -
In the File name box, enter a file name with the .snippet file name extension. -
Click Save. Copy the following into your .snippet file and then modify the title, shortcut and code of the snippet. <?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Title of snippet</Title>
<Shortcut>mysnippet</Shortcut>
</Header>
<Snippet>
<Code Language="csharp">
<![CDATA[
// YOUR CODE HERE
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Copy the file into C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Visual C#\. You are also able to manage this folder structure to organize larger volumes of snippets
Summary
Although this is a really simple code snippet, one is able to create really fancy snippets. Depending on the feedback and demand, I may post some cute little tricks to make intuitive snippets.
Have fun and post useful snippets into the forums!
|
-
Abstract The Visual Studio development environment is rather powerful and important to learn well as this a developers primary tool. Code snippets are one of the many awesome features which allows one to automatically insert blocks of code using IntelliSense. It is simply used by typing a short key word and pressing the TAB key. Using code snippets There are two basic ways to insert snippets, the first is in the editor and the second is from the menus. Inserting a code snippet in the Code Editor Start typing the shortcut name for the code snippet, followed by the TAB key. - You may need to press the TAB key twice. The first is to auto complete the shortcut word and the second time to actually insert the snippet
After pressing the TAB key twice the code of the snippet is automatically inserted. After the snippet has been inserted, parameters are shown as highlighted options allowing you to change the values, e.g. in the snippet above, you could change the data types and names. To move between parameters use TAB and SHIFT-TAB. Inserting a code snippet from using the menus. There are three ways to do this: - In the Edit, IntelliSense Menu choose Insert Snippet.
- Press CTRL-K CTRL-X
- Right click in the code editor and choose Insert Snippet
The following will appear Choose the category and then the name of the snippet Table of snippets in C# | Snippet | Code | | #if | #if true #endif | | #region | #region MyRegion #endregion | | attribute | [global::System.AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] sealed class MyAttribute : Attribute { // See the attribute guidelines at // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconusingattributeclasses.asp readonly string _positionalString; int _namedInt; // This is a positional argument. public MyAttribute(string positionalString) { this._positionalString = positionalString; // TODO: Implement code here. throw new Exception("The method or operation is not implemented."); } public string PositionalString { get { return this._positionalString; } } // This is a named argument. public int NamedInt { get { return this._namedInt; } set { this._namedInt = value; } } } | | checked | checked { } | | class | class MyClass { } | | ctor | public MyClass() { } | | cw | Console.WriteLine(); | | do | do { } while (true); | | else | else { } | | enum | enum MyEnum { } | | equals | // override object.Equals public override bool Equals(object obj) { // // See the full list of guidelines at // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconequals.asp // and also the guidance for operator== at // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconimplementingequalsoperator.asp // if (obj == null || GetType() != obj.GetType()) { return false; } // TODO: write your implementation of Equals() here. throw new Exception("The method or operation is not implemented."); return base.Equals(obj); } // override object.GetHashCode public override int GetHashCode() { // TODO: write your implementation of GetHashCode() here. throw new Exception("The method or operation is not implemented."); return base.GetHashCode(); } | | exception | [global::System.Serializable] public class MyException : Exception { // // For guidelines regarding the creation of new exception types, see // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp // and // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp // public MyException() { } public MyException(string message) : base(message) { } public MyException(string message, Exception inner) : base(message, inner) { } protected MyException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } | | for | for (int i = 0; i < length; i++) { } | | foreach | foreach (object var in collection_to_loop) { } | | forr | for (int i = length - 1; i >= 0 ; i--) { } | | If | if (true) { } | | Indexer | public object this[int index] { get { /* return the specified index here */ } set { /* set the specified index to value here */ } } | | interface | interface IInterface { } | | invoke | EventHandler temp = MyEvent; if (temp != null) { temp(); } | | iterator | public System.Collections.Generic.IEnumerator<ElementType> GetEnumerator() { throw new Exception("The method or operation is not implemented."); yield return default(ElementType); } | | Iterindex | public MyViewIterator MyView { get { return new MyViewIterator(this); } } public class MyViewIterator { readonly MyOuterClass outer; internal MyViewIterator(MyOuterClass outer) { this.outer = outer; } // TODO: provide an appropriate implementation here public int Length { get { return 1; } } public ElementType this[int index] { get { // // TODO: implement indexer here // // you have full access to MyOuterClass privates. // throw new Exception("The method or operation is not implemented."); return default(ElementType); } } public System.Collections.Generic.IEnumerator<ElementType> GetEnumerator() { for (int i = 0; i < this.Length; i++) { yield return this[i]; } } } | | Lock | lock (this) { } | | Mbox | MessageBox.Show("Test"); | | namespace | namespace MyNamespace { } | | Prop | private int myVar; public int MyProperty { get { return myVar;} set { myVar = value;} } | | Propg | private int myVar; public int MyProperty { get { return myVar;} } | | sim | static int Main(string[] args) { return 0; } | | struct | struct MyStruct { } | | svm | static void Main(string[] args) { } | | switch | switch (switch_on) { default: } | | try | try { } catch (Exception) { throw; } | | tryf | try { } Finally { } | | unchecked | unchecked { } | | unsafe | unsafe { } | | using | using(resource) { } | | while | while (true) { } | You can also develop your own snippets.
|
-
Microsoft has released beta 2 of VS 2008 (codename Orcas) which you can Download from here. Below is a short overview of the version.
|
-
Abstract The .NET Garbage Collector (GC) provides high-speed allocation and de-allocation of memory on the heap. It is important that application abide by the simple rules set out, failure to do so will drastically impact the performance of the entire .NET platform. This article explains how the garbage collector works and then discusses some performance and interaction issues and solutions. The garbage collector arranges memory in three distinct categories called generations. When the object is first created, it is placed in generation 0, or another generation based on the size of the object (see table below). Generation 0 objects are constantly checked if they need destruction as this is highly probable. Generation 1 objects are scanned frequently, but not as frequently as Generation 0. Finally Generation 3 objects are the older and bigger objects that will only be checked Memory allocation When the application is first loaded into memory, the CLR automatically creates a managed heap for objects to be placed on. The managed heap consists of four storage bins, namely generation 0, 1, 2 and the Large Object Heap. All objects that are smaller than 85Kb are placed on the Generation 0 managed heap and objects greater than 85Kb are placed on the Large Object Heap. Both the Generation 0 and LOB heaps have a Next Object Pointer which indicates the position in the heap where the next object is to be placed. After an object positioned on the heap, the NextObjPtr moves by the size of the object to the next available free position. | 1 | | Object A is inserted into the managed heap at the location of the NextObjPtr. | | 2 | | After the object is inserted the NextObjPtr moves along the heap by the size of Object A to the next free position. | | 3 | | Object B is then inserted at the NextObjPtr. | | 4 | | The NextObjPtr moves along the managed heap by the size of Object B to the next free position. | | 5 | | This process repeats for every object that needs to be created. | Unlike malloc in C++ managed insertion is faster. In C++ a link list of memory blocks has to be searched looking for a block that is large enough to contain the object. Once the block is found, it needs to be split by the object size and then a new link-list item created for the remaining free memory. In managed allocation, the NextObjPtr is always at the correct position for new objects. Thus, memory acquisition is faster in managed code. The ugly ... this managed allocation model has two serious flaws. The first is that it presumes memory is infinite and it can merrily append to the end of the heap until the application exits. Secondly, it does not reclaim unused memory and this remains in the heap. These two "serious" problems are easily overcome by the the garbage collector. Identifying collectable objects In this section, the mechanism the Common Language Runtime uses to identify objects that are reclaimable. Whenever the garbage collector runs, it will scan all objects searching whether the object is reclaimable and if it is reclaimable it is then freed from memory. This is simply done by determining whether the application is currently using the object on the heap or not. As an application executes, the running method and all of its return variables, arguments and internal variables are stored on the stack. As each method and calls other methods so are these child methods pushed onto the stack. Reference type objects when created by the new keyword are created on the heap. However the new operator returns a pointer to the memory location where the object was created. Look at the following code: class Point
{
public int X;
public int Y;
}
...
Point p;
p = new Point();
When a program executes, it defines a reference variable (Point p; ). This reference however stores a pointer to an object on the heap of type Point. The reference however does reside on the stack and contains the pointer. Initially the value of the pointer is set to null which indicates that it does not reference any valid heap object.
The p = new Point(); statement is complex as the new operator creates an object on the heap of type Point and returns a pointer. The variable p is then assigned using the assignment (=) operator the return value of the new operator.
The object on the heap is thus bound to the reference type on the stack, which is called rooted. The garbage collector manages this rooting mechanism and is shown in the diagram below:
When the method containing the reference type exits and is popped of the stack, the heap object no longer is being used. This is called an un-rooted object. The diagram below illustrates this:
The object on the heap is now ready for collection and the garbage collector will collect it.
Rooted objects and nested objects
Rooted objects are objects that are either used by static variables or the stack and are easy to determine by walking the stack. However these objects may include nested or inner objects and these in turn other objects building a complete object model. The garbage collector prior to collection treats all objects on the stack as collectable. It then starts identifying rooted objects by walking the stack. Each object is then interrogated for its internal objects and these objects are then also checked. Within a short period of time the garbage collector has a complete object graph of all objects. Any object that is not identified as rooted or leaf objects are ready for collection.
The garbage collector the maintains this state so that it does not need to re analyze all these objects again. It however implements a effective mechanism to determine whether inner objects have change and perhaps refer to other objects, this is done through write barriers.
Generations
As briefly mentioned above, the Common Language Runtime divides managed heap memory into 3 Generations and one Large Object Heap. This is to assist in optimizing the speed at which objects are collected.
The general assumptions the garbage collector makes
- The larger the object in memory, the more likely the object is to stay in memory for longer time is highly probable. This assumption presumes, the bigger the object, the more intense the process to create the object and programmers will only create big objects when necessary and possibly keep them in memory for longer, i.e. in some cache.
- The longer an object stays in memory, the chances that it will stay in memory for longer is greatly increased.
- All objects are deemed as invalid and need to prove they are rooted, if they are un-rooted they are reclaimed.
Most running applications create a lot of small objects for a short period of time and destroy them soon afterwards. The GC has been optimized for this type of behavior and thus creates different heaps, discussed below
|
Generation 0 |
This heap is the smallest heap and is only 256Kb in size. All new objects are placed into this generation.
Typically most objects are short lived and do not survive past the first collection and thus this heap is the most optimized heap for both creation and destruction of objects. |
|
Generation 1 |
After a collection phase objects that still exist on in the Generation 0 heap are compacted and added to this heap. This heap is 2Mb in size and thus can contain more objects and will only be collected when this heap is full.
This should happen far less frequently than generation 0 collections. |
|
Generation 2 |
After collecting generation 1, any objects that still exist will be compacted and added to the Generation 2 heap.
This heap is 10Mb in size.
GC only collects this heap on a full garbage collect. |
|
Large Objects |
Any object created that is bigger than 85Kb will automatically be added to this heap and will only be collected on a full garbage collection. |
When collection is done all objects on this heap 256Kb (very small and thus processed quickly) are scanned to ensure that they are still rooted to some threads stack. It also analysis all the objects used by the rooted object and builds a tree structure of the object hierarchy. The scanning algorithm not only identifies nested objects, it tracks for circular references and double linked items.
Any object found not to be rooted or used by a rooted object is up for collection. These objects are then marked for collection and will be discussed below.
Items that are still valid are then moved from Generation 0 to Generation 1, thus completely emptying out Generation 0. These new generation 1 items are repacked and memory optimized. Likewise when the Garbage collector collects Generation 1 objects, any objects that are still used are moved and repacked onto the Generation 2 heap. The Generation 1 heap is only 2 Mb and is also processed quickly.
When items are moved from Generation 0 to 1 to 2, their physical memory locations are changed and all reference variables that use these objects are also updated.
The Generation 2 heap and the Large Object heap are only collected when the GC performs a full garbage collection.
At runtime the Garbage Collector may adjust the sizes of Gen 0, 1 and 2 due to load on machine.
Sample
In the sample below, a new object (L) needs to be inserted by a new operator; however the Generation 0 heap is full and the garbage collector runs.
In scanning valid and invalid objects the GC determines object A, G, K are still in use and Objects B, C, D, E, F, H, I and J need to be collected and moved to the collection mechanism. Objects A, G and K are repacked and moved into Generation 1 with all references to them updated. This effectively clears Generation 0. The new object L is then inserted to Generation 0.
As with generation 0, the same mechanism applies to Generation 1 objects and when Generation 1 is full it will move and repack items to generation 2.
When garbage collection is performed
Garbage collection is performed in the following conditions.
- A new item needs to be created in the Generation 0 heap (which is initially 256Kb) and there is insufficient space for the new object.
- When overall system memory is low.
- The GC.Collect() method is executed.
- When the extents of memory pressure are reached.
- The limit of unmanaged resource is reached.
|
-
-
When writing applications we need to interact with the operating system, platform and user interface environment to perform tasks. We may need to interact with the file system to create, read and write files. We may need to create either a web or windows user front end with various controls such as buttons, list boxes, text boxes and a whole lot more. Our applications may need to interact with other systems such as mail, active directory or web services. The list of possibilities is endless. The .NET Framework delivers a huge library of classes, interfaces, and value types that we can use to deliver our systems. Thus the library provides access to system functionality and is designed to be the foundation on which .NET Framework applications, components, and controls are built. The size of the library is huge and is categorized into functional areas called namespaces. The namespace is a hierarchical model with namespaces within namespaces. Functionality provided by the .NET Framework is defined in the System namespace. Each namespace contains several sets of classes, interfaces and value types to use. It is virtually impossible to learn the entire framework and all the thousands of items within it, one however has to have a general understanding of the framework and what it can deliver. The diagram below shows the system namespace Below is a overview of all the namespaces within the .NET Framework. | System Contains fundamental classes and base classes that define commonly used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. Other classes provide services supporting data type conversion, method parameter manipulation, mathematics, remote and local program invocation, application environment management, and supervision of managed and unmanaged applications. | | System.CodeDom Contains classes that can be used to represent the elements and structure of a source code document. These elements can be used to model the structure of a source code document that can be output as source code in a supported language using the functionality provided by the System.CodeDom.Compiler namespace. | | | System.CodeDom.Compiler Contains types for managing the generation and compilation of source code in supported programming languages. Code generators can each produce source code in a particular programming language based on the structure of Code Document Object Model (CodeDOM) source code models consisting of elements provided by the System.CodeDom namespace. | | System.Collections Contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hashtables and dictionaries. | | | System.Collections.Generic Contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections. | | | System.Collections.ObjectModel Contains classes that can be used as collections in the object model of a reusable library. Use these classes when properties or methods return collections. | | | System.Collections.Specialized Contains specialized and strongly typed collections; for example, a linked list dictionary, a bit vector, and collections that contain only strings. | | System.ComponentModel Provides classes that are used to implement the run-time and design-time behavior of components and controls. This namespace includes the base classes and interfaces for implementing attributes and type converters, binding to data sources, and licensing components. | | | System.ComponentModel.Collections | | | | System.ComponentModel.Collections.Generic Contains classes that define generic collections used specifically to support the run-time and design-time behavior of components and controls. | | | System.ComponentModel.Design Contains classes that developers can use to build custom design-time behavior for components and user interfaces for configuring components at design time. The design time environment provides systems that enable developers to arrange components and configure their properties. | | | | System.ComponentModel.Design.Data Contains classes for implementing design-time behavior of data-related components. | | | | System.ComponentModel.Design.Serialization Provides types that support customization and control of serialization at design time. | | System.Configuration Contains the types that provide the programming model for handling configuration data. | | | System.Configuration.Assemblies Contains classes that are used to configure an assembly. | | | System.Configuration.Install Provides classes that allow you to write custom installers for your own components. The Installer class is the base class for all custom installers in the .NET Framework. | | | System.Configuration.Provider Contains the base classes shared by both server and client applications to support a pluggable model to easily add or remove functionality. | | System.Data Contains classes that constitute most of the ADO.NET architecture. The ADO.NET architecture enables you to build components that efficiently manage data from multiple data sources. In a disconnected scenario (such as the Internet), ADO.NET provides the tools to request, update, and reconcile data in multiple tier systems. The ADO.NET architecture is also implemented in client applications, such as Windows Forms, or HTML pages created by ASP.NET. | | | System.Data.Common Contains classes shared by the .NET Framework data providers. A .NET Framework data provider describes a collection of classes used to access a data source, such as a database, in the managed space. | | | System.Data.Design Contains classes that can be used to generate a custom typed dataset. | | | System.Data.Odbc Contains classes that encapsulate the .NET Framework Data Provider for ODBC. The .NET Framework Data Provider for ODBC describes a collection of classes used to access an ODBC data source in the managed space. | | | System.Data.OleDb Contains classes that encapsulate the .NET Framework Data Provider for OLE DB. The .NET Framework Data Provider for OLE DB describes a collection of classes used to access an OLE DB data source in the managed space. | | | System.Data.OracleClient Contains classes that encapsulate the .NET Framework Data Provider for Oracle. The .NET Framework Data Provider for Oracle describes a collection of classes used to access an Oracle data source in the managed space. | | | System.Data.Sql Contains classes that support SQL Server-specific functionality. The API extensions in this class add to the .NET Framework Data Provider for SQL Server (System.Data.SqlClient). | | | System.Data.SqlClient Contains classes that encapsulate the .NET Framework Data Provider for SQL Server. The .NET Framework Data Provider for SQL Server describes a collection of classes used to access a SQL Server database in the managed space. | | | System.Data.SqlServerCE Describes a collection of classes that can be used to access a database in SQL Server CE from Windows CE-based devices in the managed environment. With this namespace you can create SQL Server CE databases on a device and also establish connections to SQL Server databases that are on a device or on a remote server. | | | System.Data.SqlTypes Contains classes for native data types within SQL Server. These classes provide a faster alternative to other data types. Using the classes in this namespace helps prevent type conversion errors caused in situations where loss of precision could occur. Because other data types are converted to and from SqlTypes behind the scenes, explicitly creating and using objects within this namespace results in faster code as well. | | System.Deployment Contains the classes you need to programmatically update a ClickOnce application with its latest version. | | System.Diagnostics Provides classes that allow you to interact with system processes, event logs, and performance counters. This namespace also provides classes that allow you to debug your application and to trace the execution of your code. For more information, see the Trace and Debug classes. | | | System.Diagnostics.CodeAnalysis Contains classes for interaction with code analysis tools. Code analysis tools are used to analyze code for conformance to coding conventions such as naming or security rules. | | | System.Diagnostics.Design Contains classes that can be used to extend design-time support for application monitoring and instrumentation. | | | System.Diagnostics.SymbolStore Provides classes that allow you to read and write debug symbol information, such as source line to Microsoft intermediate language (MSIL) maps. Compilers targeting the .NET Framework can store the debug symbol information into programmer's database (PDB) files. Debuggers and code profiler tools can read the debug symbol information at run time. | | System.DirectoryServices Provides easy access to Active Directory from managed code. The namespace contains two component classes, DirectoryEntry and DirectorySearcher, which use the Active Directory Services Interfaces (ADSI) technology. ADSI is the set of interfaces that Microsoft provides as a flexible tool for working with a variety of network providers. ADSI gives the administrator the ability to locate and manage resources on a network with relative ease, regardless of the network's size. | | | System.DirectoryServices.ActiveDirectory Provides a high level abstraction object model that builds around Microsoft® Active Directory® directory service tasks. The Active Directory® directory service concepts such as forest, domain, site, subnet, partition and schema are part of the object model. | | | System.DirectoryServices.Protocols Provides the methods defined in the Lightweight Directory Access Protocol (LDAP) version 3 (V3) and Directory Services Markup Language (DSML) version 2 (V2) standards. | | System.Drawing Provides access to GDI+ basic graphics functionality. More advanced functionality is provided in the System.Drawing.Drawing2D, System.Drawing.Imaging, and System.Drawing.Text namespaces. | | | System.Drawing.Design Contains classes that extend design-time user interface (UI) logic and drawing. You can further extend this design-time functionality to create custom toolbox items, type-specific value editors that can edit and graphically represent values of their supported types, or type converters that can convert values between certain types. This namespace provides the basic frameworks for developing extensions to the design-time UI. | | | System.Drawing.Drawing2D Provides advanced 2-dimensional and vector graphics functionality. This namespace includes the gradient brushes, the Matrix class (used to define geometric transforms), and the GraphicsPath class. | | | System.Drawing.Imaging Provides advanced GDI+ imaging functionality. Basic graphics functionality is provided by the System.Drawing namespace. | | | System.Drawing.Printing Provides print-related services. Typically, you create a new instance of the PrintDocument class, set the properties that describe what to print, and call the Print method to actually print the document. | | | System.Drawing.Text Provides advanced GDI+ typography functionality. Basic graphics functionality is provided by the System.Drawing namespace. The classes in this namespace allow users to create and use collections of fonts. | | System.EnterpriseServices Provides an important infrastructure for enterprise applications. COM+ provides a services architecture for component programming models deployed in an enterprise environment. This namespace provides .NET Framework objects with access to COM+ services, making the .NET Framework objects more practical for enterprise applications. | | | System.EnterpriseServices.CompensatingResourceManager Provides classes that allow you to use a Compensating Resource Manager (CRM) in managed code. A CRM is a service provided by COM+ that enables you to include non-transactional objects in Microsoft Distributed Transaction Coordinator (DTC) transactions. Although CRMs do not provide the capabilities of a full resource manager, they do provide transactional atomicity (all-or-nothing behavior) and durability through the recovery log. | | | System.EnterpriseServices.Internal Provides infrastructure support for COM+ services. The classes and interfaces in this namespace are specifically intended to support calls into System.EnterpriseServices from the unmanaged COM+ classes. | | System.Globalization Contains classes that define culture-related information, including the language, the country/region, the calendars in use, the format patterns for dates, currency, and numbers, and the sort order for strings. These classes are useful for writing globalized (internationalized) applications. | | System.IO Contains types that allow synchronous and asynchronous reading and writing on data streams and files. | | | System.IO.Compression Contains classes that provide basic compression and decompression for streams. | | | System.IO.IsolatedStorage Contains types that allow the creation and use of isolated stores. With these stores, you can read and write data that less trusted code cannot access and help prevent the exposure of sensitive information that can be saved elsewhere on the file system. Data is stored in compartments that are isolated by the current user and by the assembly in which the code exists | | | System.IO.Ports Contains classes that control serial ports, providing a framework for synchronous and event-driven I/O, access to pin and break states, access to serial driver properties, and enumerations for specifying port characteristics. | System.Management Provides access to a rich set of management information and management events about the system, devices, and applications instrumented to the Windows Management Instrumentation (WMI) infrastructure. | | | System.Management.Instrumentation Provides the classes necessary for instrumenting applications for management and exposing their management information and events through WMI to potential consumers. Consumers such as Microsoft Application Center or Microsoft Operations Manager can then manage your application easily, and monitoring and configuring of your application is available for administrator scripts or other applications, both managed as well as unmanaged. | System.Messaging Provides classes that allow you to connect to, monitor, and administer message queues on the network and send, receive, or peek messages. | | | System.Messaging.Design Contains classes that can be used to extend design-time support for System.Messaging classes. | System.Net Provides a simple programming interface for many of the protocols used on networks today. The WebRequest and WebResponse classes form the basis of what are called pluggable protocols, an implementation of network services that enables you to develop applications that use Internet resources without worrying about the specific details of the individual protocols. | | | System.Net.Cache Defines the types and enumerations used to define cache policies for resources obtained using the WebRequest and HttpWebRequest classes. | | | System.Net.Configuration Contains classes that applications use to programmatically access and update configuration settings for the System.Net namespaces. | | | System.Net.Mail Contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery. | | | System.Net.Mime Holds types that are used to represent Multipurpose Internet Mail Exchange (MIME) headers. These types are used with the types in the System.Net.Mail namespace to specify Content-Type, Content-Disposition and Content-transfer-Encoding headers when sending email using the SmtpClient class. | | | System.Net.NetworkInformation Provides access to network traffic data, network address information, and notification of address changes for the local computer. The namespace also contains classes that implement the Ping utility. You can use Ping and related classes to check whether a computer is reachable across the network. | | | System.Net.Sockets Provides a managed implementation of the Windows Sockets (Winsock) interface for developers who need to help control access to the network. | System.Reflection Contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types. | | | System.Reflection.Emit Contains classes that allow a compiler or tool to emit metadata and Microsoft intermediate language (MSIL) and optionally generate a PE file on disk. The primary clients of these classes are script engines and compilers. | System.Resources Provides classes and interfaces that allow developers to create, store, and manage various culture-specific resources used in an application. | | | System.Resources.Tools Contains the StronglyTypedResourceBuilder class, which provides support for strongly typed resources. Beginning with the .NET Framework version 2.0, this compile-time feature encapsulates access to resources by creating classes that contain a set of static read-only (get) properties, thus making it easier to consume resources. | System.Runtime Contains advanced types that support diverse namespaces such as System, the Runtime namespaces, and the Security namespaces. | | | System.Runtime.ConstrainedExecution Defines a set of types that enumerate and define a contract for reliability between the author of some code, and the developers who take a dependency on that code. | | | System.Runtime.Hosting Contains advanced types that are used in application activation within application domains. | | | System.Runtime.CompilerServices Provides functionality for compiler writers using managed code to specify attributes in metadata that affect the run-time behavior of the common language runtime. The classes in this namespace are for compiler writers use only. | | | System.Runtime.InteropServices Provides a wide variety of members that support COM interop and platform invoke services. If you are unfamiliar with these services, see Interoperating with Unmanaged Code. | | | | System.Runtime.InteropServices.ComTypes Contains methods that are defintions of COM functions for managed code. These functions replace the now-obsolete UCOM* methods in the System.Runtime.InteropServices namespace. | | | | System.Runtime.InteropServices.CustomMarshalers Supports the .NET infrastructure and is not intended to be used directly from your code. | | | | System.Runtime.InteropServices.Expando Contains the IExpando interface which allows modification of an object by adding or removing its members. | | | System.Runtime.Remoting Provides classes and interfaces that allow developers to create and configure distributed applications. | | | | System.Runtime.Remoting.Activation Provides classes and objects that support server and client activation of remote objects. | | | | System.Runtime.Remoting.Channels Contains classes that support and handle channels and channel sinks, which are used as the transport medium when a client calls a method on a remote object. | | | | | System.Runtime.Remoting.Channels.Http Contains channels that use the HTTP protocol to transport messages and objects to and from remote locations. By default, the HTTP channels encode objects and method calls in SOAP format for transmission, but other encoding and decoding formatter sinks can be specified in the configuration properties of a channel. | | | | | System.Runtime.Remoting.Channels.Ipc Defines a communication channel for remoting that uses the Interprocess Communication (IPC) system of the Windows operating system. Because it does not use network communication, the IPC channel is much faster than the HTTP and TCP channels, but it can only be used for communication between application domains on the same physical computer. | | | | | System.Runtime.Remoting.Channels.Tcp Contains channels that use the TCP protocol to transport messages and objects to and from remote locations. By default, the TCP channels encode objects and method calls in binary format for transmission, but other encoding and decoding formatter sinks can be specified in the configuration properties of a channel. | | | | System.Runtime.Remoting.Contexts Contains objects that define the contexts all objects reside within. A context is an ordered sequence of properties that defines an environment for the objects within it. Contexts are created during the activation process for objects that are configured to require certain automatic services such synchronization, transactions, just-in-time (JIT) activation, security, and so on. Multiple objects can live inside a context. | | | | System.Runtime.Remoting.Lifetime Contains classes that manage the lifetime of remote objects. Traditionally, distributed garbage collection uses reference counts and pinging for control over the lifetime of objects. This works well when there are a few clients per service, but doesn't scale well when there are thousands of clients per service. The remoting lifetime service associates a lease with each service, and deletes a service when its lease time expires. The lifetime service can take on the function of a traditional distributed garbage collector, and it also adjusts well when the numbers of clients per server increases. | | | | System.Runtime.Remoting.Messaging Contains classes used to create and remote messages. The remoting infrastructure uses messages to communicate with remote objects. Messages are used to transmit remote method calls, to activate remote objects, and to communicate information. A message object carries a set of named properties, including action identifiers, envoy information, and parameters. | | | | System.Runtime.Remoting.Metadata Contains classes and attributes that can be used to customize generation and processing of SOAP for objects and fields. The classes of this namespace can be used to indicate the SOAPAction, type output, XML element name, and the method XML namespace URI | | | | | System.Runtime.Remoting.Metadata.W3cXsd2001 Contains the XML Schema Definition (XSD) defined by the World Wide Web Consortium (W3C) in 2001. The XML Schema Part2: Data types specification from W3C identifies format and behavior of various data types. This namespace contains wrapper classes for the data types that conform to the W3C specification. All date and time types conform to the ISO standards specification. | | | | System.Runtime.Remoting.MetadataServices Contains the classes used by the Soapsuds.exe command line tool and the user code to convert metadata to and from XML schema for the remoting infrastructure. | | | | System.Runtime.Remoting.Proxies Contains classes that control and provide functionality for proxies. A proxy is a local object that is an image of a remote object. Proxies enable clients to access objects across remoting boundaries. | | | | System.Runtime.Remoting.Services Contains service classes that provide functionality to the .NET Framework. | | | System.Runtime.Serialization Contains classes that can be used for serializing and deserializing objects. Serialization is the process of converting an object or a graph of objects into a linear sequence of bytes for either storage or transmission to another location. Deserialization is the process of taking in stored information and recreating objects from it. | | | | System.Runtime.Serialization.Formatters Provides common enumerations, interfaces, and classes that are used by serialization formatters. | | | | | System.Runtime.Serialization.Formatters.Binary Contains the BinaryFormatter class, which can be used to serialize and deserialize objects in binary format. | | | | | System.Runtime.Serialization.Formatters.Soap Contains the SoapFormatter class, which can be used to serialize and deserialize objects in the SOAP format. | System.Security Provides the underlying structure of the .NET Framework security system, including base classes for permissions. | | | System.Security.Cryptography Provides cryptographic services, including secure encoding and decoding of data, as well as many other operations, such as hashing, random number generation, and message authentication. | | | | System.Security.Cryptography.Pkcs Provides programming elements for Public Key Cryptography Standards (PKCS). | | | | System.Security.Cryptography.X509Certificates Contains the common language runtime implementation of the Authenticode X.509 v.3 certificate. This certificate is signed with a private key that uniquely and positively identifies the holder of the certificate. | | | | System.Security.Cryptography.Xml Contains classes to support the creation and validation of XML digital signatures. The classes in this namespace implement the World Wide Web Consortium Recommendation, "XML-Signature Syntax and Processing", described at http://www.w3.org/TR/xmldsig-core/. | | | System.Security.Permissions Defines classes that control access to operations and resources based on policy. | | | System.Security.Policy Contains code groups, membership conditions, and evidence. These three types of classes are used to create the rules applied by the .NET Framework security policy system. Evidence classes are the input to security policy and membership conditions are the switches; together these create policy statements and determine the granted permission set. Policy levels and code groups are the structure of the policy hierarchy. Code groups are the encapsulation of a rule and are arranged hierarchically in a policy level. | | | System.Security.Principal Defines a principal object that represents the security context under which code is running. | System.ServiceProcess Provides classes that allow you to implement, install, and control Windows service applications. Services are long-running executables that run without a user interface. Implementing a service involves inheriting from the ServiceBase class and defining specific behavior to process when start, stop, pause, and continue commands are passed in, as well as custom behavior and actions to take when the system shuts down. | System.Text Contains classes representing ASCII, Unicode, UTF-7, and UTF-8 character encodings; abstract base classes for converting blocks of characters to and from blocks of bytes; and a helper class that manipulates and formats String objects without creating intermediate instances of String. | | | System.Text.RegularExpressions Contains classes that provide access to the .NET Framework regular expression engine. The namespace provides regular expression functionality that can be used from any platform or language that runs within the Microsoft .NET Framework. | System.Threading Provides classes and interfaces that enable multithreaded programming. In addition to classes for synchronizing thread activities and access to data (Mutex, Monitor, Interlocked, AutoResetEvent, and so on), this namespace includes a ThreadPool class that allows you to use a pool of system-supplied threads, and a Timer class that executes callback methods on thread pool threads. | System.Timers Provides the Timer component, which allows you to raise an event on a specified interval. | System.Transactions Contains classes that allow your code to participate in transactions. The classes support transactions with multiple, distributed participants, multiple phase notifications, and durable enlistments. | | | System.Transactions.Configuration Contains classes that describe configuration options used by System.Transactions classes | | | System.Transactions.Ltm Contains classes used for transaction management by the lightweight transaction manager. | | | System.Transactions.Oletx Contains classes used for transaction management by the OLE transaction manager | System.Web Supplies classes and interfaces that enable browser-server communication. This namespace includes the HTTPRequest class, which provides extensive information about the current HTTP request, the HTTPResponse class, which manages HTTP output to the client, and the HTTPServerUtility class, which provides access to server-side utilities and processes. System.Web also includes classes for cookie manipulation, file transfer, exception information, and output cache control. | | | System.Web.Administration Contains classes used by the Web Site Administration Tool to administer and configure ASP.NET applications on a Web server. | | | System.Web.Caching Provides classes for caching frequently used data on the server. This includes the Cache class, a dictionary that allows you to store arbitrary data objects, such as hash tables and data sets. It also provides expiration functionality for those objects, and methods that allow you to add and remove the objects. You can also add the objects with a dependency upon other files or cache entries, and perform a callback to notify your application when an object is removed from the cache. | | | System.Web.Compilation Contains classes for generating and compiling custom file types within the ASP.NET build environment. | | | System.Web.Configuration Contains classes that are used to set up ASP.NET configuration. | | | System.Web.Handlers Contains HTTP handler classes that process HTTP requests to a Web server. | | | System.Web.Hosting Provides the functionality for hosting ASP.NET applications from managed applications outside of Microsoft Internet Information Services (IIS). | | | System.Web.Mail The classes in this namespace are obsolete; use the classes in the System.Net.Mail namespace. Contains classes that enable you to construct and send messages using the CDOSYS message component. The mail message is delivered through either the SMTP mail service built into Microsoft Windows 2000 or through an arbitrary SMTP server. The classes in this namespace can be used either from ASP.NET or from any managed application. | | | System.Web.Management Contains classes and interfaces for managing and monitoring the health of Web applications. | | | System.Web.Mobile Contains the core capabilities, including authentication and error-handling, required for building ASP.NET mobile Web applications. | | | System.Web.Profile Contains classes that are used to implement the ASP.NET user profile in Web server applications. | | | System.Web.RegularExpressions Provides regular expressions used to parse ASP.NET files. All members of the System.Web.RegularExpressions namespace are descendants of the Regex class. | | | System.Web.Security Contains classes that are used to implement ASP.NET security in Web server applications. | | | System.Web.Services Consists of the classes that enable you to create XML Web services using ASP.NET and XML Web service clients. XML Web services are applications that provide the ability to exchange messages in a loosely coupled environment using standard protocols such as HTTP, XML, XSD, SOAP, and WSDL. XML Web services enable the building of modular applications within and across companies in heterogeneous environments making them interoperable with a broad variety of implementations, platforms and devices. The SOAP-based XML messages of these applications can have well-defined (structured and typed), or loosely defined parts (using arbitrary XML). The ability of the messages to evolve over time without breaking the protocol is fundamental to the flexibility and robustness of XML Web services as a building block for the future of the Web. | | | | System.Web.Services.Configuration Consists of the classes that configure how XML Web services created using ASP.NET run. | | | | System.Web.Services.Description Consists of the classes that enable you to publicly describe an XML Web service by using the Web Services Description Language (WSDL). Each class in this namespace corresponds to a specific element in the WSDL specification, and the class hierarchy corresponds to the XML structure of a valid WSDL document. | | | | System.Web.Services.Discovery Consists of the classes that allow XML Web service clients to locate the available XML Web services on a Web server through a process called XML Web services Discovery. | | | | System.Web.Services.Protocols Consists of the classes that define the protocols used to transmit data across the wire during the communication between XML Web service clients and XML Web services created using ASP.NET. | | | System.Web.SessionState Supplies classes and interfaces that enable storage of data specific to a single client within a Web application on the server. The session state data is used to give the client the appearance of a persistent connection with the application. State information can be stored within local process memory or, for Web farm configurations, out-of-process using either the ASP.NET State Service or a SQL Server database. | | | System.Web.UI Provides classes and interfaces that allow you to create controls and pages that will appear in your Web applications as user interface on a Web page. This namespace includes the Control class, which provides all controls, whether HTML, Web, or User controls, with a common set of functionality. It also includes the Page control, which is generated automatically whenever a request is made for a page in your Web application. Also provided are classes which provide the Web Forms Server Controls data binding functionality, the ability to save the view state of a given control or page, as well as parsing functionality for both programmable and literal controls. | | | | System.Web.UI.Adapters Contains the base classes for control adapters and page adapters, which you can use to override lifecycle states of pages and controls to modify their default markup or behavior for new markup standards or for specific browsers. | | | | System.Web.UI.Design Contains classes that can be used to extend design-time support for Web Forms and Web server controls. | | | | | System.Web.UI.Design.MobileControls Obsolete. Contains classes that provide design-time support for the classes in the System.Web.UI.MobileControls namespace. The classes in this namespace are obsolete; use the classes in System.Web.UI.Design.WebControls instead. | | | | | | System.Web.UI.Design.MobileControls.Converters Contains classes that provide design-time support for data type converters in mobile controls. | | | | | System.Web.UI.Design.WebControls Contains classes that can be used to extend design-time support for Web server controls. | | | | | | System.Web.UI.Design.WebControls.WebParts Contains classes that provide design-time support for controls derived from classes in the System.Web.UI.WebControls.WebParts namespace. | | | | System.Web.UI.HtmlControls Consists of a collection of classes that allow you to create HTML server controls on a Web Forms page. HTML server controls run on the server and map directly to standard HTML tags supported by most browsers. This allows you to programmatically control the HTML elements on a Web Forms page. | | | | System.Web.UI.Imaging Contains classes for generating dynamic images and creating custom image generation services. | | | | System.Web.UI.MobileControls Obsolete. Contains a set of ASP.NET server controls that can intelligently render your application for different mobile devices. The classes in this namespace are obsolete; use the controls in System.Web.UI.WebControls instead. | | | | | System.Web.UI.MobileControls.Adapters Contains classes you can use to override lifecycle stages of a mobile control to modify its default HTML, CHTML, or WML markup or behavior for new markup standards or for specific browsers and mobile devices. | | | | | | System.Web.UI.MobileControls.Adapters.XhtmlAdapters Contains classes you can use to override lifecycle stages of a mobile control to modify its default XHTML markup or behavior for new markup standards or for specific browsers and mobile devices. | | | | System.Web.UI.WebControls Contains classes that allow you to create Web server controls on a Web page. Web server controls run on the server and include form controls such as buttons and text boxes. They also include special purpose controls such as a calendar. Because Web server controls run on the server, you can programmatically control these elements. Web server controls are more abstract than HTML server controls. Their object model does not necessarily reflect HTML syntax. | | | | | System.Web.UI.WebControls.Adapters Contains classes you can use to override lifecycle stages of a Web control to modify a control's default markup or behavior for new markup standards or for specific browsers. | | | | | System.Web.UI.WebControls.WebParts Contains an integrated set of classes and interfaces for creating Web pages whose appearance and behavior can be modified (personalized) by end users. The user-defined settings for each page are saved for future browser sessions. | | | System.Web.Util Contains classes that enable callback methods to be run under the scope of a transaction and that enable work to be posted to separate threads. | System.Windows Contains classes for creating Windows-based applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system. | | | System.Windows.Forms Contains classes for creating Windows-based applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system. | | | | | System.Windows.Forms.ComponentModel | | | | | | System.Windows.Forms.ComponentModel.Com2Interop Contains helper classes that Visual Studio uses to display property pages while in design mode. | | | | | System.Windows.Forms.Design Contains classes that support design-time configuration and behavior for Windows Forms components. These classes consist of: Designer classes that provide support for Windows Forms components, a set of design time services, UITypeEditor classes for configuring certain types of properties, and classes for importing ActiveX controls. | | | | | | System.Windows.Forms.Design.Behavior Contains classes for creating custom user interface behavior for components at design time. | | | | | System.Windows.Forms.Layout Contains classes that support design-time and run-time layout behaviors. | | | | | System.Windows.Forms.Printing Provides classes for creating simple reports that have headers, footers, running strips, and a tabular layout. Printing is performed with the SimplePrintDocument class and makes writing to the printer as easy as writing to the console. | | | | | System.Windows.Forms.PropertyGridInternal Provides internal support for the PropertyGrid control. The classes in this namespace support the .NET Framework infrastructure and are not intended to be used directly from your code | System.Xml Provides standards-based support for processing XML. | | | System.Xml.Schema Contains the XML classes that provide standards-based support for XML Schemas definition language (XSD) schemas. | | | System.Xml.Serialization Contains classes that are used to serialize objects into XML format documents or streams. | | | System.Xml.XPath Contains the XPath parser and evaluation engine. It supports the W3C XML Path Language (XPath) Version 1.0 Recommendation (www.w3.org/TR/xpath). | | | System.Xml.Xsl Provides support for Extensible Stylesheet Transformation (XSLT) transforms. It supports the W3C XSL Transformations (XSLT) Version 1.0 Recommendation (www.w3.org/TR/xslt). | | | | System.Xml.Xsl.Runtime Provides internal support for the classes in the System.Xml.Xsl namespace. The classes in this namespace support the .NET Framework infrastructure and are not intended to be used directly from your code. |
|
-
Abstract In order to use and develop in .NET, there are several topics that need to be understood as this foundation will allow you to understand the strategy behind .NET. This article aims to discuss an overview of the Common Language Runtime. Introduction The common language runtime (CLR) is an execution engine for .NET applications. The .NET Framework provides a large library of classes, interfaces and data types. The common language runtime provides many benefits that make the technology choice attractive to system designers. Some of these benefits are - the ability to run applications of different operating systems
- the ability to run applications on different hardware architectures
- freedom of programming language choice
- ease of data integration through the common type system
- language neutral component development
- full object orientation
- large framework for developing services, components, form and web based applications.
- powerfully debugging environment
- integration with legacy components in an unmanaged mode.
- large commercial vendor component base
- large community skill base
- memory management
We will now enter into a discussion around all the features of .NET CLR Compilers and programming languages .NET achieves this by allowing you to choose a language where you are familiar with the general syntax. Many .NET languages have evolved to take full advantage .NET and object orientation. However by choosing a language you are already familiar with cuts down the learning curve. Currently there are 17 languages supported, some are - Visual Basic .NET
- Visual C++ Managed Code
- C#
- J# (Java)
- COBOL .NET
- Python.NET
- Delphi.NET
- Eiffel
- Perl
- APL
- Pascal
- Haskell
- ML
- Oberon
- Scheme
- Smalltalk.
- Microsoft Intermediary Language
Assemblies, Microsoft Intermediary Language and the Just-In-Time Compiler As you develop applications in your development environment you will compile these into assemblies. The assembly is however not compiled for a specific hardware architecture e.g. 32, 64 bit, RISC, CISC and Mobile; it is compiled into an intermediary .NET language called Microsoft Intermediary Language (MSIL). When the application is finally executed, the Just-In-Time compiler will convert the MSIL code to the native hardware's instruction set (machine code). By having your applications in MSIL, you can easily execute them on different hardware devices even with different operating systems. This is achieved by downloading the common language runtime (CLR) for your specific hardware / operating system. Microsoft have release several CLR for various operating systems and hardware platforms within their product range. However, there are some community projects that release runtimes for different hardware and software platforms. For example the Mono project provides a CLR for 32 and 64 bit Linux machines. This is exceptionally powerful as a developer can focus on writing the application without concern for hardware and operating system. Obviously there are some limitations that each hardware\software CLR has. For example you would not host an ASP.NET web site on your mobile device or require Active Directory functionality on your Linux box. Thus you will need to carefully decide on your target operating systems and hardware carefully and look at limitations of .NET functionality on those platforms. Having said that there are limitations, common business applications should work on all platforms without any code modifications. E.g. Capture, validate, process and persist information. .NET Framework When the common library runtime is installed onto a operating system \ hardware combination, another set of powerful components are installed, this is the .NET Framework. The .NET Framework is a huge library of classes, interfaces, structures and data types that perform many everyday programming functions. Developers will quickly start using the framework as this radically cuts down development time. Threading Features to create simple multi threaded applications to complex thread pooling using IO completion ports. Web Forms A full set of functionality to deliver high performance web sites with custom controls with both server and client side processing. The toolset even allows for component development for products like SharePoint Server. Windows User Interfaces Client user interfaces can be built by creating forms, dialogs and controls. This framework lets you implement the standard Windows UI in your .NET-based applications. Many functions that were previously only accessible by means of application programming interface (API) calls are now available as part of the forms themselves, making development much easier and more powerful. Graphic intense applications can now access GDI+ functionality and image processing functionality. Xml The XML functionality provides support for XML . It includes an XML parser and a writer, which are both W3C-compliant. The Extensible Stylesheet Language (XSL) transformation is provided. A powerful set of components allows classes to easily serialized into XML documents and then passed between processes or saved to disk. Helpers String manipulation, regular expressions, date and time manipulation, mathematical functions and access to file systems. Database The System.Data namespace consists of classes that constitute the ADO.NET object model. At a high level, the ADO.NET object model is divided into two layers: the connected layer and the disconnected layer. The System.Data namespace includes the DataSet class, which represents multiple tables and their relations. These DataSets are completely self contained data structures that can be populated from a variety of data sources. One data source could be XML, another could be OLEDB, and a third data source could be the direct adapter for SQL Server. Integration SOAP, Sockets, Interproces Communication and web services. Security Full security functionality is provided by the framework allowing integration with LDAP, Active Directory and custom security functionality. Throughout the framework a large focus is on security. Framework Versions The common language runtime is static and MSIL consistent through releases. However what does change in enhancements within the huge Framework of class libraries. These libraries are constantly being optimized, simplified and extended. Each Framework then either standard or implemented on a specific operating system / hardware CLR release. | Version | Description | | Framework 1.0 | The initial release of the .NET framework was a completely successful and stable. It proved many sceptics in the technology wrong. | | Framework 1.1 | Optimisations on the Framework were released with subtle language enhancements to various languages and ease-of-use redesigns made, especially with System.Data namespace. | | Framework 2.0 | This very successful framework release extended the framework significantly with a high drive on Web services and Web applications. Other areas such as reflection were introduced making processing engine development significantly easier. | | Framework 3.0 | Framework 3.0 was release with new functionalty such as Workflow. | | Framework 3.5 | With significant changes to some backend servers such as SQL 2008, integration with SharePoint, data access using embedded LINQ | In the future of the framework will continue to evolve at a rapid pace with optimizations and significant new functionality. The framework will adapt to new inventions and technologies in the software industry. The current development base within Microsoft, component makers and development shops is unbelievably huge, with so much skill and innovation out in the market, the entire industry will benefit. The only foreseeable problem is that these enhancements will be coming in at a huge rate making it very difficult for programmers and companies to keep abreast. One will see that it will be common practice for a development shop to skip a version or two in the framework before the attraction of new functionality out weights the functionality of the current framework. Common Type System The common type system defines various data types that is enforced in each language implementation. The different data types are owned by the CLR and defined within the Framework. This powerful design facilitates integration between all .NET applications and components regardless of the language they were written in.
|
-
Abstract This post explains how reference or value type variables interact with the stack and the heap. A brief description of how the garbage collector reclaims memory from the stack is also described. Memory The common library runtime provides two memory mechanisms that will be used. The clr also provides powerfull memory managment and garbage collection which do a lot of work for you and thus is not really necessary for most programmers to delve into. However, if you are looking at performance of your applications and working with the correct data types in the right places, this will radically improve your code. The two memory mechanisms are the stack and the heap. Stack When your assembly is first loaded into memory, the entry point (the Main method) a thread is started that will run the application. As the Main method will start to execute other methods and intern they will call methods, the thread will need to "remember" where it is and where it is called from. This is observed when you run the application in debug mode with the IDE and monitor the call stack. Each method may also declare variables internally which are stored on the stack. Arguments to methods and return data is also stored on the stack. Thus as a method runs, the CLR pops memory for the method's parameters, return values and internal variables on the stack. When the method finishes the memory is popped of the stack. The stack memory is thus used to control the flow of the application and maintain execution state. Should the application launch multiple threads, each thread will have its own stack to maintain what method the thread is in and what variables each method requires. The default stack size is 1Mb per thread. This may seem small, however you will need one exceptionally large application that is badly developed to run out of stack space. Heap The heap is intended to store your data and pass data from method to method allowing each method to work on the data and possibly change the data. To use memory on the heap you simply request it by using the new keyword in C#. The memory requested is tracked by the garbage collector and when it becomes un-rooted (not used), the GC will free the memory back to the virtual machine and O/S. Unlike the stack, there are no constraints to what can be placed on the heap. Memory is limited to your physical memory and page file maximum sizes, however there are limitations set by the underlying operating systems and hardware platforms. Data types The .NET common type specification defines two distinct data types. These two data types are - Value type
- Reference type
Value types - Implemented as structures
- value types directly contain their data
- Value types are either implemented directly on the stack or inline within a structure or class.
- Enumerations are value types
- Variables that are value types each have their own copy of the data, and therefore operations on one variable do not affect other variables.
Reference types - Implemented as classes
- Reference types store a reference to the value's memory address
- Reference types are allocated on the heap
- Reference types can be self-describing types, pointer types, or interface types.
- The internal fields of the class can either be other classes, boxed value types and delegates.
- Variables that are reference types can refer to the same object; therefore, operations on one variable can affect the same object referred to by another variable.
- When a reference type is created the data is created on the heap, the variable on the stack that references the heap data will only be a small memory pointer.
The following diagram illustrates the data types Sample Application The sample application below is used to demonstrate value and reverence type utilization on the stack and heap. To run the application, create a simple console based application and copy the code below into the application. Compile the application with the Debug configuration and start stepping through the code. Further down in the document is a step-by-step walk through of the code. namespace Brett.StackDemo { using System; class Point { public int X; public int Y; } class Program { static void Main() { Run(); } static void Run() { int answer = 0; int a = 5; int b = 3; Console.WriteLine("a={0} b={1} answer={2}", a, b, answer); answer = StackDemo(a, b); Console.WriteLine("a={0} b={1} answer={2}", a, b, answer); Point p; p = new Point(); p.X = 50; p.Y = 30; Console.WriteLine("p.X={0} p.Y={1}", p.X, p.Y); HeapDemo(p); Console.WriteLine("p.X={0} p.Y={1}", p.X, p.Y); } static int StackDemo(int no1, int no2) { no1 += 10; return no1 + no2; } static void HeapDemo(Point point) { point.X += 100; point.Y += 100; } } } Code walk through The table below describes how the variables are created an placed on either the stack or heap. | Running code | Description | | static void Main() { | - The assembly is loaded by the class loader which looks for the entry point method Main() and places it onto the call stack.
- Maid does not return data, nor does it declare any arguments or have any internal variables.
| | Run(); | - Run method is about to be called, however it does not take arguments nor does it return any data;
| | static void Run() { | - As the Run method is started, all variables declared within the method are placed onto the stack
| | int answer = 0; int a = 5; int b = 3; | - a,b and answer are initialized
| | Console.WriteLine("a={0} b={1} answer={2}", a, b, answer); | The following output is generated:
| | answer = StackDemo(a, b); | - The StackDemo method is about to be called from within Run().
| | static int StackDemo(int no1, int no2) { |
- A jump is made to the StackDemo method, however it takes in two arguments as well as returns an integer.
- Memory is allocated onto the stack for the two arguments and the return parameter.
- The two parameters are assigned to the calling values
At this point it is important to note that int is a value type and thus the data is copied from a and b into no1 and no2 respectively. | | no1 += 10; | 
- The no1 stack variable is incremented by 10.
| | return no1 + no2; |  - The calculation (no1 + no2) is preformed and the return value on the stack is set
| | } | The StackDemo method exits and the execution stack is modified, however the return value is still on the stack. | | answer = StackDemo... |
- The return value (18) is then copied over to the answer through the assignment (=) operator.
- The answer is also popped of the stack and execution within the Run() statement resumes.
| | Console.WriteLine("a={0} b={1} answer={2}", a, b, answer); | The following is displayed in the output window.
| | p = new Point(); | This complex statement runs in several separate phases - The new keyword allocates sufficient memory on the heap to store all internal fields of the class (i.e X and Y).
- Behind the scenes the new heap memory is registered to the garbage collector for future collection.
- All value type fields within the class are initialized.
- The default constructor Point() is executed to perform any further custom initialization.
| | p = new Point(); | - The p = assignment operator is executed thus p to reference the item on the heap. In this step the p variable is rooted once to the heap.
As p is rooted to the memory in the heap through the garbage collector, it will not be reclaimed by the garbage collector and thus is "in use". | | p.X = 50; p.Y = 30; | | | Console.WriteLine("p.X={0} p.Y={1}", p.X, p.Y); | The following is displayed in the output window
| | HeapDemo(p); | Heap demo is about to be called. | | static void HeapDemo(Point point) { | - When the HeapDemo method is called, it is placed on the call stack and so are all return values, arguments and internal variables created.
- The argument point is set to the value of p, however p is a reference type and therefore point then points to the same heap element.
At this point the item on the heap is rooted to two stack reference variables, namely Run::p and HeapDemo::point. It will thus not be collected by the garbage collector. | | point.X += 100; point.Y += 100; |
- The values of X and Y are both incremented by 100.
Again not that Run::p points to the same heap and thus is also changed. | | } | - The HeapDemo method exists and therefore all variables it uses is popped off the stack.
This now has resulted that the memory on the heap is now singly rooted to Run::p. | | Console.WriteLine("p.X={0} p.Y={1}", p.X, p.Y); | The following is displayed in the output window
| | } | - The Run method exits and is popped off the stack.
Note that the memory on the heap still exists, however is no longer rooted to any variable on the stack and thus is ready to be disposed. The heap variable is said to be un-rooted as there is no longer any variable on the stack that references it. | | |
- The garbage collector runs and Finalizes the Point on the heap and then frees the memory.
Note that the garbage collector will runs independently of the application and thus frees up any objects as and when needed. This step coincidentally might run immediately or at a later state even after main has finished running. | | } | - The Main method exits thus popping of the entry point of the application off stack and all its variables.
- The running assembly is then disposed.
| Conclusion Classes, arrays and interfaces are reference type and are created using the new keyword. The data created is stored on the stack, however a pointer to this data exists on the stack. When the pointer on the stack goes out of scope and the data on the heap is no longer referenced, it is collected by the garbage collector. Structures however are implemented on the heap. Although you cannot use inheritance on structures, the System.ValueType class is inherited by the structure. This class defines the storage of data.
|
More Posts
|
|
|