Search This Blog

Tuesday, September 14, 2010

Transports in Windows Communication Foundation

Transports in Windows Communication Foundation
The main transports used in Windows Communication Foundation (WCF) are HTTP, HTTPS, TCP, and named pipes. The topics in this section discuss choosing among these transports, configuring the transport, and setting tuning properties.
Choosing a Transport
This topic discusses criteria for choosing among the three main transports that are included in Windows Communication Foundation (WCF): HTTP, TCP, and named pipes.
The WCF programming model separates endpoint operations (as expressed in a service contract) from the transport mechanism that connects two endpoints. This gives you the flexibility to decide how to expose your services to the network. If you must connect to an existing client or server, you may not have a choice about using a particular transport. However, WCF services can be made accessible through multiple endpoints, each with a different transport. When a single transport does not cover the intended audience for your service, consider exposing the service over multiple endpoints. Client applications can then use the endpoint that is best for them.
When to Use HTTP Transport
HTTP is a request/response protocol between clients and servers. The most common application consists of Web-browser clients that communicate with a Web server. The client sends a request to a server, which listens for client request messages. When the server receives a request, it returns a response, which contains the status of the request. If successful, optional data, such as a Web page, an error message, or other information is returned.The HTTP protocol is not connection-based—once the response is sent, no state is maintained. To handle multiple-page transactions, the application must persist any necessary state.
When to Use the TCP Transport
TCP is a connection-based, stream-oriented delivery service with end-to-end error detection and correction. Connection-based means that a communication session between hosts is established before exchanging data. A host is any device on a TCP/IP network identified by a logical IP address.TCP provides reliable data delivery and ease of use. Specifically, TCP notifies the sender of packet delivery, guarantees that packets are delivered in the same order in which they are sent, retransmits lost packets, and ensures that data packets are not duplicated. Note that this reliable delivery applies between two TCP/IP nodes, and is not the same thing as WS-ReliableMessaging, which applies between endpoints, no matter how many intermediate nodes they may include.
When to Use the Named Pipe Transport
A named pipe is an object in the Windows operating system kernel, such as a section of shared memory that processes can use for communication. A named pipe has a name, and can be used for one-way or duplex communication between processes on a single machine.When communication is required between different WCF applications on a single computer, and you want to prevent any communication from another machine, then use the named pipes transport. An additional restriction is that processes running from Windows Remote Desktop may be restricted to the same Windows Remote Desktop session unless they have elevated privileges.

Tuesday, September 7, 2010

WCF Services

WCF Services

All communication with a Windows Communication Foundation (WCF) service occurs through the endpoints of the service. Endpoints provide clients access to the functionality offered by a WCF service.

Each endpoint consists of four properties:

An address that indicates where the endpoint can be found. The address uniquely identifies the endpoint and tells potential consumers of the service where it is located. It is represented in the WCF object model by the EndpointAddress class.

A binding that specifies how a client can communicate with the endpoint. The binding specifies how to communicate with the endpoint. This includes:

-The transport protocol to use (for example, TCP or HTTP).

-The encoding to use for the messages (for example, text or binary).

-The necessary security requirements (for example, SSL or SOAP message security).

A contract that identifies the operations available. The contract outlines what functionality the endpoint exposes to the client. A contract specifies:

-What operations can be called by a client.

-The form of the message.

-The type of input parameters or data required to call the operation.

-What type of processing or response message the client can expect.

A set of behaviors that specify local implementation details of the endpoint. You can use endpoint behaviors to customize the local behavior of the service endpoint. Endpoint behaviors achieve this by participating in the process of building a WCF runtime. An example of an endpoint behavior is the ListenUri property, which allows you to specify a different listening address than the SOAP or Web Services Description Language (WSDL) address.

Data transfer and serialization in WCF service.

The Windows Communication Foundation (WCF) can be thought of as a messaging infrastructure. Service operations can receive messages, process them, and send them messages. Messages are described using operation contracts. For example, consider the following contract.

[ServiceContract] - This shows what services are offered to the client.

[OperationContract] - This shows what operations are exposed within the service to the client.

[DataContract] - This is used when the parameter passed need to act as both for request and reply messages. They makes use of DataContractSerializer.

[MessageContract] - This is used to represent the request and the reply message using single type. This can be implemented using datacontract also. But message contract avoids unnecessary levels of wrapping in the resultant xml. Also, message contracts can specify what shld be the message body and what shld be message header.

Sessions, Instancing, and Concurrency in Windows Communication Foundation

A session is a correlation of all messages sent between two endpoints. Instancing refers to controlling the lifetime of user-defined service objects and their related InstanceContext objects. Concurrency is the term given to the control of the number of threads executing in an InstanceContext at the same time.

Monday, September 6, 2010



Language-Integrated Query (LINQ) is a new feature in Visual Studio 2008 and the .NET Framework 3.5. LINQ extends powerful query capabilities to the language syntax of C# and Visual Basic in the form of standard, easily-learned query patterns. This technology can be extended to support potentially any kind of data store. The .NET Framework 3.5 includes LINQ provider assemblies that enable the use of LINQ for querying .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.

The components of LINQ that are part of the .NET Framework 3.5 are:

The System.Linq namespace, which contains the set of standard query operators and types and interfaces that are used in the infrastructure of a LINQ query. This namespace is in the System.Core.dll assembly.

The System.Data.Linq namespace, which contains classes that support interaction with relational databases in LINQ to SQL applications.

The System.Data.Linq.Mapping namespace, which contains classes that can be used to generate a LINQ to SQL object model that represents the structure and content of a relational database.

The System.Xml.Linq namespace, which contains the classes for LINQ to XML. LINQ to XML is an in-memory XML programming interface that enables you to modify XML documents efficiently and easily. Using LINQ to XML, you can load XML, serialize XML, create XML trees from scratch, manipulate in-memory XML trees, and validate by using XSD. You can also use a combination of these features to transform XML trees from one shape into another.

New types in the System.Web.UI.WebControls and System.Web.UI.Design.WebControls namespaces. These new types, such as LinqDataSource, support the use of LINQ in ASP.NET Web pages through a data source control.

The DataRowComparer, DataRowExtensions, and DataTableExtensions classes in the System.Data namespace support LINQ queries against ADO.NET DataSet objects.

In the class library, the LINQ extension methods that apply to a class are listed in the members page for the class, in the Contents pane, and in the Index pane.

Friday, September 3, 2010

New features of .Net 3.5

New features of .Net 3.5

Lets check out some new features included in the latest but one version thats .Net 3.5 framework. However, .Net 4.0 version has already been launched and is making news!!!

The .NET Compact Framework version 3.5 expands support for distributed mobile applications by including the Windows Communication Foundation (WCF) technology. It also adds new language features such as LINQ, new APIs based on community feedback, and improves debugging with updated diagnostic tools and features.

The most significant advance is improved support for the development of AJAX-enabled Web sites. ASP.NET supports server-centric AJAX development with a set of new server controls and APIs. You can enable an existing ASP.NET 2.0 page for AJAX by adding a ScriptManager control and an UpdatePanel control so that the page can update without requiring a full page refresh.

Other improvements in ASP.NET include a new data control, ListView, for displaying data; a new data source control, LinqDataSource, that exposes Language Integrated Query (LINQ) to Web developers through the ASP.NET data source control architectures; a new tool, ASP.NET Merge Tool (Aspnet_merge.exe), for merging precompiled assemblies; and tight integration with IIS 7.0. ListView is a highly customizable control (using templates and styles) that also supports edit, insert, and delete operations, as well as sorting and paging functionality. The paging functionality for ListView is provided by a new control called DataPager. You can use the merge tool to combine assemblies to support a range of deployment and release management scenarios. The integration of ASP.NET and IIS 7.0 includes the ability to use ASP.NET services, such as authentication and caching, for any content type. It also includes the ability to develop server pipeline modules in ASP.NET managed code and supports unified configuration of modules and handlers.

Other improvements in Visual Web Developer include multitargeting support, inclusion of Web Application Projects, a new Design view, new Cascading Style Sheets (CSS) design tools, and support for LINQ for SQL databases. Multitargeting enables you to use Visual Web Developer to target development of Web applications to specific versions of the .NET Framework, including versions 2.0, 3.0, and 3.5.

Monday, August 30, 2010

Introduction to .Net Assemblies

Introduction to .NET Assemblies

In the previous post we learnt something about Garbage collector shortly called GC. In this new post we will try learn something about the famous .Net Assemblies!

You must have heard the word assembly many times in .NET documentation. In this article I will share some thing about .NET assemblies.

What is an assembly?

 An Assembly is a logical unit of code

 Assembly physically exist as DLLs or EXEs

 One assembly can contain one or more files

 The constituent files can include any file types like image files, text files etc. along with DLLs or EXEs

 When you compile your source code by default the exe/dll generated is actually an assembly

 Unless your code is bundled as assembly it can not be used in any other application

 When you talk about version of a component you are actually talking about version of the assembly to which the component belongs.

 Every assembly file contains information about itself. This information is called as Assembly Manifest.

What is assembly manifest?

 Assembly manifest is a data structure which stores information about an assembly

 This information is stored within the assembly file(DLL/EXE) itself

 The information includes version information, list of constituent files etc.

What is private and shared assembly?

The assembly which is used only by a single application is called as private assembly. Suppose you created a DLL which encapsulates your business logic. This DLL will be used by your client application only and not by any other application. In order to run the application properly your DLL must reside in the same folder in which the client application is installed. Thus the assembly is private to your application.

Suppose that you are creating a general purpose DLL which provides functionality which will be used by variety of applications. Now, instead of each client application having its own copy of DLL you can place the DLL in 'global assembly cache'. Such assemblies are called as shared assemblies.

What is Global Assembly Cache?

Global assembly cache is nothing but a special disk folder where all the shared assemblies will be kept. It is located under <drive>:\WinNT\Assembly folder.

How assemblies avoid DLL Hell?

As stated earlier most of the assemblies are private. Hence each client application refers assemblies from its own installation folder. So, even though there are multiple versions of same assembly they will not conflict with each other. Consider following example :

 You created assembly Assembly1

 You also created a client application which uses Assembly1 say Client1

 You installed the client in C:\MyApp1 and also placed Assembly1 in this folder

 After some days you changed Assembly1

 You now created another application Client2 which uses this changed Assembly1

 You installed Client2 in C:\MyApp2 and also placed changed Assembly1 in this folder

 Since both the clients are referring to their own versions of Assembly1 everything goes on smoothly

Now consider the case when you develop assembly that is shared one. In this case it is important to know how assemblies are versioned. All assemblies has a version number in the form:

If you change the original assembly the changed version will be considered compatible with existing one if the major and minor versions of both the assemblies match.

When the client application requests assembly the requested version number is matched against available versions and the version matching major and minor version numbers and having most latest build and revision number are supplied.

How do I create shared assemblies?

Following steps are involved in creating shared assemblies :

 Create your DLL/EXE source code

 Generate unique assembly name using SN utility

 Sign your DLL/EXE with the private key by modifying AssemblyInfo file

 Compile your DLL/EXE

 Place the resultant DLL/EXE in global assembly cache using AL utility

How do I create unique assembly name?

Microsoft now uses a public-private key pair to uniquely identify an assembly. These keys are generated using a utility called SN.exe (SN stands for shared name). The most common syntax of is :

sn -k mykeyfile.key

Where k represents that we want to generate a key and the file name followed is the file in which the keys will be stored.

How do I sign my DLL/EXE?

Before placing the assembly into shared cache you need to sign it using the keys we just generated. You mention the signing information in a special file called AssemblyInfo. Open the file from VS.NET solution explorer and change it to include following lines :


Now recompile the project and the assembly will be signed for you.

Note : You can also supply the key file information during command line compilation via /a.keyfile switch.

How do I place the assembly in shared cache?

Microsoft has provided a utility called AL.exe to actually place your assembly in shared cache.

AL /i:my_dll.dll

Now your dll will be placed at proper location by the utility.

Thursday, August 26, 2010

Garbage Collection in .Net

This is my first post and thought of b-logging in some stuff for the technical guys. This post will be useful only to those who are little bit aware of what .Net is and what can it do. I am going to put some information on the Garbage collection concept in .Net. Hopefully that will help in understanding the basic of GC!

Garbage Collector - .Net

Memory management is one of those housekeeping duties that takes a lot of programming time away from developing new code while you track down memory leaks. A day spent hunting for an elusive memory problem usually isn’t a productive day. .NET hopes to do away with all of that within the managed environment with the garbage collection system. Garbage collection runs when your application is apparently out of free memory, or when it is implicitly called but its exact time of execution cannot be determined. Let’s examine how the system works.

When your application requests more memory, and the memory allocator reports that there is no more memory on the managed heap, garbage collection is called.The garbage collector starts by assuming everything in memory is trash that can be freed. It then walks though your application’s memory, building a graph of all memory that is currently referenced by the application. Once it has a complete graph, it compacts the heap by moving all the memory that is genuinely in use together at the start of the free memory heap. After this is complete, it moves the pointer that the memory allocator uses to determine where to start allocating memory from the top of this new heap. It also updates all of your application’s references to point to their new locations in memory.This approach is commonly called a mark and sweep implementation.

Normally you will just let the CLR take care of running garbage collection when it is required. However, at times you may want to force the garbage collector to run, perhaps before starting an operation that is going to require a large amount of memory.To do this, just call GC.Collect(). And if you want to report on your memory use at various points during your application’s execution to help you determine when might be a good time to force collection, you can use

GC.GetTotalMemory(bool forceFullCollection).

The methods in this class influence when garbage collection is performed on an object, and when resources allocated by an object are released. Properties in this class provide information about the total amount of memory available in the system and the age category, or generation, of memory allocated to an object.

The garbage collector tracks and reclaims objects allocated in managed memory. Periodically, the garbage collector performs garbage collection to reclaim memory allocated to objects for which there are no valid references. Garbage collection happens automatically when a request for memory cannot be satisfied using available free memory. Alternatively, an application can force garbage collection using the Collect method.

Garbage collection consists of the following steps:

1. The garbage collector searches for managed objects that are referenced in managed code.

2. The garbage collector attempts to finalize objects that are not referenced.

3. The garbage collector frees objects that are not referenced and reclaims their memory.

During a collection, the garbage collector will not free an object if it finds one or more references to the object in managed code. However, the garbage collector does not recognize references to an object from unmanaged code, and might free objects that are being used exclusively in unmanaged code unless explicitly prevented from doing so. The KeepAlive method provides a mechanism that prevents the garbage collector from collecting objects that are still in use in unmanaged code.

Aside from managed memory allocations, implementations of the garbage collector do not maintain information about resources held by an object, such as file handles or database connections. When a type uses unmanaged resources that must be released before instances of the type are reclaimed, the type can implement a finalizer.

In most cases, finalizers are implemented by overriding the Object.Finalize method; however, types written in C# or C++ implement destructors, which compilers turn into an override of Object.Finalize. In most cases, if an object has a finalizer, the garbage collector calls it prior to freeing the object. However, the garbage collector is not required to call finalizers in all situations; for example, the SuppressFinalize method explicitly prevents a finalizer from being called. Also, the garbage collector is not required to use a specific thread to finalize objects, or guarantee the order in which finalizers are called for objects that reference each other but are otherwise available for garbage collection.

In scenarios where resources must be released at a specific time, classes can implement the IDisposable interface, which contains the IDisposable.Dispose method that performs resource management and cleanup tasks. Classes that implement Dispose must specify, as part of their class contract, if and when class consumers call the method to clean up the object. The garbage collector does not, by default, call the Dispose method; however, implementations of the Dispose method can call methods in the GC class to customize the finalization behavior of the garbage collector.

It is recommended, but not required, that garbage collectors support object aging using generations. A generation is a unit of measure of the relative age of objects in memory. The generation number, or age, of an object indicates the generation to which an object belongs. Objects created more recently are part of newer generations, and have lower generation numbers than objects created earlier in the application life cycle. Objects in the most recent generation are in generation zero.

Notes to Implementers This implementation of the garbage collector supports three generations of objects. MaxGeneration is used to determine the maximum generation number supported by the system. Object aging allows applications to target garbage collection at a specific set of generations rather than requiring the garbage collector to evaluate all generations.

Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. Finalize is protected and, therefore, is accessible only through this class or a derived class.

This method is automatically called after an object becomes inaccessible, unless the object has been exempted from finalization by a call to SuppressFinalize. During shutdown of an application domain, Finalize is automatically called on objects that are not exempt from finalization, even those that are still accessible. Finalize is automatically called only once on a given instance, unless the object is re-registered using a mechanism such as ReRegisterForFinalize and GC.SuppressFinalize has not been subsequently called.

GC Methods

GC.AddMemoryPressure(); - Informs runtime about large amount of memory allocation that should be taken into consideration when GC is scheduled to run.

GC.Collect(); - Forces garbage collection of all generations.

GC.CollectionCount(int generation); - Returns the number of times garbage collection has occurred for the specified generation.

GC.GetGeneration(); - Returns the current generation number.

GC.GetTotalMemory(true); - Returns the number of bytes thought to be allocated. True indicates if this method can wait for short interval of time before returing, to allow the garbage collector to collect and finalize.

GC.KeepAlive(); - GC does not recognize the referenced objects in unmanaged code and clears up by default. This method prevents an object being cleared from unmanaged code.

GC.MaxGeneration(); - Gets the maximum number generations supported by system.

GC.RemoveMemoryPressure() – Informs runtime that the large amount of memory allocation has been released and need not be considered for GC.

GC.ReRegisterForFinalize(); - Finalize is ran only once for an object. If we want to to run the finalize again for an object then this method could be used unless we have not called the suppressFinalize subsequently for that object.

GC.SuppressFinalize(); - Finalize is by default called for all the object that come under GC, untill this method is explicitly called to prevent the finalize method being called for that object.

GC.WaitForPendingFinalizers(); - Current thread is suspended to wait for another thread that is processing the queue of finalizers finishes up.