Quantcast
Sunday 28 november 2010 7 28 /11 /Nov /2010 07:11
 

WCF FAQ Part 3 – 10 security related FAQ

Get Interview tutorials and videos on .NET 3.5, 4.0, WCF,ASP.NET, SQL Server, CAS, Security, WCF, SharePoint, Azure, OOPS and many more on www.questpond.com


This 10 minutes small video explains how transport security can be implemented using SSL in WCF services.


 




Introduction and Goal


WCF FAQ Part 1 and 2 series

What are the core security features that WCF addresses?

What is transport level and message level security?

For which bindings are transport, message and mixed mode supported?

So what are the scenarios, advantages and disadvantages of transport VS message security?

Can you explain a simple example of how to implement transport security?

Can you show a simple example of message level security ?

What is the difference between BasicHttpBinding and WsHttpBinding ?

Can you show the security differences between BasicHttpBinding VS WsHttpBinding ?

When should we use WsHttp as compared to BasicHttp ?

How can we enable windows authentication on WCF using ‘BasicHttpBinding’?

Source Code

 

 

Introduction and Goal

In this article we will start with transport and message security understanding. We will then see simple code samples of how to implement transport and message security using WsHTTP bindings. We will also see what is the difference between ‘BasicHttpBinding’ and ‘WsHttpBinding’ with the help of a simple source code. WCF security is a huge topic by itself, but we are sure with this article you will get a quick start of how to go about WCF security.

I have collected around 400 FAQ questions and answers in WCF, WPF, WWF, SharePoint, design patterns, UML etc. Feel free to download these FAQ PDF’s from my site http://www.questpond.com


What are the core security features that WCF addresses?

There are four core security features that WCF addresses:-

Confidentiality: This feature ensures that the information does not go in wrong hands when it travels from the sender to the receiver.

Integrity: This feature ensures that the receiver of the message gets the same information that the sender sends without any data tampering.

Authentication: This feature verifies who the sender is and who the receiver is.

Authorization: This feature verifies whether the user is authorized to perform the action they are requesting from the application.





What is transport level and message level security?

When we talk about WCF security there are two aspects, the first is the data and the second is the medium on which the data travels i.e. the protocol. WCF has the ability to apply security at the transport level (i.e. protocol level) and also at message level (i.e. data).





Figure: - Transport and Message level 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 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.


For which bindings are transport, message and mixed mode supported?

Note :- The below table is taken from book Pro WCF: Practical Microsoft SOA Implementation -- Chris peiris and Denis mulder – Apress 2007

Below is a table which shows for which binding which mode is supported. We did not discuss the mixed mode. It’s nothing but combination of transport and mixed mode. For instance data encrypted and passed over WsHttp using HTTPS is a mixed mode of security. Encryption is nothing but message security and HTTPS is a transport mode. In a combination they form mixed mode.

Binding

Transport Mode?

Message Mode?

Mixed Mode?

BasicHttpBinding

Yes

Yes

Yes

WsHttpBinding

Yes

Yes

Yes

WsDualHttpBinding

No

Yes

No

NetTcpBinding

Yes

Yes

Yes

NetNamedPipeBinding

Yes

No

No

NetMsmqBinding

Yes

Yes

No

MsmqIntegrationBinding

Yes

No

No

 

So what are the scenarios, advantages and disadvantages of transport VS message security?

 

 

Transport

Message

Scenarios when we should be using one of them

When there are no intermediate systems in between this is the best methodology.  

If it’s an intranet type of solution this is most recommended methodology.

When there are intermediate systems like one more WCF service through which message is routed then message security is the way to go.

Advantages

  • Does not need any extra coding as protocol inherent security is used.
  • Performance is better as we can use hardware accelerators to enhance performance.
  • There is lot of interoperability support and communicating clients do not need to understand WS security as it’s built in the protocol itself.

 

  • Provides end to end security as it’s not dependent on protocol. Any intermediate hop in network does not affect the application.
  • Supports wide set of security options as it is not dependent on protocol. We can also implement custom security.

Disadvantages

  • As it’s a protocol implemented security so it works only point to point.
  • As security is dependent on protocol it has limited security support and is bounded to the protocol security limitations.
  • Needs application refactoring to implement security.
  • As every message is encrypted and signed there are performance issues.
  • Does not support interoperability with old ASMX webservices/





Figure: - Route paths
 

Can you explain a simple example of how to implement transport security?

Let’s make a simple sample which will demonstrate how we can use transport security using WsHttp binding with HTTPS security.

Step 1:- Create a simple service using WCF project

The first step is to create a simple WCF project. So click on new project and select WCF service project. By default WCF project creates a default function ‘GetData()’. We will be using the same function for this sample.

public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}

Step 2 :- Enable transport level security in the web.config file of the service

Next step is to enable transport security in WsHttp binding. This is done using the ‘Security’ XML tag as shown in the below code snippet.

<bindings>
<wsHttpBinding>

<binding name="TransportSecurity">
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</wsHttpBinding>
</bindings>

Step 3:- Tie up the binding and specify HTTPS configuration

We need now tie up the bindings with the end points. So use the ‘bindingConfiguration’ tag to specify the binding name. We also need to specify the address where the service is hosted. Please note the HTTS in the address tag.

Change ‘mexHttpBinding’ to ‘mexHttpsBinding’ in the second end point.

<service name="WCFWSHttps.Service1" behaviorConfiguration="WCFWSHttps.Service1Behavior">
<!-- Service Endpoints -->

<endpoint address="https://localhost/WCFWSHttps/Service1.svc" binding="wsHttpBinding" bindingConfiguration="TransportSecurity" contract="WCFWSHttps.IService1"/>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>

</service>
In the ‘serviceMetadata’ we also need to change ‘httpGetEnabled’ to ‘httpsGetEnabled’.
<serviceBehaviors>
........
.........
<serviceMetadata httpsGetEnabled="true"/>
.........
.........
</serviceBehaviors>


Step 4:- Make the web application HTTPS enabled

Now that we are done with the WCF service project creation and the necessary configuration changes are done. It’s time to compile the WCF service project and host the same in IIS application with HTTPS enabled.

We will be using ‘makecert.exe’ which is a free tool given by Microsoft to enable HTTPS for testing purpose. MakeCert (Makecert.exe) is a command-line tool that creates an X.509 certificate that is signed by a system test root key or by another specified key. The certificate binds a certificate name to the public part of the key pair. The certificate is saved to a file, a system certificate store, or both.

You can get the same from “C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin” or you can also get it from windows SDK.

You can type the below thing through your dos prompt on “C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin”. Please note “compaq-jzp37md0” is the server name so you need to replace with your PC name.

makecert -r -pe -n "CN= compaq-jzp37md0 " -b 01/01/2000 -e 01/01/2050 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12
 

If you run the same through your command prompt you should get a succeeded message as shown below.




Now it’s time to assign this certificate to your IIS website. So go to IIS properties , click on directory security tab and you should see server certificate tab.





So click on the server certificate tab and you will then be walked through an IIS certificate wizard. Click ‘Assign a existing certificate’ from the wizard.



You can see a list of certificates. The “compaq-jzp37md0” certificate is the one which we just created using ‘makecert.exe’.




Now try to test the site without ‘https’ and you will get an error as shown below….That means your certificate is working.





Do not forget to enable IIS anonymous access.

Step 5:- Consume the service in a web application

It’s time to consume the service application in ASP.NET web. So click on add service reference and specify your service URL. You will shown a warning box as shown in the below figure. When we used makecert.exe we did not specify the host name as the service URL. So just let it go.


Step 6:- Suppress the HTTPS errors

‘makecert.exe’ creates test certificates. In other words it’s not signed by CA. So we need to suppress those errors in our ASP.NET client consumer. So we have created a function called as ‘IgnoreCertificateErrorHandler’ which return true even if there are errors. This function is attached as a callback to ‘ServicePointManager.ServerCertificateValidationCallback’.

In the same code you can also see service consuming code which calls the ‘GetData’ function.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplicationConsumer.ServiceReference1;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace WebApplicationConsumer
{
public partial class _Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler); 
Service1Client obj = new Service1Client();
Response.Write(obj.GetData(12));
}
public static bool IgnoreCertificateErrorHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
}


Step 7:- Enjoy success

Now to the easiest step, compile you ASP.NET client and enjoy success.

Can you show a simple example of message level security ?

Let’s do a simple example of message security using Wshttp with X509 certificates.

Step 1:- Create client and server certificates

Create two certificates one for the server and the other for the client using makecert.exe. You can get makecert.exe from “C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin” folder. So you can goto dos prompt and run the below command snippet.

makecert.exe -sr CurrentUser -ss My -a sha1 -n CN=WCfServer -sky exchange -pe
makecert.exe -sr CurrentUser -ss My -a sha1 -n CN=WcfClient -sky exchange -pe
 

Below is a detailed explanation of various attributes specified in the ‘makecert.exe’.


Attribute

Explanation

-sr

Specifies the registry location of the certificate store. The SubjectCertStoreLocation argument must be either of the following:
currentUser
Specifies the registry location HKEY_CURRENT_USER.
localMachine
Specifies the registry location HKEY_LOCAL_MACHINE.

-ss

Specifies the name of the certificate store where the generated certificate is saved.

-a

Specifies the algorithm. Can be either MD5 or SHA1.

-n

Specifies a name for the certificate. This name must conform to the X.500 standard. The simplest method is to use the "CN=MyName" format.If the /n switch is not specified; the default name of the certificate is "Joe's Software Emporium".

-sky

Specifies how will be the key type. Can be either exchange or signature.

-pe

This makes the key exportable.




Note: - Makecert.exe is a free tool provided by Microsoft which helps to create X.509 certificate that is signed by a system test root key or by another specified key. This is a test certificate and not a real one and should not be used for production purpose. For production buy proper certificates from Thawte, Verisign, GeoTrust etc.
 

Currently we have specified that we want to create the client key with ‘WcfClient’ name and server key with ‘WCFServer’. The certificates should be created for the current user and should be exportable.


Once you run the command you should see the ‘Succeeded’ message as shown in the below figure. Below figure shows keys created for both server and client.




Step 2 :- Copy the certificates in trusted people certificates

Go to start à run and type MMC and press enter. You will be popped with the MMC console. Click on file à Add/remove snap-in.




ou will be popped up with a Add/Remove Snap-in , click on the add button , select certificates and select ‘My user Account’.
You can see the certificates created for client and server in the personal certificates folder. We need to copy those certificates in trusted people à certificates folder.




Step 3 :- Specify the certification path and mode in the WCF service web.config file

Now that we have created both the certificates we need to refer these certificates in our WCF project.
So we have created two projects one which has the WCF service and the other project is a web application which will consume the WCF service.




Let’s open the web.config file of the WCF service and enter two important things:-
• Where the certificate is stored, location and how WCF application should find the same. This is defined using ‘serviceCertificate’ tag as shown in the below snippet.
• The ‘certificationvalidationmode’ defines how client certificates will be authenticated.


Certification validation mode

Description

Chain trust

In this situation the client certificate is validated against the root certificate.

Peer trust

PeerTrust ensures that the public key portion of the certificate is in the Trusted People certificate folder on the clients computer

ChainORPeertrust

This is just a OR condition for both chain and peer.




The above two points is clubbed together and entered in the web.config file of the WCF service.

<serviceCredentials>

<clientCertificate>
<authentication certificateValidationMode="PeerTrust"/>
</clientCertificate>
<serviceCertificate findValue="WCfServer"
storeLocation="CurrentUser"
storeName="My"

x509FindType="FindBySubjectName" />
</serviceCredentials>


Step 4 :- Define bindings

Now that we have defined our certificates and authentication type we need to define that the authentication values will be sent through message using certificates. You can see we have defined the ‘WsHttpBinding’ with message attribute specifying that the WCF client needs to send a certificate for validation.

<bindings>

<wsHttpBinding>
<binding name="wsHttpEndpointBinding">
<security>
<message clientCredentialType="Certificate" />
</security>
</binding>
</wsHttpBinding>

</bindings>


Step5 :- Tie up the bindings with end point

Once done we need to tie up this binding with the end point. This is done by using ‘bindingConfiguration’ tag as shown in the below code snippet.

<endpoint address="" binding="wsHttpBinding" "BACKGROUND-COLOR: #ffff00">bindingConfiguration"BACKGROUND-COLOR: #ffff00">="wsHttpEndpointBinding" contract="WCFServiceCertificate.IService1">

Step 6 :- Make your web application client for consuming the WCF service

That’s all we need to from the WCF service perspective. So compile the WCF service and reference the same in the ASP.NET web application using ‘Service reference’. Below is the code snippet where we have referenced the service and called the ‘GetData’ function of the service/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
"BACKGROUND-COLOR: #ffff00">using WebConsumer.ServiceReference1;
namespace WebConsumer
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
"BACKGROUND-COLOR: #ffff00">Service1Client obj = new Service1Client();
"BACKGROUND-COLOR: #ffff00">Response.Write(obj.GetData(12));
}
}
}

Now if you try to run the client i.e. the web application as it is you should get an error as shown below. The error clearly indicates you can use the WCF service until you do not provide the client certificate.


Step 7 :- Define certificates in WCF client

So let’s start the process of defining certificates in the WCF client. The way we have defined authentication certification mode and the path of the certificate, in the same way we need to define it for WCF client. You can see we have defined the authentication mode as ‘peertrust’ and we have specified the client certificate name as ‘WcfClient’.

<behaviors>
<endpointBehaviors>

<behavior name="CustomBehavior">
<clientCredentials>
<clientCertificate findValue="WcfClient" x509FindType="FindBySubjectName" storeLocation="CurrentUser" storeName="My" />

<serviceCertificate>
<authentication certificateValidationMode="PeerTrust"/>
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>

Step 8 :- Tie up the behavior with end point on WCF client

We need to tie up the above defined behavior with the end point. You can see we have bounded the behavior using ‘behaviorConfiguration’ property. We also need to specify that the DNS value will be ‘WcfServer’ which your server certificate name.

<client>
<endpoint address="http://localhost:1387/Service1.svc" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IService1" contract="ServiceReference1.IService1"

name="WSHttpBinding_IService1" 
"BACKGROUND-COLOR: #ffff00">behaviorConfiguration="CustomBehavior">
<identity>
"BACKGROUND-COLOR: #ffff00"><dns value="WcfServer" />
</identity>

</endpoint>
</client>

Step 9 :- Enjoy your hard work

Once we are done you can run the ASP.NET web and you should see the below display.




What is the difference between BasicHttpBinding and WsHttpBinding ?

If we want to summarize in one sentence the difference between ‘WsHttpBinding’ and ‘BasicHttpBinding’ is tha ‘WsHttpBinding’ 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.


Criteria

BasicHttpBinding

WsHttpBinding

Security support

This supports the old ASMX style i.e WS-BasicProfile 1.1.

This exposes web services using WS-* specifications.

Compatibility

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

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.

Soap version

SOAP 1.1

SOAP 1.2 and WS-Addressing specification.

Reliable messaging

Not supported. In other words if a client fires two or three calls you really do not know they will return back in the same order.

Supported as it supports WS-* specifications.

Default security options

By default there is not security provided for messages when the client calls happen. In other words data is sent as plain text.

As WsHttBinding supports WS-* it has WS-Security enabled by default. So the data is not sent in plain text.

Security options

  • None
  • Windows – default authentication.
  • Basic
  • Certificate
  • None
  • Transport.
  • Message.
  • Transport with message credentials.




One of the biggest differences you must have noticed is the security aspect. By default ‘BasicHttpBinding’ sends data in plain text while ‘WsHttpBinding’ sends in encrypted and secured manner. To demonstrate the same let’s make two services one using ‘BasicHttpBinding’ and the other using ‘WsHttpBinding’ and then let’s see the security aspect in a more detailed manner.

We will do a small sample to see how ‘BasicHttpBinding’ sends data in plain text format and how ‘WsHttpBinding’ encrypts data.

Note :- By Default security is not enabled on ‘BasicHttpBinding’ for interoperability purpose. In other words it like our old webservice i.e. ASMX. But that does not mean we cannot enable security in ‘BasicHttpBinding’. Sometimes back we had a written a article on how to enable security on ‘BasicHttpBinding’ WCFBasicHttpBinding.aspx
 

Can you show the security differences between BasicHttpBinding VS WsHttpBinding ?

In order to understand the security differences between both these entities we will do a small project. In this project we will create two WCF service one service using ‘BasicHttpBinding’ and the second service using ‘WsHttpBinding’.




Step1:-
So let’s first create a simple service using ‘BasicHttpBinding’. For that we just a create a simple WCF project and then modify the ‘ServiceModel’ element as shown below. You can see in the ‘endpoint’ tag we have specified ‘basicHttpBinding’ as the protocol.

<system.serviceModel>
<services>

<service name="WCFBasicHttpBinding.Service1" behaviorConfiguration="WCFBasicHttpBinding.Service1Behavior">
<!-- Service Endpoints -->
<endpoint address="" binding="basicHttpBinding" contract="WCFBasicHttpBinding.IService1">
<!-- 
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>
<behaviors>
<serviceBehaviors>
<behavior name="WCFBasicHttpBinding.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>



Step 2 :-
We also need to create one more service using ‘WsHttpBinding’. For that you do not need to anything special as such. By default WCF project is created using ‘WsHttpBinding’. Below is how the Web.config file looks like. You can see how the endpoint tag is using ‘wsHttpBinding’.

<system.serviceModel>
<services>
<service name="WCFWsHttpBindingHttps.Service1" behaviorConfiguration="WCFWsHttpBindingHttps.Service1Behavior">
<!-- Service Endpoints -->

<endpoint address="" binding="wsHttpBinding" contract="WCFWsHttpBindingHttps.IService1">
<!-- 
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>
<behaviors>

<serviceBehaviors>
<behavior name="WCFWsHttpBindingHttps.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>




Step 3 :-
We will not be creating any new methods in both the services. We will just use the default code created by the WCF template. So both these services will have a ‘GetData’ function which returns a string. The ‘GetData’ function is a default function created WCF project.

public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}


Step 4 :-
Now that out services are created we need to create a client which will consume this service. So we have created a simple web application and we have added two references one is a service reference i.e. ‘WsHttpBinding’ and the second is a web reference i.e. ‘BasicHttpBinding’. Please note when you right click to add reference you need to use the ‘Add service reference’ to add ‘WsHttpService’ and you need to add web reference for ‘BasicHttpBinding’.




We will add two buttons on the default aspx page. One button will call the http service and the other will call the wshttp service. Below is how the function ‘GetData’ is called in both the button clicks.



Step 5 :- So now we are ready with the complete project it is time to sniff and see how data is transported between client and the service in both the scenarios. So let’s download a simple http data recorder from http://www.ieinspector.com/httpanalyzer/download.html  . We will then click both the buttons one by one and record the data transfer using httpanalyzer. You can see the posted data is in simple plain XML format for basic http protocol and it’s in an encrypted format for wshttp protocol.






When should we use WsHttp as compared to BasicHttp ?

If you are looking for back ward compatibility and to support lot of clients then basic http binding is the way to go or else WsHttp is the great way to start if you are seeing your clients made in .NET 3.0 and above.

How can we enable windows authentication on WCF using ‘BasicHttpBinding’?

 

Step 1:- Create a project of WCF service application as shown in the below figure.




Circle WCF service application àSelect this
 

By default the WCF project creates a class file which has ‘GetData’ function. This function takes in a number values and displays a explanatory sentence like ‘You entered 1 value’ , in case you have entered ‘1’.

public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}

Step 2:- When we create a WCF service application it also has a web.config file associated with it. So open the web.config file and ensure that authentication mode is windows.

<authentication mode="Windows" />

Step 3:- The third step is to define the bindings and the transport type. To define the bindings we need to enter ‘basicHttpBinding’ element inside the ‘bindings’ XML tag. We also need to define the ‘clientCredentialType’ as windows.

<system.serviceModel>

<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>

</binding>
</basicHttpBinding>
</bindings>
<services>
.........
.........
</system.serviceModel>

Step 4:- Now the bindings defined needs to be associated with service interface i.e. ‘service1’. So we need to modify the services elements as shown below. You can note that we have defined a end point which has the binding association.

<system.serviceModel>
........
........
........
<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>
.........
.........
.........
.........
</system.serviceModel>

So over all your <system.serviceModel> XML part as whole with bindings and services is a shown below.

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

Step 5 :- Go to IIS properties and click on security tab and ensure that anonymous access is disabled and only windows authentication is enabled.


 

 

Step 6:- We need to host our service in the IIS. So make the directory as an IIS application so that your service can be hosted. Now if you try to browse the service i.e. the SVC file you will see that it pops up the authentication authorization security dialog box. So this service cannot be executed with windows authentication.

 

 

 

 

Step 7:- So let’s consume this WCF services. So add an ASP.NET webapplication and do a add webreference. You will be popped up with a dialog box as shown below. Click on add reference so that a proxy is generated for the WCF service.

 

 

 

 

 

Step 8:- Type in the following code snippet in your page load. So add the namespace reference and call the method ‘GetData’. The most important step to note is the credential supplied. ‘DefaultCredentials’ passes the current windows identity to the WCF service.

 

 

 

 

 

 

If you execute the service you should get the following display as shown below.

 

 

 

 

 

You can try commenting the below code in your client in other words we are not passing any credentials.

obj.Credentials = System.Net.CredentialCache.DefaultCredentials;

Now if you execute you should get the below error stating that this is a unauthorized call.

 

 

 

Source Code

Whatever code we have discussed in the above FAQ can be downloaded from http://www.codeproject.com/KB/WCF/WCFFAQPart3/WCFSourceCode.zip

By Shivprasad koirala
Enter comment - View the 0 comments
Saturday 27 november 2010 6 27 /11 /Nov /2010 15:04

 

Windows Communication Foundation FAQ quick starter - Part 2


Get Interview tutorials and videos on .NET 3.5, 4.0, WCF,Asp.Net, SQL Server, CAS, Security, WCF, SharePoint, Azure, OOPS and many more on www.questpond.com


 

 

This 10 minutes small video explains how transport security can be implemented using SSL in WCF services.


 

 

Introduction

Can you explain duplex contracts in WCF?

How can we host a service on two different protocols on a single server?

How can we use MSMQ bindings in WCF?

Can you explain transactions in WCF?

What different transaction isolation levels provided in WCF?

Can we do transactions using MSMQ?

Can we have two-way communications in MSMQ?

What are Volatile queues?

What are Dead letter queues?

 




Introduction


In this section we will run through a quick FAQ for WCF. I am sure after reading this you will get a good understanding of the fundamentals of WCF.

Watch my 500 videos on various topics like design patterns,WCF, WWF , WPF, LINQ ,Silverlight,UML, Sharepoint ,Azure,VSTS and lot more @www.questpond.com , you can also catch me on my trainings @ www.questpond.com


Can you explain duplex contracts in WCF?


In duplex contracts when client initiates an operation the server service provides a reference call back Uri back to the client. So the client initiates a call using the proxy class and when server finishes its work it notifies the client using the callback channel. This is called as duplex messaging in WCF. If you remember in the previous question, we had no way to know when the server finished its task.

 Figure 18:- Duplex Service code

 


Let us try to understand the duplex concept by doing a small sample. The code snippet is as shown in the above figure. We will extend the previous sample, which was shown in the first question only that now we will provide the notification to the client once the doHugeTask is completed.
The first step is to change the service class. Above is the code snippet of the service class. Again, we have numbered them so that we can understand how to implement it practically line by line. So below is the explanation number by number:-
1 - In the service contract attribute we need to specify the callback contract attribute. This Callback Contract attribute will have the interface, which will define the callback.
2 - This is the interface which client will call. In order that it should be asynchronous, we have defined the one-way attribute on the doHugeTask method.
3 -This is the most important interface. As it forms the bridge of communication between server and client. The server will call the client using Completed method. Client needs to provide implementation for the completed method at the client side and server will call that method once it completes the doHugeTask method.
4 and 5 - In this we implement the Interface Duplex interface and provide implementation for doHugeTask () method.
6 - This is an important step. The OperationContext.Current.GetCallBackChannel will be used to make callback to the client.
7 - We will expose the service using HTTP protocol. In this sample, because we want to do duplex communication we need to use wsDualHttpBinding rather than just using simple Http Binding. This new binding configuration is then assigned to the end on which the service is hosted.
This completes the server side explanation for duplex.

 


Figure: - 19 Duplex Client side code


Above is the code snippet for client side. So let us explain the above code with numbers.
1- We implement the completed method. This is the callback method, which the server will call when doHugeTask is completed.
2- In this step we create object of the Instance Context class. Instance Context represents context information of a service. The main use of Instance Context is to handle incoming messages. In short, proxy is used to send messages to server and Instance Context is used to accept incoming messages.
3 -In this step we pass the Instance Context object to the constructor of the proxy. This is needed, as the server will use the same channel to communicate to the client.
4 - In this section two windows are shown. The top windows is the servers output and the below windows is of the client. You can see in the below window that server as made a callback to the client.

Note: - You can get source code for the same in WCFDuplex folder. Feel Free to experiment with it. Try making one simple project of client to client chat using WCF duplex fundamentals I am sure your doubts will be cleared in and out.
 

How can we host a service on two different protocols on a single server?


Let us first understand what this question actually means. Let us say we have made a service and we want to host this service using HTTP as well as TCP. You must be wondering why to ever host services on two different types of protocol. When we host a service, multiple types of client consume it and it’s very much possible that they have there own protocol of communication. A good service has the capability to downgrade or upgrade its protocol according the client who is consuming him.
Let us do a small sample in which we will host the ServiceGetCost on TCP and HTTP protocol.

Note: - You can the below sample in “WCFMultipleProtocolGetHost” folder in the CD provided.


Below is the code snippet pasted from the same sample? As usual, we have numbered them and here is the explanation of the same:-
1 and 2 - As we are hosting the service on two protocols we need to create two objects if the URI. You can also give the URI through config file. Pass these two objects of the URI in the constructor parameter when creating the service host object.





Figure 20:- Server side code for Multi Protocol hosting


3 – In the config file we need to define two bindings and end as we are hosting the service in multiple protocols.
Once we are done the server side coding its time to see make a client by which we can switch between the protocols and see the results. Below is the code snippet of the client side for multi-protocol hosting.

 

Figure 21:- Multi Protocol Client code


Let us understand the code:-
1 - In the generated config file we have added two ends. When we generate the config file, it generates only for one protocol. The other end has to be manually added.
2 - To test the same we have a list box, which has the name value given in the end point.
3 - In the list box select event we have then loaded the selected protocol. The selected protocol string needs to be given in the proxy class and finally call the proxy class GetTotalCost.

 

How can we use MSMQ bindings in WCF?

First let us understand why MSMQ came in to picture and then rest will follow. Let us take a scenario where your client needs to upload data to a central server. If everything will works fine and the server is available 24 hours to client then there are no issues. In case the server is not available, the clients will fail and the data will not be delivered. There is where MSMQ comes in to picture. It eliminates the need of persistent connection to a server. Therefore, what you do is deploy a MSMQ server and let the clients post message to this MSMQ server. When your actual server runs, it just picks up the message from the queue. In short, neither the client nor the server needs to be up and running on the same time. In WCF we have a client and service model and in real world it is very much practical possible that both the entities will not be available at one time.
In order to use MSMQ you need to install the Message queuing by click on Install windows component and selecting MSMQ queuing. Once that done we are all set to make our sample of MSMQ using WCF





Figure 22:- MSMQ Installation


This sample will be simple. We send some messages from the client and keep the server down. As the server is down it will make postings to the MSMQ server. Then we will run the server service and service should pick up the message and display the same.




Figure 23:- MSMQ Server side code walkthrough
 

Above snippet is the server side code. So let us understand the whole snippet:-

1 – First thing is the queue name where the messages will go if the server is not running. The server name we can get from the config file. You can see in the above snippet we have defined the Mismanage in App.config file.
2 – We first check does this queue exist if it exists then go-ahead. If not then go to create a queue. Please note you need import using System. Messaging namespace. Then we can use the Message Queue to create a queue if the queue does not exist.
3 – First thing which should surprise you is why we are creating a URI with HTTP protocol as we are going to use MSMQ. Ok! This is bit tricky but fun. As we know in order to connect to this service, we need to generate a client proxy using SVCUTIL. Therefore, this URI will help us do that. It is not actually used by the client to connect.
4 – We need our end and the MSMQ bindings.
5 and 6 – Again as usual we need is an interface and implementation for the same. In implementation we have created a method called send Message.
Once the above steps are executed, run the server and generate the client proxy using SVCUTIL utility.
Now comes the final step making a client. One change you need to make is change the address to the MSMQ server in the app.config. In this, we have just looped ten times and fired an offline message. Please note to keep your server down.




Figure 24:- MSMQ Client side code
 

Now go to computer management and you can see your queue messages waiting to be picked by the server. Run the server and below should be the output. If you come back again you will see that there are no messages in the queue


.



Figure 25:- MSMQ Server side display


One of the important concepts is to understand when to use MSMQ protocol. When we expect that client and server will not be available, at one time this is the best option to opt for.


Can you explain transactions in WCF?


What different transaction isolation levels provided in WCF?

Transactions assure that a group of related activity occurs as a single atomic unit. In simple words, every activity in the unit must either all succeed or all should fail. WCF provides a central transaction system that can be used to handle transaction operations. One of the things WCF provides is a single unified transaction system for both database and non-database activity. For instance, BeginTrans and CommitTrans are database related syntaxes but we can not use the same for other activities like if we want to upload all message in a single transaction to a MSMQ server. One thing to note is that WCF transaction abides to WS specifications. That means any other language like JAVA can take advantage of this transaction…. I think that is the best part of WCF embracing other languages.





Figure 26:- Transactions in WCF


In order to support transaction the service should first support transactions. Above is a simple code snippet of the server service and client and explanation for the same:-

The top code snippet is of the server service and the below code snippet is of the client.

1 - At interface level the operation contract is attributed with [Transaction Flow] attribute. There are three values for it Allowed (which mean operation mar or may not be used in transaction), Not Allowed (Where it is never used in transaction) and required (Where the service can only be used in transactions). Below code snippet currently says that this service can only be used with transactions.

2 - In this section the [Service Behavior] attribute specifies the transaction isolation level property. Transaction isolation specifies the degree of isolation most compatible with other applications. So let us review what are the different levels you can provide in transaction isolation.
The data affected by a transaction is called volatile.

Chaos: - pending changes from more highly isolated transactions cannot be overridden.
Read Committed: - Volatile data can be modified but it cannot be read during the transaction.
Read Uncommitted: - Volatile data can be read as well as modified during the transaction.
Repeatable Read: - Volatile data can be read but not modified during the transaction and new data can be added.
Serializable: - Volatile data can be only read. However, no modifications and adding of new data is allowed.
Snapshot: - Volatile data can be read. However, before modifying the data it verifies if any other transaction had changed data. If yes then it raises error.
By default, the System. Transactions infrastructure creates Serializable transactions.

3 - This defines the transaction behavior with in the service. [Operation Behavior] has a property called as transaction scope. Transaction Scope setting indicates that operation must be called within a transaction scope. You can also see TransactionAutoComplete is set to true which indicates that transaction will complete by default if there are no errors. If you do not provide the TransactionAutoComplete to true then you will need to call OperationContext.Current.SetTransactionComplete() to make the transaction complete.
Now let us make a walkthrough of the client side code for the service.

4 and 5 - You can see from the client we need to define Isolation level and the scope while making the call to our Update Accounts method

Can we do transactions using MSMQ?

While doing MSMQ there can be scenarios in the project, where we would like all the messages are uploaded to either MSMQ or all messages read from MSMQ. After any message is read from MSMQ, it is deleted from the queue. Therefore, some times this can be critical if there are exceptions in reading or uploading messages. As said before WCF transaction can be applied to database as well as other operations like MSMQ. So let us try to understand the same by doing a small sample.

Below is a numbered code snippet of MSMQ transactions.

1 - Send message is the exposed method in the service. We have marked this method as TransactionScopeRequired=true

2 - On the client side we have use the transaction scope to say that we are starting a transaction to MSMQ server. You can see we have used the send Message to send the messages to MSMQ.

3- We can then use Complete or Dispose method to complete or rollback the transactions.
The below MSMQ transaction code ensures that either all messages are send to the server or none are sent. Thus satisfying consistency property of transactions.




Figure 27:- Transaction snippet code


Can we have two-way communications in MSMQ?

Yes

What are Volatile queues?

There are scenarios in the project when you want the message to deliver in proper time. The timely delivery of message is more important than losing message. In these scenarios, Volatile queues are used.
Below is the code snippet, which shows how to configure Volatile queues. You can see the binding Configuration property set to Volatile Binding. This code will assure that message will deliver on time but there is a possibility that you can lose data.

<appSettings>
<!-- use appSetting to configure MSMQ queue name -->
<add key="queueName" value=".\private$\ServiceModelSamplesVolatile" />
</appSettings>

<system.serviceModel>
<services>
<service name="Samples.StockTickerServ"
behaviorConfiguration="CalculatorServiceBehavior">
...
<!-- Define NetMsmqEndpoint -->
<endpoint address="net.msmq://localhost/private/ServiceModelSamplesVolatile"
binding="netMsmqBinding"
bindingConfiguration="volatileBinding"
contract="Samples.InterfaceStockTicker" />
...
</service>
</services>

<bindings>
<netMsmqBinding>
<binding name="volatileBinding"
durable="false"
exactlyOnce="false"/>
</netMsmqBinding>
</bindings>
...
</system.serviceModel>
 

What are Dead letter queues?

The main use of queue is that you do not need the client and the server running at one time. Therefore, it is possible that a message will lie in queue for long time until the server or client picks it up. But there are scenarios where a message is of no use after a certain time. Therefore, these kinds of messages if not delivered within that time span it should not be sent to the user.
Below is the config snippet, which defines for how much time the message should be in queue.

<bindings>
<netMsmqBinding>
<binding name="MyBindings"
deadLetterQueue="Custom"
customDeadLetterQueue="net.msmq://localhost/private/ServiceModelSamples"
timeToLive="00:00:02"/>
</netMsmqBinding>
 

By Shivprasad koirala
Enter comment - View the 0 comments
Saturday 27 november 2010 6 27 /11 /Nov /2010 14:11

Windows Communication Foundation FAQ quick starter - Part 1

Get Interview tutorials and videos on .NET 3.5, 4.0, WCF, ASP.NET, SQL Server, CAS, Security, WCF, SharePoint, Azure, OOPS and many more on www.questpond.com

 

 

Introduction

What is .NET 3.0?

What is Windows Card Space?

What is WCF?

What are the important principles of SOA (Service oriented Architecture)?

What are ends, contract, address, and bindings?

Which specifications does WCF follow?

What are the main components of WCF?

Explain how Ends, Contract, Address, and Bindings are done in WCF?

what is a service class?

what is a service contract, operation contract and Data Contract?

what are the various ways of hosting a WCF service?

How do we host a WCF service in IIS?

what are the advantages of hosting WCF Services in IIS as compared to self-hosting?

what are the major differences between services and Web services?

What is the difference WCF and Web services?

What are different bindings supported by WCF?

Which are the various programming approaches for WCF?

What is one-way operation?
This 10 minutes small video explains how transport security can be implemented using SSL in WCF services.


Introduction


In this section we will run through a quick FAQ for WCF. I am sure after reading this you will get a good understanding of the fundamentals of WCF.

Watch my 500 videos on various topics like design patterns,WCF, WWF , WPF, LINQ ,Silverlight,UML, Sharepoint ,Azure,VSTS and lot more @ http://www.questpond.com  you can also catch me on my trainings @ http://www.questpond.com

What is .NET 3.0?


In one simple equation .NET 3.0 = .NET 2.0 + Windows Communication Foundation + Windows Presentation Foundation + Windows Workflow Foundation + Windows Card Space.

What is Windows Card Space?


It was previously known by its codename Info Card. It is a framework by Microsoft, which securely stores digital identities of a user and provides a unified interface to choose the identity for a particular transaction, such as logging in to a website. Windows Card Space is a central part of Microsoft’s effort to create an identity met system, or a unified, secure and interoperable identity layer for the internet.

What is WCF?


First let us give a short answer to this: - “WCF (Indigo was the code name for WCF) is a unification of .NET framework communication technologies “.WCF is a unification technology, which unites the following technologies:-
• NET remoting
• MSMQ
• Web services
• COM+.
Below figure depicts WCF fundamentals pictorially.

 


Figure: 1 - WCF Components


What are the important principles of SOA (Service oriented Architecture)?


WCF is based on SOA. All big companies are playing big bets on SOA. So how can Microsoft remain behind? So in order to implement SOA architecture easily you need to use WCF.
SOA is based on four important concepts:-

• Boundaries are well defined


In SOA, everything is formalized. The client who is consuming the service does not need to know how the implementation of the service is done. If you look at some old methodologies of communication like DCOM. Any changes at server level the client also has to change. Therefore, the server and client implementation was so much bound that changes need to be done at all places. In SOA, the rule is if you do enhancement you do not need to change anything at the client. SOA based application only understands that there is an end point, contract, and bindings.

Note: - Just to clarify shortly about end point and contract. Any SOA service is exposed through an end point. End point defines three important aspects What, Where and How. We will understand more details of the same in the later questions.


• Services evolve


Change is the law of nature and services will evolve. In SOA, services can be versioned and you can host those services in new ends. For instance, you have a service called as “Search Tickets (Ticket Number) “which gives details based on Ticket Number and its exposed on end point “ep1”. Tomorrow you want make your Search Tickets service more useful by also providing an extra option of allowing him to search by passenger name. Therefore, you just declare a new end “ep2” with service “Search Tickets (Ticket Number, Passenger Name)”. So the client who is consuming the service at end ep1 continues and at the other end, we have evolved our service by adding new ends ep2.

• Services share only schemas and contracts


Services use Schemas to represent data and contracts to understand behavior. They do not use language dependent types or classes in order to understand data and behavior. XML is used to define schemas and contracts. Due to this, there is not heavy coupling between environments.

• Service compatibility is policy based


Policy describes the capabilities of the system. Depending on policies, the service can degrade to match the service for the client. For instance your service needs to be hosted for two types of client one which uses Remoting as the communication methodology while other client uses DCOM. An ideal SOA service can cater to both of them according to there communication policies.

Note: - Many people assume Web services are the base for SOA. The answer is 50 % right. What web services lack is the policy based Service compatibility. If you host a web service it can only serve with HTTP communication channel and SOAP message. Any other type of client trying to communicate he will not degrade it self. This is what is provided by WCF. You can host the service in one or more mode. For instance you can host a WCF service using remoting and ASMX.
 

What are ends, contract, address, and bindings?


The above terminologies are the core on which SOA stands. Every service must expose one or more ends by which the service can be available to the client. End consists of three important things where, what and how:-

• Contract (What)


Contract is an agreement between two or more parties. It defines the protocol how client should communicate with your service. Technically, it describes parameters and return values for a method.

• Address (Where)


An Address indicates where we can find this service. Address is a URL, which points to the location of the service.

• Binding (How)


Bindings determine how this end can be accessed. It determines how communications is done. For instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP. So for each of these communications medium two bindings will be created.
Below figure, show the three main components of end. You can see the stock ticker is the service class, which has an end hosted on www.soa.com with HTTP and TCP binding support and using Stock Ticker interface type.

Figure 2: - Endpoint Architecture


Note: - You can also remember the end point by ABC where A stands for Address, B for bindings and C for Contract.
 

Which specifications does WCF follow?


WCF supports specifications defined by WS-* specifications. WS-* specifications are defined together by Microsoft, IBM, SUN and many other big companies so that they can expose there service through a common protocol. WCF supports all specifications defined we will understand them one by one.

• Messaging (WS-Addressing):-
SOAP is the fundamental protocol for web services. WS Addressing defines some extra additions to SOAP headers, which makes SOAP free from underlying transport protocol. One of the good things about Message transmission is MTOM, also termed as Message Transmission Optimization Mechanism. They optimize transmission format for SOAP messages in XML-Binary formant using XML optimized packaging (XOP). Because the data will sent in binary and optimized format, it will give us huge performance gain.

• Security (WS-Security, WS-Trust, and WS-Secure Conversation):-
All the three WS- define authentication, security, data integrity and
privacy features for a service.
• Reliability (WS-Reliable Messaging):- This specification ensures end-to-end communication when we want SOAP messages to be traversed back and forth many times.

• Transactions (WS-Coordination and WS-Atomic Transaction):- These two specifications enable transaction with SOAP messages.


• Metadata (WS-Policy and WS-Metadata exchange):- WSDL is a implementation of WS-Metadata Exchange protocol. WS-Policy defines more dynamic features of a service, which cannot be expressed by WSDL.
We have stressed on the WS-* specification as it is a specification which a service has to follow to be compatible with other languages. Because WCF follows WS-* specifications other languages like JAVA , C++ can also exploit features like Messaging , Security , Reliability and transactions written in C# or VB.NET. This is the biggest achievement of WCF to integrate the above features with other languages.

Note: - During interview the interviewer expects that you know what WS-* specification are supported by WCF and its advantages with respect to interacting with other languages.


What are the main components of WCF?


We need to define three main components in WCF:-
• Service class.
• Hosting environment
• End point

Explain how Ends, Contract, Address, and Bindings are done in WCF?


what is a service class?


what is a service contract, operation contract and Data Contract?


In this example, we will make simple service, which displays the total cost of the complete product group. In simple words, this service will take three parameters per product cost, number of products and the product name. In return the service will return the total cost of all the products by multiplying number of products * cost per product. As we go ahead in this explanation, we will try to understand all the terminologies, which are asked in the above question.
First, you need to create a Winfx service project. You can see in the below figure we have selected the Winfx project.


Figure 3: - Create new WinFX Service class


In this project, we add a new class and name it as “serviceGetCost.cs”. This class will have our core implementation and this is the class, which has all the action. The service class, which has to be exposed to the external client. We need to use the Service Contract attribute to mark it as a service class.
Service Contract attribute define saying which application interface will be exposed as a service.
You can see in the below code snippet we have made an interface and marked it as Service Contract. It is not essential that you need to use an interface you can also use a simple class and mark it as Service but interface represent a contract and do not have implementation. In short, they stand at a very higher level of abstraction. So as a good design practice-using interface to represent a service contract makes more sense.
The next thing to note is the Operation Contract attribute.
Operation Contract dictates which methods should be exposed to the external client using this service.
It defines individual exchange or request and replies. In the current sample, we have defined GetTotalCost method, which will be used by the end client to get the total cost results.
The next thing to note in the code snippet is the Data Contract attribute. In the previous two steps, we have exposed class as a service by using Service Contract and methods by using Operation Contract. Every operation will definitely do some kind of data transfer.
Data Contract attributes defines which type of complex data will be exchanged between the client and the service. They determine which parameters to be serialized.
When you are using simple data types like int, bolo etc it is not necessary that you need to mark the data contract attribute. Because you will always find matching types on the client. However, complex structure like one shown in the below code snippet you will need to define a data contract. Remember data contract define how this data will be passed during transmission. In short data contract attribute define how data will be serialized will transmission.
In the below sample we have marked the structure product data to be serialized.


Figure 4:- The Service class


As data contract are all about serialization you need to import System.Runtime.Serialization name space.
In the next step, we implement the GetTotalCost function. It just returns a simple string with product name and the total cost of all products.
Once our service class is done its time to host this service. There are various ways of hosting a WCF service we will look in to the same in the next question. For the current example, we will host in their own process.


Figure 5: - Hosting the service


Hosting the WCF service needs two things one is the config file and second is the hosting code on startup. Because we are hosting this service in its own application process this needs to be a windows application. So first let us have a look what entries do, we need to make in the App.config file. In the above figure, everything is clear but let us understands all the section defined in the App.config file.
In the configuration section, we need to add a new section <system.serviceModel>. The most important part of <system.serviceModel> is the endpoint tag. As said in the previous answer End gives three important answers Where, What and How. In short where is the service, what the contract of the service is and how do we communicate with the service.
In the above code snippet, we have only defined the contract i.e. what and how that is bindings. The where is defined in the application entry point static void main ().
Therefore, the contract attribute defines the interface and binding says that the end clients can communicate using “HTTP” protocol.
In Static void Main method, we create an object of Service Host class and use the open method to host the service. We have used the URI object to define the address where the service will be hosted.


Figure 6: - Service Started


If you compile the project, you will see something as shown in the above figure. This says that the service is up and running and ready to serve any WCF client. Now its time to develop consumer, which will consume this WCF service. Microsoft has provided a decent automation to generate the client. Therefore, below figure depicts the various steps.




Figure 7: - svcutil in action


Go to command prompt of windows SDK and run the following command:-
Svcutil <Service hosted URI>
In the above command <Service Hosted URI> is the URI on which the service is hosted. One you run the command against the URI it will generate two files one is the config file and the other is the proxy. You can see in the above figure two files are generated serviceGetCost.cs and output.config file. With the help of these two files, we will make our client.



Figure 8: - Client code walkthrough


You can see in the above figure we have made WFCClientGetCost project. In that, we have added output.config and serviceGetCost.cs to the client project. We have renamed output.config to app.config.
Once we have done with everything, its time to write the client code, which calls the proxy who in turn will call the service hosted. In the above figure, you can see we have the client code also. It is a simple code we first created the object of the data structure set the values. Then we create the object of the service and call the GetTotalCost function.
If everything is compiled and you run the server and client, you should get your output as shown below.


Figure 9: - Output of WCF service


what are the various ways of hosting a WCF service?


There are three major ways to host a WCF service:-
• 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.

How do we host a WCF service in IIS?


Note: - The best to know how to host a WCF in IIS is by doing a small sample. So what we will do is host the same GetCost sample which was self hosted in the previous question.


First thing you will need is to create the SVC file, which exposes the service class. SVC file contains the pointer to the class. You can see from the figure below the class attribute points to the class whose interface is exposed by the service.svc.cs file. Also, note the actual interface is in service.svc.cs file. Below figure, have both the files service.svc, which has the class attribute which points to the service class, and the interface, which resides in service.svc.cs file. We have taken the same sample, which was self-hosted in the previous question.


Figure 10: - The SVC file and the behind code


We also need to provide implementation for the interface. So we have made a class ServiceGetCost which has the actual implementation. Below figure shows the same in detail. In the below figure you can also see the solution files.


Figure 11: - Implementation of Service.svc.cs


We also need to specify the service type and endpoint in web.config file. Also, note we have specified HTTP binding because we will be hosting the service on IIS.


Figure 12: - Web.config file for hosting service on IIS


Now that we are done with the coding part. We need to create the virtual directory in IIS. In the below figure in Step1 and Step2 we have shown how to create the virtual directory in IIS. One important thing to note while creating virtual directory set the access permission to execute.



Figure 13:- IIS Configuration


In the third step, we will publish the website to our virtual directory. Note the fourth step in which we have copied the svc file so that the service can be requested.
Note: - ASP.NET compilation has changed in ASP.NET 2.0. In 2.0 there is no concept of solution files. So if you want to have full compiled DLL you need to publish the project to a virtual directory.
Once you have hosted the SVC file you can test the same by request the service.svc file. If everything works fine you will get something as shown in the below figure

Figure 14:- IIS WCF client


Using the Svcutil.exe, you will need to generate the proxy class and the config file. The proxy and config will be same, as we had done for self-hosting. The one important change is the address. The config file URL now points to the service.svc, which is hosted on IIS. You can run the same client, which we had created for self-hosting. The only change you will need to do is change the endpoint address.


Figure 15:- Output of WCF client at IIS


LOL…You should get the same output, which we had received, for self-hosting.

what are the advantages of hosting WCF Services in IIS as compared to self-hosting?


There are two main advantages of using IIS over self-hosting:-

Automatic activation


IIS provides automatic activation that means the service is not necessary to be running in advance. When any message is received by the service it then launches and fulfills the request. But in case of self hosting the service should always be running.

Process recycling


If IIS finds that a service is not healthy that means if it has memory leaks etc, IIS recycles the process. Ok let us try to understand what is recycling in IIS process. For every browser instance, a worker process is spawned and the request is serviced. When the browser disconnects the worker, process stops and you loose all information. IIS also restarts the worker process. By default, the worker process is recycled at around 120 minutes. So why does IIS recycle. By restarting the worker process it ensures any bad code or memory leak do not cause issue to the whole system.
In case of self-hosting both the above features, you will need to code yourself. Lot of work right!!. That is why IIS is the best option for hosting services until you are really doing something custom.
Below figure shows where the recycle option is located in IIS. You need to click on the DefaultAppool and then Properties.

Figure 16:- IIS recycle option


what are the major differences between services and Web services?


What is the difference WCF and Web services?


Web services can only be invoked by HTTP. While Service or a WCF component can be invoked by any protocol and any transport type. Second web services are not flexible. However, 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.

What are different bindings supported by WCF?


WCF includes predefined bindings. They cover most of bindings widely needed in day-to-day application. However, just incase you find that you need to define something custom WCF does not stop you. So let us try to understand what each binding provides.
BasicHttpBinding: - This binding is used when we need to use SOAP over HTTP. This binding can also be configured to be used as HTTPS. It can be also configured to send data in plain text or in optimized form like MTOM.

Note: - MTOM is discussed in one of the pervious questions in this chapter.


WsHttpBinding: - It is same like BasicHttpBinding. In short, it uses SOAP over HTTP. But with it also supports reliable message transfer, security and transaction. WS-Reliable Messaging, security with WS-Security, and transactions with WS-Atomic Transaction supports reliable message.

NetTcpBinding: - This binding sends binary-encoded SOAP, including support for reliable message transfer, security, and transactions, directly over TCP. The biggest disadvantage of NetTcpBinding is that both server and client should be also made in .NET language.

NetNamedPipesBinding:-Ths binding Sends binary-encoded SOAP over named pipes. This binding is only usable for WCF-to-WCF communication between processes on the same Windows-based machine.

Note: - An interprocess control (IPC) protocol is used for exchanging information between two applications, possibly running on different computers in a network. The difference between Named pipes and TCP is that named pipes have good performance in terms of communication with in processes. But when it comes to communicate across network TCP holds the best choice. So if you are using WCF to communicate with process it’s the best choice to use in terms for performance. Named pipes do not perform when the traffic is heavy as compared to TCPIP.


NetMsmqBinding: - This binding sends binary-encoded SOAP over MSMQ. This binding can only be used for WCF-to-WCF communication.

Which are the various programming approaches for WCF?


What is one-way operation?

IsOneWay equal to true ensures that the client does not have to wait for the response. So methods marked by IsOneWay to true should always return void. In this, the caller does not get anything in return so it is called as one-way communication.
In order to understand one-way implementation in WCF lets make a code walkthrough of a sample.
Note: - You can find code for the same in “WCFIsOneWay” folder in CD.

Figure 17: - One-Way in action


Above is the code snippet, which describes practically how one way works in WCF. The above given code snippet is numbered. Below is the explanation according to the numbers marked in figure:-
1 - This is the code snippet of the server service. We have created a method called as doHugeTask. DoHugeTask makes the method sleep for 5000 MS and then displays the time when the task is completed.
2 - This code snippet is for client. It creates a proxy object of serviceIsOneWay and calls the doHugeTask method. After calling the doHugeTask, the client execution continues ahead. So as a proof, we display the time when the method calling was completed.
3 - This screen shot shows the output given by both server and client. The top window displays the server output and the below windows displays the client output.

Note: - You can find the code for the same in WCFIsOneWay folder. For generating the proxies you have to follow the same steps which are shown in the previous steps.
 

So run the server program first i.e. ServiceIsOneWay and run the client later. You will see the client runs the doHugeTask and moves ahead. Therefore, the client completion time is less than the server is. One more thing to understand is that one way does not give any notification back of completion. Therefore, it is like fire and forgets.

By Shivprasad koirala
Enter comment - View the 0 comments
Thursday 25 november 2010 4 25 /11 /Nov /2010 12:44

C# and .NET interview questions and answers around global assembly cache (GAC)


One of the most asked questions in .NET interviews are around assembly and GAC. Most of the times .NET developers get confused with these questions. Below are some of the question which keeps coming from GAC perspective.

Interviewer normally starts with what is GAC?

GAC is a central repository folder where you can share your DLL among different applications running in the same computer. So for example you have accounting and invoicing application running in the same computer and both these application need some common utility like the logging DLL then you need to register them in GAC and share them.

If you are able to answer the top interview questions the next question can be on versioning.

If we have different versions of DLL in GAC how can the application identify them?

This is done by using binding redirect and specifying older version and new version value. So which ever version you put in the new version will be used by the application.

The other question can come from the perspective of how you can register a DLL in GAC. Interviewer expectation is that you do not just talk about GACUTIL but you need talk more realistic.

What are the various ways by which you can register a DLL in GAC?

We can use the GACUTIL tool to register the DLL in GAC.

But when we talk about application they have 100 of DLL’s so how feasible is GACUTIL tool?

We need to create installation package which will register the DLL in GAC.

If we do not have strong name can assembly be registered in GAC?

This is again a catchy question which is testing do you know the pre-requisites to register DLL in GAC. No, you cannot register DLL in GAC without strong names.

How do we create strong named DLL?

By using SN.EXE or by going to the project properties and making the assembly string named.

So next time you face a question in GAC in C# and .NET interviews understand the above twist and twirls. Happy job hunting.
C# and .NET interview questions and answers

By questpond.over-blog.com
Enter comment - View the 0 comments
Sunday 21 november 2010 7 21 /11 /Nov /2010 12:08

.NET Interview question and answers training

For More Information Visit www.questpond.com

 

This is the most important section in .NET interviews - Basics. It's possible in interviews you do not know higher end technologies like WCF , Entity framework , Azure etc , but not answering simple .NET questions like generics , reflection can eliminate you in the first round itself.

 

In this section the videos starts with basics of IL code , CLR common language run time , CTS common type systems and Just in time JIT compilers. In this section we have shown sample demos for each of these core concepts.

 

Some time interviewer probe in to what are the different kind of JIT , this section also has a nice videos which demonstrates what are different kind of  JIT compilers and how to NGEN exe.

 

 

CAS (Code access security) is not much used but the most asked in interviews. We have two dedicated videos which explain what is CAS with sample demonstration and then what are the changes made for CAS in 4.0.

 

 

Garbage collector the most talked topic in .NET interviews. We have 2 solid videos for garbage collector one which explains what is GC and the different generations and the second video show the importance of Idisposable interface from GC performance point of view.

 

 

There is one saying in .NET interviews - ".NET interview is not completed without a question on delegates and events". We have four rock star videos which talks about delegates, events, multicast delegates, differences between delegates and event and how to call a delegate asynchronously.

 

 

Sometimes .NET interviewers are really silly to ask questions like stack, heap , value type , reference type  , boxing and unboxing. We have 2 great videos which explain all these concepts with sample demonstration so that you can talk about them well in interviews videos.

 

 

This is the most important section in .NET interviews - Basics. It's possible in interviews you do not know higher end technologies like WCF , Entity framework , Azure etc , but not answering simple .NET questions like generics , reflection can eliminate you in the first round itself.

 

 

In this section the videos starts with basics of IL code , CLR common language run time , CTS common type systems and Just in time JIT compilers. In this section we have shown sample demos for each of these core concepts.

 

 

Some time interviewer probe in to what are the different kind of JIT , this section also has a nice videos which demonstrates what are different kind of  JIT compilers and how to NGEN exe.

 

 

CAS (Code access security) is not much used but the most asked in interviews. We have two dedicated videos which explain what is CAS with sample demonstration and then what are the changes made for CAS in 4.0.

By questpond.over-blog.com
Enter comment - View the 0 comments

Important .NET and C# interview questions and answers

.Net interview questions: - Explain why it is not preferred to use finalize for clean up?

.Net interview questions: - Show the five levels in CMMI?

.NET interview questions and answers: – Which is the best place to store connection string in .NET projects?

C# interview questions and answers: – Explain the use of Icomparable in c#?

C# interview questions: - How can we check which rows have changed since dataset was loaded?

C# interview questions and answers: - Can you write a simple c# code to display Fibonacci series?

.NET interview questions and answers: - What is difference betweenIcomparable VS Icomparer ?

C# and .NET interview question: -What is short circuiting in C#?

C# and .NET interview question: - What are symmetric and asymmetric algorithms?

Important c# and .NET interview question on object pooling and Gridview events?

.NETinterview questions and answers: – Will the finally run in this code?

How to prepare for c# and .NETinterviews?

C# and .NET Interview questions: - What is Thread.Join () in threading?

.NET Interview questions and answers: -What is serialization and deserialization in .NET?

C# and .NET interview question: - What is hashing?

c# and .NET interview question:- what connects dataset and data source ?

.Net interview questions and answers: - What is the difference between “Web.config” and “Machine.Config”?

.NET interview questions and answers: - What is TPL?

.NET Interview questions and answers: -What are different access modifiers?

.NET and c# Interview Question and answers: – If we want to update interface with new methods, what is the best practice?

 MVC ( Model view controller) interview questions and answers      

ASP.NET Application and Page Life Cycle 

12 Important FAQ’s on VSTS Testing (Unit testing, load testing, automated testing, database testing and code coverage) 

 6 important use of Partial/Mock testing

6 important uses of Delegates and Events

7 Simple Steps to Run Your First Azure Blob Program

8 Steps to Create Workflows using SharePoint Designer

Azure FAQ Part 1

C# Code Reviews using StyleCop – Detailed Article

Four real world uses of Partial classes and Partial methods

SharePoint Quick Start FAQ Part 1

SharePoint Quick Start FAQ Part 6 – Workflows, Workflows and Workflows

SharePoint Workflow Basics

 

 

 

 

. NET and C# interview questions videos

Algorithm Interview Questions

Algorithm interview questions and answers: – Can you write code for bubble sort algorithm?

Algorithm interview questions and answers: – What is inserted sort algorithm?

ASP.NET Interview Questions & Answers Article







 

SQL Server Interview Questions & Answers Article

 

SQL Server Interview Questions & Answers Article

SQL Server interview questions and answers: - What is HID data type in SQL Server ?

 

.NET INTERVIEW QUESTIONS & ANSWERS ARTICLE

 

.NET interview questions and answers: - How to reverse a string in .NET ( DotNet)?

.NET interview questions and answers: - What is the use of Click Once?

.NET interview questions and answers: - Will the below codes create new instances?

C# and .NET interview questions with answers – What is Nuget?

Dependency injection (DI) VS Inversion of Control (IOC)

.NET interview questions with answers: - What is the difference between Reflection and Dynamic?


WPF INTERVIEW QUESTIONS & ANSWERS ARTICLE

 

6 important WPF and Silverlight Multi-threading interview questions with answers


Create your blog for free on over-blog.com - Contact - Terms of Service - Earn Royalties - Report abuse - Most commented articles