Wednesday, April 21, 2010

Windows Communication Foundation (WCF)

What is WCF?
Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.

WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it.

Which Namespace is used to access WCF service?
System.ServiceModel


Difference between WCF and Webservice?
  • Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type. 
  •  Web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends. 
  •  We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc 
  •  WCF is flexible because its services can be hosted in different types of applications. The following lists several common scenarios for hosting WCF services:    
          IIS         
         WAS
         Self-hosting
         Managed Windows Service
  •  Webservice works in stateless environment
What are the various ways of hosting WCF services?
There are three major ways of hosting a WCF services
  • Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class.
  • Host in application domain or process provided by IIS Server.
  • Host in Application domain and process provided by WAS (Windows Activation Service) Server.

What was the code name for WCF?
The code name of WCF was Indigo .

WCF is a unification of .NET framework communication technologies which unites the following technologies:-

NET remoting
MSMQ
Web services
COM+


What are the main components of WCF?
The main components of WCF are

1. Service class
2. Hosting environment
3. End point


How to set the timeout property for the WCF Service client call?
The timeout property can be set for the WCF Service client call using binding tag.

<client>  
   <endpoint  
      ...  
      binding = "wsHttpBinding"  
      bindingConfiguration = "LongTimeout"   
      ...  
   />  
</client>  
<bindings>  
   <wsHttpBinding>  
      <binding name = "LongTimeout" sendTimeout = "00:04:00"/>   
   </wsHttpBinding>  
</bindings>


If no timeout has been specified, the default is considered as 1 minute.


What is transport reliability and Message reliability?
Transport reliability (such as the one offered by TCP) offers point-to-point guaranteed delivery at the network packet level, as well as guarantees the order of the packets. Transport reliability is not resilient to dropping network connections and a variety of other communication problems.

Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service.


What are the different elements of WCF Services Client configuration file?

WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like


<system.serviceModel>  
   <client>  
      <endpoint name = "MyEndpoint"  
         address  = "http://localhost:8000/MyService/"  
         binding  = "wsHttpBinding"  
         contract = "IMyContract"  
      />  
   </client>  
</system.serviceModel>  


What are contracts in WCF?

In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.

WCF defines four types of contracts.

Service contracts
Describe which operations the client can perform on the service.

There are two types of Service Contracts.
ServiceContract - This attribute is used to define the Interface.
OperationContract - This attribute is used to define the method inside Interface.

[ServiceContract]  
interface IMyContract  
{  
   [OperationContract]  
   string MyMethod( );  
}  
class MyService : IMyContract  
{  
   public string MyMethod( )  
   {  
      return "Hello World";  
   }  
}


Data contracts
Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.

There are two types of Data Contracts.
DataContract - attribute used to define the class
DataMember - attribute used to define the properties.


[DataContract]  
class Contact  
{  
   [DataMember]  
   public string FirstName;  
  
   [DataMember]  
   public string LastName;  
}


If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service.

Fault contracts
Define which errors are raised by the service, and how the service handles and propagates errors to its clients.


Message contracts
Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.


What is endpoint in WCF?
Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.

The Endpoint is the fusion of Address, Contract and Binding.


What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

WCF supports nine types of bindings.

Basic binding
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.

TCP binding
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.

Peer network binding
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.


IPC binding
Offered by the NetNamedPipeBinding class, 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 and it supports a variety of features similar to the TCP binding.


Web Service (WS) binding
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.


Federated WS binding
Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.


Duplex WS binding
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.


MSMQ binding
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.


MSMQ integration binding
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.


Where we can host WCF services?
Every WCF services must be hosted somewhere. There are three ways of hosting WCF services.

They are

1. IIS
2. Self Hosting
3. WAS (Windows Activation Service)


What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.

WCF supports following transport schemas

HTTP
TCP
Peer network
IPC (Inter-Process Communication over named pipes)
MSMQ

The sample address for above transport schema may look like

http://localhost:81
http://localhost:81/MyService
net.tcp://localhost:82/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService


What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world.

The client of a service is merely the party consuming the service.

Tuesday, April 6, 2010

How Authentication and Authorization Works?

The following section lists the sequence of events that take place in the authentication and authorization process when a new request arrives.

The IIS first checks the validity of the incoming request. If the authentication mode is anonymous (default) then the request is authenticated automatically. But if this authentication mode is overridden in the web.config file settings, the IIS performs the specified authentication check first before the request is passed on to ASP.NET.

Now ASP.NET checks whether Impersonation is enabled or not. If impersonation is enabled, ASP.NET executes with the identity of the entity on behalf of which it is performing executing the task. If impersonation is not enabled, the application runs with the identity of the IIS local machine’s identity and the privileges of the ASP.NET user account. ASPNET or NETWORK SERVICE is the default ASP.NET unprivileged account on Windows XP and Windows Server 2003, respectively. Now, the identity that has already been authenticated and verified is used to request resources from the operating system. Then ASP.NET performs an authorization check on the requested resources and if the user is authorized, it returns the request through IIS.

What is Authorization in ASP.Net?

Authorization

Authorization is the process of determining the accessibility to a resource for a previously authenticated user. Note that authorization can only work with authenticated users, hence ensuring that no un-authenticated user can access the application. The default authentication mode is anonymous authentication. There can be three types of authorization in ASP.NET. They are

·         URL Authorization

·         File Authorization

·         Authorization based on ACLs

Authorization like authentication is specified in the web.config file of the application. The following specification in the web.config file allows or grants access to the user Joydip but denies the same to Jini and all anonymous users.  Note that the allow/ and deny/ element ordering is important, since the first one that matches the request will be used.  Hence, if you were to add a deny users="*" / to the top of the list, it would always deny everyone, regardless of any allow / elements that followed it.

authorization
  allow users="Joydip"/
  deny users="Jini"/
  deny users="?"/
/authorization

Authentication in ASP.Net

Authentication

Authentication is the process of determining the authenticity of a user based on the user’s credentials. Whenever a user logs on to an application, the user is first authenticated and then authorized. The application’s web.config file contains all of the configuration settings for an ASP.NET application. It is the job of the authentication provider to verify the credentials of the user and decide whether a particular request should be considered authenticated or not. An authentication provider is used to prove the identity of the users in a system. ASP.NET provides three ways to authenticate a user:

· Forms authentication

· Windows authentication

· Passport authentication

Hence, ASP.NET contains the three respective authentication providers to support the above authentication modes.

Forms Authentication

This authentication mode is based on cookies where the user name and the password are stored either in a text file or the database. After a user is authenticated, the user’s credentials are stored in a cookie for use in that session. When the user has not logged in and requests for a page that is insecure, he or she is redirected to the login page of the application. Forms authentication supports both session and persistent cookies. Authentication modes can be specified in the application’s web.config file as shown below:

Listing 1

configuration
system.web
    authentication mode="[Windows/Forms/Passport/None]"
    /authentication
/system.web
/configuration

The following needs to be specified in the application’s web.config file for using Forms Based Authentication in ASP.NET:

Listing 2

configuration
system.web
authentication mode="Forms"/
    forms name="login"loginUrl="login.aspx" /
   authorization
        deny users="?"/
/authorization
/system.web
/configuration

Note: The statement in the web.config file as stated in Listing 2 implies that all permissions are granted only to the authenticated users. The users who are not authenticated are not granted any permission. The symbol "?" indicates all Non Authenticated and Anonymous users.

Generally the user’s credentials are stored in the database and the entered credentials are verified using those that are stored in the database. Typically, the user enters the username and the password, clicks the login button and the form validates the values against values from the database. This is shown in the code snippet below:

Listing 3

if (Verify (txtUserName.Text, txtPassword.Text))
{
  FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False);
    else
  lblMessage.Text = "Invalid login name orpassword specified...";
}

private Verify(string userName, string password)
{
      //Usual Code to connect to the DB
      // and verify the user's credentials
}

The static method RedirectFromLoginPage creates an authentication ticket and is used to redirect an authenticated user back to the originally requested URL or the default URL. The authentication ticket creates a persistent cookie that becomes a part of the HttpResponse object. Later, when the user tries to access a page in a restricted folder, the ASP.NET framework uses the cookie to retrieve the ticket and determine whether the user has access to that particular resource. The first parameter to this method identifies the user while the second is used to specify whether the user’s authentication cookie needs to be persisted across multiple site visits.

The user’s credentials can be also be specified in the web.config file as shown below:

Listing 4
 

configuration
   system.web
    authentication mode="Forms"
    forms loginUrl="login.aspx"
        credentialspasswordFormat="Clear"
            user name="Joydip"password="Joydip" /
        /credentials
    /forms
    /authentication
        authorization
    /system.web
/configuration

Windows Authentication

This is the default authentication mode in ASP.NET. Using this mode, a user is authenticated based on his/her Windows account. Windows Authentication can be used only in an intranet environment where the administrator has full control over the users in the network. The following should be set in the web.config file to use Windows Authentication:

Listing 5

authentication mode="Windows"/

authorization
allow users ="*" /
/authorization

Note: The symbol "*" indicates all users inclusive of Authenticated and Anonymous users. Hence the statement in the web.config file as stated in Listing 5 indicates that all permissions are granted to both the Anonymous and Authenticated users.

Windows authentication can be of the following types

·         Anonymous Authentication

·         Basic Authentication

·         Digest Authentication

·         Integrated Windows Authentication

Passport Authentication

Passport authentication is a centralized authentication service that uses Microsoft's Passport Service to authenticate the users of an application. It allows the users to create a single sign-in name and password to access any site that has implemented the Passport single sign-in (SSI) service. The following code shows how we can specify Passport Authentication in the web.config file:

Listing 6
 

configuration
  system.web
    authenticationmode="Passport"
      passportredirectUrl="login.aspx" /
    /authentication
    authorization
      deny users="?" /
    /authorization
  /system.web
/configuration

ASP.NET also supports custom authentication. In such a case the authentication mode has to be specified as none in the web.config file as shown below:
 

authentication mode="none"

Then we need to write our own custom authentication provider.

How to create appdomain?

In the following cases generally we create an application domain
1. If we create our own runtime host application,
2. If our application needs to create or work with additional application domains that are not automatically generated by the runtime.
3. If the requirement is such that some assemblies have to be managed personally, If this is the case we create our own application domain, load the assemblies that are supposed to be managed personally into application Domain.
AppDomain Class has CreateDomain() method
//To create an app Domain Explicitly
AppDomain.CreateDomain("AppDomainName");
Console.WriteLine(app.FriendlyName); // Displays child domain name
Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); // Displays Host Domain name

Unloading :
When you call a Web service by using SSL and an application domain must be unloaded If the call is in progress, the application domain does not unload, a System.CannotUnloadAppDomainException exception is thrown, and the Microsoft ASP.NET worker process may die. So when we make a call to web service using SSL we explicitly unload the application domain programmatically by AppDomain.Unload method
Note: An application domain may be unloaded for some reason that is unrelated to calling the Web service. For example, if the Web.config file is modified, the application domain may be unloaded

what is the use of appdomain?

Operating systems and runtime environments typically provide some form of isolation between applications. For example, Microsoft Windows uses processes to isolate applications. This isolation is necessary to ensure that code running in one application cannot adversely affect other, unrelated applications.

Application domains provide an isolation boundary for security, reliability, and versioning, and for unloading assemblies. Application domains are typically created by runtime hosts, which are responsible for bootstrapping the common language runtime before an application is run.

What is application domain ?

The application Domain is used to isolate an application from other applications. One process has its own virtual memory and does not over lap the other process's virtual memory; due to this one process can not crash the other process. As a result any problem or error in one process does not affect the other process. In .Net they went one step ahead introducing application domains. In application domain multiple applications can run in same process with out influencing each other. If one of the application domains throws error it does not affect the other application domains.