A Place for C Sharpers/.Netters

I Will do coding till last moment of life-Kiran Patil

Posts Tagged ‘WCF’

WCF Behavioral Contracts and Message Exchange Patterns

Posted by kiranpatils on October 16, 2011

Challenge:

Architect was busy on other tasks, So, he was not able to share his WCF knowledge with you since last few days. He apologize for this!

Architect’s team liked his WCF Fundamentals notes and they requested him to share his all notes whatever he has related to WCF!

So, here’s the 3rd part (1st part, 2nd part) of WCF Story where our architect would like to share his WCF Behavioral Contracts and Message Exchange Patterns with you!

Solution:

Here’s the discussion between Architect and his team!

Contracts

Contract defines:

  • What service operations you are going to get?
  • How to format the messages you send to a given service.?
  • What will it do when it receives the messages?
  • What kind of response message you should expect in return, or if something goes wrong, what kind of fault does the service issue?

WCF Structures an overall contract by with its consumers by defining the following three core contracts:

  • Service Contract :- Defines which operations the service makes available to be invoked as request messages are sent to the service from the client.
  • Data Contract :- Defines the structure of the data included in the payloads of the messages flowing in and out of the service.
  • Message Contract :- Enables you to control the headers that appear in the messages and how the messages are structured.

Categorically there are two types of contracts:

1. Behavioral Contracts

2. Structural Contracts

Today we are going to delve in to first category — Behavioral contract

Behavioral Contracts

  • Tools to start defining WCF services.
  • It helps you to define how your service will behave (and in OOPs term we define class’s behavior using methods]

It focused on .NET attributes you need from System.ServiceModel namespace to specify the behavioral aspects of your WCF Service:

  • How the service behaves and what operations it exposes.
  • When the service might issue faults and what kind of faults it might issue.
  • What are the MEPs required to interact with the service? – Operation is request/response way, one way or duplex.

Basically there are 3 types of Behavioral contracts:

  1. ServiceContractAttribute
  2. OperationContractAttribute
  3. Fault Contracts

Let’s discuss them one by one.

ServiceContractAttribute
Service contract describes the operation that service provide. A Service can have more than one service contract but it should have at least one Service contract.

  • It describes the client-callable operations (functions) exposed by the service
  • It maps the interface and methods of your service to a platform-independent description
  • It describes message exchange patterns that the service can have with another party. Some service operations might be one-way; others might require a request-reply pattern
  • It is analogous to the element in WSDL

To create a service contract you define an interface with related methods representative of a collection of service operations, and then decorate the interface with the ServiceContract Attribute to indicate it is a service contract.

Named parameter options:

Named Parameter Description
Name
•Specifies a different for the contract instead of the default,
which is simply the interface or class type name. This contract name will
appear in WSDL.
Namespace
•Specifies a target namespace in the WSDL for the service.
The default namespace is http://tempuri.org . It’s really good practice to provide
Namespace.

Just a note : Please note that there are other named parameters as well. But it has been omitted intentionally to make things simple.

[ServiceContract(Name="CalculatorService",
Namespace="http://schemas.demo.com/2011/10/calc/")]
public interface ICalculator
{
[OperationContract]
double Add(double number1, double number2);
}

TIP:

  1. Always use Namespace property to provide a URI that in some way uniquely identifies both your organization and the conceptual or business domain in which the service operates. W3C standard – year and month to differentiate versions of your service.
  2. Good practice to use the Name property to remove the leading I because I is more of a .NET idiom.

OperationContractAttribute

  • Can be applied only to methods
    Used to declare the method belonging to a Service contract.

Named parameter options:

Named Parameter Description
Name
•Specifies a different name for the operation instead of using the default
which is the method name.
IsOneWay
•Indicates whether the operation is one-way and has no reply.

Just a note : Please note that there are other named parameters as well. But it has been omitted intentionally to make things simple.

[ServiceContract(Name="CalculatorService",
Namespace="http://schemas.demo.com/2011/10/calc/")]
public interface ICalculator
{
[OperationContract(Name=“AddMethod",
IsOneWay=true)]]
double Add(double number1, double number2);
}

Fault Contracts

  • When something goes wrong – what to do? (When service issues some faults then what type of information should be issued)
  • Faults (SOAP Faults) Vs. Exceptions (Exceptions) : Faults and exceptions are not the same thing. Exceptions, as referred to here, are a .NET mechanism used to communicate problems encountered as a program executes. The .NET Lang. allows you to throw, catch/handle, and possibly ignore exceptions so that they can be further propagated up the call stack. At the same point they should be handled else .NET runtime will terminate that thread.
    Fault, refer to the SOAP fault mechanism for transferring error or fault conditions from a service. The SOAP specification includes definition for SOAP Faults. Issue faults in a standard way.
  • WCF FaultException Class :- Provides standard mechanism for translating between two world of .NET Exceptions and SOAP Faults – WCF serialized your exception in SOAP Fault.
  • FaultContractAttribute :- enables a service developer to declare which faults a given service might issue if things go wrong. It can be applied to operations only and also more than once if needed.

// Service Contract
[OperationContract]
[FaultContract(typeof(string))]
double Divide(double numerator, double denominator);

// Service Implementation
public double Divide(double numerator, double denominator)
{
if (denominator == 0.0d)
{
string faultDetail = "cannot divide by zero";
throw new FaultException(faultDetail);
}
return numerator / denominator;
}

Message Exchange Patterns (MEP)

MEPs describe the protocol of message exchanges a consumer must engage in to converse properly with the service. For instance, if a consumer sends a message, it needs to know whether it should expect a message back or whether simply sending the request is enough. Further, can the consumer expect unsolicited messages back from the service? WCF supports
the following three MEPs:

1. One-way

  • One-way operation can be enabled by setting IsOneWay property to true in Operation contract attribute.
  • It can’t be used in conjunction with Fault Contract – Because it needs two-way channel.  Also, One way is not really one way!

In One-Way operation mode, client will send a request to the server and does not care whether it is success or failure of service execution. There is no return from the server-side, it is one-way communication.
Client will be blocked only for a moment till it dispatches its call to service. If any exception thrown by service will not reach the server.
Client can continue to execute its statement, after making one-way call to server. There is no need to wait, till server execute. Sometime when one-way calls reach the service, they may not be dispatched all at once but may instead be queued up on the service side to be dispatched one at a time, according to the service’s configured concurrency mode behavior. If the number of queued messages has exceeded the queue’s capacity, the client will be blocked even if it’s issued a one-way call. However, once the call is queued, the client will be unblocked and can continue executing, while the service processes the operation in the background.

[ServiceContract(Name = "PizzaService",
Namespace = "http://schemas.demo.com/2011/10/pizza/")]
public interface IPizzaService
{
[OperationContract(IsOneWay = true)]
void CancelPizza(int pizzaOrderNumber);
}

2. Request / Response [Default Message exchange pattern]

By default all WCF will be operated in the Request-Response [IsOneWay property of OperationContractAttribute is false) mode. It means that, when client make a request to the WCF service and client will wait to get response from service (till receiveTimeout). After getting the response it will start executing the rest of the statement. If service doesn’t respond to the service within receiveTimeout, client will receive TimeOutException

Void method doesn’t mean OneWay. It can use Request/Response and it’s really good practice to use it because this MEP allows to receive faults.

3. Duplex

Duplex MEP is a two-way message channel whose usage might be applicable in following situation:

  • Consumer sends a message to the service to initiate longer-running processing and then subsequently requires notification back from the service, confirming the requested processing has been done.

Duplex MEP has following issues:

  • it’s problematic in real world because a service needs connection back to the client – Firewalls and NAT problems.
  • Not Scalable. – We want stateless.
  • You lose interoperability. Because to implement Duplex MEP we need to use Callback method in WCF. But what if client is JAVA – which doesn’t supports callback methods.
  • Threading problems.

In Short Duplex is Complex! – Avoid using it. Use it if you really need it! – Okay, then how to deal with above given situation without Duplex?

Stay tuned for next story! (Just a note : If you would like to get email update whenever new story get posted, please do subscribe using subscription form — given right side)

Happy WCF Programming! :-)

Posted in WCF | Tagged: | 2 Comments »

WCF Fundamentals and Quick start

Posted by kiranpatils on October 1, 2011

Challenge:

After receiving lot of appreciation and positive comments on my first WCF article Why we need Windows Communication Foundation? and suggestion from Manaday (Which was going back of my mind. But somehow I was not bringing it in implementation), Henceforth I am going to post full WCF Series based on last fictional story.

So, here’s the 2nd part of WCF Story where our architect would like to share his WCF Fundamentals with you!

Solution:

Architect was kind enough to share his WCF Fundamental notes what he created for his team with you! [We should be thankful to him :) ]

WCF provides API for creating systems that send messages between clients and services. Which can be sent either Intranet or Internet over TCP,HTTP,MSMQ, Web Services etc. Also it’s Interoperable!

Following are most of the concepts and terms used in WCF:

  • Message: Self-contained packets of data that may consist of several parts including header and body. All parts of a message can be encrypted and digitally signed except for the header which must be in clear text.
  • Service: A software module (EXE or DLL) that provides 1 to n endpoints with each endpoint providing 1 to n service operations.
  • Endpoint: A single interface that is used to establish communications between clients and hosts. Each endpoint has its own address that is appended to the base address of the service, making it a unique entity. A WCF service is a collection of endpoints.
  • Binding: A set of properties that define how an endpoint communicates with the outside world. At the very least, the binding defines the transport (HTTP or TCP) that is necessary to communicate with the endpoint. A binding may also specify other details such as security or the message pattern used by the endpoint.
  • System-provided bindings: A collection of bindings that are optimized for certain scenarios. For example, WSHttpBinding is designed for interoperability with Web Services that implement various WS-* specifications.
  • Service Contract: The contract defines the name of the service, its namespace, and other global attributes. In practice, a contract is defined by creating an interface (interface in C#) and applying the [ServiceContract] attribute. The actual service code is the class that implements this interface.
  • Operation Contract: Given that a service contract is defined by creating an interface and annotating it with [ServiceContract], an operation contract is a member method of that interface that defines the return type and parameters of an operation. Such an interface method must be annotated with [OperationContract].
  • Data Contract: Data types used by a service must be described in metadata to enable clients to interoperate with the service. The descriptions of the data types are known as data contracts and the types may be used in any message (parameters or return types).
  • Service operation: A method that is implemented and exposed by a service for consumption by any client. If a service contract is defined by creating an interface, then a service operation is the class that implements this interface.The method may or may not return a value, and may or may not take any arguments. Note while a method invocation might appear as a single operation on the client, it can result in sending multiple messages to the service. For example, a method with two arguments called on a WCF client results in two messages sent to the service.
  • Host: A host is an application (typically .exe) that is used to control the lifetime of a service. A host can be a console, a Windows Service, a Window Activation Service (WAS) and Internet Information Service (IIS) among others. For IIS, you can set a virtual directory that contains the service assemblies and configuration file. When a message is received, IIS starts the service and control its lifetime. When a client (or clients) end(s) the session, IIS closes the application and releases it resources.
  • Behavior: A behavior is a type (i.e., class) that augments the runtime functionality of a service. Service behaviors are enabled by applying a [ServiceBehavior] attribute to a service class and setting properties to enable various behaviors. Behaviors are used to control various runtime aspects of a service or endpoint. Behaviors are grouped according to scope: Common behaviors affect all endpoints, service behaviors affect only service-related aspects, and endpoint behaviors affect only endpoint-related properties. For example, an endpoint behavior may specify where and how to find a security credential.
  • Instancing: A service has an instancing model which controls how many instances of the service can run at one time. There are four instancing models: single, per call, per session, and shareable. The first two are similar in concepts to the Singleton and Single Call SAOs in .NET Remoting. Instancing is a behavior and and as such it is specified as part of the [ServiceBehavior] attribute as follows: [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)].
  • Client Application: A program that exchanges messages with one or more endpoints. The client application typically creates a WCF Client Object and then calling methods on this proxy object.
  • Channel: This is the transport connection between a client application and an endpoint in a service. A client uses a transport (TCP, HTTP, etc.) and an address to construct a channel to a specific endpoint.
  • WCF Client Object: This a client-side construct that encapsulates service operations as methods, in other words, a WCF Client Object is a proxy to the service methods. Note that any application can host a WCF Client Object, even an application hosting a service. Therefore, it is possible to create a service that includes and uses proxies to other services. These proxies are typically generated using the svcutil.exe command-line utility.
  • Metadata: data that is generated by the svcutil.exe command-line utility. This data includes:
  1. XML schema that define the data contract of the service.
  2. WSDL to describe the methods of the service.
  3. Application configuration files.
  • Metadata exchange point: An endpoint with its own address that is used to publish metadata.
  • Security: Security in WCF includes encryption of messages, integrity of messages, authentication and authorization. These functions can be provided by either using existing security mechanisms such as HTTPS or by implementing one or more of the various WS-* security specifications.
  • Message pattern: The message pattern determines the relationship and direction of messages between the client and the service. The most basic pattern is the one-shot (or one way) pattern is which a message is sent to the server but not response is expected. The most complex pattern is a dual HTTP pattern where two HTTP channels are constructed between a client and a service, with both sides invoking operations on each other.
  • Reliable messaging: The assurance that a message is received only once and in the order in which it was sent.
  • Sessions: A session is used to establish communication between a client and a service in which all messages are tagged with an ID that identifies the sessions. If a session is interrupted, it can be restarted with the session ID. If a service contract supports a session, then you will need to use Instancing to determine how the class that implements the service contract behaves during the session. See the Duplex Message Pattern example in Designing Contracts chapter.

Basic WCF Programming Lifecycle

Here are the basic steps of WCF Programming Lifecycle – Order matters!

  1. Define the service contract. A service contract specifies the signature of a service, the data it exchanges, and other contractually required data.
  2. Implement the contract. To implement a service contract, create the class that implements the contract and specify custom behaviors that the runtime should have.
  3. Configure the service by specifying endpoint information and other behavior information.
  4. Host the service in an application.
  5. Build a client application.

Just a note : Although the topics in this section follow this order, some scenarios do not start at the beginning. For example, if you want to build a client for a pre-existing service, you start at step 5. Or if you are building a service that others will use, you may skip step 5.

WCF Quick start

Following steps will help you to create your first WCF service (In this example we are going to create two console applications one console application will be hosting the service and second one will be consuming the service):

Step 1 : Define a Windows Communication Foundation Service Contract : When creating a basic WCF service, the first task is to create the contract for the service that is shared with the outside world that describes how to communicate with the service. This contract specifies the collection and structure of messages required to access the operations offered by the service. This is done by creating an interface that defines the input and output types, which apply the ServiceContractAttribute to the interface and OperationContractAttribute to the methods that you want to expose.

NOTE : We need to add reference to System.ServiceModel

The service contract that is used here employees a request-reply message exchange pattern by default that is not explicitly specified. You can specify this and other message exchange patterns for client-service communications by setting properties of the OperationContractAttribute and ServiceContractAttribute in the contract.

Example:


namespace WCFService
{
[ServiceContract]
public interface ICalculator
{
// It will be exposed to clients
[OperationContract]
double Add(double number1, double number2);
}
}

Step 2 : Implement a Windows Communication Foundation Service Contract : Implement the Service Contract defined in step1.

Example:


namespace WCFService
{
public class CalculatorService : ICalculator
{
#region ICalculator Members

public double Add(double number1, double number2)
{
Console.WriteLine("Service called at : {0}", DateTime.Now.ToString());
Console.WriteLine(@"Calculator Service got called
with two parameters {0} and {1}",
number1,
number2);
double result = number1 + number2;
Console.WriteLine("The result is : {0}",result);
Console.WriteLine("-------------------------------");
return result;

}
#endregion
}
}

Step 3 : Run a Basic Windows Communication Foundation Service :

This topic describes how to run a basic Windows Communication Foundation (WCF) service. This procedure consists of the following steps:

  • Create a base address for the service.
  •  Create a service host for the service.
  •  Enable metadata exchange.
  •  Open the service host.

Example:


namespace WCFService
{
class Program
{
static void Main(string[] args)
{
// Address
Uri baseAddress =
new Uri("http://localhost:8080/WCFService/Service");

// Host
ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService),
baseAddress);
try
{
// Binding, Contract
serviceHost.AddServiceEndpoint(typeof(ICalculator),
new WSHttpBinding(),
"CalculatorService");

// Metadatabehavior
// WSDL information we need to expose to clients
// it works on HTTP GET Method
ServiceMetadataBehavior serviceMetadatabehavior
= new ServiceMetadataBehavior();
serviceMetadatabehavior.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(serviceMetadatabehavior);

// Start the service
serviceHost.Open();

Console.WriteLine("Service started : {0}",
DateTime.Now.ToString());

// Stop the service
Console.WriteLine("Press  ENTER to shut down the service");
Console.ReadLine();
serviceHost.Close();

Console.WriteLine(@"Service shutdown successfully.
Thank you for using our service!");

}
catch (CommunicationException ce)
{
Console.WriteLine(ce.Message);
serviceHost.Abort();
}
}
}
}

Step 4: Create a Windows Communication Foundation Client : This topic describes how to retrieve metadata from a WCF service and use it to create a proxy that can access the service. This task is most easily completed by using the ServiceModel Metadata Utility Tool (Svcutil.exe) provided by WCF. This tool obtains the metadata from the service and generates a managed source code file for a client proxy in the language you have chosen. In addition to creating the client proxy, the tool also creates the configuration file for the client that enables the client application to connect to the service at one of its endpoints.

svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config

By default, the client proxy code is generated in a file named after the service (in this case, for example, CalculatorService.cs or CalculatorService.vb where the extension is appropriate to the programming language: .vb for Visual Basic or .cs for C#). The /out switch used changes the name of the client proxy file to “generatedProxy.cs”. The /config switch used changes the name of the client configuration file from the default “output.config” to “app.config”.

Just a note : If you would like to test your service quickly. You can use WCFTestClient.exe utility which will help you to test your service without writing a single line of code for your WCF Client!

Step 5: Configure a Basic Windows Communication Foundation Client : This topic adds the client configuration file that was generated using the Service Model Metadata Utility (Svcutil.exe) to the client project and explicates the contents of the client configuration elements. Configuring the client consists of specifying the endpoint that the client uses to access the service. An endpoint has an address, a binding and a contract, and each of these must be specified in the process of configuring the client.

svcutil.exe will provide you the default configuration automatically.

Step 6 : Use a Windows Communication Foundation Client : Once a Windows Communication Foundation (WCF) proxy has been created and configured, a client instance can be created and the client application can be compiled and used to communicate with the WCF service. This topic describes procedures for creating and using a WCF client. This procedure does three things: creates a WCF client, calls the service operations from the generated proxy, and closes the client once the operation call is completed.

Now, copy paste the svcutil generated files (CS and Config file) within your console project and then you can call your service from your client application as shown below:

Example:

namespace WCFClient
{
class Program
{
static void Main(string[] args)
{
CalculatorClient calculatorClient = new CalculatorClient();
Console.WriteLine("Proxy calling service...");
Console.WriteLine(calculatorClient.Add(10, 20));
// Good practice
calculatorClient.Close();
Console.WriteLine("closed!");
}
}
}

And then first start your service (your service must be in running state before you run the client) and then run the client. And this is how it will look like:

Resources

Mike Taulty’s Video : Windows Communication Foundation:” Hello World”:

http://go.microsoft.com/?linkid=4091084
http://download.microsoft.com/download/f/b/3/fb3c2a8b-604e-479b-ab22-e31dc094a40d/WCF_Hello_World.zip

Stay tuned for next story! (Just a note : If you would like to get email update whenever new story get posted, please do subscribe using subscription form — given right side) :)

Happy WCF Programming! :-)

Posted in WCF | Tagged: | 2 Comments »

Why we need Windows Communication Foundation?

Posted by kiranpatils on September 29, 2011

Challenge:

In earlier days, when i was totally newbie to WCF, I was not clear why we need WCF? one thing I was clear that it has something to do with Web Services. But other than that nothing was much clear.

Then at one fine day, I came across Shivprasad Koirala’s .NET Interview questions book. In which he explained why we need WCF and what is WCF using a fictional story. It is really nicely written and it clears why we need WCF.

Before couple of days, I got good time (as I was on holidays) to convert that story in a comic — To make it more funny (And that’s what philosophy I follow — “Coding should be fun” :-) ) and comic blog — a new concept which I always wanted to start!

So, here we go my first comic blog article which explains why we need WCF?

Solution:

  • Long Long time ago there lived a hardworking and a nice architecture.
  • Develop a Booking Engine which books tickets for any flight carriers.
  • The nice and hardworking architecture and his team developed a nice booking engine by which you can book tickets through any of the flight Carriers. The Travel Agent Company was very happy with the architecture and his team Member’s achievements.

  • As time passed by the travel agent’s business grew in multiples
  • Architecture and his team was very excited and they started to work on this new stuff
  • All franchises run on Windows Platform.
  • Booking engine was located in the main head office and all the franchise should communicate to this booking engine.
  • After months he rolled out his project successfully.

  • Time passed by and because of the good automated booking service more companies wanted to take the franchise from the travel agent. But the big issue was many of the franchise did not have windows operating system. They worked on Linux and other Non-Microsoft operating systems.
  • Due to this limitation travel agent was losing lot of franchise business.
  • Now, booking engine runs on two platforms .NET Remoting (for Windows based clients) and Web Services (for non-windows based clients).

  • Franchise client had to wait to get response and was not able to process the next ticket booking until the first one was served. Travel Agent started receiving huge complaints because of this synchronous processing.
  • Booking engine had the capacity of serving 20 tickets / second but it had now to serve 50 tickets / second.
  • when the travel agent makes a booking it will come and fall in the queue and release the travel agent. Booking engine will always poll for this queue. When the booking engine finishes he will publish the booking results back to the queue. Travel agent client can then come at his leisure and see the results.

  • Everyone in the travel company was really happy and impressed by the architect and his team members
  • Travel Agent then felt a huge necessity of a good security model with the booking engine.

  • Till now the travel agent was booking one ticket at a time. But soon he started getting lot of orders to book group family tickets.
  • Consistency – If father’s ticket gets canceled. Kid’s ticket should also be got canceled.

They were working on:

  • .NET
  • .NET Remoting
  • Web Services
  • MSMQ
  • WSE
  • COM+

WCF is a unification of all distributed technologies like:

  • .NET Remoting
  • MSMQ
  • Web Services
  • COM+

Thanks a lot Shivprasad Koirala for writing such a nice story!

Happy Coding! :-)

Posted in WCF | Tagged: | 6 Comments »

Hosting a WCF Service in IIS 7.0

Posted by kiranpatils on September 29, 2008

If you would like to deploy your WCF Service within following environment:

  1. Windows Server 2008
  2. IIS 7.0

Or facing following Error:

Server Error in Application “DEFAULT WEB SITE/ EmployeeService “Internet Information Services 7.0

Error Summary

HTTP Error 404.3 – Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map. Detailed Error InformationModule StaticFileModule

Notification ExecuteRequestHandler

Handler StaticFile

Error Code 0×80070032

Requested URL http://localhost:80/EmployeeService/ EmployeeService.svc

Physical Path

C:\inetpub\wwwroot\Employee.Net.Services\/EmployeeService \EmployeeService.svc

Logon Method Anonymous

Logon User Anonymous

Most likely causes:

It is possible that a handler mapping is missing. By default, the static file handler processes all content.

The feature you are trying to use may not be installed.

The appropriate MIME map is not enabled for the Web site or application. (Warning: Do not create a MIME map for content that users should not download, such as .ASPX pages or .config files.)

If ASP.NET is not installed.

Things you can try:

In system.webServer/handlers:

Ensure that the expected handler for the current page is mapped.

Pay extra attention to preconditions (for example, runtimeVersion, pipelineMode, bitness) and compare them to the settings for your application pool.

Pay extra attention to typographical errors in the expected handler line.

Please verify that the feature you are trying to use is installed.

Verify that the MIME map is enabled or add the MIME map for the Web site using the command-line tool appcmd.exe.

To set a MIME type, use the following syntax: %SystemRoot%\windows\system32\inetsrv\appcmd set config /section:staticContent /+[fileExtension='string',mimeType='string']

The variable fileExtension string is the file name extension and the variable mimeType string is the file type description.

For example, to add a MIME map for a file which has the extension “.xyz”: appcmd set config /section:staticContent /+[fileExtension='.xyz',mimeType='text/plain']

Warning: Ensure that this MIME mapping is needed for your Web server before adding it to the list. Configuration files such as .CONFIG or dynamic scripting pages such as .ASP or .ASPX, should not be downloaded directly and should always be processed through a handler. Other files such as database files or those used to store configuration, like .XML or .MDF, are sometimes used to store configuration information. Determine if clients can download these file types before enabling them.

Install ASP.NET.

Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, click here.

And looking some work around for it then this article for you…..go ahead…

For deploying WCF you need to do one way from the following one:

  1. You have to run servicemodelreg -i as an administrator using VS 2008 Command prompt (you can find it in <WINDOWSDRIVE>:\Windows\WinFx\v3.0\Windows Communication Foundation).

Credit goes to: http://www.u2u.info/Blogs/Peter/Lists/Posts/Post.aspx?ID=151

2. If you want to do it from scratch…just follow this article:

http://blah.winsmarts.com/2008-4-Host_a_WCF_Service_in_IIS_7_-and-amp;_Windows_2008_-_The_right_way.aspx

That’s it…

Let me know if you face some problem…may be i can help..

-Kiran

Posted in WCF | Tagged: , | 6 Comments »

“The underlying connection was closed: The connection was closed unexpectedly.” While returning Data Table from WCF service.

Posted by kiranpatils on September 22, 2008

Error:

“The underlying connection was closed: The connection was closed unexpectedly.”

StackTrace:

System.ServiceModel.CommunicationException was unhandled by user code

Message=”The underlying connection was closed: The connection was closed unexpectedly.”

Source=”mscorlib”

StackTrace:

Server stack trace:

at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)

at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)

at System.ServiceModel.Channels.ClientReliableChannelBinder`1.RequestClientReliableChannelBinder`1.OnRequest(TRequestChannel channel, Message message, TimeSpan timeout, MaskingMode maskingMode)

at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout, MaskingMode maskingMode)

at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout)

at System.ServiceModel.Security.SecuritySessionClientSettings`1.SecurityRequestSessionChannel.Request(Message message, TimeSpan timeout)

at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)

at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)

at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)

at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)

at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:

at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)

at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)

at System.Web.UI.Control.OnLoad(EventArgs e)

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

InnerException: System.Net.WebException

Message=”The underlying connection was closed: The connection was closed unexpectedly.”

Source=”System”

StackTrace:

at System.Net.HttpWebRequest.GetResponse()

at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

InnerException:

Scenario:

I have one OperationContract defined in my service contract which was returning DatTable as its return Type So it was looking like this:

[OperationContract]

DatTable LoadEmployeeInformation(long employeeID);

And in implementation I am filling this data Table using Table Adapter and returning it.

But it was throwing me error which was really annoying i had spent 4-5 hours to figure out it…

Solution:

I have changed my operation Contract to return Dataset Instead of Data Table

[OperationContract]

DataSet LoadEmployeeInformation(long employeeID);

and it worked like a charm!!!! For me…and hope that it works for you also…then go ahead and try this change….

Root cause:

Sorry guys I don’t know the root cause of this error. But i read some forums from Microsoft and they says that don’t use Data Table as a return type because some problem occurs in deserializaing it at client side…hooh…but I think it is BUG of WCF!!

Webliography:

http://connect.microsoft.com/wcf/feedback/ViewFeedback.aspx?FeedbackID=286535

http://processmentor.com/community/blogs/scott_middleton/archive/2007/06/08/169.aspx

http://blogs.msdn.com/lifenglu/archive/2007/08/01/passing-datatable-across-web-wcf-services.aspx

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1828652&SiteID=1&mode=1

http://blogs.conchango.com/merrickchaffer/archive/2007/09/19/WCF-System.Net.WebException_3A00_-The-underlying-connection-was-closed_3A00_-The-connection-was-closed-unexpectedly.aspx

-Kiran

Posted in WCF | Tagged: , | 23 Comments »

Web service Software factory Quickstart or Security with Web Service Software Factory Using Direct Using Direct Authentication

Posted by kiranpatils on December 10, 2007

Target Audience:

if you want to make one demo application in Windows Service factory and also want to see security features of WCF than this is for you…so good to go….if not than go….

prerquisities:

Web Service Software Factory–July 2006

Visual studio 2005

get it from here:http://msdn2.microsoft.com/en-us/library/aa480534.aspx

You can use the WCF Security Guidance Package to configure and test security settings used by Windows Communication Foundation (WCF) services. The guidance package contains recipes that are used to configure authentication protocols. In addition, a recipe is also included that can be used to validate the configuration and perform code analysis using FxCop. The authentication recipes represent an automated process that makes it very easy to configure security.

You can also use the Service Configuration Editor included in the Microsoft Windows Software Development Kit (SDK) for .NET Framework 3.0 to manually configure WCF security settings. The guidance package is easier to use than the service configuration editor, but there may be cases when you have to modify security settings on a computer that does not have the guidance package installed. As a result, this topic discusses both automated configuration using the guidance package and manual configuration using the configuration editor.

Employee Service

1. Create A project By File->new->Project

WCF SERVICE 01

WCF SERVICE 02WCF SERVICE 03

It will generate the solution structure as shown above.

How to: Implement EmployeeService

EmployeeService.DataContracts

To create your data contract using the Create Data Contract recipe

WCF SERVICE 04

This will bring up the recipe wizard

WCF SERVICE 06

Click Next

WCF SERVICE 07

When Table is validated at that time only the Finish Button is going to be enable

It will generate following file:

using System;

using System.Collections.Generic;

using System.Runtime.Serialization;

namespace EmpService.DataContracts

{

/// <summary>

/// Data Contract Class – Employee

/// </summary>

[DataContract(Namespace = "http://EmpService.DataContracts/2007/12", Name = "Employee")]

public partial class Employee

{

private System.Int32 EmployeeIDField;

[DataMember(IsRequired = true, Name = "EmployeeID", Order = 0)]

public System.Int32 EmployeeID

{

get { return EmployeeIDField; }

set { EmployeeIDField = value; }

}

private System.String FirstNameField;

[DataMember(IsRequired = false, Name = "FirstName", Order = 1)]

public System.String FirstName

{

get { return FirstNameField; }

set { FirstNameField = value; }

}

private System.String LastNameField;

[DataMember(IsRequired = true, Name = "LastName", Order = 2)]

public System.String LastName

{

get { return LastNameField; }

set { LastNameField = value; }

}

private System.String NoteField;

[DataMember(IsRequired = false, Name = "Note", Order = 3)]

public System.String Note

{

get { return NoteField; }

set { NoteField = value; }

}

}

}

EmployeeService.ServiceContracts

To create your service contract using the Create Service Contract recipe

WCF SERVICE 08

This will show up a Service Contract Recipe

WCF SERVICE 09

WCF SERVICE 10

Service Contract Example[Fill values in above table like shown as below Table. if value is not in belows table you can keep it as it is.]

Name

Request

Response

FindEmployeeByLastName

System.String

 

EmployeeService.DataContracts.Employe

WCF SERVICE 11

For this example, you do not generate the service contract implementation

Just Build the Solution.

 

EmployeeService.ServiceImplementation

To implement the service contract

WCF SERVICE 12

WCF SERVICE 14

it will generate following code:

public EmpService.DataContracts.Employee FindEmployeeByLastName(string request)

{

EmpService.DataContracts.Employee emp = new EmpService.DataContracts.Employee();

System.Security.Principal.IPrincipal principal = System.Threading.Thread.CurrentPrincipal;

emp.EmployeeID = (request.Length > 0) ? request[0].GetHashCode() : 0;

emp.FirstName = principal.Identity.Name;

emp.LastName = request;

emp.Note = “AuthType = “ + principal.Identity.AuthenticationType;

return emp;

}

This is test code that returns the Employee data contract with the FirstName property equal to the current authenticated user name, the LastName property equal to the request, and the Note property initialized with the authentication type used by the WCF service

How to: Expose and Test the Service

Services are exposed and tested through the provided sample host. This host is a file system–based Web application that uses the built-in Web server included in ASP.NET 2.0 for developing and testing purposes. To enable the host, use the Expose Service recipe.

WCF SERVICE 17

WCF SERVICE 19

To test the host

1. In Solution Explorer, right-click EmployeeManager.svc (it was added in the previous step), point to Service Factory (WCF), and then click View in Browser or Debug Host. This opens a browser window.

2. In the browser window that opens, you can examine the WSDL and learn how to use Svcutil.exe to generate client code used to access the service. Svcutil.exe is a service model metadata utility tool included in the Microsoft Windows Software Development Kit (SDK) for .NET Framework 3.0.

WCF SERVICE 20

How to: Implement the Test Client

Services are tested through the provided sample client application. The client application included with the WCF Service template is a Windows Forms application that includes a grid to view the results.

WCF SERVICE 21

WCF SERVICE 22

Copy this URL

WCF SERVICE 23

WCF SERVICE 24

WCF SERVICE 25

To test the service clientTabClick

 

Press Enter And TAB it will generate the code shown as below:

//TODO: Call proxy method

using( proxy = new ())

{

[] dts = proxy.FindBy(this.SearchText.Text);

ResultsGrid grid = new ResultsGrid(dts);

grid.ShowDialog(this);

}

Now fill it like this:

private void ExecuteButton_Click(object sender, EventArgs e)
{
//TODO: Call proxy method
using(EmployeeManager.EmployeeManagerClient proxy = new EmployeeManager.EmployeeManagerClient ())
{
EmployeeManager.Employee dts = proxy.FindEmployeeByLastName(this.SearchText.Text);

ResultsGrid grid = new ResultsGrid(dts);

grid.ShowDialog(this);
}
}

This implies that you have implemented a FindEmployeeByLastName method in the EmployeeManager class. This is your business logic.

WCF SERVICE 35

WCF 29

WCF 30

It looks Good…..na so much work gives you so nice result…isn’t it?????

WCF SECURITY

To use the security package, you have to enable it using the Guidance Package Manager. After it is enabled, you have to modify security settings for the solution before you use any of the other security recipes. For information about how to enable the security package and configure the solution, see the following subtopics:

How to: Enable the WCF Security Guidance Package

WCF 31

WCF 34

click on enable/Disable Packages..

WCF 37

Select Web Service software factory security->OK->Close.

 

In short Steps:

To enable the WCF Security Guidance Package

1. On the Tools menu, click Guidance Package Manager.

2. Click Enable / Disable Packages.

3. Select the Web Service Software Factory – Security (WCF) check box.

4. Click OK.

5. Click Close

How to: Modify Your Security Settings

 

Using the Modify Security Settings recipe, you can constrain the security settings for the solution. It is intended to be used by an architect or lead developer who wants to pre-configure security settings for services within the solution.

To modify your security settings

1. In Solution Explorer, right-click the solution, point to Service Factory (WCF Security), and then click Modify security settings.

WCF 36

 

2. On the Security Settings page, you can set the security settings that are available for the solution. The following options are available:

· Kerberos

· X.509 Certificates

· Direct Authentication (using UsernameToken) with Windows accounts

· Direct Authentication (using UsernameToken) with ADAM provider

· Direct Authentication (using UsernameToken) with SQL Server provider

· Anonymous

WCF 38

 

3. On the Message Protection Settings page, you can set the protection levels that are available for the solution. The following options are available:

· None

· Sign

· Sign and Encrypt (XML signatures are also encrypted)

WCF 39

Press FINISH.

It will save the settings in solution means now whenever you click on Security Settings it will show you the settings which you have modified.

 

The following is optional [I have also copied and pasted from MSDN :-) ]

TO DO IT MANUALLY

How to: Use the Service Configuration Editor

The Microsoft Windows Software Development Kit (SDK) for .NET Framework 3.0 provides a tool named Service Configuration Editor that can be used to create and modify security settings in a configuration file. There are several options that can be used to open a configuration file using the configuration editor; this topic describes two options. The first option is to launch the editor and open the configuration file using editor menus. The second option is to add the service configuration file to the list of programs that can be used in the Open With dialog box in Visual Studio.

To launch the configuration editor and open a file

1. On the Start menu, point to All Programs, point to Microsoft Windows SDK, point to Tools, and then click Service Configuration Editor.

2. On the File menu of the configuration editor, point to Open, and then click Config file.

3. In the Open dialog box, navigate to the configuration file you want to open, select the file, and then click Open.

Alternatively, you can create a new configuration file using the configuration editor. To do this, click New Config on the File menu.

To open a file and add the Service Configuration Editor to the Visual Studio Open With dialog box

1. In the Visual Studio Solution Explorer, select the configuration file you want to open.

2. Right-click the configuration file, and then click Open With.

3. Click Add, and then type the following in the Program Name box: C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin\SvcConfigEditor.exe. In the Friendly Name box, type Service Configuration Editor, and then click OK.

4. In the Open With dialog box, click Service Configuration Editor (it was added in step 3), and then click OK.

Figure 1 illustrates the Service Configuration Editor with an open Web.config file.

WCF 41

Service Configuration Editor

In the Service Configuration Editor, the tree view in the left pane is used to navigate through different elements in the configuration file. Many of the folders shown in the tree view represent XML elements under the <system.serviceModel> element in a configuration file. The main pane on the right is used to configure different attributes for the element selected in the left pane. Examining all the different configuration settings is beyond the scope of this discussion; however, this subtopic reviews settings that are used to control security.

ms-help://MS.VSCC.v80/MS.VSIPCC.v80/ms.wssf.2006Dec/WSSF/local/note.gifNote:

Many folders in the service configuration tree view represent XML elements in a configuration file. The main pane in the Service Configuration Editor is used to set attributes of the element that is selected in the tree view.

As shown in Figure 1, there are five top-level folders: Services, Client, Bindings, Diagnostics, and Advanced.

The Services folder represents the services configuration element, which contains one or more service configurations. Under each service element is an endpoints element that contains one or more endpoint configurations. An endpoint for a service identifies the contract that defines the service interface. With the example illustrated in Figure 1, the service contract is defined as EmployeeService.ServiceContracts.IEmployeeManager.

Each endpoint element must contain binding information that indicates how a client application connects to the service. The endpoint can also identify a behavior that can be used to extend the default behavior of a WCF service.

The Client folder represents a client configuration element. The client element contains an endpoint element used to define the address of the WCF service accessed by the client application. Similar to the service endpoint, the client endpoint also contains binding and behavior information.

The Bindings folder represents the bindings configuration element, which contains one or more binding configurations. Bindings specify communication details used to connect to a WCF endpoint, such as transport protocols, security requirements, and encoding requirements. Security requirements for a binding include authentication protocols with related encryption and signing requirements.

The Diagnostics folder represents a diagnostics element that contains different configuration elements used to enable actions such as tracing and message logging.

The Advanced folder does not represent a configuration element; however, some child folders, such as Endpoint Behaviors and Service Behaviors, represent elements in the configuration file. Endpoint Behaviors represents an element named endpointBehaviors that can contain one or more behavior configurations that can be used by an endpoint. The Service Behaviors folder represents an element named serviceBehaviors that contains one or more behavior elements that can be used by a service. Several behaviors are included in the .NET Framework 3.0 runtime that can be used to perform operations such as authorization.

The following is a summary of elements that control security:

  • · A service element contains information used to specify how client applications connect to and interact with the service. For example:
  • Endpoints in a service identify a service contract and binding type.
  • Service behaviors can be used to perform authorization and supply credentials for a service.
  • A binding element specifies transport protocols, security requirements, and encoding requirements used to connect to a service

When using X.509 certificates, direct authentication, or anonymous authentication, you have to install X.509 certificates in a certificate store located on your server or client workstation. For information about how to request and install these certificates, see the following subtopic:

How to: Install X.509 Certificates in the Local Certificate Store

There are two types of certificates you will need to install and use when configuring and testing WCF security using the Web Service Software Factory - Security (WCF) guidance package. The first one is a computer certificate that will be installed in the Local Computer certificate store. The second one is a client certificate that will be installed in the Current User certificate store. These tasks will be accomplished using a Microsoft Management Console (MMC) snap-in, which is described in How to: Use the X.509 Certificate Management Tools of Web Service Security: Scenarios, Patterns, and Implementation Guidance for Web Services Enhancements (WSE) 3.0.

To initialize the MMC snap-in for certificates

WCF 43

WCF 44

WCF 45

WCF 46

WCF 48

WCF 49

WCF 51

WCF 51

WCF 54

It will save the file:

WCF56

In short Steps are:

To initialize the MMC snap-in for certificates

1. On the taskbar, click Start, and then click Run.

2. In the Run box, type mmc, and then click OK.

3. On the File menu, click Add/Remove Snap-in, and then click Add.

4. Under Snap-in, double-click Certificates.

5. Click My user account, and then click Finish.

This allows you to manage certificates for the current user. Certificates – Current User appears on the list of selected snap-ins.

6. Under Snap-in, double-click Certificates.

7. Click Computer account, click Next, click Local Computer, and then click Finish.

This allows you to manage local computer certificates.

8. Click Close, and then click OK.

9. To save the console, click Save on the File menu.

10. In the File name box, type Certificates.msc, and then click Save.

This will add a new menu item named Certificates.msc to the Administrator menu. The Certificates.msc menu item can be used to open the certificates snap-in.

After the certificates snap-in has been initialized, the next step is to request a computer certificate that will be used for the WCF services you are configuring.

To obtain an X.509 computer certificate

1. Open the Certificates.msc Microsoft Management Console (MMC) snap-in.
WCF56

Expand Certificates (Local Computer), expand Personal, and then select Certificates.

3. Right-click Certificates, point to All Tasks, and then click Request New Certificate.

4. Create a computer certificate by following the wizard steps:

a. Click Next.

b. In the Certificate types list, click Computer, and then click Next.

c. In the Friendly name box, type a name.

d. (Optional) In the Description box, type a description.

e. Click Next.

f. Click Finish.

How to: Secure Your WCF Service Using Direct Authentication

Direct authentication is a process where a user’s ID and proof-of-possession are used by a service to authenticate the user. Proof-of-possession could be a password or smart card. The combination of user ID and proof-of-possession represent a user’s credentials. The credentials are sent as part of the message to a service, which validates the credentials and sends a response.

WCF 57

As illustrated in Figure 1, the following steps describe the direct authentication process:

1. The client sends a request to the Web service. Credentials are attached to the request message.

2. The Web service validates the credentials against an identity store and makes authorization decisions about the client.

3. (Optional) The Web service returns a response to the client.

In Chapter 1 of Web Service Security: Scenarios, Patterns, and Implementation Guidance for Web Services Enhancements (WSE) 3.0, the architecture pattern section named “Direct Authentication” describes the following forces that would justify using direct authentication:

· The credentials that the client presents to the Web service are based on shared secrets such as passwords. Frequently, authentication of individual users is performed with passwords. Computers and applications often use higher quality secrets that are more secure than passwords. The client and the Web service must securely exchange the shared secrets before interaction is possible. The exchange of shared secrets must occur through an out-of-band mechanism.

· The Web service can validate credentials from the client against an identity store. The Web service must have direct access to the identity store, including appropriate permissions for accessing identity information.

· The Web service is relatively simple, and does not require support for capabilities such as singlesign-on or support for non-repudiation. In these circumstances, an effective, low cost solution that does not use an authentication broker may be possible.

· The client and the Web service trust one another to manage credentials securely. In this situation, both parties should consider the credentials as equal in value to the information and services they protect. If either the Web service or the client manage the credentials in an insecure manner, neither party can be sure that the mishandled credentials prove the identity of the user or application.

The WCF Security guidance package contains three recipes for direct authentication that support different identity stores:

ADAM. Active Directory Application Mode (ADAM) is a lightweight directory service that is accessed using a Lightweight Directory Access Protocol (LDAP).
SQL Server. User credentials are stored in a database and accessed using membership and role provider classes that are available in the .NET Framework.
Windows accounts. Credentials are used to authenticate users stored in Active Directory.

To secure your WCF service using direct authentication:

1. In Solution Explorer, right-click the Web service Host project, point to Service Factory (WCF Security), and then click Secure a Service Using Direct Authentication with [Provider].

WCF58

2. Specify your service properties, including service name, endpoint, binding name, and behavior name.

WCF59

WCF60

3. Select the X.509 certificate you want to use from a certificate store. The X.509 certificate in this step is used to provide data origin authentication.

WCF61

4. Select your message protection requirements The configuration options for message protection requirements and algorithm suite will be dependant on the options that you specified in How to: Modify Your Security Settings. In addition, enable signature confirmation, establish secure conversation, or negotiate service credential configuration settings may be available based on the type of direct authentication being configured.

WCF62

5. Configure the identity provider.

WCF62

That’s done.

I can understand after doing this much long exercise you will fill tired..so go at home….or not than keep reading i will make u…..

Thanks

Source code is Here: Click on Me

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

Posted in Windows service Factory3.0 | Tagged: , , | 3 Comments »

 
Follow

Get every new post delivered to your Inbox.

Join 102 other followers