जगदीश खोलिया: April 2011

Wednesday, April 27, 2011

Application Domains for ASP.NET Programmers


When we launch the Notepad program in Windows, the program executes inside of a container known as a process. We can launch multiple instances of Notepad, and each instance will run in a dedicated process. Using the Task Manager application, we can see a list of all processes currently executing in the system.

A process contains the executable code and data of a program inside memory it has reserved from the operating system. There will be at least one thread executing instructions inside of the process, and in most cases there are multiple threads. If the program opens any files or other resources, those resources will belong to the process.

A process is also boundary. Erroneous code inside of a process cannot corrupt areas outside of the current process. It is easy to communicate inside of a process, but special techniques are required to communicate from one process to another. Each process also runs under a specific security context which can dictate what the process can do on the machine and network. 

A process is the smallest unit of isolation available on the Windows operating system. This could pose a problem for an ISP who wants to host hundreds of ASP.NET applications on a single server. The ISP will want to isolate each ASP.NET application to prevent one application from interfering with another company’s application on the same server, but the relative cost of launching and executing a process for hundreds of applications may be prohibitive.

Introducing the Application Domain

.NET introduces the concept of an application domain, or AppDomain. Like a process, the AppDomain is both a container and a boundary. The .NET runtime uses an AppDomain as a container for code and data, just like the operating system uses a process as a container for code and data. As the operating system uses a process to isolate misbehaving code, the .NET runtime uses an AppDomain to isolate code inside of a secure boundary.

Note, however, that the application domain is not a secure boundary when the application runs with full trust. Applications running with full trust can execute native code and circumvent all security checks by the .NET runtime. ASP.NET applications run with full trust by default.

An AppDomain belongs to only a single process, but single process can hold multiple AppDomains. An AppDomain is relatively cheap to create (compared to a process), and has relatively less overhead to maintain than a process. For these reasons, an AppDomain is a great solution for the ISP who is hosting hundreds of applications. Each application can exist inside an isolated AppDomain, and many of these AppDomains can exist inside of a single process – a cost savings.

AppDomains And You

You’ve created two ASP.NET applications on the same server, and have not done any special configuration. What is happening?

A single ASP.NET worker process will host both of the ASP.NET applications. On Windows XP and Windows 2000 this process is named aspnet_wp.exe, and the process runs under the security context of the local ASPNET account. On Windows 2003 the worker process has the name w3wp.exe and runs under the NETWORK SERVICE account by default.

An object lives in one AppDomain. Each ASP.NET application will have it’s own set of global variables: Cache, Application, and Session objects are not shared. Even though the code for both of the applications resides inside the same process, the unit of isolation is the .NET AppDomain. If there are classes with shared or static members, and those classes exist in both applications, each AppDomain will have it’s own copy of the static fields – the data is not shared. The code and data for each application is safely isolated and inside of a boundary provided by the AppDomain

In order to communicate or pass objects between AppDomains, you’ll need to look at techniques in .NET for communication across boundaries, such as .NET remoting or web services.

Note again: the one caveat to the idea of an AppDomain as a boundary is that ASP.NET applications will run with full trust by default. Fully trusted code can execute native code, and native code can essentially have access to anything inside the process. You’ll need to run applications with partial trust to restrict access to unmanged code and verify all managed code to secure AppDomains.

Shadow Copies and Restarts

Once an assembly is loaded into an AppDomain, there is no way to remove the assembly from the AppDomain. It is possible, however, to remove an AppDomain from a process.

If you copy an updated dll into an application’s bin subdirectory, the ASP.NET runtime recognizes there is new code to execute. Since ASP.NET cannot swap the dll into the existing AppDomain , it starts a new AppDomain. The old application domain is “drain stopped”, that is, existing requests are allowed to finish executing, and once they are all finished the AppDomain can unload. The new AppDomain starts with the new code and begins taking all new requests.

Typically, when a dll loads into a process, the process locks the dll and you cannot overwrite the file on disk. However, AppDomains have a feature known as Shadow Copy that allows assemblies to remain unlocked and replaceable on disk.

The runtime initializes ASP.NET with Shadow Copy enabled for the bin directory. The AppDomain will copy any dll it needs from the bin directory to a temporary location before locking and loading the dll into memory. Shadow Copy allows us to overwrite any dll in the bin directory during an update without taking the web application offline.

Master Of Your Domain

Application domains replace the OS process as the unit of isolation for .NET code. An understanding of application domains will give you an idea of the work taking place behind the scenes of an ASP.NET application. Using the CurrentDomain property of the AppDomain class you can inspect properties about the AppDomain your code is executing in, including the Shadow Copy settings we discussed in this article.

Thursday, April 21, 2011

MVC Tutorial

MVC Architecture Model In ASP.NET


When developing ASP.NET applications the need of reducing code
duplication increases along with their complexity. This is because
testing and performing changes become very difficult tasks when having
many different sources of code with the same functionality.

Model View Controller architecture (or pattern) allows us to separate
different parts of our applications into tiers to fulfill this need.


MVC Overview


Model View Controller architecture aims to separate an application into three parts:


Model: It is the business logic of an application. From an
object oriented perspective it would consist of a set of classes that
implement the critical functionality of an application from a business
point of view.


View: It can consist of every type of interface given to the
user. In ASP.NET the view is the set of web pages presented by a web
application.


Controller: This part of the architecture is the most
difficult to explain, hence the most difficult to implement in many
platforms. The controller is the object that allows the manipulation of
the view. Usually many applications implement Model-Controller tiers
that contain the business logic along with the necessary code to
manipulate a user interface. In an ASP.NET application the controller is
implicitly represented by the code-behind or the server side code that
generates the HTML presented to the user.


Implementing MVC in ASP.NET


A basic diagram that would help us understand perfectly the specific
parts that implement the Model View Controller architecture in an
ASP.NET application is presented below:


MVC implementation in ASP.NET

MVC Model Implementation


When implementing the business logic of an application it is a must
to use a Class Library project in order to generate a .dll file that
will encapsulate all the functionality. This is critical as we as
professional developers would not like to jeopardize the source code of a
software product by placing the actual .cs files as a reference in a
web application.


This type of project can be easily created in Visual Studio 2005 under the Visual C# or Visual Basic tabs:


Creating a Class Library Project

As a tutorial example we will develop a simple calculator under a new namespace we will call "Math".


Once the project is created we will add a class called Calculator:


Adding Calculator class

As the code is very simple and a sample is provided in this tutorial
we will not get into much detail as far as how it is developed. The only
important thing we need to mention is the way errors have to be handled
in this class. Take a look at the following code:


1. protected
float Divide(float
fNumber1, float fNumber2)


2. {

3.
  if (fNumber2 == 0)


4.
 {


5.    
      throw
new Exception(
"Second number cannot be equal to zero.");


6.    }


7.
  return
(fNumber1 / fNumber2);


8. }

When implementing the Divide function we need to ensure that the user
would not be able to set the "fNumber2" parameter (line 1) to zero as a
division between zero does not exist. The validation statement in lines
3-6 takes care of this case but the important fact we need to notice is
that this class will NEVER use specific methods to present errors like
message boxes or writing into labels. Errors captured in the model part
of the architecture ALWAYS have to be presented in the form of
exceptions (line 5). This will allow us to use this object in several
types of applications like ASP.NET applications, Windows applications,
Web services, etc.


Once we have finished coding our Calculator class the project has to
be built in order to get the .dll file we will use in our Web
application.


MVC View-Controller Implementation


The View and the Controller objects will be implemented by using a
common ASP.NET Website. Once we have created our project we need to add
the reference to the .dll file we created before.


The option to do this can be found in the context menu when right-clicking the project in the solution explorer:


Adding the a reference

We can find the file in the path "\bin\Release" (or "\bin\Debug"
depending on how you build your class library) inside our main folder
containing the math class library project:


Adding Math.dll reference

Once we have referenced our library we will create a simple web page
that will allow us to choose between the four basic arithmetic
operations and type two different numbers to operate.


The web page will look like this:


Calculator Web page

In the code behind we need to reference the Math namespace in order
to use our Calculator class. The following statement will do that:


using Math;


As the code for this application is also simple we will only explain the method called when the "Operate!" button is clicked:


1. protected
void btnOperate_Click(object
sender, EventArgs e)


2. {

3.
  if
(pbValidateNumbers())


4.
  {


5.
       Calculator
cOperator = new
Calculator();


6.
        
try


7.
        {


8.
              txtResult.Text
= cOperator.Operate(float.Parse(txtNumber1.Text.Trim()),
float.Parse(txtNumber2.Text.Trim()),
Convert.ToInt16(rblOperations.SelectedValue)).ToString();


9.
              
lbError.Text
= "";

10.
       }


11.
       catch (Exception
ex)



12.
       {


13.
             txtResult.Text
= "";


14.
             lbError.Text
= ex.Message;


15.
       }


16.
 }


17.}


In line 3 we call the bool function "pbValidateNumbers" that will
return true if the numbers typed in both textboxes are valid. These
types of validations have to be performed by the controller object as
they allow the interface to work properly and have nothing to do with
the business logic.

In line 5 we create an instance of our Calculator class so we can
perform the arithmetic operation. We call the method "Operate" (line 8)
and return the value in another textbox. An important thing to mention
is that we have to use a try-catch statement (lines 6-15) to handle any
exception that could be thrown by our method "Operate" as every error
caught in our Calculator class is handled by throwing a "digested"
exception that is readable to the user.


In the code above we can appreciate how well encapsulated the
business logic is, hence it can be reused in several applications
without having to code it again.


Advantages of using MVC in ASP.NET


  • There's no duplicated code.

  • The business logic is encapsulated; hence the controller code is transparent and safer.

  • The business logic can be used in several front ends like Web pages, Web services, Windows applications, services, etc.

  • Exception handling is well managed showing the user only digested error messages.

  • Testing every part of an application is easier as it can be done separately using automated methods.

  • Application changes are easier to apply as they are focused in one part of the architecture only.

Saturday, April 9, 2011

What is CLR in .NET?

What is CLR in .NET?
Common Language Runtime - It is the implementation of CLI. The core runtime engine in the Microsoft .NET Framework for executing applications. The common language runtime supplies managed code with services such as cross-language integration, code access security, object lifetime management, resouce management, type safety, pre-emptive threading, metadata services (type reflection), and debugging and profiling support. The ASP.NET Framework and Internet Explorer are examples of hosting CLR.

The CLR is a multi-language execution environment. There are currently over 15 compilers being built by Microsoft and other companies that produce code that will execute in the CLR.

The CLR is described as the "execution engine" of .NET. It's this CLR that manages the execution of programs. It provides the environment within which the programs run. The software version of .NET is actually the CLR version.

When the .NET program is compiled, the output of the compiler is not an executable file but a file that contains a special type of code called the Microsoft Intermediate Language (MSIL, now called CIL, Common Intermediate Language). This MSIL defines a set of portable instructions that are independent of any specific CPU. It's the job of the CLR to translate this Intermediate code into a executable code when the program is executed making the program to run in any environment for which the CLR is implemented. And that's how the .NET Framework achieves Portability. This MSIL is turned into executable code using a JIT (Just In Time) complier. The process goes like this, when .NET programs are executed, the CLR activates the JIT complier. The JIT complier converts MSIL into native code on a demand basis as each part of the program is needed. Thus the program executes as a native code even though it is compiled into MSIL making the program to run as fast as it would if it is compiled to native code but achieves the portability benefits of MSIL.

WCF Tutorial

Windows Communication Foundation (WCF)

Windows Communication Foundation (WCF) is a dedicated communication framework provided by Microsoft. WCF is a part of .NET 3.0. The runtime environment provided by the WCF enables us to expose our CLR types as services and to consume other existing services as CLR types.
Background:

In the world there are a lot of distributed communication technologies that exist. Some of them are:

  • ASP.NET Web Services (ASMX)
  • Web Services Enhancements (WSE)
  • Messaging (MSMQ)
  • .NET Enterprise Services (ES)
  • .NET Remoting
ExistingTechnologies.gif

Creating and Consuming a Sample WCF Service:


Three major steps are involved in the creation and consumtion of the WCF services. Those are:
  1. Create the Service.(Creating)
  2. Binding an address to the service and host the Service. (Hosting)
  3. Consuming the Service.(Consuming)

Step 1: Creating the Service

In WCF, all services are exposed as contracts. A contract is a neutral way of describing what the service does. Mainly we have four types of contracts:
  1. Service Contract
    This contract describes all the available operations that a client can perform on the service.
    .Net uses "System.ServiceModel" Name space to work with WCF services.

    ServiceContract attribute is used to define the service contract. We can apply this attribute on class or interface. ServiceContract attribute exposes a CLR interface (or a class) as a WCF contract.
    OperationContract attribute, is used to indicate explicitly which method is used to expose as part of WCF contract. We can apply OperationContract attribute only on methods, not on properties or indexers. 
    [ServiceContract] applies at the class or interface level. [OperatiContract] applies at the method level.
  2. Data ContractThis contract defines the data types that are passed into and out of the service.
    [DataContract] attribute is used at the custom data type definition level, i.e. at class or structure level.[DataMember] attribute is used for fields, properties, and events.
  3. Fault Contract
    This contract describes about the error raised by the services.
    [FaultContract(<<type of Exception/Fault>>)] attribute is used for defining the fault contracts.
  4. Message Contracts
    This contract provides the direct control over the SOAP message structure. This is useful in inter-operability cases and when there is an existing message format you have to comply with.
    [MessageContract] attribute is used to define a type as a Message type. [MessageHeader] attribute is used for those members of the type we want to make into SOAP headers[MessageBodyMember] attribute is used for those members we want to make into parts of the SOAP body of the message. 

Sample Service Creation :
[ServiceContract]
          public interface IFirstWCFService
                    {
                   [OperationContract]
                   int Add(int x, int y);
 
 
                   [OperationContract]
                   string Hello(string strName);
                  
                  int Multiplication(int x, int y);
                   }
Here "IFirstWCFService" is a service exposed by using the servicecontract attribute. This service exposes two methods "Add","Hello" by using the [OperationContract] attribute. The method "Multiplication" is not exposed by using the [OperationContract] attribute. So it wnt be avlible in the WCF service.
public class FrtWCFService : IFirstWCFService
    {
        public int Add(int x, int y)
        {
            return x + y;
        }
 
        public string Hello(string strName)
        {
            return "WCF program  : " + strName;
        }
 
        public int Multiplication(int x, int y)
        {
            return x * y;
        }
 
    }
"FrtWCFService" is a class,which implements the interface "IFirstWCFService". This class definse the functionality of methods exposed as services. 


STEP 2:  Binding and Hosting

Each service has an end point. Clients communicates with this end points only. End point describes 3 things :
  1. Address
  2. Binding type
  3. Contract Name (which was defined in STEP 1)


Endpoints.GIF
Address

Every service must be associated with a unique address. Address mainly contains the following  two key factors :
  1. Transport protocal used to communicate between the client proxy and service.
    WCF supports the following transport machinisams:
    • HTTP   (ex : http://  or https:// )
    • TCP     (ex :  net.tcp :// )
    • Peer network   (ex: net.p2p://)
    • IPC (Inter-Process Communication over named pipes) (ex: net.pipe://)
    • MSMQ  (ex: net.msmq://)

  2. Location of the service. Location of the service describes the targeted machine (where service is hosted) complete name (or) path  and optionally port / pipe /queue name.  Example :   localhost:8081  Here local host is the target machine name. 8081 is the optional port number.  Example 2:  localhostThis is with out optional parameter. 

Here are a few sample addresses:
 
 
http://localhost:8001
http://localhost:8001/MyFirstService
net.tcp://localhost:8002/MyFirstService
net.pipe://localhost/MyFirstPipe
net.msmq://localhost/MyFirstService
net.msmq://localhost/MyFirstService
Binding is nothing but a set of choices regarding the  transport protocol (which transport protocal we have to use : http /tcp /pipe etc.) ,message encoding (tells about the message encdong / decoidng technique)  ,communication pattern (whether communication is asynchronous, synchronous,  message queued etc.) , reliability, security, transaction propagation, and interoperability.
WCF defines the nine basic bindings:
Binding Type .Net Class implements this binding Transport Encoding Inter operable Comments
Basic Binding BasicHttpBinding Http / Https Text / MTOM Yes Used to expose a WCF service as a legacy ASMX web service.
TCP binding NetTcpBinding TCP Binary NO TCP is used for cross-machine communication on the intranet.
Peer network binding NetPeerTcpBinding P2P Binary NO In this peer network transport schema is used to communicate.
IPC binding NetNamedPipeBinding IPC Binary NO This uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine.
WSbinding WSHttpBinding Http / Https Text / MTOM Yes This uses Http / Https as a communication schema.
Federated WS binding WSFederationHttpBinding Http / Https Text / MTOM Yes This is a specialization of the WS binding. This offers the support for federated security
Duplex WS binding WSDualHttpBinding Http Text / MTOM Yes This is a WS binding with bidirectional communication support from the service to the client.
MSMQ binding NetMsmqBinding MSMQ Binary NO This supports for disconnected queued calls
MSMQ integration binding MsmqIntegrationBinding MSMQ Binary Yes This is designed to interoperate with legacy MSMQ clients.

Hosting:
Every service must be hosted in a host process. Hosting can be done by using the
  • IIS
  • Windows Activation Service (WAS)
  • Self hosting
     

Hosting Type Advantages Limitations
IIS Hosting IIS manages the life cycle of host process. ( like application pooling, recycling, idle time management, identity management, and isolation) Only HTTP transport schemas WCF service are hosted in IIS.
WAS Hosting
  • WAS supports for all available WCF transports, ports, and queues.
  • WAS manages the life cycle of host process.
Some adv of self hosted processing is missing.
Self Hosting
  • Developer can have explicit control over opening and closing the host.
  • In-Proc hosting can be done.
Missing the host process life cycle management.


IIS Hosting
IIS hosting is the same as hosting the traditional web service hosting. Create a virtual directory and supply a .svc file.
In Vs2008 select a project type: "WCF Service Application". 
ProjectType.GIF

In the solution explorer, under the App_code folder you can find the two files: "IService.cs" and "Service.cs".

"IService.cs" class file defines the contracts. "Service.cs" implements the contracts defined in the "IService.cs". Contracts defined in the "IService.cs" are exposed in the service. 

Check in the Web.Config file, under <system.serviceModel> section: 
<services>
      <service name="Service" behaviorConfiguration="ServiceBehavior">
        <!-- Service Endpoints -->
        <endpoint address="" binding="wsHttpBinding" contract="IService">
          <!--
              Upon deployment, the following identity element should be removed or replaced to reflect the
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity
              automatically.
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services> In this one , end point node specifies the : address, binding type, contract (this is the name of the class that defines the contracts.)
Another end point node endpoint address="mex" specify about the Metadata end point for the service.
Now host this serivce by creating the virtual directory and browse the *.SVC file: 

IISHosting.GIF
 
Hosting with Windows Activation Service (WAS)

WAS is a part of IIS 7.0. It comes with VISTA OS. The hosting with the Windows Activation Service is same as hosting with IIS. The only difference between these two is, IIS supports for HTTP binding only. Whereas WAS supports for all transport schemas.

Self Hosting
In this technique developer is only responsible for providing and managing the life cycle of the host process. In this one host service must be running before the client calls the service.  To host the service we use the .NET class ServiceHost.  We have to create an instance of the "ServiceHost".  Constructor of this class takes two parameters: service type, base address. (Base address can be empty set.)
Uri baseaddress = new Uri("http://localhost:8080");
ServiceHost srvHost = new
ServiceHost(typeof(WCFService.FrtWCFService),baseaddress);


Add the Service End points to the host :

We will use the AddServiceEndpoint() to add an end point to the host. As we are that end point contains three things:  type of service, type of binding, service Name.
So, AddServiceEndpoint() method accepts these three as the required parameters.
srvHost.AddServiceEndpoint(typeof(WCFService.IFirstWCFService), new BasicHttpBinding(), "FirstWCFService");

Adding the Meta Data End points to the host:
For the Meta data, service type will be: typeof(IMetadataExchange)
srvHost.AddServiceEndpoint(typeof(IMetadataExchange), httpBinding, "MEX");
Up to Now, we have created the host process and added the end points to it. Now call the open() method on the host. By calling the Open( ) method on the host, we allow calls in, and by calling the Close( ) method, we stylishly exit the host instance, that means, allowing calls in progress to complete, and yet refusing future new client calls even if the host process is still running
srvHost.Open();

STEP 3: Consuming the Service

With WCF, the client always communicates with the proxy only. Client never directly communicates with the services, even though the service is located on the same machine. Client communicates with the proxy; proxy forwards the call to the service.  Proxy exposes the same functionalities as Service exposed.

ServiceBoundaries.GIF
  
Consuming WCF Service Hosted by IIS/WAS

Consuming WCF service is a very similar way of consuming a web service by using the proxy. To consume the service, in the solution explorer click on "Add service Reference" and add the service created in the STEP1.

AddServiceRef.GIF 



AddServiceRef_2.GIF

A service reference is created under the service reference folder. Use this proxy class to consume the WCF service as we are doing with web services.
ServiceReference1.FirstWCFServiceClient obj = new                 
             UsingWCFService.ServiceReference1.FirstWCFServiceClient();
 
Console.WriteLine(obj.Add(2, 3).ToString());
 
obj.Close();

Alternatively: We can create  the proxy class by using the following command
svcutil.exe [WCFService Address]

This generates a service proxy class, just include this class in to the solution and consume the service.

Consuming by creating the channel factory:

We can consume the service by creating the channel factory manually. While creating the channel, we have to provide the same binding type and end point address where the service is hosted.
IFirstWCFService chnl = new ChannelFactory<IFirstWCFService>
(new BasicHttpBinding(), new EndpointAddress("http://localhost:8080/MYFirstWCFService")).CreateChannel();
Here IFirstWCFService is the service contract interface, that is exposed.