Sunday, 5 August 2012

Webservice


What is Web Service?
  • Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet.
  • Web Service is
    • Language Independent
    • Protocol Independent
    • Platform Independent
    • It assumes a stateless service architecture.
  • We will discuss more on web service as the article proceed. Before that lets understand bit on how web service comes into picture.

History of Web Service or How Web Service comes into existence?
  • As i have mention before that Web Service is nothing but means for Interacting with objects over the Internet.
  • 1. Initially Object - Oriented Language comes which allow us to interact with two object within same application.
  • 2. Than comes Component Object Model (COM) which allows to interact two objects on the same computer, but in different applications.
  • 3. Than comes Distributed Component Object Model (DCOM) which allows to interact two objects on different computers, but within same local network.
  • 4. And finally the web services, which allows two object to interact internet. That is it allows to interact between two object on different computers and even not within same local network.
Example of Web Service
  • Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.
  • Stock Quote: You can display latest update of Share market with Stock Quote on your web site.
  • News Headline: You can display latest news update by using News Headline Web Service in your website.
  • In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your companiesadvertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.

Web Service Communication
Web Services communicate by using standard web protocols and data formats, such as
  • HTTP
  • XML
  • SOAP
Advantages of Web Service Communication
Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.

Terms which are frequently used with web services
  • What is SOAP?
    • SOAP are remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.
  • What is WSDL?
    • WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.
    • WSDL contains every details regarding using web service
      • Method and Properties provided by web service
      • URLs from which those method can be accessed.
      • Data Types used.
      • Communication Protocol used.
  • What is UDDI?
    • UDDI allows you to find web services by connecting to a directory.
  • What is Discovery or .Disco Files?
    • Discovery files are used to group common services together on a web server.
    • Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service.
    • .Disco File (static)
      • .Disco File contains
        • URL for the WSDL
        • URL for the documentation
        • URL to which SOAP messages should be sent.
      • A static discovery file is an XML document that contains links to other resources that describe web services.
    • .VsDisco File (dynamic)
      • A dynamic discovery files are dynamic discovery document that are automatically generated by VS.Net during the development phase of a web service.
  • What is difference between Disco and UDDI?
    • Disco is Microsoft's Standard format for discovery documents which contains information about Web Services, while UDDI is a multi-vendor standard for discovery documents which contains information about Web Services.
  • What is Web Service Discovery Tool (disco.exe) ?
    • The Web Services Discovery Tool (disco.exe) can retrieve discovery information from a server that exposes a web service.
  • What is Proxy Class?
    • A proxy class is code that looks exactly like the class it meant to represent; however the proxy class doesn't contain any of the application logic. Instead, the proxy class contains marshalling and transport logic.
    • A proxy class object allows a client to access a web service as if it were a local COM object.
    • The Proxy must be on the computer that has the web application.
  • What is Web Service Description Language Tool (wsdl.exe)?
    • This tool can take a WSDL file and generate a corresponding proxy class that you can use to invoke the web service.
    • Alternate of generating Proxy class through WSDL.exe is you can use web reference. Web Reference automatically generate a proxy classes for a web service by setting a web reference to point to the web service.
    • Advantage of using Web Reference as compare to using WSDL.exe Tool is you can update changes done in web service class easily by updating web reference, which is more tedious task with WSDL.exe tool.
  • Testing a Web Service?
    • You can test web service without building an entire client application.
      • With Asp.net you can simply run the application and test the method by entering valid input paramters.
      • You can also use .Net Web Service Studio Tool comes from Microsoft.

Example of Creating Web Service in .Net
This Web Service will retrieve CustomerList Country Wise and return as dataset to client application for display.
Step1: Create a Web Service Application by File > New > Web Site > Asp.net Web Services
Named the web service, for example here i have choosen name "WSGetCustomerCountryWise"

Step2: Rename the default Service.asmx file to proper name, you also need to switch design view and change the class name with the same name you use to rename the service.asmx.
For example, "WSGetCustomerCountryWise.asmx" and switch to design view and change the class="Service" to class="WSGetCustomerCountryWise"

Step3: Rename the Service.CS File to proper name, you need to change the class name and constructor name too.
For example, "WSGetCustomerCountryWise.CS" and switch to code view and change the class and constructor name to "WSGetCustomerCountryWise"

After three steps your solution explorer looks as shown in figure




Step4: Create a Logic for Web Service
  • Create a Method "GetCustomerCountryWise"
  • Note: You need to specify [WebMethod] before method definition, if you want it to be accessible public, otherwise the method would not be accessible remotely.
  • Specify proper argument and return type for method in web service.
  • It is also good practise to specify the use "Description" attribute to tell what method is meant for.
For example, here i need to access data of northwind customers and want to return customer list country wise, so add namespace for

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

[WebMethod(Description="It will generate Customer List, Country Wise")] public System.Xml.XmlElement GetCustomerCountryWise(string sCountry) 
{
string sConn = ConfigurationManager.ConnectionStrings["connStr"].ToString();

string sSQL = "select CustomerId, CompanyName, ContactTitle, City " +
" from Customers where country = '" + sCountry + "'";

SqlConnection connCustomer = new SqlConnection(sConn);

DataSet dsCustomer = new DataSet();

SqlDataAdapter daCustomer = new SqlDataAdapter(sSQL, sConn);

daCustomer.Fill(dsCustomer,"Customers");

//Known bug while return "DataSet" is "Data source is an invalid type.
It must be either an IListSource, IEnumerable, or IDataSource."
//For more details on Error: http://support.microsoft.com/kb/317340

//So to access data we need to make use of XmlElement.

// Return the DataSet as an XmlElement.
System.Xml.XmlDataDocument xdd = new System.Xml.XmlDataDocument(dsCustomer);
System.Xml.XmlElement docElem = xdd.DocumentElement;
return docElem;
}

Step5: Build Web Service and Run the Web Service for testing by pressing F5 function key.






By pressing "Invoke" button will generate XML File.

So you are done creating web service application.

Example of Testing Web Service in .NetThis Web Service will display the information which had been retrieved from Remote computer by accessing public method "GetCustomerCountryWise".Step1: Create a Test Web Site by File > New > Web Site > Asp.net Web Site
Named the web site, for example here i have choosen name "TestGetCustomerCountryWise"

Step2: Displaying data in gridview, so drag the gridview on to the form.

Step3: Right Click Solution Explorer and Choose "Add Web Reference"



Step4: Choose the option Web Service on the local machine or you can enter the .WSDL File address directly in URL space and press Go button.




Step5: Press "Add Reference button"


Step6: Writing Code for Displaying data in GridView
Here note: I have Pass "USA" as parameter in Country Field.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Create object of WSGetCustomerCountryWise Object
localhost.WSGetCustomerCountryWise objGetCustomerCountryWise
= new localhost.WSGetCustomerCountryWise();

DataSet dsCustomer = new DataSet();

// Get the data from Webservice.
XmlElement elem = objGetCustomerCountryWise.GetCustomerCountryWise("USA");

// Load the XML to the Typed DataSet that you want.
XmlNodeReader nodeReader = new XmlNodeReader(elem);
dsCustomer.ReadXml(nodeReader, XmlReadMode.Auto);

GridView1.DataSource = dsCustomer;

GridView1.DataBind();
}
}


Step7: Output as data displayed in GridView.




Few Facts about Web Service in .Net
  • Each Response from web service is a new object, with a new state.
  • Web Service are asynchronous because the request object from the client application and the response object from the web service are unique SOAP envelopes that do not require shared connection.
  • This allow client application and the web service to continue processing while the interaction is ongoing.
  • Instead of a user interface, it provides a standard defined interface called a contract.

WebMethodAttribute Members

Public Properties

public propertyBufferResponse

Property Value

true if the response for this request is buffered; otherwise, false. The default is true.

Remarks

Setting BufferResponse to true, serializes the response of the XML Web service method into a memory buffer until either the response is completely serialized or the buffer is full. Once the response is buffered, it is returned to the XML Web service client over the network. When BufferResponse is false, the response to the XML Web service method is sent back to the client as it is serialized. In general, you only want to set BufferResponse to false, if it is known that an XML Web service method returns large amounts of data to the client. For smaller amounts of data, XML Web service performance is better with BufferResponse to true.
When BufferResponse is false, SOAP extensions are disabled for the XML Web service method.
public propertyCacheDuration

Property Value

The number of seconds the response should be held in the cache. The default is 0, which means the response is not cached.

Remarks

When caching is enabled requests and responses are held in memory on the server for at least the cache duration so caution must be used if you expect requests or responses to be very large or you expect requests to vary widely.
public propertyDescription
Supported by the .NET Compact Framework.
A descriptive message describing the XML Web service method.

Property Value

A descriptive message describing the XML Web service method. The default value is String.Empty.

Remarks

The descriptive message is displayed to prospective consumers of the XML Web service when description documents for the XML Web service are generated, such as the Service Description and the Service help page.
public propertyEnableSessionIndicates whether session state is enabled for an XML Web service method.

Property Value

true if session state is enabled for an XML Web service method. The default is false.

Remarks

In order to store session state in the ASP.NET HttpSessionState object, the XML Web service must inherit fromWebService and a WebMethodAttribute applied to the XML Web service method, setting the EnableSession property to true. If session state is not needed for an XML Web service method, then disabling it may improve performance.
An XML Web service client is uniquely identified by an HTTP cookie returned by an XML Web service. In order for an XML Web service to maintain session state for a client, the client must persist the cookie. Clients can receive the HTTP cookie by creating a new instance of CookieContainer and assigning that to the CookieContainer property of the proxy class before calling the XML Web service method. If you need to maintain session state beyond when the proxy class instance goes out of scope, the client must persist the HTTP cookie between calls to the XML Web service. For instance, a Web Forms client can persist the HTTP cookie by saving the CookieContainer in its own session state. Because not all XML Web services use session state and thus clients are not always required to use the CookieContainer property of a client proxy, the documentation for the XML Web service should state whether session state is used.
public propertyMessageName
Supported by the .NET Compact Framework.
The name used for the XML Web service method in the data passed to and returned from an XML Web service method.

Property Value

The name used for the XML Web service method in the data passed to and from an XML Web service method. The default is the name of the XML Web service method.

Remarks

The MessageName property can be used to alias method or property names. The most common use of theMessageName property will be to uniquely identify polymorphic methods. By default, MessageName is set to the name of the XML Web service method. Therefore, if an XML Web service contains two or more XML Web service methods with the same name, you can uniquely identify the individual XML Web service methods by setting the MessageName to a name unique within the XML Web service, without changing the name of the actual method name in code.
When data is passed to an XML Web service it is sent in a request and when it is returned it is sent in a response. Within the request and response, the name used for the XML Web service method is its MessageName property.
The message name associated with an XML Web service method must be unique within the XML Web service.
If a new XML Web serivce method with the same name but different parameters is added after clients are calling the original method, a different message name should be specified for the new method but the original message name should be left as is to ensure compatability with existing clients.
public propertyTransactionOptionIndicates the transaction support of an XML Web service method.

Property Value

The transaction support of an XML Web service method. The default is Disabled.

Remarks

XML Web service methods can only participate as the root object in a transaction, due to the stateless nature of the HTTP protocol. XML Web service methods can invoke COM objects that participate in the same transaction as the XML Web service method, if the COM object is marked to run within a transaction in the Component Services administrative tool. If an XML Web service method with a TransactionOption property of Required or RequiresNew invokes another XML Web service method with a TransactionOption property of Required or RequiresNew, each XML Web service method participates in its own transaction, because an XML Web service method can only act as the root object in a transaction.
public propertyTypeId (inherited from Attribute)When implemented in a derived class, gets a unique identifier for this Attribute.

Property Value

An Object that is a unique identifier for the attribute.

Remarks

As implemented, this identifier is merely the Type of the attribute. However, it is intended that the unique identifier be used to identify two attributes of the same type.

http://msdn.microsoft.com/en-us/library/0hcwfb96(v=vs.71).aspx

No comments:

Post a Comment