Tuesday, May 19, 2015

Method Overloading in WCF: Part 5


Please read my previous article :


  WCF Service-Part 1

 WCF Features-Part 2

 ABC of WCF-Part 3
 wcf demo appication-part 4

Let's make two OperationContract with same name in ImyService. 


  1. using System.ServiceModel;  
  2.   
  3. namespace myFirstApp  
  4. {  
  5.     public interface IMyService  
  6.     {  
  7.      [OperationContract]  
  8.         int AddTwoNo(int intFirstNo, int intSecondNo);  
  9.        
  10.      [OperationContract]  
  11.         double AddTwoNo(double dbFirst, double dbSecond);  
  12.     }  
  13. }  
And implement these two OperationContracts in MyService.svc.cs:

  1. using System.ServiceModel;  
  2.   
  3. namespace myFirstApp  
  4. {  
  5.     [ServiceBehavior(AddressFilterMode=AddressFilterMode.Any)]  
  6.     public class MyService : IMyServiceNew  
  7.     {  
  8.         public int AddTwoNo(int intFirstNo, int intSecondNo)  
  9.         {  
  10.             return intFirstNo + intSecondNo;  
  11.         }  
  12.   
  13.         public double AddTwoNo(double dbFirst, double dbSecond)  
  14.         {  
  15.             return dbFirst + dbSecond;  
  16.         }  
  17.     }  
  18. }  
 I got an error while updating my service reference.
Error says: cannot have two operations in the same contract with the same name. You can change the name of an operation by changing the method name or using the name property of OperationContractAttribute.
By default WSDL does not support operational overloading, but we can do this using the Name property of OperationContract.
  1. using System.ServiceModel;  
  2.   
  3. namespace myFirstApp  
  4. {  
  5.     [ServiceContract(Name="IMyService")]  
  6.     public interface IMyServiceNew  
  7.     {  
  8.         [OperationContract(Name="AddTwoNoInteger")]  
  9.         int AddTwoNo(int intFirstNo, int intSecondNo);  
  10.   
  11.         [OperationContract(Name = "AddTwoNoDouble")]  
  12.         double AddTwoNo(double dbFirst, double dbSecond);  
  13.     }  
  14. }  
Now update your service reference and run the application. It will work fine.

If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website

wcf demo appication-part 4


Please read my previous article :


  WCF Service-Part 1

 WCF Features-Part 2

 ABC of WCF-Part 3


Let's make a WCF application. In this application we are trying to add two numbers using a WCF service. I am using Visual Studio 2012. Open Visual Studio and go to "File" -> "New" -> "Project..." and select WCF Service Application and name it myFirstApp.

Visual Studio provides some auto-generated code. Let's delete the IService1.cs and Service1.svc files. Add a WCF service file and name it MyService.svc and provide it the following code. It adds the following two files.
  1. IMyService.cs
  2. MyService.svc
Delete all code of ImyService and write the following code.

  1. using System.ServiceModel;  
  2.   
  3. namespace myFirstApp  
  4. {  
  5.    [ServiceContract]  
  6.    public interface IMyService  
  7.    {  
  8.       [OperationContract]  
  9.       int AddTwoNo(int intFirstNo, int intSecondNo);  
  10.    }  
  11. }  
ServiceContract describes which operation the client can perform on the service.

OperationContract is defined within a ServiceContract. It defines the parameters and return type of the operation.

Now implement the ImyService interface in MyService.svc.cs. Let's delete all the code first from MyService.svc.cs and write the following:
  1. namespace myFirstApp  
  2. {  
  3.    public class MyService : IMyService  
  4.    {  
  5.       public int AddTwoNo(int intFirstNo, int intSecondNo)  
  6.       {  
  7.          return intFirstNo + intSecondNo;  
  8.       }  
  9.    }  
  10. }  
Hit F5 to run this application.

WCF test client

After running it successfully double-click on AddTwoNo() and fill in the value in intFirstNo and intSecondNo respectively. I am putting 5 and 6 and hitting the invoke button.

design view

Output:

response

Note: The default binding in WCF is basicHttpBinding. We can see all details of this service at http://localhost:36246/myservice.svc that is shown in the preceding image.

Now I am calling this WCF service using an ASP.NET application.

Open a new Visual Studio instance and go to "File" -> "New" -> "Project..." and select ASP.NET Empty Web Application and name it WCFClientApp.

Add a webform and name it default.aspx and add the service reference.

Right-click on the project (WCFClientApp).

add service reference

Click on Add service reference and fill in the address and click go. Then change the namespace as you want and click OK. I am keeping the WCFReference namespace.

my service

In default.aspx
  1. <table>  
  2.    <tr><td>First No</td><td><asp:TextBox ID="txtFirst" runat="server"></asp:TextBox></td></tr>  
  3.    <tr><td>Second No</td><td><asp:TextBox ID="txtSec" runat="server"></asp:TextBox></td></tr>  
  4.    <tr><td colspan="2"><asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" /></td></tr>  
  5.    <tr><td colspan="2"><asp:Label ID="lblResult" runat="server"></asp:Label></td></tr>  
  6. </table>  
In default.aspx.cs
  1. using System;  
  2.   
  3. namespace WCFClientApp  
  4. {  
  5.    public partial class _default : System.Web.UI.Page  
  6.    {  
  7.       protected void btnAdd_Click(object sender, EventArgs e)  
  8.       {  
  9.          int intFirstNo = 0, intSecNo = 0, intResult = 0;  
  10.          intFirstNo = Convert.ToInt16(txtFirst.Text);  
  11.          intSecNo = Convert.ToInt16(txtSec.Text);  
  12.          WCFReference.MyServiceClient client = new WCFReference.MyServiceClient();  
  13.          intResult = client.AddTwoNo(intFirstNo, intSecNo);  
  14.          lblResult.Text = "Result is :"+intResult;  
  15.       }  
  16.    }  
  17. }  
Run the application.

Output

output

I hope this article is helpful for you.

If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website

ABC of WCF-Part 3

Please read my previous article :


  WCF Service-Part 1

 WCF Features-Part 2

ABC of WCF

ABC stands for Address, Binding and Contracts respectively.

Address

An address is a URL that points to the location of the service. In WCF every service has a unique address. The address provides two important things. First is the location of that service and the second is the transport protocol. WCF supports the following transports but we implement the HTTP transport.
  1. Http/Https
  2. TCP
  3. IPC
  4. Peer newtwork
  5. MSMQ
  6. Service bus
Suppose I made a WCF application and name it myfirstapp and using basicHttpBinding then the URL should be like http://localhost:8080/myfirstapp.

Bindings

Bindings expose a service that can be accessed using HTTP or MSMQ. There are multiple aspects of communication with any given service and there are many possible communication patterns. WCF 4.0 supports the following bindings:
  1. basicHttpBinding
  2. wsHttpBinding
  3. wsDualHttpBinding
  4. wsFederationHttpBinding
  5. netTcpBinding
  6. netNamedPipeBinding
  7. netMsmqBinding
  8. netPeerTcpBinding
  9. msmqIntegrationBinding
  10. basicHttpContextBinding
  11. netTcpContextBinding
  12. webHttpBinding
  13. wsHttpContextBinding
Contract

A contract is an agreement between two parties. It defines how a client should communicate with your service. In other words a contract is a platform and standard way of describing what the service does. There are the following four types of contracts in WCF:
  1. Service Contractt
  2. Data Contract
  3. Fault Contract
  4. Message Contract

If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website

WCF Features-Part 2

Please read my previous article 

WCF Service-Part 1


WCF supports the following features:
·  Service Orientation
One consequence of using WS standards is that WCF enables you to create service oriented applications. Service-oriented architecture (SOA) is the reliance on Web services to send and receive data. The services have the general advantage of being loosely-coupled instead of hard-coded from one application to another. A loosely-coupled relationship implies that any client created on any platform can connect to any service as long as the essential contracts are met.
·  Interoperability
WCF implements modern industry standards for Web service interoperability. For more information about the supported standards, see Interoperability and Integration.
·  Multiple Message Patterns
Messages are exchanged in one of several patterns. The most common pattern is the request/reply pattern, where one endpoint requests data from a second endpoint. The second endpoint replies. There are other patterns such as a one-way message in which a single endpoint sends a message without any expectation of a reply. A more complex pattern is the duplex exchange pattern where two endpoints establish a connection and send data back and forth, similar to an instant messaging program. For more information about how to implement different message exchange patterns using WCF see Contracts.
·  Service Metadata
WCF supports publishing service metadata using formats specified in industry standards such as WSDL, XML Schema and WS-Policy. This metadata can be used to automatically generate and configure clients for accessing WCF services. Metadata can be published over HTTP and HTTPS or using the Web Service Metadata Exchange standard. For more information, see Metadata.
·  Data Contracts
Because WCF is built using the .NET Framework, it also includes code-friendly methods of supplying the contracts you want to enforce. One of the universal types of contracts is the data contract. In essence, as you code your service using Visual C# or Visual Basic, the easiest way to handle data is by creating classes that represent a data entity with properties that belong to the data entity. WCF includes a comprehensive system for working with data in this easy manner. Once you have created the classes that represent data, your service automatically generates the metadata that allows clients to comply with the data types you have designed. For more information, see Using Data Contracts
·  Security
Messages can be encrypted to protect privacy and you can require users to authenticate themselves before being allowed to receive messages. Security can be implemented using well-known standards such as SSL or WS-SecureConversation. For more information, see Windows Communication Foundation Security.
·  Multiple Transports and Encodings
Messages can be sent on any of several built-in transport protocols and encodings. The most common protocol and encoding is to send text encoded SOAP messages using is the HyperText Transfer Protocol (HTTP) for use on the World Wide Web. Alternatively, WCF allows you to send messages over TCP, named pipes, or MSMQ. These messages can be encoded as text or using an optimized binary format. Binary data can be sent efficiently using the MTOM standard. If none of the provided transports or encodings suit your needs you can create your own custom transport or encoding. For more information about transports and encodings supported by WCF see Transports in Windows Communication Foundation.
·  Reliable and Queued Messages
WCF supports reliable message exchange using reliable sessions implemented over WS-Reliable Messaging and using MSMQ. For more information about reliable and queued messaging support in WCF see Queues and Reliable Sessions.
·  Durable Messages

A durable message is one that is never lost due to a disruption in the communication. The messages in a durable message pattern are always saved to a database. If a disruption occurs, the database allows you to resume the message exchange when the connection is restored. You can also create a durable message using the Windows Workflow Foundation (WF). For more information, see Workflow Services.
·  Transactions
WCF also supports transactions using one of three transaction models: WS-AtomicTtransactions, the APIs in the System.Transactions namespace, and Microsoft Distributed Transaction Coordinator. For more information about transaction support in WCF see Transactions [from BPUEDev11].
·  AJAX and REST Support
REST is an example of an evolving Web 2.0 technology. WCF can be configured to process "plain" XML data that is not wrapped in a SOAP envelope. WCF can also be extended to support specific XML formats, such as ATOM (a popular RSS standard), and even non-XML formats, such as JavaScript Object Notation (JSON).
·  Extensibility
The WCF architecture has a number of extensibility points. If extra capability is required, there are a number of entry points that allow you to customize the behavior of a service. For more information about available extensibility

If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website

WCF Service-Part 1

 WCF Service


Windows Communication Foundation (WCF)  is a framework for building service-oriented applications. Most of WCF functionality is included in a single assembly called System.ServiceModel.dll, located in the System.ServiceModel namespace.

Why WCF WCF is a generic communication mechanism that allows you to set up a generic host communication between two clients. Let me explain what I am trying to say. Suppose I have three clients and we need to implement a service for them but all three clients have different implementations.

    The first client uses PHP/Java. So the client wants a response/message in XML format.
    The second is using .Net but the service execution time requirements are high so the client wants responses/messages in binary format and the protocol to be TCP.
    Third is using COM+.

For the first client we need to use a webservice, for the second we use .Net remoting and for the third we use COM+. Webservice, .Net remoting and COM+ are different technologies. So the developer must learn these technologyies But WCF unites all the technologies under one umbrella.

WCF = Webservice + .Net remoting + MSMQ + COM+

If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website

Friday, February 6, 2015

Fwd: WCF Introduction and Contracts

Introduction
This article demonstrates how to create a WCF service application. This article also covers basic information of all the contracts and a code demonstration.

What is WCF?

WCF is a combined feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication. It is a part of .Net 3.0. 

What-is-WCF.jpg

Difference between WCF and Web service
  • In a web service we need to add the [WebService] attribute to the class. 
    In WCF we need to add the [ServiceContract] attribute to the class.
     
  • Add the [WebMethod] attribute to the method in a web service.
    Add the [OperationContract] attribute to the method in WCF.
     
  • For serialization in a web service use the System.Xml.serialization namespace.
    WCF uses the System.Runtime.Serialization namespace for serialization.
     
  • We can host a web service in IIS.
    We can host WCF in IIS, WAS (Windows Activation Service), self-hosting and a Windows Service .
Let's see how to create a WCF service application step-by-step.

Step 1

Start Menu >> All Programs >> Microsoft Visual Studio 2010 >> Microsoft Visual Studio 2010

In that "File" >> "New" >> "Project..."

Microsoft-Visual-Studio-2010.jpg

Step 2
  • Select WCF from Installed Templates
  • Select .NET Framework 4 from dropdownlist
  • Select WCF Service Application
  • Give desired name and select the location
  • Click on OK button

    Select-WCF-Installed-Templates.jpg
Step 3

Now your Windows Communication Foundation service application is ready as a default service. You will see in Solution Explorer Service1.svc and IService1.cs

Open the IService1.cs file, as in:

Open-Service1.cs-file.jpg

In this file you willl find a ServiceContract, OperationContract and DataContract.

Service Contract

Service contract is an attribute applied to an interface i.e. IService1. It describes which operations the client can perform on the services. 

Service-Contract.jpg

Operation Contract

Operation Contract is an attribute applied to methods in interfaces i.e. IService1. It is used to define a method in an interface.

Operation-Contract.jpg

Data Contract

DataContract defines which data types are passed to and from the service. It is used to define a class and the DataMember attribute is used to define the properties.

Data-Contract.jpg

WCF Contracts map directly to a corresponding web services standard:
  • ServiceContracts map to WSDL
  • DataContracts map to XSD
  • MessageContracts map to SOAP
Step 4

There is one method "GetData" which accepts parameters of type int.

WCF-Contracts-map.jpg

An implementation of this method is in the Service1.svc.cs file. This method returns a string with the value you passed as a parameter.

Service1-svc-cs.jpg

Step 5

Now let us run this service. 

run-this-service.jpg

You can test your service in WCF Test Client. WCF Test Client is a GUI tool which enables us to enter parameters, invoke services with these parameters and view the responses returned by services.

Now double-click on the "GetData" method and enter a parameter value of type System.int32. Here I enter "25" as a parameter value and press the "Invoke" button. You will get "You entered: 25" as a response.

GetData-method.jpg

Conclusion

We have seen a very basic example of a WCF Service application. We entered a parameter value of type int and got the entered value as a response. 


If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website

Wednesday, August 20, 2014

How to use YouTube API to search videos

Using YouTube API to search videos

In the past, you needed to register and obtain developer key to use YouTube API. Now you can search videos as anonymous, all data reading is not restricted. Developer key is needed only for things like upload your videos to YouTube programmatically. For example, let say I want to search for Age of Empires videos (AoE is popular strategic game). Simple syntax would be:
http://gdata.youtube.com/feeds/api/videos?q=age+of+empires&prettyprint=true&alt=rss
YouTube service will return XML with search results. To analyze this XML easier, I added prettyprint= true in request. This option format XML output nicely with line breaks and tabs. Complete list of available parameters you can find on http://code.google.com/apis/youtube/2.0/reference.html#Searching_for_videos page. Default XML format is atom, but in this example we'll use alt=rss to get output formatted as RSS feed.
My YouTube Search form will contain one TextBox control named tbSearch, one Button control named btnSearch and GridView to show search results. RSS returned from YouTube API has not structure acceptable for GridView. Because of that, I will use XmlDataSource control to load RSS and additional XSLT file to convert XML to format acceptable for GridView.

Code of XSLT file (named YouTube-Transform.xslt) that converts YouTube XML to XML for GridView control would be:

xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:msxsl="urn:schemas-microsoft-com:xslt"
 xmlns:media='http://search.yahoo.com/mrss/'
 xmlns:yt='http://gdata.youtube.com/schemas/2007'
 exclude-result-prefixes="msxsl">
 <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
 <xsl:template match="/">
  <xsl:element name="items">
   <xsl:for-each select="/rss/channel/item">
    <xsl:element name="item">
     <xsl:attribute name="title">
      <xsl:value-of select="title"/>
     </xsl:attribute>
     <xsl:attribute name="description">
      <xsl:value-of select="media:group/media:description" />
     </xsl:attribute>
     <xsl:attribute name="author">
      <xsl:value-of select="author" />
     </xsl:attribute>
     <xsl:attribute name="keywords" >
      <xsl:value-of select="media:group/media:keywords" />
     </xsl:attribute>
     <xsl:attribute name="videoId" >
      <xsl:value-of select="media:group/yt:videoid"/>
     </xsl:attribute>
     <xsl:attribute name="duration" >
      <xsl:value-of select="media:group/yt:duration/@seconds"/>
     </xsl:attribute>
    </xsl:element>
   </xsl:for-each>
  </xsl:element>
 </xsl:template>
</xsl:stylesheet>


User will type search terms in TextBox and click Search button. I will use XmlDataSource control to bind returned data to GridView. GridView will show search results in one template column. ASP.NET markup code would be like this:

<asp:TextBox runat="server" ID="tbSearch" />
<asp:Button Text="Search" runat="server" ID="btnSearch" onclick="btnSearch_Click" /><br /><br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EnableViewState="false">
<Columns>
 <asp:TemplateField>
 <ItemTemplate>
 <table width="550"><tr>
 <td valign="top">
 <a href='http://www.beansoftware.com/ASP.NET-YouTube-Player.aspx?id=<%# Eval("videoId") %>'>
 <img border='0' src='http://img.youtube.com/vi/<%# Eval("videoId") %>/1.jpg' /><br /><br />
 <img border='0' src='http://img.youtube.com/vi/<%# Eval("videoId") %>/2.jpg' /><br /><br />
 <img border='0' src='http://img.youtube.com/vi/<%# Eval("videoId") %>/3.jpg' />
 </a>
 </td>
 <td valign="top">
 <h1><a href='http://www.beansoftware.com/ASP.NET-YouTube-Player.aspx?id=<%# Eval("videoId") %>'><%# Eval("title") %></a></h1><br />
 <p><b>Description:</b><%# Eval("description") %></p>
 <p><b>Author:</b> <%# Eval("author") %><br />
 <b>Keywords:</b> <%# Eval("keywords") %><br />
 <b>Duration:</b> <%# Eval("duration") %> seconds</p>
 </td>
 </tr></table>  
 </ItemTemplate>
 </asp:TemplateField>
</Columns>
</asp:GridView>
 
<asp:XmlDataSource ID="XmlDataSource1" runat="server" TransformFile="YouTube-Transform.xslt">
</asp:XmlDataSource>

On search button click, RSS will be loaded from YouTube, converted by XSLT and finally shown in GridView:

[ C# ]
protected void btnSearch_Click(object sender, EventArgs e)
{
 XmlDataSource1.DataFile = "http://gdata.youtube.com/feeds/api/videos?v=2&q=" +
   Server.UrlEncode(tbSearch.Text) + "&alt=rss";
 GridView1.DataSourceID = XmlDataSource1.ID;
}

[ VB.NET ]
Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
 XmlDataSource1.DataFile = "http://gdata.youtube.com/feeds/api/videos?v=2&q=" & _
   Server.UrlEncode(tbSearch.Text) & "&alt=rss"
 GridView1.DataSourceID = XmlDataSource1.ID
End Sub
By default, YouTube API returns first 25 records. You can change that using max-results parameter (max value is 50). To see other videos increase start-index parameter which is 0 by default. For example, if your page size is 20 records and you want to show third page, set start-index = 41 and max-results = 20.

If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website

How to get all information of YouTube video

How to get all information of YouTube video

 To get all video information, use this syntax:

http://gdata.youtube.com/feeds/api/videos/5P6UU6m3cqk
Bolded part is video ID. This link will return all video data in different formats. Default format of feed is atom, other valid values are rss, json and json-in-script. Use alt parameter to change format, for example, to return video data in form of RSS feed set alt=rss, like this:
http://gdata.youtube.com/feeds/api/videos/5P6UU6m3cqk?alt=rss
Returned feed contains data like video title, description, categories, author, date published, rating, duration, keywords, statistics etc. You can load this feed into XPathDocument object and access items using XPath queries. Example code that finds video title and description could look like this:
[ C# ]
using System;
 
// We need System.Xml.XPath namespace to query XML
using System.Xml.XPath;
 
public partial class _Default : System.Web.UI.Page
{
 
 protected void Page_Load(object sender, EventArgs e)
 {
   // Load video information from YouTube
   XPathDocument videoInfo = new XPathDocument(
     "http://gdata.youtube.com/feeds/api/videos/5P6UU6m3cqk?alt=rss");
 
   // Create XPath navigator
   XPathNavigator videoInfoNavigator = videoInfo.CreateNavigator();
 
   // Gets YouTube video title
   string Title = videoInfoNavigator.SelectSingleNode("/item[1]/title").Value;
   // Gets YouTube video description
   string Description = videoInfoNavigator.SelectSingleNode("/item[1]/description").Value;
 
   // Write results
   Response.Write("Video title: " + Title + "
"
+

     "Description: " + Description);
  }
}
[ VB.NET ]
Imports System
Imports System.Web
 
' We need System.Xml.XPath namespace to query XML
Imports System.Xml.XPath
 
Partial Class DefaultVBNET
 Inherits System.Web.UI.Page
 
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
   ' Load video information from YouTube
   Dim videoInfo As XPathDocument = New XPathDocument( _
     "http://gdata.youtube.com/feeds/api/videos/5P6UU6m3cqk?alt=rss")
 
   ' Create XPath navigator
   Dim videoInfoNavigator As XPathNavigator = videoInfo.CreateNavigator()
 
   ' Gets YouTube video title
   Dim Title As String = videoInfoNavigator.SelectSingleNode("/item[1]/title").Value
   ' Gets YouTube video description
   Dim Description As String = videoInfoNavigator.SelectSingleNode("/item[1]/description").Value
 
   ' Output results
   Response.Write("Video title: " & Title & "
"
& _

     "Description: " & Description)
 End Sub
End Class

 


If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website