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

Tuesday, June 14, 2011

Hosting a WCF Service in a Managed Application

WCF enables you to host your service through any managed application. This means you can use a Console application, a Windows service, a Windows Forms application, or even an application built with Windows Presentation Foundation.

Hosting a WCF Service by Using a Console Application

The Console application must specifically create and open an instance of the ServiceHost object. The ServiceHost then remains open and available until it is no longer needed.

Eg:
• Create a New Project from the File menu and select WcfServiceLibrary.
Create and Implement service.
Build the project.
• Create ConsoleApplication named ConsoleServiceHost. From the project menu select Add Reference option and select the WcfServiceLibrary1.dll. Click ok.
Write the following code in the Main function.


ServiceHost host = new ServiceHost(typeof(WcfServiceLibrary1.Service1));
host.Open();
Console.WriteLine("Service Started...");
Console.WriteLine("\nPress any key to stop...");
Console.ReadLine();
host.Close();

Add an Application Configuration file to the project. And write the following configuration settings in the app.config.
<configuration>
<system.serviceModel>
<services>
<service name="WcfServiceLibrary1.Service1" behaviorConfiguration="WcfServiceLibrary1.Service1Behavior">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8731/Design_Time_Addresses/WcfServiceLibrary1/Service1/" />
</baseAddresses>
</host>
<endpoint address ="" binding="wsHttpBinding" contract="WcfServiceLibrary1.IService1">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WcfServiceLibrary1.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>

• Create a new console application. Copy the address from the app.config of ConsoleServiceHost application. Add service reference. Write the following code in the main function.
Console.WriteLine("Press ENTER when the service has started");
Console.Read();

ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();

Console.WriteLine(client.GetData(33));
client.Close();
Console.WriteLine("Press any key to exit");
Console.ReadLine();
Console.ReadLine();

Monday, June 13, 2011

Hosting a WCF Service on a Web Server

Hosting a Service on an IIS Web Server
Hosting a service on an IIS Web server is very similar to hosting a traditional Web service. Services exposed this way will be highly available and scalable, but they will require the installation and configuration of an IIS Web server.

To register WCF in IIS Run the following command.

C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation>ServiceModelReg.exe -i.

You can host a WCF Service in two different ways.

1. Create WCF service in HTTP mode.
When creating a WCF Service in HTTP Mode it automatically hosted in IIS webserver. To create a service in HTTP Mode, your system must have IIS get installed.




2. Manually host the service in IIS like websites.
You can also do hosting a service by creating a virtual directory in IIS and paste you service files into your virtual directory.

Publishing Metadata Through Endpoints

WCF enables you to publish service metadata, using the HTTP-GET protocol. Clients can access the metadata using an HTTP-GET request with a ?wsdl query string appended. You do this by specifying a service behavior either programmatically or through a configuration file. The behavior is then referenced when specifying the service.

You also need to create a metadata exchange endpoint. This special endpoint can append mex to the HTTP address the service uses. The endpoint should use the IMetadataExchange interface as the contract and mexHttpBinding as the binding.

<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServiceBehavior">
<endpoint address="http://localhost:50187/WCFService1/" binding="wsHttpBinding" contract="IService"></endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

Sunday, May 15, 2011

WCF Service Endpoint Basics

Service Endpoint Basics

All communication with a Windows Communication Foundation (WCF) service happens through the endpoints of the service. Endpoints allow clients to access the functionality offered by a WCF service. Every endpoint must be associated with an address, a binding, and a contract

Eg:
<endpoint address="" binding="wsHttpBinding" contract="IService">

ABCs of Endpoints


Address: The address for an endpoint is a unique Uniform Resource Locator (URL) that identifies the location of the service. The address should follow the Web Service Addressing (WS-Addressing) standard.
 
Binding: The binding determines how the service can be accessed. This means that the binding can specify not only the protocol used to access the service but an encoding method used to format the message contents.
 
Contract: The final element in the service endpoint is the contract. This identifies the operations exposed by the service, and it typically refers to the interface name, preceded by the project namespace. By including the namespace, you are using the fully qualified type name for the contract.

Saturday, May 14, 2011

Message Contracts in WCF

Message Contracts


When developing your WCF services, Data contracts enable you to define the structure of the data that will be sent in the body of your SOAP messages, either in the inbound (request) messages or in the outbound (response) messages.

Message Contract Attributes are used to

A. control how the SOAP message body is structured and, ultimately, how it is serialized

B. Supply and access custom headers.



To define Message contracts, use the following attributes: MessageContract Attribute, MessageHeader Attribute, and MessageBodyMember Attribute.

The MessageContract Attribute: The MessageContract Attribute can be applied to classes and structures to define your own message structure.

The MessageHeader Attribute: The MessageHeader Attribute can be applied to members of a Message contract to declare which elements belong among the message headers.

The MessageBodyMemberAttribute: The MessageBodyMemberAttribute can be applied to members of your Message contracts to declare which elements belong within the message body.

Wednesday, September 29, 2010

Defining Structural Contracts

Defining Structural Contracts
Data Contracts:

Data contracts are the contractual agreement about the format and structure of the payload data (that is, the SOAP body) in the messages exchanged between a service and its consumer.
Data contracts are the preferred WCF way to enable serialization of complex types included in operation signatures, either as parameters or as return values.

Using a data contract, you can specify exactly how the service expects the data to be formatted as XML. The data contract is used by a data contract serializer in WCF client applications to describe how to serialize the data for parameters into XML, and by a data contract serializer in the service to deserialize the XML back into data values that it can process. Values returned by a service are similarly serialized as XML and transmitted back to the client application, which deserializes them.


DataContract Attribute
The DataContract Attribute, defined in the System.Runtime.Serialization namespace, is used to declare a type as a Data contract.
It can be applied to enums, structs, and classes only.


DataMember Attribute
The DataMember Attribute, also part of the System.Runtime.Serialization namespace, is applied only to members and is used to declare that the member should be included in the serialization of the data structure.


EnumMember Attribute
The final Data contract–related attribute to consider is the EnumMemberAttribute. As the name suggests, it is used to declare that a given element of an enum that has been declared with a DataContractAttribute should be considered as part of the Data contract.

Eg: Create a WCF Service and write the following code in the IService.cs file.

[ServiceContract]
public interface IService
{
    [OperationContract]
    Employee GetEmployee();
}

[DataContract]
public class Employee
{
    string name, job;
    [DataMember]
    public string Name
    {
        set { name = value; }
        get { return name; }
    }
    [DataMember]
    public string Job
    {
        set { job = value; }
        get { return job; }
    }
}

Write the following code in the Service.cs

public class Service : IService
{
    public Employee GetEmployee()
    {
        Employee emp = new Employee
        {
            Name = "Jobin John",
            Job = "Software Eng"
        };
        return emp;
    }
}


Add a new website to Solution. Place a button and write the following code.

        protected void btnDisplay_Click(object sender, EventArgs e)
        {
            EmployeeServiceReference.ServiceClient client = new WebApplication1.EmployeeServiceReference.ServiceClient();

            EmployeeServiceReference.Employee emp = client.GetEmployee();
            Response.Write("Name : " + emp.Name);
            Response.Write("
Job : " + emp.Job); }

Monday, August 9, 2010

Message Exchange Patterns

Message Exchange Patterns


MEPs describe the protocol of message exchanges a consumer must engage in to converse properly with the service.

Request/Response

OneWay

Duplex

1. Request/Response

This is by far the most common MEP and very little has to be done to set it up because the default value for the IsOneWay property of OperationContractAttribute is false.

Even with a void return type, if you are using Request/Response, then a response message is still going back to the consumer when the operation is called; it just would have an empty SOAP body.



2. OneWay

Sometimes, you simply want to send a message off to a service and have it trigger some sort of business logic, and you aren’t in fact interested in receiving anything back from the service. In such cases, you might want to use the OneWay MEP, that is, have the consumer simply send one-way messages into the service endpoint without any responses back from the service. This MEP is declared by setting the IsOneWay property on the OperationContractAttribute to true.

The most important one is that such an operation cannot pass any data back to the client application; it must return a void and cannot have parameters marked as out or ref.

When a OneWay operation starts running in the service, the client application has no further contact with it and will not even be aware of whether the operation was successful or not.

If the operation raises an exception that would normally generate a SOAP fault message, this SOAP fault message is simply discarded and never sent to the client.

Eg:

[OperationContract(IsOneWay=true)]
void Cancel(string action);

Duplex

The Duplex MEP is a two-way message channel whose usage might be applicable in either of these two situations.

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

• The consumer needs to be able to receive unsolicited messages from the service.



There are two Service contracts to consider in a Duplex MEP scenario, namely

1. the Service contract and

2. the Callback contract

This MEP is declared by associating the Callback contract with the Service contract. This association is done through the CallbackContract property of the ServiceContractAttribute that is adorning the service that needs to be capable of calling back to a consumer.

The MessageParameter Attribute

The MessageParameter Attribute


The MessageParameter Attribute also defined in the System.ServiceModel namespace, controls how the names of any operation parameters and return values appear in the service description, that is, how they are emitted as part of the WSDL for the service. This attribute has only one property, the Name property.

One concrete case in which this attribute can be useful is when you need to have a .NET keyword or type name for the name of the XML element that is serialized at the wire-level transport layer.

Eg:

[OperationContract]
int Display(
[MessageParameter(Name="int")]
int a);

The OperationContract Attribute

The OperationContract Attribute:


The OperationContract Attribute, also defined in the System.ServiceModel namespace, can be applied only to methods. It is used to declare the method as belonging to a Service contract.

As with the ServiceContractAttribute, the OperationContractAttribute can be declared with a variety of named parameters that provide control over the service description and message formats.

• Name Specifies a different name for the operation instead of using the default, which is the method name.

Eg:
[OperationContract]
int Add(int a, int b);

Service Contracts and Service Types

Service Contracts and Service Types:


The ServiceContractAttribute, defined in the System.ServiceModel namespace, can be applied to either .NET interfaces or .NET classes. It is used to declare the type as a Service contract.

The Service Contract attribute enables the WCF runtime to generate a description for the service.

The ServiceContractAttribute can be declared without any parameters, but it can also take named parameters.

Name: Specifies a different name for the contract instead of the default, which is simply the interface or class type name. This contract name is what will appear in the portType name when consumers access the WSDL.

Namespace Specifies a target namespace in the WSDL for the service. The default namespace is http://tempuri.org.

Eg:

[ServiceContract(Name="MathService")]
public interface IService1
{
}

Sunday, August 8, 2010

Introduction to WCF | Inter-Process Communications Technologies

Inter-Process Communications Technologies:


Networking solutions enabled PCs to be able to communicate with each other. Inter-Process Communications Technologies are:

1. COM

2. DCOM

3. COM+

4. .NET FRAMEWORK

Microsoft originally designed COM to enable communications between components and applications running on the same computer.

COM was followed by DCOM (distributed COM), enabling applications to access components running on other computers over a network.

DCOM was itself followed by COM+. COM+ incorporated features such as integration with Microsoft Transaction Server, enabling applications to group operations on components together into transactions so that the results of these operations could either be made permanent (committed) if they were all successful, or automatically undone (rolled back) if some sort of error occurred. COM+ provided additional capabilities, such as automatic resource management (for example, if a component connects to a database, you can ensure that the connection is closed when the application finishes using the component), and asynchronous operations (useful if an application makes a request to a component that can take a long time to fulfill; the application can continue processing, and the component can alert the application by sending it a message when the operation has completed).

COM+ was followed in turn by the .NET Framework, which further extended the features available and renamed the technology as Enterprise Services. The .NET Framework also provided several new technologies for building networked components. One example was Remoting, which enabled a client application to access a remote object hosted by a remote server application as though it was running locally, inside the client application.

The Web Services

Technologies such as COM, DCOM, COM+, Enterprise Services, and .NET Framework Remoting all work well when applications and components are running within the same local area network inside an organization.

A Web service is an application or component that executes on the computer hosting the Web site rather than the user’s computer. A Web  service can receive requests from applications running on the user’s computer, perform operations on the computer hosting the Web service, and send a response back to the application running on the user’s computer. A Web service can also invoke operations in other Web services, hosted elsewhere on the Internet. These are global, distributed applications.

WCF ( Windows Communication Foundation)

The purpose of WCF is to provide a unified programming model for many of technologies (Web Services, COM, Remoting, MSMQ etc..), enabling you to build applications that are as independent as possible from the underlying mechanism being used to connect services and applications together.