WCF

http://www.codeproject.com/Articles/426776/WCF-Top-Interview-Questions

WCF NEW

Difference between ASP.net Web Service and Windows Communication Foundation

Difference between WCF and ASP.NET Web Service

WCF

ServiceContract and OperationContract attributes are used for defining WCF service.

Supports various protocols like HTTP, HTTPS, TCP, Named Pipes and MSMQ.

Hosted in IIS, WAS (Windows Activation Service), Self-hosting, Windows Service.

Supports security, reliable messaging, transaction and AJAX and REST supports.

Supports DataContract serializer by using System.Runtime.Serialization.

Supports One-Way, Request-Response and Duplex service operations.

WCF are faster than Web Services.

Hash Table can be serialized.

Unhandled Exceptions does not return to the client as SOAP faults. WCF supports better exception handling by using FaultContract.

Supports XML, MTOM, Binary message encoding.

Supports multi-threading by using ServiceBehaviour class.

ASP.NET Web Service

WebService and WebMethod attributes are used for defining web service.

Supports only HTTP, HTTPS protocols.

Hosted only in IIS.

Support security but is less secure as compared to WCF.

Supports XML serializer by using System.Xml.Serialization.

Supports One-Way and Request-Response service operations.

Web Services are slower than WCF

Hash Table cannot be serialized. It can serializes only those collections which implement IEnumerable and ICollection.

Unhandled Exceptions returns to the client as SOAP faults.

Supports XML and MTOM (Message Transmission Optimization Mechanism) message encoding.

Doesn’t support multi-threading.

Web Services (ASMX)

Web Services are used to send/receive messages using the Simple Object Access Protocol (SOAP) via HTTP only. Web Services can be accessed only over HTTP & it works in stateless environment, 

It is available in the namespace “System.Web.Services. WebService Class” with a constructor, methods, prosperities and events.

WCF Service

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another.

WCF is used to exchange messages using any format via any transport protocol like HTTP, TCP/IP, MSMQ, Named Pipes and and so on. Its default format is SOAP.

In what scenarios must WCF be used

The development of web service with ASP.NET relies on defining data and relies on the XmlSerializer to transform data to or from a service.

Key issues with XmlSerializer to serialize .NET types to XML

The WCF uses the DataContractAttribute and DataMemeberAttribute to translate .NET FW types into XML.

[DataContract(Namespace = "http://www.rrd.com/Rrdl/Services/Financial/DataContracts/")]     public class SAPCostContract : FinancialTransactionErrorContract     {                  [DataMember(IsRequired = true)]  [StringConstraints(MaxLength = 50, AllowNullString = false, AllowEmptyString = false)]         public string CostType;                   [DataMember(IsRequired = false)]         public string CostTypeDescription;                  [DataMember(IsRequired = false)]         public decimal CostTotal;      }                       

Hide   Copy Code

[DataContract]  public class Item  {      [DataMember]      public string ItemID;      [DataMember]      public decimal ItemQuantity;      [DataMember]      public decimal ItemPrice; }

The DataContractAttribute can be applied to the class or a strcture. DataMemberAttribute can be applied to field or a property and theses fields or properties can be either public or private.

Important difference between DataContractSerializer and XMLSerializer.

Developing Service

To develop a service using ASP.NET, we must add the WebService attribute to the class and WebMethodAttribute to any of the class methods.

Example

Hide   Copy Code

[WebService]  public class Service : System.Web.Services.WebService  {        [WebMethod]        public string Test(string strMsg)        {            return strMsg;        }  }

To develop a service in WCF, we will write the following code:

Hide   Copy Code

[ServiceContract]  public interface ITest  {         [OperationContract]         string ShowMessage(string strMsg);  }  public class Service : ITest  {         public string ShowMessage(string strMsg)         {            return strMsg;         }  }

The ServiceContractAttribute specifies that an interface defines a WCF service contract, 

OperationContract attribute indicates which of the methods of the interface defines the operations of the service contract.

A class that implements the service contract is referred to as a service type in WCF.

Hosting the Service

ASP.NET web services are compiled into a class library assembly and a service file with an extension .asmx will have the code for the service. The service file is copied into the root of the ASP.NET application and Assemblywill be copied to the bin directory. The application is accessible using URL of the service file.

WCF Service can be hosted within IIS or WindowsActivationService.

Client Development

Clients for the ASP.NET Web services are generated using the command-line tool WSDL.EXE.

WCF uses the ServiceMetadata tool (svcutil.exe) to generate the client for the service.

Message Representation

The Header of the SOAP Message can be customized in ASP.NET Web service.

WCF provides attributes MessageContractAttribute, MessageHeaderAttribute and MessageBodyMemberAttribute to describe the structure of the SOAP Message.

Service Description

Issuing a HTTP GET Request with query WSDL causes ASP.NET to generate WSDL to describe the service. It returns the WSDL as a response to the request.

The generated WSDL can be customized by deriving the class of ServiceDescriptionFormatExtension.

Issuing a Request with the query WSDL for the .svc file generates the WSDL. The WSDL that generated by WCF can be customized by using ServiceMetadataBehavior class.

Exception Handling

In ASP.NET Web services, unhandled exceptions are returned to the client as SOAP faults.

In WCF Services, unhandled exceptions are not returned to clients as SOAP faults. A configuration setting is provided to have the unhandled exceptions returned to clients for the purpose of debugging.

    [DataContract]     public class MathFaultException     {           [DataMember]          public string operation;          [DataMember]          public string problemType;     }      [ServiceContract]     public interface IWcfAddtion     {          [OperationContract]         string GetData(int value);          [OperationContract]         int GetDataUsingDataContract(CompositeType composite);          [OperationContract]         [FaultContract(typeof(MathFaultException))]         CompositeType AddValue(int item1, int item2);     } 

You can catch exception in client using this way.

try     {     }     catch (FaultException exception)     {     } 

State Management

The HttpContext object can be used to update and retrieve application state information by using its Application property, and can be used to update and retrieve session state information by using its Session property.

ASP.NET provides considerable control over where the session state information accessed by using the Session property of the HttpContext is actually stored. It may be stored in cookies, in a database, in the memory of the current server, or in the memory of a designated server. The choice is made in the service’s configuration file.

The WCF provide extensible object for state management which are implemented from IExtensibleObject. Examples of extensible objects areServiceHostBase and InstanceContext. ServiceHostBase allows you to maintain state that all of the instances of all of the service types on the same host can access, while InstanceContext allows you to maintain state that can be accessed by any code running within the same instance of a service type.

Security

ASP.NET web service is used IIS securities which are used in any IIS application. WCF is capable to run in any .NET executable, so it needs independent security capabilities. WCF has many security option, Claim-based Authorization is an one example. It support for authorizing access to protected resources based on claims. Authorization based on claims is accomplished by comparing a set of claims to the access requirements of the operation and, depending on the outcome of that comparison, granting or denying access to the operation. In WCF, you can specify a class to use to run claims-based authorization, once again by assigning a value to the ServiceAuthorizationManager property of ServiceAuthorizationBehavior.

Basic difference between Web Services and Web APIs

Web Service:

1) It is a SOAP based service and returns data as XML.

2) It only supports the HTTP protocol.

3) It can only be hosted on IIS.

4) It is not open source, but can be used by any client that understands XML.

5) It requires a SOAP protocol to receive and send data over the network, so it is not a light-weight architecture.

Web API:

1) A Web API is a HTTP based service and returns JSON or XML data by default.

2) It supports the HTTP protocol.

3) It can be hosted within an application or IIS.

4) It is open source and it can be used by any client that understands JSON or XML.

5) It is light-weight architectured and good for devices which have limited bandwidth, like mobile devices.

Difference between BasicHttpBinding and WsHttpBinding

The difference between WsHttpBinding and BasicHttpBinding is thatWsHttpBinding supports WS-* specification. WS-* specifications are nothing but standards to extend web service capabilities.

Below is a detailed comparison table between both the entities from security, compatibility, reliability and SOAP version perspective.

<wsHttpBinding>     <binding          allowCookies="Boolean"         bypassProxyOnLocal="Boolean"         closeTimeout="TimeSpan"         hostNameComparisonMode="StrongWildCard/Exact/WeakWildcard"         maxBufferPoolSize="integer"         maxReceivedMessageSize="Integer"         messageEncoding="Text/Mtom"          name="string"         openTimeout="TimeSpan"          proxyAddress="URI"         receiveTimeout="TimeSpan"         sendTimeout="TimeSpan"         textEncoding="UnicodeFffeTextEncoding/Utf16TextEncoding/Utf8TextEncoding"         transactionFlow="Boolean"         useDefaultWebProxy="Boolean">         <reliableSession ordered="Boolean"            inactivityTimeout="TimeSpan"            enabled="Boolean" />         <security mode="Message/None/Transport/TransportWithCredential">            <transport clientCredentialType="Basic/Certificate/Digest/None/Ntlm/Windows"                 proxyCredentialType="Basic/Digest/None/Ntlm/Windows"                 realm="string" />           <message               algorithmSuite="Basic128/Basic192/Basic256/Basic128Rsa15/                   Basic256Rsa15/TripleDes/TripleDesRsa15/Basic128Sha256/                   Basic192Sha256/TripleDesSha256/Basic128Sha256Rsa15/                   Basic192Sha256Rsa15/Basic256Sha256Rsa15/TripleDesSha256Rsa15"              clientCredentialType="Certificate/IssuedToken/None/UserName/Windows"              establishSecurityContext="Boolean"              negotiateServiceCredential="Boolean" />         </security>         <readerQuotas maxDepth="integer"             maxStringContentLength="integer"            maxByteArrayContentLength="integer"            maxBytesPerRead="integer"            maxNameTableCharCount="integer" />     </binding> </wsHttpBinding>

  <wsHttpBinding>             <!--The following is the expanded configuration section for a-->             <!--WSHttpBinding. Each property is configured with the default-->             <!--value. See the ReliableSession, TransactionFlow, -->             <!--TransportSecurity, and MessageSecurity samples in the WS -->             <!--directory to learn how to configure these features. -->             <binding name="Binding1"                       bypassProxyOnLocal="false"                       transactionFlow="false"                       hostNameComparisonMode="StrongWildcard"                       maxBufferPoolSize="524288"                       maxReceivedMessageSize="65536"                       messageEncoding="Text"                       textEncoding="utf-8"                       useDefaultWebProxy="true"                       allowCookies="false">               <reliableSession ordered="true"                                inactivityTimeout="00:10:00"                                enabled="false" />               <security mode="Message">                 <message clientCredentialType="Windows"                          negotiateServiceCredential="true"                          algorithmSuite="Default"                          establishSecurityContext="true" />               </security>             </binding>           </wsHttpBinding>

-----------------------------------------------------------------------------------------------------------------------------------

<behaviors>       <endpointBehaviors>         <behavior name="FinancialServiceEndPointBehavior">           <dataContractSerializer maxItemsInObjectGraph="2147483647" />         </behavior>       </endpointBehaviors>       <serviceBehaviors>         <behavior name="FinancialServiceServiceBehavior">           <serviceMetadata httpGetEnabled="true" />           <dataContractSerializer maxItemsInObjectGraph="2147483647" />           <bufferedReceive maxPendingMessagesPerChannel="2147483647" />           <serviceDebug includeExceptionDetailInFaults="true" />         </behavior>       </serviceBehaviors>     </behaviors>     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />     <services>       <service behaviorConfiguration="FinancialServiceServiceBehavior" name="Rrdl.Services.Financial.FinancialService">         <endpoint address="" behaviorConfiguration="FinancialServiceEndPointBehavior" binding="basicHttpBinding" bindingConfiguration="FinancialService.BasicHttpBinding" 

name="FinancialService.BasicHttpEndPoint" contract="Rrdl.Services.Financial.IFinancialService" />         <endpoint address="mex" behaviorConfiguration="FinancialServiceEndPointBehavior" binding="mexHttpBinding" bindingConfiguration="FinancialService.Mex.Binding" 

name="FinancialService.MetaDataEndPoint" contract="IMetadataExchange" />         <host>           <baseAddresses>             <add baseAddress="http://localhost:1932" />           </baseAddresses>         </host>       </service>     </services>     <bindings>       <basicHttpBinding>         <binding name="FinancialService.BasicHttpBinding" closeTimeout="10:00:00" openTimeout="10:00:00" receiveTimeout="10:00:00" sendTimeout="10:00:00" maxBufferSize="2147483647" 

maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Mtom">           <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />         </binding>       </basicHttpBinding>       <mexHttpBinding>         <binding name="FinancialService.Mex.Binding" closeTimeout="02:00:00" openTimeout="02:00:00" receiveTimeout="02:00:00" sendTimeout="02:00:00" />       </mexHttpBinding>     </bindings>   </system.serviceModel>

----------------------------------------------------------------------------------------------------

What is “mexHttpBinding”?

It is a binding that returns metadata so you can build a proxy at the client side. See HERE.

Metadata:http://www.danrigsby.com/blog/index.php/2008/05/27/wcf-metadata/

namespace Metadata.Samples {     [ServiceContract]     public interface ISimpleService     {         [OperationContract]         string SimpleMethod(string msg);     }      class SimpleService : ISimpleService     {         public string SimpleMethod(string msg)         {             Console.WriteLine("The caller passed in " + msg);             return "Hello " + msg;         }     } 

One-Way

In One-Way operation mode, client will send a request to the server and does not care whether it is success or failure of service execution. There is no return from the server side, it is one-way communication.

[ServiceContract]

public interface IMyService {     [OperationContract(IsOneWay=true)]     void MyMethod(EmployeeDetails emp);

    [OperationContract(IsOneWay = true, IsInitiating = false,IsTerminating = true)]     string CloseSessionService(int id);

}

http://wcftutorial.net/One-Way.aspx

[PrincipalPermission(SecurityAction.Demand, Role = "Readers")][OperationContract]bool Read();[PrincipalPermission(SecurityAction.Demand, Role = "Writers")][OperationContract]bool Write();

To utilize AD groups, configure a service behavior:

<system.serviceModel>   <behaviors>     <serviceBehaviors>       <adServiceBehavior>         <serviceAuthorization principalPermissionMode="UseWindowsGroups" />       </adServiceBehavior>     </serviceBehaviors>   </behaviors></system.serviceModel>

Application Domains

Application domains provide a flexible and secure method of isolating running applications.

Application domains are usually created and manipulated by run-time hosts. Occasionally, you may want your application to programmatically interact with your application domains, for example, to unload a component without having to stop your application from running.

Application domains aid security, separating applications from each other and each other's data. A single process can run several application domains, with the same level of isolation that would exist in separate processes. Running multiple applications within a single process increases server scalability.

Application domains have the following properties:

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

Web Services Description Language (WSDL)

ASMX - Active Server Method Extended 

ASPX - Active Server Page Extended 

ASCX - Active Server Control Extended

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

https://sites.google.com/site/onlinearmywarrior/designpatterns/abstract-factory

http://technet.microsoft.com/en-us/library/dd364124(v=ws.10)http://www.dotnetfunda.com/articles/article821-beginners-guide-how-iis-process-aspnet-request.aspx

IIS:

What is an Application Pool?

                                  An Application Pool can contain one or more applications and allows us to configure a level of isolation between different Web applications. 

For example, if you want to isolate all the Web applications running in the same computer, you can do this by creating a separate application pool for every Web application and placing them in their corresponding application pool. Because each application pool runs in its own worker process, errors in one application pool will not affect the applications running in other application pools. Deploying applications in application pools is a primary advantage of running IIS 6.0 in worker process isolation mode because you can customize the application pools to achieve the degree of application isolation that you need.

When you configure application pools for optimum availability, you also should consider how to configure application pools for application security. For example, you might need to create separate application pools for applications that require a high level of security, while allowing applications that require a lower level of security to share the same application pool. In the later part of this article, we will see how to configure identities at the application pool level.

In previous versions of IIS, worker processes ran as LocalSystem, a powerful account that has system administrator privileges on the server. Because LocalSystem has access to almost all resources on 

the operating system, this caused security implications. As mentioned previously, in IIS 6.0, you can set the identity of the worker process at the application pool level. The identity of an application pool is 

the account under which the application pool's worker process runs. By default, application pools operate under the NetworkService account, which has low-level user access rights. 

The NetworkService account has the following seven privileges:

By running the worker process using a very low-privileged account such as NetworkService, you can reduce the security vulnerability. However, by using IIS manager, you can configure the application pool 

to run as any of the following pre-defined accounts:

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

Three ways by which you can handle concurrency in WCF is Single, multiple and reentrant. To specify WCF concurrency we need to use the ‘ServiceBehavior’ tag as shown below with appropriate ‘ConCurrencyMode’ property value.

Figure:

Single: - A single request has access to the WCF service object at a given moment of time. So only one request will be processed at any given moment of time. The other requests have to wait until the request processed by the WCF service is not completed.

Multiple: - In this scenario multiple requests can be handled by the WCF service object at any given moment of time. In other words request are processed at the same time by spawning multiple threads on the WCF server object. So you have great a throughput here but you need to ensure concurrency issues related to WCF server objects.

Reentrant: - A single request thread has access to the WCF service object, but the thread can exit the WCF service to call another WCF service or can also call WCF client through callback and reenter without deadlock.

You can also view video on WCF one way contract as follows: -

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

How to host WCF Self-Hosting?

Step1:    //Create a URI to serve as the base address            // Address as well binding

Uri httpUrl = new Uri("http://localhost:8010/MyService/HelloWorld");

Step2: //Create ServiceHost           

 ServiceHost host = new ServiceHost(typeof(ClassLibrary1.HelloWorldService),httpUrl);

Step3: //Add a service endpoint      

host.AddServiceEndpoint(typeof(ClassLibrary1.IHelloWorldService) , new WSHttpBinding(), "");

Step4: //Enable metadata exchange

ServiceMetadataBehavior smb = new ServiceMetadataBehavior();smb.HttpGetEnabled = true;            host.Description.Behaviors.Add(smb);

Step5: //Start the Service           

host.Open();

Step6:

Console.WriteLine("Service is host at " + DateTime.Now.ToString());           Console.WriteLine("Host is running... Press <Enter> key to stop");            Console.ReadLine();

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

Basic Httpbinding:In httpbinding Data is sent as a plain text.In other words,there is no security provided for the message when the client calls happen.

This is aimed for clients who do not have .NET 3.0 installed and it supports wider ranges of clients. Many of the clients like Windows 2000 still do not run .NET 3.0. So older version of 

.NET can consume this service.It uses SOAP1.1 version.

WShttpbinding:As WsHttBinding supports WS-*, it has WS-Security enabled by default.

 So the data is not sent in plain text.As its built using WS-* specifications, 

it does not support wider ranges of client and it cannot be consumed by older .NET version less than 3 version.It uses SOAP 1.2 and WS-Addressing specification.

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

In WCF there are two types of Security, transport level security and message level security.

Transport Security: Transport level security happens at the channel level. Transport level security is the easiest to implement as it happens at the communication level. WCF uses transport protocols like TCP, HTTP, MSMQ etc and every of these protocols have their own security mechanisms.  One of the common implementation of transport level security is HTTPS. HTTPS is implemented over HTTP protocols with SSL providing the security mechanism.  No coding change is required it’s more of using the existing security mechanism provided by the protocol.

Message Security: Message level security is implemented with message data itself. Due to this it is independent of the protocol.  Some of the common ways of implementing message level security is by encrypting data using some standard encryption algorithm.

Advantages 

 .Net Remoting is a distributed objects infrastructure. It allows processes to share objects to call methods on and access properties of objects that are hosted in different application domains with in the same process, different processes executing on the same computer, on computers on an intranet or on computers distributed over wide areas 

 .Net Remoting supports many different communivations protocols including SOAP/HTTP protocol used by ASP.Net web services. Net Remoting on the other hand can share objects from any type application. 

 .Net Remoting system is an integral part of the .NET Framework supports full .Net type system fidelity. We can pass any object across the wire to client. Disadvantages 

 There is no security built in the .Net Remoting infrastructure the application layer. 

 Remoting applications are tightly coupled. They rely on assembly metadata to describe types which means that any application that communivates with another must have some intimate knowledge of the others inner working. The contract between Remoting applications is the class interface. 

 The dependence on assembly metadata implies the client applications must understand .NET concepts. As a result applications that make use of Net Remoting are not operable with other systems. 

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. 

Second 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.