I guess before you can show someone how to create and consume a Web Service, you need to ensure they know and understand what a Web Service actually is. The following is the easiest, simplest definition I've been able to come up for "What is a web service":
What is a Web Service you say? Well a Web Service is very general model for building applications that can be implemented for any operating system that supports communication over the web. To some this may sound a lot like a Web Site, but that is not the case, there are many differences between the two.
Here are the main differences between a Web Service and a Web Site:
First, lets take a look at creating a simple Web Service. To do this, open Visual Studio, once it loads click File > New Website, when the New Project Dialog opens, select Web Service from the list of available projects, then for Location select either HTTP or File System (your own IIS), and lastly for Language select C#.
When the project is created it creates a Service.amsx and Service.cs file, you can either rename these, or delete and add new ones with the name of SampleService asmx and SampleService.cs.Now double-click on SampleService.cs to open the code file, then make sure you have the following references at the top of your class:
Heres whats going on here, line 1 declares the Web Service's Namespace, and you might now be wondering Well whats a namespace? Well luckily theres an answer to that: Tempuri.Org defines a Web Service Namespace as:
Each XML Web Service needs a unique namespace in order for client applications to distinguish it from other services on the Web. By default, ASP.Net Web Services use http://tempuri.org/ for this purpose. While this suitable for XML Web Services under development, published services should use a unique, permanent namespace.
Your XML Web Service should be identified by a namespace that you control. For example, you can use your company's Internet domain name as part of the namespace. Although many namespaces look like URLs, they need not point to actual resources on the Web.
The next line of the first section of the Web Service uses the WebServiceBinding Method to create the Web Service's version of an Interface. After those 2 lines then you have your Initializer, which is, of course, the same as any other class. Here you can instantiate any objects you need used in each instance of the service:
Nothing new there, now we get to jump into the heart of a Web Service, which is, of course, to make it do something, to perform some service. When you create your methods, if you want them to be visible from the client thats consuming the service, you have to add the [WebMethod()] Attribute to it. This tells the service that its ok to expose that method to the client which is consuming it.
Since this is just a simple, basic Web Service it only has a single method, just to show you what can be done with a Web Service. Since this service is communicating with a Sql Database, it needs access to the System.Data.SqlClient Namespace. There are other Namespaces the service will use, we listed them above, but lets take a closer look at them:
This operates as explained. It opens a connection to our database, retrieves all the user information from the users table, then populates a Dataset ans returns the DataSet to the client. Notice the [WebMethod()] attribute at the start of the method, this says that any client that consumes this Web Service will have access to that method, and the data it returns.
Believe it or not, our Web Service is complete. Now with a Web Service in a production environment will have much more meat on its bones, but for our demonstration, this is really all we need to show how a Web Service works. Next question people ask is "Ok, we have this service out there on our server, how do we access it and use it?". Well thats a good question, to use the Web Service we just created you need a consumer, a client that will connect to the service and gather the data.
In this example we will create an ASP.Net Web Application that will consume our Web Service, then display the returned data in a GridView Control. So, in your Solution Explorer window, right-click on the very top node, the solution name, then select Add > New Project. Once the New Project Dialog opens, you will this time select ASP.Net Web Site as the project type, once again either HTTP or File System for the Location and C# for the Language.
When the project is created is automatically adds a Default.aspx, and Default.aspx.cs. It's the CS file we will be doing the programming in. You always want to keep your presentation separate from your logic, thats why Microsoft offers both files for a single page in .Net.
Since this is just a sample, open Default.aspx in Design Mode, add a table to the page, then a GridView to the page. The GridView is what we'll use to display the data returned from our Web Service. You are now finished designing our ASPX page for consuming our Web Service. Now open Default.aspx.cs, and make sure you have the following references at the top of your class:
Those are the only references you will need for this example. Now we need to add a reference to the Web Service we just created, to do this:
Now we have a reference to our Web Service and can starting using it. In our ASPX page we have a single method, BindGrid(), and this method will:
Simple enough isn't it? Now to use this, we will call this method from our Page_Load Event in our page, and that looks like this:
Believe it or not, thats it, thats all the code required to consume our Web Service and display the returned data. The one difference in our BindGrid method is this:
WebServiceConsumer.Sample.SampleService sample = new WebServiceConsumer.Sample.SampleService();
That is where we create the reference to our Web Service, then we can use sample.WhateverMethodIsThere for utilizing the methods in the Web Service, instead of typing the long name out.
Thank you for reading, and I hope you found this helpful
What is a Web Service you say? Well a Web Service is very general model for building applications that can be implemented for any operating system that supports communication over the web. To some this may sound a lot like a Web Site, but that is not the case, there are many differences between the two.
Here are the main differences between a Web Service and a Web Site:
- Web Site has an interface - Web Service has no interface
- Web Site is designed to interact with people - Web Service is designed to interact with other applications
- Web Site is designed to work with web browser clients - Web Service is designed to work with any type of client or device
First, lets take a look at creating a simple Web Service. To do this, open Visual Studio, once it loads click File > New Website, when the New Project Dialog opens, select Web Service from the list of available projects, then for Location select either HTTP or File System (your own IIS), and lastly for Language select C#.
When the project is created it creates a Service.amsx and Service.cs file, you can either rename these, or delete and add new ones with the name of SampleService asmx and SampleService.cs.Now double-click on SampleService.cs to open the code file, then make sure you have the following references at the top of your class:
using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Data.SqlClient; using System.Data; using System.Configuration; If all the references aren't there, add the ones that are missing. Next, you will notice the first 2 lines are out of the ordinary, if you've never created a Web Service these two lines are downright weird: [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
Heres whats going on here, line 1 declares the Web Service's Namespace, and you might now be wondering Well whats a namespace? Well luckily theres an answer to that: Tempuri.Org defines a Web Service Namespace as:
Each XML Web Service needs a unique namespace in order for client applications to distinguish it from other services on the Web. By default, ASP.Net Web Services use http://tempuri.org/ for this purpose. While this suitable for XML Web Services under development, published services should use a unique, permanent namespace.
Your XML Web Service should be identified by a namespace that you control. For example, you can use your company's Internet domain name as part of the namespace. Although many namespaces look like URLs, they need not point to actual resources on the Web.
The next line of the first section of the Web Service uses the WebServiceBinding Method to create the Web Service's version of an Interface. After those 2 lines then you have your Initializer, which is, of course, the same as any other class. Here you can instantiate any objects you need used in each instance of the service:
public SampleService ()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
Nothing new there, now we get to jump into the heart of a Web Service, which is, of course, to make it do something, to perform some service. When you create your methods, if you want them to be visible from the client thats consuming the service, you have to add the [WebMethod()] Attribute to it. This tells the service that its ok to expose that method to the client which is consuming it.
Since this is just a simple, basic Web Service it only has a single method, just to show you what can be done with a Web Service. Since this service is communicating with a Sql Database, it needs access to the System.Data.SqlClient Namespace. There are other Namespaces the service will use, we listed them above, but lets take a closer look at them:
- System Namespace: Base class for all Namespace's
- System.Web: Provides classes and interfaces required for server/browser communication
- System.Web.Services: Provides all the functionality required to create a Web Service
- System.Web.Services.Protocols: Provides all required protocols the Web Service needs to transferring data
- System.Configuration: Provides the programming model for handling configuration data (such as the web.config file)
- Query a SQL Server
- Retrieve all the information for all users in the system
- Populate a DataSet using a SqlDataAdapter
- Pass the DataSet back to the client.
/// <summary>
/// Here we're going to create a [WebMethod] that
/// can be called from an aspx page, then return
/// a populated DataSet to the calling aspx page
/// </summary>
/// <returns>A dataset popululated with the Members informaiopn</returns>
[WebMethod]
public DataSet GetAllUserInfo()
{
//Build the SqlCilent Objects we need
SqlConnection conn = new SqlConnection(Utlilties.GetConnectionString("WebService_Conn"));
SqlCommand cmd = new SqlCommand();
///SqlDataAdapter to populate our DataSet
SqlDataAdapter adapter = new SqlDataAdapter();
///DataSet to hold the users information
DataSet dsInfo = new DataSet();
///String to hold our stored procedure
string query = "RetrieveUserInfo";
///try...catch block to handle any unhandeled exceptions
try
{
//set our SqlCommands Objects
cmd.CommandText = query;
cmd.CommandType = CommandType.StoredProcedure; //tell it its a Stored Procedure we're executing
//if using inline SQL change the CommandType to Text
//cmd.CommandType = CommandType.Text;
//set its connection property
cmd.Connection = conn;
//now handle the connection state
///of our SqlConnection Object
/// Utlilties.HandleConnectionState(conn);
//set the SelectCommand Property
///of our SqlDataAdapter Object
adapter.SelectCommand = cmd;
//now we fill our DataSet
///using the Fill Method of
///the SqlDataAdapter
adapter.Fill(dsInfo, "Members");
//return the DataSet to the calling aspx page
return dsInfo;
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.Message);
return null;
}
finally
{
///put everyting in the finally section
///of the try...catch block you want executed
///whether theres an exception or not, in this
///case we want to close the connection no
///matter what happens
///close the connection
/// Utlilties.HandleConnectionState(conn);
}
}
This operates as explained. It opens a connection to our database, retrieves all the user information from the users table, then populates a Dataset ans returns the DataSet to the client. Notice the [WebMethod()] attribute at the start of the method, this says that any client that consumes this Web Service will have access to that method, and the data it returns.
Believe it or not, our Web Service is complete. Now with a Web Service in a production environment will have much more meat on its bones, but for our demonstration, this is really all we need to show how a Web Service works. Next question people ask is "Ok, we have this service out there on our server, how do we access it and use it?". Well thats a good question, to use the Web Service we just created you need a consumer, a client that will connect to the service and gather the data.
In this example we will create an ASP.Net Web Application that will consume our Web Service, then display the returned data in a GridView Control. So, in your Solution Explorer window, right-click on the very top node, the solution name, then select Add > New Project. Once the New Project Dialog opens, you will this time select ASP.Net Web Site as the project type, once again either HTTP or File System for the Location and C# for the Language.
When the project is created is automatically adds a Default.aspx, and Default.aspx.cs. It's the CS file we will be doing the programming in. You always want to keep your presentation separate from your logic, thats why Microsoft offers both files for a single page in .Net.
Since this is just a sample, open Default.aspx in Design Mode, add a table to the page, then a GridView to the page. The GridView is what we'll use to display the data returned from our Web Service. You are now finished designing our ASPX page for consuming our Web Service. Now open Default.aspx.cs, and make sure you have the following references at the top of your class:
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;
Those are the only references you will need for this example. Now we need to add a reference to the Web Service we just created, to do this:
- Right-click on the project name
- Select Add Web Reference
- Once the dialog box opens select Web Services in this solution
- Once it finds your service, click on its name
- Wait for it to connect to the Web Service (when this happens the TextBox in the right-hand side of the dialog will be populated with the word localhost
- Click the Add Reference button
Now we have a reference to our Web Service and can starting using it. In our ASPX page we have a single method, BindGrid(), and this method will:
- Create a reference to our Web Service
- Create a new DataSet
- Set our DataSet to the GetAllUserInfo method in our Web Service (remember, it returns a populated DataSet)
- Bind the returned DataSet to our GridView
private void BindGrid()
{
//create our DataSet to hold the member information returned
DataSet dsMembers = new DataSet();
//create our WebService object
WebServiceConsumer.Sample.SampleService sample = new WebServiceConsumer.Sample.SampleService();
//set our DataSet to the GetAllUsers Method of our web service
dsMembers = sample.GetAllUserInfo();
//now we need to set some properties for our data grid
gvMembers.AutoGenerateColumns = true;
gvMembers.DataSource = dsMembers.Tables["Members"].DefaultView;
gvMembers.DataMember = "UserID";
gvMembers.DataBind();
}
Simple enough isn't it? Now to use this, we will call this method from our Page_Load Event in our page, and that looks like this:
protected void Page_Load(object sender, EventArgs e)
{
BindGrid();
}
Believe it or not, thats it, thats all the code required to consume our Web Service and display the returned data. The one difference in our BindGrid method is this:
WebServiceConsumer.Sample.SampleService sample = new WebServiceConsumer.Sample.SampleService();
That is where we create the reference to our Web Service, then we can use sample.WhateverMethodIsThere for utilizing the methods in the Web Service, instead of typing the long name out.
Thank you for reading, and I hope you found this helpful
0 Comments On This Entry
Trackbacks for this entry [ Trackback URL ]
Tags
- .Net
- .Net Framework 4.0
- 5 stages of data loss
- 52 Weeks Challenges
- 52 Weeks of Code
- Apple
- ASP.NET
- C#
- C# 4.0
- C# 64-Bit support
- C#4.0
- cross-thread exception
- data linking
- extension methods
- General Life
- General Programming
- INI files
- Iron Python
- jQuery
- Linux
- Mac vs PC
- Microsoft
- MSSQL
- P/Invoke
- Parallel Programming
- Ping class
- Rantings
- System.NetworkInformation Namespace
- Visual Studio 2010
- Windows 7
Recent Entries
Recent Comments
Search My Blog
1 user(s) viewing
1 Guests
0 member(s)
0 anonymous member(s)
0 member(s)
0 anonymous member(s)
My Blog Links
Blog Roll
Martyr2
SixOfEleven
SwiftStriker00
DogStopper
Lemur
erik.price
Core
KYA
born2c0de
More will be coming soon
SixOfEleven
SwiftStriker00
DogStopper
Lemur
erik.price
Core
KYA
born2c0de
More will be coming soon
|
|



Leave Comment










|