Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Sunday, November 21, 2010

WCF Contracts


WCF supports following contracts:
1. Service Contract
2. Operation Contract
3. Message Contract
4. Fault Contract

Service Contract: We can use this service contract attribute on interface which will be exposed to client to consume the WCF service.

[ServiceContract]
public interface IStudentContract
{
[OperationContract()]
List GetStudents();

[OperationContract]
Student GetStudent(int studentId);

}

Here we added “ServiceContract” attribute to IStudentContract interface. So WCF will expose this interface as a WCF service.

Operation Contract: We need to use “OperationContract” attribute to the methods which needs to be exposed as a service method. In above example, We have added “OperationContract” attribute to “GetStudents” and “GetStudent” methods.

Message Contract: Sometime we need to change SOAP message format, then we can use Message contract. We can place some variables in body and some in header part as per requirement.

[MessageContract]
public class Student
{
[MessageHeader]
public int StudentId;

[MessageBodyMember]
public string StudentName;

[MessageBodyMember]
public int Standard;
}

Here, student class is decorated as a MessageContract attribute. When we transfer object of student class between client and service then WCF will include “StudentId” attribute to Message Header and “StudentName” and “Standard” attribute in Message Body.

Fault Contract: Fault contract is used to managing fault (exception) in WCF service. You can decorate any class as a Fault contract and send it as an Exception from service to client.

ABC of WCF


ABC of WCF is “Address, Binding and Contract”. Address part specify where the service is available. Binding part specify which protocol and encoding method, service is using. And Contract specify which message format, service is expected from the client.

Address:
WCF supports many types of addresses to host/consume WCF service like HTTP, HTTPS, Net TCP, Net MSMQ etc... Address gives information where client needs to send message.

Binding:

WCF supports following in-build binding:

1. basicHttpBinding
2. wsHttpBinding
3. wsDualHttpBinding
4. wsFederationHttpBinding
5. netTcpBinding
6. netNamedPipeBinding
7. netMSMQBinding
8. netPeerTcpBinding
9. webHttpBinding
10. msmqIntegrationBinding

Binding gives information about the protocol and encoding method to send the message.

Contract:
Contract expose functionality to client. Contract have message signature so client can send the message to service via consuming service contract.

WCF Hosting Options


WCF gives facility to developer to host their WCF service on following hosting options:

1. IIS
2. Console Application
3. Windows Application
4. Windows Service
5. Self Hosting

IIS:
Developer can host WCF service on IIS. We need to create virtual directory in IIS and create SVC file for exposing WCF service. After doing that, IIS will take care of availability of service. Whenever you will start your machine, WCF service will be available to your customer. You don't required to start any program.

IIS also gives some in-built functionality like web gardening, web farming, recycling etc.

Console application:
Developer can host WCF service on Console application. This option mainly used for testing purpose. You must need to start Console application for service availability. If anybody will close console application then service will not be available to any customer for consumption.

Windows Application:
Developer can host WCF service on Windows application. This option also mainly used for testing purpose. You must need to start Windows application for service availability. If anybody will close windows application then service will not be available to any customer for consumption.

Windows Service:
Developer can also host WCF service in Windows Service. Windows service runs in background. This option is best option to host WCF service if IIS is not available on the server. You can set windows service startup property to Automatic. Windows service will start as soon as machine start so you don't need to start any application for service availability.

Self hosting:
WCF also provides facility to host itself. This used for only testing purpose on developer machine. You can select WCF service project and mark it as startup project. After running the project, Visual Studio IDE will host the WCF service in itself.

WCF Tenets


There are four tenets of WCF:

1. Service boundaries are explicit
In WCF, we must need to expose the service contract to client so client can consume the service and call service method. If we will expose the implemented class then it will mess the boundaries of your service.
2. Service are autonomous
Service must be give full information about itself to client who wants to consume it like address where service is available, which message format service is expected, what transport service is using to receive messages etc.
3. Share Schema not the implementation
Expose only service contract (interface) to client. Never share implemented code to client. It will be very difficult to manage the changes if we will share code with the clients. We need to change code to every place if any change needs into service code.
4. Service Compatibility is Policy based
Service compatibility must be policy based so whenever Admin user will change any policy developer does not required to change accordingly.

What is WCF


WCF stands for Windows Communication Foundation. Foundation means the framework. In short WCF is framework to communicate applications on windows platform.

Earlier, We (Microsoft .Net developer) use different different methodologies to develop application which communicate with different application. For example, If you want to send/receive messages from another application which is developed in Java then you must need to go with ASPX based web service and if you want to communicate application in organization boundary then you can choose .Net remoting. There are lots of way to develop application which can send/receive messages. Some of them are listed below:

• ASPX based Web service
• .Net remoting
• MSMQ based application
• COM+

But when you want to change your application from one method to another then you need to write it from the beginning. Because it is not feasible to migrate from one method to another. So Microsoft have put all those methodologies and create new framework where developer does not required to worry about communication methodologies.

WCF provides most of all the communication methodologies.

WCF is loosely coupled service. You can host your WCF service on any type of applications like

IIS
Console Applications
Windows Application
Windows Service

Wednesday, April 7, 2010

Get Windows Username in WCF service method


For configuring windows authentication in WCF service, please refer my previous blog Windows Authentication in WCF

In some scenario, we need to find out the user name who calls WCF service method. You can find out current logged in user who called WCF service method using below code:


OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name


The above property will return logged in user name with domain name. For example, it returns “DOMAIN\USER”.

windows authentication in WCF


WCF stands for Windows Communication Foundation. WCF provides functionality to create service library. Now a day, everyone wants to implement their solution as a service so anybody else can consume it and will use it.

For example, online payment integration software gives functionality to integrate their API with your application like First Data Global gateway, PayPal etc…

WCF use to expose these services so any client can consume those services and use the service. Some services are not required any authorization to use it. But some services needs authentication before using it. We can develop security in many ways in WCF service. Common ways are defined below:

  • Windows Authentication
  • Form Authentication (Custom Authentication)
  • Certificate base authentication

Here I talked about Windows authentication to secure your service. Windows authentication use logged on user for authentication.

Follow below steps to implement Windows authentication in your WCF service.
  • Create new “WCF Service Application” project from File menu and selecting “New Project” option and select “Web” as a project type and “WCF Service Application” as a project template.
  • Update SerivceModel section in web.config which is given below
  • Also check authentication mode is Windows. If not then change it with “Windows”
  • Open IIS and select virtual directory.
  • In virtual directory property windows, Select “Directory Setting” tab and click on Edit button under “Anonymous access and authentication control”.
  • Remove anonymous access and select “Integrated Windows Authentication”.

Snap of updated web.config file:

<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="WCFWindowsBasicHttpBinding.Service1Behavior" name="WCFWindowsBasicHttpBinding.Service1">
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="BasicHttpEndpointBinding"
name="BasicHttpEndpoint" contract="WCFWindowsBasicHttpBinding.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCFWindowsBasicHttpBinding.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>


We have mentioned security mode in binding section and bind that binding configuration with endpoint. Also remove the “mex” endpoint from the list of end points.

Now service is ready to use. You can consume the service in your client application. You have to pass user credential before calling WCF service. In client application, give following code before calling WCF service method:


Service1 client = new Service1();
client.Credentials = System.Net.CredentialCache.DefaultCredentials;


This will assign current user credential to service object. Now when you will call WCF service method, WCF will execute that method in context of that logged in user.

If user doesn’t have access on this method then WCF service will return with authentication failure exception.

You can download code from here.

DotNet Code Guru