Thursday 16 April 2015

Send DataSet and DataTable

Send DataSet and DataTable From Webservice and Consume in Application


I am writing simple instructions with snapshots for a good understanding and for your use in your projects.

Let's create our web service first for sending a DataSet and DataTable.

Step 1 : Open Visual Studio then select  "File" -> "New" -> "Project..." then provide a project name.



I have provided the project name WebServicewithpassingliat.

After adding the project name we will just create a new web service.

Step 2 : Let us add a web service for sending a DataSet and DataTable.

For adding the web service right-click on the solution then select Add > Add New Item then select Web Service then click the Add button.



Step 3 : After adding the web service you will see a WebMethod with the name Helloworld; just remove it.

And create a new WebMethod of type DataSet and name it MobileDataset() and add another Web Method of type DataTable and name it MobileDatatable().

For reference see the following image:

  1. DataSet Code Snippet.

    And this Webmethod will return a DataSet.
  2. DataTable code snippet.

And this Webmethod will return a DataTable.

Just run your application now.

You will see the same screen that is given below.



Now just copy this URL.

http://localhost:2157/Service1.asmx

Step 4 :
 Let's create another project then it will consume this list.

Open Visual Studio then select "File" -> "New" -> "Project..." then provide a project name.

Here I am using the name WebApplication2.



After creating it you will see your solution like the following:



Step 5 : Then just right-click on the solution and select Add Web Reference.



After selecting Add Web Reference a new dialog will pop up asking for an address.



Step 6 : Just paste the preceding address that you copied.

http://localhost:2157/Service1.asmx



After adding the URL just click the Add Reference button.

Now your solution will look like this.



Now we have completed the adding of the service.

Step 7: Now we just want to use this service.

We have a default page that is created by default.

On the page load of that page I have created a couple of methods with the names:
  1. GET_DATASET(); // For Getting the Dataset
  2. GET_DATATABLE(); // for Getting the DataTable
Code of the default page:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using WebApplication2.localhost;  
  9. using System.Text;  
  10.   
  11. namespace WebApplication2  
  12. {  
  13.     public partial class _Default : System.Web.UI.Page  
  14.     {  
  15.         protected void Page_Load(object sender, EventArgs e)  
  16.         {  
  17.             GET_DATASET();  
  18.             GET_DATATABLE();  
  19.               
  20.         }  
  21.   
  22.         public void GET_DATATABLE()  
  23.         {  
  24.             localhost.Service1 mo = new WebApplication2.localhost.Service1();  
  25.             DataTable dt = mo.MobileDatatable();  
  26.             GridView1.DataSource = dt;  
  27.             GridView1.DataBind();  
  28.         }  
  29.   
  30.         public void GET_DATASET()  
  31.         {  
  32.             localhost.Service1 mo = new WebApplication2.localhost.Service1();  
  33.             DataSet ds = mo.MobileDataset();  
  34.             GridView2.DataSource = ds;  
  35.             GridView2.DataBind();  
  36.         }  
  37.     }  
  38. }  
Namespace
  1. using WebApplication2.localhost; // is the namespace for accessing service objects  
In this code I have created an object of web service that we have added.
  1. localhost.Service1 mo = new WebApplication2.localhost.Service1();    
After creating an object I have passed an object to the DataSet.
  1. localhost.Service1 mo = new WebApplication2.localhost.Service1();  
  2. DataSet ds = mo.MobileDataset();  
For the DataTable I have created an object. I have passed an object to the DataTable.
  1. localhost.Service1 mo = new WebApplication2.localhost.Service1();  
  2. DataTable dt = mo.MobileDatatable();  
Design of Default page
  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head runat="server">  
  3.     <title></title>  
  4. </head>  
  5. <body>  
  6.     <form id="form1" runat="server">  
  7.     <div>  
  8.         <asp:GridView ID="GridView1" runat="server">  
  9.         </asp:GridView>  
  10.         <br />  
  11.         <asp:GridView ID="GridView2" runat="server">  
  12.         </asp:GridView>  
  13.     </div>  
  14.     </form>  
  15. </body>  
  16. </html>  
I have only added 2 GridViews for displaying data of both the DataTable and DataSet.

After doing that, just run the application and check it.

Here is the output:



Now we have successfully transferred a DataTable and DataSet.

Consuming Web Service.


Consuming Web Service In an ASP.Net Web Application 

By Vithal Wadje on Jun 02, 2013
Background
In my previous article 
Introduction to Web Service with Example in ASP.Net we learned how to create a simple Web Service. This article explains how to consume the Web Service in an ASP.Net web Application.
And remember, I have written this article only focusing on beginners. So let us start step-by-step so beginners can understand it very easily.

Requirement

You need to keep a Web Service application in running mode so it can be accessible for use, so go to my article
Introduction to Web Service with Example in ASP.Net and create a Web Service and keep it in running mode I hope you have done that.
What does consuming mean?

Many beginners are confused about what means consuming means, but its very simple, it means to use the Web Services in an application.

Example:
I have created Web Services and now I want to use it in a real requirement so I used it in an ASP.Net Web Application. In other words, I am consuming the Web Service in an ASP.Net web application. Similarly you can use the same Web Service in Windows, console application, Java and other applications.
I hope you understand the word "consuming".

So let us create the simple ASP.Net Web Application as:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New" - "Project..." then in the New Project window "C#" - "Empty Project" (to avoid adding a master page).
  3. Give the project a name, such as "Consumingwebservice" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer and select "Add New Item" - "Default.aspx" page.
  5. Then drag three Text Boxes, one Button, and one Label onto the "Default.aspx" page.
Then the <body> section of the Default.aspx page looks as in the following:
Default.png
 
In the preceding source code, you have seen that I have taken three text boxes to get input from users because we know that our Web Service method created as in my article Introduction to Web Service with Example in ASP.Net  takes the three input values day, month and year so I have taken the three text boxes and button click event. We will call the Web Service method and the output will be displayed on the label control so I have also taken one button and label control.
I hope you understand it.

Now your Solution Explorer of ASP.Net Web Application will be as in the following:
Slnexplorer.png 

Adding a Web Service Reference in the ASP.Net Web Application 

The most important task whem consuming a Web Service in an ASP.Net Web Application is adding the Web Service reference into the ASP.Net web application. So how to add it? Let us see the procedure.

1. Right-click on the ASP.Net Web Application and click on "Add Service Reference" as in the following:
AddServiRef.png 

2.  Then after clicking on the above option, the following window will appear, then click on the "Advanced" tab.
Advtab.png

3. Now after clicking on the Advanced tab, it will show the following window then click on the "Add Web Reference" option as in the following in a circle:
FAddsevice.png 
.
4. After clicking on the Add Web Reference tab, it will show the following window. Now this is a very important step, when adding the web reference to the ASP.Net web Application. Since you see "URL" option in the following window, on that window we need to paste or type the Web Service URL address.

RefScreen.png

So how to add the URL Reference in the preceding URL box, let us see the procedure again.
ServiceUrl.png
As you clearly see there, in the preceding window, it displays the method named "converttodaysweb" as we created in our Web Service, now just you need to copy the preceding URL that I have circled in red and paste it into the Step 4 window URL option, then the Step 4 window will look as in the following:
AddingRef.png
-----What After Pasting the URL in the preceding URL box
After pasting the URL in the preceding window box, click on the green right headed arrow button, it will discover the Web Services available related to that URL address and you see that in that related URL one Web Service is found message is displayed along with the Web Service name, "Web Services" in the preceding right hand side window.
The Name of the Web Service is "WebService" because I have given the class name as Web Service, that's why the name is Web Services, in your case it might be different or the class name is anything so you can use any name for Web Service so don't be confused about it.
  • Web Reference Name
In the right hand corner of the window you have seen the option for the Web reference name; the web reference name is anything you wish and this name will be added in your ASP.Net Web Application as allies name for Web Service. In my article I have given the web reference name as "local host".
Then after adding the Web Service reference in the ASP.Net web application the Solution Explorer will look as in the following:
AddedRefinsolu.png
 

In the preceding window, you have clearly seen that the Web Service reference named "localhost" is added into the ASP.Net web Application. I hope you understand how to add the Web Service reference into the ASP.Net web application.
Calling the Web Service method from the ASP.Net Web Application
We have added the Web Service reference into our  web application. Now next is how to call the Web Service method that we created in our Web Service Application from the ASP.Net Web Application.
The following is the procedure:
1. Go to the Default.aspx page of our ASP.Net Web application and double-click on the button that we have placed on the Default.aspx page.
2. Now write the following code in the button click to create the object of the Web Service class:
localhost.webservice age=new  localhost.webservice();
 In the code above, I have created the object of Web Service class named "age" followed by the Web reference name ("localhost") and Web Service class ("webservice"), I hope you understand how to create the object of the Web Service class.
The entire code of the Default.aspx.cs page will be as follows:
Cscode.png
Code Explanation
In the code above, I first created the object of the Web Service class named "age" followed by Web reference name ("localhost") and Web Service class ("webservice").
Then I declared the three integer variables "day", "month" and "year" to store the values provided by the user as input from the Textbox1, Textbox2 and Textbox3.
Now, in the next step, as you know our new Web Service method takes three parameters, so I passed the three input parameters "day", "month" and "year" to the Web Service method "converttodaysweb".
Then I declared another integer variable, "a", to store the values returned by the Web Service method "converttodaysweb".
And finally I displayed the values returned by the Web Service method "converttodaysweb" on the label control using variable "a"  because, as you know, we have stored the returned values of the method into the variable a, so the final result will be stored in the variable a.
Now, run the ASP.Net web application and provide the input of day, month and year. I will enter my Date of Birthand then I will click on the "Calculate" button, it will show the output as in the following:
outputScreen.png
In the preceding screen, you see that currently, I am 8702 days old, which means that for the last 8702 days, I have been on this earth.
Note:
  • For detailed code please download the zip file attached above.
  • Also refer to my previous article about creating a Web Service.
Summary
I hope that beginners as well as students understand the creation and consumption of Web Services in ASP.Net web applications using my two articles. If you have any suggestion regarding this articles then please contact me. Student suggestions are also welcomed.

.Net Web Services


.NET Web Services from 

Learning Modules
  • Introduction
  • Distributing components Technologies
  • Building Simple Web Services
  • Web Services Components
  • Consuming Web Service
  • Refining Web Service
Introduction

Software Developers have struggled to create software components that can be called remotely over your local networks and the internet. In this process several technologies have come into light but some of them are not quite successful due to many limitations and hurdles such as communication over an unreliable internet, or network of computers running on diverse types of hardware and operating systems.

This is where XML web services are useful. To interact with web a service you simply need to send an XML message over HTTP. Because every internet enabled device supports HTTP, and every programming framework includes a higher level toolkit that enables communication with a web service (XML is platform independent). XML web services are not .NET framework specific, they can also be consumed in other programming frameworks, such as Java, PHP, AJAX, ASP etc...

Distributed Computing Technologies

Distributed computing is the partitioning of application logic into units that are executed on two or more computers in a network. There are numerous technologies that has been developed to allow the distribution and reuse of application logic.
Comparison of various Distributed Technologies
Characteristics
Web Services
DCOM
CORBA
Cross Platform
Yes
NO
Partly
Firewall Friendly
LOW
HIGH
HIGH
Protocol Complexity
Yes
NO
NO
Discovery
UDDI
Registry
Naming Service
Interface Description
WSDL
IDL
IDL
RPC Mechanism
HTTP
DCE-RPC
IIOP
Encoding
XML
NDR
CDR
Many reasons exist for distributed application logic such as the following:
  • High Scalability
  • Improved Security
  • Easy Deployment
  • Load Balancing
Problem with Distributed Components
In a major enterprise, very rarely do you find that the entire organization and its data repository reside on a single vendor platform. Organization consists of a patchwork of systems, some based on Microsoft, some on UNIX, FREEBSD and others. So there is a big question, how do these disparate systems communicate each other? Interoperatibilty and Load balancing issues prevalent in CORBA and DCOM because they were developed before the advent of the internet. They are fine for building enterprise applications with software running on the same platform and not appropriate for spanning platforms and the internet.

Advantage of Web Services
  • Web service is simple to build and supported on a wide range of platforms.
  • Web service can extend its interface and add new methods without affecting the client's operations.
  • Web service is firewall friendly because all communication happens through HTTP on port 80.
  • Web service are stateless, there is no permanent connection that scale up the many clients.
Building Simple Web Services

At this point, I will show you, how to create a simple web service executed under .NET. In this example we define some methods in the UtilityWebService class. They are responsible for adding two integer values and displaying a "hello world" text as in the following:
  1. Open a Visual C# .Net website in the Visual Studio 2010 IDE.
  2. Right-click on the project name from the Solution Explorer and click add new item.
  3. Choose web service from the template and name it UtilityWebService.cs.

    Web-Service-Template.jpg

    Figure 1.1: Web Service Template
     
  4. Thereafter, implement additional method functionality in the class "UtilityWebService.cs" as shown below:

    C# web service code
    using System;using System.Collections.Generic;using System.Web;using System.Web.Services;
    ///<summary>
    ///
     Summary description for UtilityWebService///</summary>[WebService(Namespace ="http://tempuri.org/")]
    [WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    publicclass UtilityWebService : System.Web.Services.WebService {
       public UtilityWebService () {
            //Uncomment the following line if using designed components         //InitializeComponent();     }
        [WebMethod]
        public string HelloWorld() {
            return "Hello World";
        }
        [WebMethod]
        public int addition(int a,int b)
        {
            return a+b;
        }
    }

  5. It is essential to add the [WebMethod] attribute before any new method definition.
  6. Finally build the project and see the output in the browser as in the following. You will notice the methods here defined in the web service class.

    Web-Service-Output.jpg

    Figure 1.2: Web Service Output
     
  7. Now click over the addition method, enter some integer values in the text box for adding them and invoke the web service class method as in the following:

    Web-Service-Method-test.jpg

    Figure 1.3: Web Service Method test
     
  8. Finally see the addition result in the form of a XML file that is passed over the wire through HTTP and compatible with almost every platform:

    method-XML-Output.jpg

    Figure 1.4: method XML Output
Web Services Components
Web Services are piece of business logic that can be accessed over the internet. You can reuse someone else's business logic instead of replicating it yourself. This technique is similar to what programmers currently do with a library of APIs, classes and components. The main difference is that web services can be located remotely on another server and managed by another vendor such as a Google Search engine which is a kind of web service, you submit a search expression, and it compiles a list of matching websites, and returns the list to your web browser.

There are some key protocol flows that make a complete web services as in the following:
  • SOAP (Simple Object Access Protocol)
  • DISCO (discovery)
  • UDDI (Universal Description, Discovery and Integration)
  • WSDL (Web Services Description Language)
SOAP

Web Services manipulate objects through a XML message. SOAP enables you to expose and consume complex data structures that includes items such as data sets and tables. The Data Sets you send or consume can flow over the same internet wire (HTTP), thereby passing through firewalls. SOAP defines the message you use to exchange the data but it doesn't describe how you send the message. In other words, to communicate with web services a client opens an HTTP connection and sends a SOAP message. SOAP is XML based; it can be interpreted by a wide range of software on many operating systems.


SOAP Request
Here a typical SOAP message sent from a Web Service client to a server as in the following:
POST /TestWS/UtilityWebService.asmx HTTP/1.1
Host: localhost
Content-Type: application/soap+xml; charset=utf-8
Content-Length: 
length
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <addition xmlns="http://tempuri.org/">
      <a>
int</a>
      <b>
int</b>
    </addition>
  </soap12:Body>
</soap12:Envelope>

SOAP Response
Here is a part of the SOAP message back from the server:
HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
 
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <additionResponse xmlns="http://tempuri.org/">
      <additionResult>int</additionResult>
    </additionResponse>
  </soap12:Body>
</soap12:Envelope>
DISCO
Before you can use a Web service, you need to know where to find the Service. The DISCO standard creates a single file that is the repository of all related web services. You can publish a DISCO file on its server that contains links to all the web services it provides. Then the client simply needs to request this file to find all the available web services. When you set a Web Reference inside .NET, the software automatically handles the details of discovery for you. But you can also get into the details of the process yourself by using DISCO.exe as in the following:

disco http://localhost:2186/TestWS/WebService.asmx

This tool disco.exe contacts the web service and creates two additional files with .discomap and .wsdl extension. These files are XML files that will show you the name of other file and the URL.

UDDI
UDDI is a centralized directory where web services are published. This is where potential client can go to search for their specific needs. Each organization may use different UDDI registries. To retrieve information from a UDDI directory, you use a web service interface.

WSDL

Before consuming a web service, it is required to have the knowledge of a SOAP message that it can send and receive. WDSL is a standard by which a web service can tell clients what message it accepts and what results it will return. WSDL defines everything about the public interface of a web service such as data type, the methods it exposes and the URL through which those methods can be accessed.

Consuming Web Service 

Before consuming a web service, we need to generate a Proxy class that wraps the call to the web services methods. It takes care of generating the correct SOAP message format and managing the transmission of the message over the wire using HTTP on port 80. When it gets the response message back, it also convert the results back to the corresponding .NET data types.

We can generate a Proxy class in .NET in either of the following two ways:
  1. Visual Studio IDE web reference feature
  2. Command line utility Wsdl.exe
Generating the Proxy class with VS IDE
  1. Deign the default.aspx with two textboxes, three labels and a single button server control as in the following.
  2. Right-click over the client project in the Solution Explorer, and select "Add Service reference", then click on the "Advanced" button in the dialog box and finally click "Add Web Reference" as in the following.
  3. Copy the Web Service URL from the image 1.2, paste into the URL text box and hit Enter. This operation will browse your web service.

    Add-Web-Reference-Dialog-box.jpg

    Figure 1.5: Add Web Reference Dialog box
     
  4. The web service test page will appear in the windows with an entire methods list and the "Add Reference" button will be enabled as:

    Adding-a-Web-Reference.jpg

    Figure 1.6: Adding a Web Reference 
  5. In the Web Reference name text box you can change the namespace in which the proxy class will generated.
  6. Now click over the "Add Reference" button.
  7. Now the web reference will appear in the Web References group for the project in the Solution Explorer window as in the following:

    Web-Reference-in-solution-explorer.jpg

    Figure 1.7: Web Reference in Solution Explorer
     
  8. Open the Default.aspx.cs file and add a button click handler and put the following code in it:
    publicpartial class_Default : System.Web.UI.Page{   
        protected void btnAdd_Click(object sender,EventArgs e)
        {
            int x, y, Result;
            x = Convert.ToInt32(TextBox1.Text);
            y = Convert.ToInt32(TextBox2.Text);
            //web service class instantiation        localhost.UtilityWebService obj = new localhost.UtilityWebService();
            //Method call        Result=obj.addition(x, y);
            //Output        Label3.Text = Result.ToString();  
        }
    }
  9. Finally run the project and enter 2 integer type values in the given text boxes and hit the button for calling the additional web service method as in the following:

    Addition-Web-Reference-Result.jpg

    Figure 1.8: Addition Web Reference Result
Generating the Proxy class WSDL.EXE

This utility takes a WSDL file and generates a corresponding proxy class that you can use to invoke the web service. This tool does not require the web service client to use the .NET IDE.
  1. Open a command prompt from "Start" -> "All Programs" -> "Microsoft Visual Studio 10" -> "Visual Studio Tools".
  2. Then navigate to the folder that contains the WSDL file and fire this command as.

    wsdl /out:UtilityWebServiceProxy.cs http://localhost:2186/TestWS/UtilityWebService.asmx

    By default the generated class is in the C# language, but you can change it by adding the /language:vb parameter.
  3. If you browse to your project directory, notice that the "UtilityWebServiceProxy.cs" file is added there.
  4. Now copy this file to your project's "App_Code" folder by selecting "Add Existing Item" from the Solution Explorer.
  5. And finally instantiate the web service class again.

    Note: if the client is already consuming the web service and you make a change later in this then you don't need to perform the entire process again. Just go the Solution Explorer, right-click over the web reference folder and select update reference. All the new definitions are reflected automatically.
Refining Web Services 
There are a couple of other features of web services. For instance, session state, data caching and transactions. The secret of applying these features is the WebMethod attribute. However several other WebMethod properties exist as described in the following table.
Arguments
Description
CacheDuration
This depicts the number of seconds that the method response will be maintained in cache.
Description
This elaborates the method description.
EnableSession
Configure the method to access information in the session collection.
TransactionOption
Get or Set the transaction type such as allowed,NotSupported,Required,Supported etc..
BufferResponse
It is true by default and determines whether the method response is buffered.
Cache duration
[WebMethod(CacheDuration=50)]
    public int addition(int a, int b)
    { 
        ..    }

Description
[WebMethod(Description="Retrun the addition of two integer")]
    public int addition(int a, int b)
    {
        ..
    }

Session
[WebMethod(EnableSession=true)]
    public int addition(int a, int b)
    {
        ..    }

Transaction Option
[WebMethod(TransactionOption=TransactionOption.RequiresNew)]
    public int addition(int a, int b)
    {
       ..    }

Buffer Response
[WebMethod(BufferResponse=false)]
    public int addition(int a, int b)
    {
       ..    }

Great inspirational Story of "ANDRHUDU"

పాసైంది పదే.. కానీ మైక్రోసాఫ్ట్లో చీఫ్ యాప్ ఆర్కిటెక్ట్ అయ్యాడు..! అదీ ఓ తెలుగోడి సత్తా::  చదువుకు.. జ్ఞానానికి సంబంధం లేదు. చదువు జ్ఞానం...