Tag Archives: WCF

When to use Channel factory in WCF

If you are using assembly-sharing (which is, let’s face it, hugely convenient if you own both ends of the pipe), then both ends already have a complete version if the interface etc. It seems redundant to run the svcutil tool (at command-prompt or via the IDE) just to get back a wrapper for what we already have. It also works very well when you want to code only to an interface, not to the wrapper class – and use some centralised code to get a channel to a particular interface at a given address. This is actually how I mainly use WCF.

The “client” approach works well for one-off services, or where it doesn’t need to go through any central tooling. It also makes for very simple demos.

How to: Use the ChannelFactory

Advertisements

Leave a comment

Filed under WCF

Explanation of WCF web.config

Explanation of WCF web.config class 

<configuration xmlns=”http://schemas.microsoft.com/.NetConfiguration/v2.0″&gt;

  <system.serviceModel>

    <services>

      <service behaviorConfiguration=”returnFaults”>

        <endpoint contract=”IMyService” binding=”wsHttpBinding”/>

      </service>

    </services>

    <behaviors>

      <serviceBehaviors>

        <behavior >

          <serviceDebug includeExceptionDetailInFaults=”true” />

<serviceMetadata httpGetEnabled=”true” />

        </behavior>

      </serviceBehaviors>

    </behaviors>

  </system.serviceModel>

  <system.web>

    <compilation debug=”true”/>

  </system.web>

</configuration> 

Within the <system.serviceModel> we will host Serivces tag, which will has all services we will have in our project or what we want to expose. 

Within   <Services> we will host service by service

Each service tag has a name attribute “the name of the service class” and “behaviorConfiguration” that specify name of behaviour tag within serviceBehaviors tag

Each service has endpoint (“ABC”) tag with three attributes

Address(“Where”): will be “” empty if the service on the localhost.

Binding(“How”): binding=”wsHttpBinding” we will use http or https for transportation and communication

Contract(What”):the Name of the interface

Within <ServiceBehaviours> there are behaviour tag

<serviceDebug includeExceptionDetailInFaults=”true />

Each behaviour has name attribute so service can find it as mentioned before

serviceDebug includeExceptionDetailInFaults=”true” specify that occurrence of exceptions include details of the exception in the message. 

<serviceMetadata httpGetEnabled=”true” />

To enable service client to get metadata of the service project assembly to view and call service contained types

Refrences

http://blog.flair-systems.com/search/label/WCF

Leave a comment

Filed under WCF

Playing with REST !

REST Services

àREST stands for Representational State Transfer, means that each unique URL is a representation of some object.

-to get the contents of that object use an HTTP GET,

-to delete you then might use a POST, PUT, or DELETE to modify the object.

àUnlike SOAP, REST is not a standard; it is just an architectural style.

àREST uses HTTP for all four CRUD (Create/Read/Update/Delete) operations.

àMuch like Web Services, a REST service is:

* Platform-independent (you don’t care if the server is Unix, the client is a Mac, or anything else),

* Language-independent (C# can talk to Java, etc.)

eg:

-The famous Twitter API is all REST.

Yahoo! offer most of their services using REST including Search API, Maps, Photos.

Flickr,

-Amazon.com offer several REST services, e.g., for their S3 storage solution

Atom is a RESTful alternative to RSS.

Like the following URL sends a REST request to Yahoo!’s web-search service:

http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=rest.

Click it, and observe the XML results, ready to be used directly.

This REST request includes two parameters:

appid“, used by Yahoo! to specify your application, and

query“, which is the actual search query.

REST vs SOAP

Yahoo’s web services are using REST and google using SOAP for their web services.

REST is Lightweight than SOAP because it does not requires lot of xml markup.

WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.

The below code shows how to expose a RESTful service

[ServiceContract]

interface IStock

{

[OperationContract]

[WebGet(UriTemplate:=”/Stock/{StockId}”)]

int GetStock(string StockId);

}

By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation, like GetStock from Stock.

We can use REST style to get order as shown in the below URL with Stock

http://localhost/stock.svc/Stock/100234

How to consume REST services

There are different ways to consume the REST services as per requirements, below I am mentioning some:

1) Here I am actually reading the Xml from REST service and writing to the file.  WebClient() is defined in System.Net
WebClient() objWebClient = new WebCleint();
objWebClient.Credentials = new NetworkCredential(uid, pwd, domain);
XmlTextReader objXmlTextReader = new XmlTextReader(objWebClient.OpenRead(path));
string objXml = string.Empty;

while(objXmlTextReader.Read())
{
   objXml = objXmlTextReader.ReadOuterXml;
}

string filePath = serverPath + “\” + Date.UtcNow.Year.Tostring();

if(File.Exists(filePath))
{  
   StreamWriter wr;
   File.Delete(filePath);
   wr = File.CreateText(filePath)
   wr.WriteLine(objXml)
   wr.Close();        
}
else
{
   StreamWriter wr;
   wr = File.CreateText(filePath)
   wr.WriteLine(objXml)
   wr.Close();
}

2) To query a REST service, like the one I mentioned above, we can use LINQ’s XML functionality.  The XElement class (declared in System.Linq.XML) provides a Load method that can retrieve an XML data from a url with GET  method:

XElement rootXml = XElement.Load(“http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=rest”);

var SearchResult = from R in rootXml.Elements()

select new { Topic = (string)R.Element(“Title”),

Detail = (string)R.Element(“Summary”),

Link = (string)R.Element(“Url”) };

foreach (var x in SearchResult)

Console.WriteLine(“{0}  {1}”, x.Topic, x.Detail, x.Link);

Console.ReadKey();

Using POST method is a bit more complex. First we have to obtain a channel by which we may POST the information. Then we have to create an instance of data entity in XML format. Finally we have to POST data through the channel.

To get access to REST service we use a HttpWebRequest since it lets use the POST method and let us specify the type of information we are posting.

HttpWebRequest channel = (HttpWebRequest)WebRequest.Create(“http://ws.geonames.org/countryInfo”);

channel.Method = “POST”;

channel.ContentType = “text/xml”;

HttpWebRequest class provides a stream to which we can write information :

StreamWriter sw = new StreamWriter(channel.GetRequestStream());

Then we can create a concerete entity to post:

XElement country = new XElement(“country” ,

new XElement(“countryCode”, “AUS”),

new XElement(“countryName” , “Australia”),

….

);

Finally we just need to save this XElement object to the stream we obtained from HttpWebRequest:

country.Save(sw);

References:

http://aspguy.wordpress.com/2008/10/10/dealing-with-rest-web-services/

http://developer.yahoo.com/dotnet/howto-rest_cs.html

2 Comments

Filed under .Net, C#