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

Sunday, July 13, 2008

Message Contracts Vs Data Contracts in WCF

There's a big confusion among WCF developers while understanding the concept of Message Contracts. Are they really required? Why were they included in WCF when Data Contracts can do everything.

Well the truth is that both Message Contracts and Data Contracts possess their own niche in SOAP messaging. In the below table, I'll be drawing a thick line to show differences between Message Contracts and Data Contracts

Data Contracts Message Contracts
Data Contracts primarily target the XSD schema definitions of Soap Messages Message Contracts primarily target the <soap:Header> and <soap:Body> construction
Data Contracts can control only the contents of Soap message data. Just the types between the <soap:Body> section Message Contracts can control the whole SOAP message
Data Contracts are mostly used while dealing with serialized types within the message body Message Contracts are mostly used while passing security information as tokens, correlation guids into the soap headers
Data contracts take care of the Data Structures of the message e.g. defining complex types, collections, etc Message Contracts take care of the overall message structure of the WSDL

 


Multiple interfaces in a WCF contract

Well most of the time we have requirement of having one ServiceContract for an endpoint. But sometimes we get into a situation when the implementation is spread across multiple interfaces and we need to include the functionality spread into both the implementations into our WCF class. To suffice such a requirement we can use the concept of Interface Aggregation. Suppose we have two interfaces
  • ITemperature
  • IRainfall

The former returns the temperature of a particular location and the latter returns rainfall measure. Now suppose we have another interface called IWeather which will hold the functionality of returning weather forecast. The below code shows how to achieve this functionality using C#

namespace AggregatedContracts{
[ServiceContract]
public interface ITemperature
{
[OperationContract]
double GetTemperature(double latitude, double longitude);
}

[ServiceContract]
public interface IRainfall
{
[OperationContract]
double GetRainfall(double latitude, double longitude);
}

ServiceContract]
public interface IWeather : ITemperature,IRainfall{};
{
[OperationContract]
string GetWeatherForecast(double latitude, double longitude);
}

public class WeatherInfo : IWeather{
//implement ITemperature


//implement IRainfall
}
}






Saturday, July 12, 2008

IIS hosted Duplex WCF Service

Today, I'm showing you how to create a Duplex Contract WCF service which will be hosted in the IIS and called from various console App clients. We will be understanding the WCF Duplex Services and Contracts concept from the classic Stock Exchange example. In this example we are having a WCF Duplex service named DuplexStock1. This service will receive subscription requests from various clients for a stock tickers like MSFT, YAHOO, etc.

The WCF Service will create separate threads for each client connecting to it (Though its not quite optimized approach,but simple to explain here). The service will push the stock values to the cilents through Duplex channe periodically (after 5 seconds). Stock values are randomly updated from 0 to 100 and pushed to the client.

The clients will show the updated stock values for the subscribed ticker in their Console Window. The main of this blog post is not explain each and every concept of Duplex Binding but to show a working example.

Lets commence by creating the Server..




namespace StockMarketServer
{
[ServiceContract(CallbackContract=typeof(IClientCallback1))]
public interface IDuplexStock1
{
[OperationContract(IsOneWay = true)]
void SubscribeForStockUpdate(string strTicker);
}

public interface IClientCallback1
{
[OperationContract(IsOneWay=true)]
void UpdatePrice(string ticker, double price);
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class DuplexStock1 : IDuplexStock1
{
public void SubscribeForStockUpdate(string strTicker)
{
Update objUpdate = new Update();
objUpdate._ticker = strTicker;
objUpdate.callback = OperationContext.Current.GetCallbackChannel();
Thread t = new Thread(new ThreadStart(objUpdate.SendUpdateToClient));
t.IsBackground = true;
t.Start();
}
}
public class Update
{
public IClientCallback1 callback=null;
public string _ticker;
public void SendUpdateToClient()
{
Random rnd= new Random();
for (int i = 0; i < 10; i++)
{
Thread.Sleep(5000);
try
{
callback.UpdatePrice(_ticker, rnd.NextDouble() * 100.0);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}


As you can see in the above code we have two interfaces one for WCF Service Contract [IDuplexStock1]other for the client [IClientCallback1]. The SubscribeForStockUpdate method is invoked by every client when it wants to subscribe for a particular stock ticker update. The service gets the client channel in which to push the updates using the GetCallbackChannel method can spawns a new thread with Update class. This class starts pushing data to client randomly.



Now lets see the WCF service configuration which will help it to be hosted in IIS
































Put the above code in Web.config of your WCF project and make the project folder as the virtual directory. If you have done everything alright, then you should be able to see service metadata when you browse the baseAddress Url in the browser.



Now lets start building the Console Application Clients. Start by adding a console application project to your solution. Then use "Add Service reference" and give the above baseAddress Url. This will create WSDL proxies and put client configuration into the app.config your ConsoleApp. Here's what your console App's app.config should look like







...blah..blah..>
maxBytesPerRead="4096" maxNameTableCharCount="16384" />


algorithmSuite="Default" />





binding="wsDualHttpBinding" bindingConfiguration="WSDualHttpBinding_IDuplexStock1"
contract="StockMarketServerProxy.IDuplexStock1" name="WSDualHttpBinding_IDuplexStock1">










Ensure that the bolded tags shown above are present in your app.config. They are the key pillars to support Duplex Communication. Now finally lets start coding the client console app




namespace StockMarketConsoleClient
{
class Program
{
static InstanceContext site = new InstanceContext(new CallbackHandler());
static DuplexStock1Client objDupCl = new DuplexStock1Client(site);
public Program()
{
try
{
Console.Write("Input Stock ticker::");
string strInputTicker=Console.ReadLine();
objDupCl.SubscribeForStockUpdate(strInputTicker);
Console.WriteLine("Server connection established, wait for updates to be pushed by the server...");
Console.Read();
}
catch (Exception ex)
{
Console.WriteLine("Exception ::" + ex.Message);
Console.Read();
}
}
static void Main(string[] args)
{
Program objPr = new Program();
}
}

public class CallbackHandler : IDuplexStock1Callback
{

public void UpdatePrice(string ticker, double price)
{
Console.WriteLine("Recieved push for ticker :: " + ticker + " value is " + price.ToString() + " on " + DateTime.Now.ToString());
}
}
}







Wednesday, July 9, 2008

WCF bare unwrapped Response

Many times we have seen that a WCF method of return type string spits Response which is wrapped in a String element e.g. the one shown below

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
<Company>Nucleus</Company></string>

We may want it to return pure Xml Response, the unwrapped one like

<Company>Nucleus</Company>

These are steps you should use to achieve it

1. Change the webmethod return type from string to System.IO.Stream
2. Remove any BodyStype property from its attributes because even the barest BodyStyle will return wrapped response.
3. Return a Stream instead of string from your webmethod. This can be done with the following simple code
return new MemoryStream(Encoding.UTF8.GetBytes(strRetXml));

Resolving Download Failure in WebClient

Today I was developing a Silverlight client program which reads cross-domain content when I started facing Download Failure exception. This is code I was using, which resulted in exception

private void btnSearch_Click(object sender, RoutedEventArgs e){
string strTopic=txtSearchTopic.Text;
string strUrl = "";
WebClient wc = new WebClient();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler
(this.DownloadCompleted);
wc.DownloadStringAsync(new Uri(strUrl));
}
private void DownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
string strResult = e.Result;
}
}


So in this code, Line 10 was throwing Download failure exception probably because my domain in not registered in GroupPolicy.xml file on the server from which I was reading the content. Now the solution to this problem is to use System.Net.HttpWebRequest object which can easily read data across domains. So here are steps:

  • Add Reference to System.Net assembly


  • Add System.Net namespace and replace the previous code with this code





private void btnSearch_Click(object sender, RoutedEventArgs e)
{
string strTopic = txtSearchTopic.Text;
string strUrl = "";
HttpWebRequest objRq = (HttpWebRequest)WebRequest.Create(new Uri(strUrl));

objRq.BeginGetResponse(new AsyncCallback(responseHandler), objRq);

}
void responseHandler(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
Stream respStream = response.GetResponseStream();
if (respStream != null)
{
StreamReader sr = new StreamReader(respStream);
//Here you will get the content in strResp string
string strResp = sr.ReadToEnd();

}
}




And the above code worked.





Monday, July 7, 2008

ProtocolException 404 Silverlight WCF

This is blog entry will help those who understand Cross Domain restrictions in Silverlight while calling a WCF service in another domain. If you already tried many prescribed things to allow Cross Domain Access like placing the clientaccesspolicy.xml in wwwroot folder and putting a crossdomain.xml on the IIS root (wwwroot folder). But still you are getting the same obstinate 404 error. Then you can try these two tricks which worked for me

1. Firstly make sure the you restart IIS whenever you create new policy files or update them.

2. Make sure that you SL client is an aspx page not HTML page (because aspx page runs in worker process account, somehow html doesn't work for some people)

3. Try changing this line in your clientaccesspolicy.xml

From :

<allow-from>
<domain uri="*"/>
</allow-from>

To:

<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>

These tricks worked for me and I wish they work for you also :)

Saturday, July 5, 2008

Step into WCF service

This article addresses a common problem encountered while debugging a WCF service hosted in IIS from a client like a Console App or a Win App. Even if you put break points in the WCF service but you are not able to step into the service by pressing F11. Instead you a get an error dialog as show below saying

"Unable to automatically step into the server. The remote procedure could not be debugged..."

excp_diag

I faced the same situation and was able get the Step In working by confirming the below conditions in my project

1. Making sure the WCF Service is complied in "Debug" mode

2. Making sure that Web.config or App.config of the WCF service contains this entry

<system.web>
<compilation debug="true" />
</system.web>

Happy debugging!

Thursday, July 3, 2008

How to read post request in WCF

Sometimes we have requirement in which we have to read data from request body / payload instead of its Querystring. Though it can be easily done in .NET 2.0 but it is hard to find in WCF. In this post, we'll see how to do it.

Here's the code to perform this


//Code Listing 1
public void MyPostHandler(Stream input){
StreamReader sr = new StreamReader(input);
string str = sr.ReadToEnd();
sr.Close();//str will contain the body payload of POST request
}

MyPostHandler method should be decorated with the WebInvoke attribute to handle Post requests. This is how it is done


//Code Listing 2
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "*")]
void MyPostHandler(Stream input);

So in the Code Listing 1 we see how raw request body was read into a string using the input Stream from which it arrived to the WCF service hosted in IIS

Monday, June 9, 2008

Creating REST web service using WCF

During last two weeks, I was working on a niche area when I was given a task to create a REST service in .NET. Upon my initial exploration, I found that REST support is only provided by Framework 3.5. I found out that finding REST in WCF articles over the net was not easy as very few and obsure links are available.

So here I'm publishing few links which will give you quick start if you want to create a REST service using WCF



Everything About REST Web Services - What and How - Part 1

Everything About REST Web Services - What and How - Part 2

Creating RESTful Web Services with Windows Communication Foundation

How to Build a REST app in .NET (with WCF)

How to create REST/POX web services with WCF