.NET Web Services Tutorial

Environment: .NET 1.0.3705, IIS 5.0

Introduction

Visual Studio .NET makes .NET programming simple and accelerates the development process. It hides a lot of repetitive and configuration details from the user and improves productivity. However, sometimes you would like to program for .NET without using VS .NET; for example, you want to learn .NET framework programming and do not have access to VS .NET or you want to know what is actually going on under the hood.

Writing a Web Service in .NET using VS .NET very is easy. However, it is possible to write Web Services using the plain .NET SDK. I struggled a lot to write Web Services without VS .NET and tried to find help on the Net. There are a lot of examples available for writing Web Services using VS.NET, but you will rarely find any examples of writing Web Services using only the .NET SDK. This article is exactly for this purpose. It looks at Web Services development using the .NET SDK alone.

We will write and publish a simple web Service. We will also write two Web Service consumers: one Web-based consumer (ASP.NET application) and another Windows application-based consumer. Let's start writing our first Web Service.

Writing a Web Service

Following is our first Web Service; it exposes two methods (Add and SayHello) as Web Services to be used by applications. This is a standard template for a Web Service. .NET Web Services use the .asmx extension. Note that a method exposed as a Web Service has the WebMethod attribute. Save this file as FirstService.asmx in the IIS virtual directory (as explained in configuring IIS; for example, c:\MyWebSerces).

FirstService.asmx
  <%@ WebService language="C" class="FirstService" %>

  using System;
  using System.Web.Services;
  using System.Xml.Serialization;

  [WebService(Namespace="http://localhost/MyWebServices/")]
  public class FirstService : WebService
  {
      [WebMethod]
      public int Add(int a, int b)
      {
          return a + b;
      }

      [WebMethod]
      public String SayHello()
      {
          return "Hello World";
      }
  }

To test a Web Service, it must be published. A Web Service can be published either on an intranet or the Internet. We will publish this Web Service on IIS running on a local machine. Let's start with configuring the IIS.

  • Open Start->Settings->Control Panel->Administrative tools->Internet Services Manager.
  • Expand and right-click on [Default Web Site]; select New ->Virtual Directory.
  • The Virtual Directory Creation Wizard opens. Click Next.
  • The "Virtual Directory Alias" screen opens. Type the virtual directory name—for example, MyWebServices—and click Next.
  • The "Web Site Content Directory" screen opens. Here, enter the directory path name for the virtual directory—for example, c:\MyWebServices—and click Next.
  • The "Access Permission" screen opens. Change the settings as per your requirements. Let's keep the default settings for this exercise. Click the Next button. It completes the IIS configuration. Click Finish to complete the configuration.

To test that IIS has been configured properly, copy an HTML file (for example, x.html) in the virtual directory (C:\MyWebServices) created above. Now, open Internet Explorer and type http://localhost/MyWebServices/x.html. It should open the x.html file. If it does not work, try replacing localhost with the IP address of your machine. If it still does not work, check whether IIS is running; you may need to reconfigure IIS and Virtual Directory.

To test our Web Service, copy FirstService.asmx in the IIS virtual directory created above (C:\MyWebServices). Open the Web Service in Internet Explorer (http://localhost/MyWebServices/FirstService.asmx). It should open your Web Service page. The page should have links to two methods exposed as Web Services by our application. Congratulations; you have written your first Web Service!!!

Testing the Web Service

As we have just seen, writing Web Services is easy in the .NET Framework. Writing Web Service consumers is also easy in the .NET framework; however, it is a bit more involved. As said earlier, we will write two types of service consumers, one Web- and another Windows application-based consumer. Let's write our first Web Service consumer.

Web-Based Service Consumer

Write a Web-based consumer as given below. Call it WebApp.aspx. Note that it is an ASP.NET application. Save this in the virtual directory of the Web Service (c:\MyWebServices\WebApp.axpx).

This application has two text fields that are used to get numbers from the user to be added. It has one button, Execute, that, when clicked, gets the Add and SayHello Web Services.

WebApp.axpx
  <%@ Page Language="C#" %>
  <script runat="server">
  void runSrvice_Click(Object sender, EventArgs e)
  {
      FirstService mySvc = new FirstService();
      Label1.Text = mySvc.SayHello();
      Label2.Text = mySvc.Add(Int32.Parse(txtNum1.Text),
                    Int32.Parse(txtNum2.Text)).ToString();
  }
  </script>
  <html>
  <head>
  </head>
  <body>
  <form runat="server">
    <p>
        <em>First Number to Add </em>:
        <asp:TextBox id="txtNum1" runat="server"
             Width="43px">4</asp:TextBox>
    </p>
    <p>
        <em>Second Number To Add </em>:
        <asp:TextBox id="txtNum2" runat="server"
             Width="44px">5</asp:TextBox>
    </p>
    <p>
        <strong><u>Web Service Result -</u></strong>
    </p>
    <p>
        <em>Hello world Service</em> :
        <asp:Label id="Label1" runat="server"
             Font-Underline="True">Label</asp:Label>
    </p>
    <p>
        <em>Add Service</em> :
        & <asp:Label id="Label2" runat="server"
               Font-Underline="True">Label</asp:Label>
    </p>
    <p align="left">
        <asp:Button id="runSrvice" onclick="runSrvice_Click"
             runat="server" Text="Execute"></asp:Button>
    </p>
  </form>
  </body>
  </html>

After the consumer is created, we need to create a proxy for the Web Service to be consumed. This work is done automatically by Visual Studio .NET for us when referencing a Web Service that has been added. Here are the steps to be followed:

  • Create a proxy for the Web Service to be consumed. The proxy is created using the wsdl utility supplied with the .NET SDK. This utility extracts information from the Web Service and creates a proxy. Thus, the proxy created is valid only for a particular Web Service. If you need to consume other Web Services, you need to create a proxy for this service as well. VS .NET creates a proxy automatically for you when the reference for the Web Service is added. Create a proxy for the Web Service using the wsdl utility supplied with the .NET SDK. It will create FirstSevice.cs in the current directory. We need to compile it to create FirstService.dll (proxy) for the Web Service.
    c:> WSDL http://localhost/MyWebServices/
                    FirstService.asmx?WSDL
    c:> csc /t:library FirstService.cs
    
  • Put the compiled proxy in the bin directory of the virtual directory of the Web Service (c:\MyWebServices\bin). IIS looks for the proxy in this directory.
  • Create the service consumer, which we have already done. Note that I have instantiated an object of the Web Service proxy in the consumer. This proxy takes care of interacting with the service.
  • Type the URL of the consumer in IE to test it (for example, http://localhost/MyWebServices/WebApp.aspx).

Windows Application-Based Web Service Consumer

Writing a Windows application-based Web Service consumer is the same as writing any other Windows application. The only work to be done is to create the proxy (which we have already done) and reference this proxy when compiling the application. Following is our Windows application that uses the Web Service. This application creates a Web Service object (of course, proxy) and calls the SayHello and Add methods on it.

WinApp.cs
  using System;
  using System.IO;

  namespace SvcConsumer{
  class SvcEater
  {
      public static void Main(String[] args)
      {
          FirstService mySvc = new FirstService();

          Console.WriteLine("Calling Hello World Service: " +
                             mySvc.SayHello());
          Console.WriteLine("Calling Add(2, 3) Service: " +
                             mySvc.Add(2, 3).ToString());
      }
  }
  }

Compile it using c:>csc /r:FirstService.dll WinApp.cs. It will create WinApp.exe. Run it to test the application and the Web Service.

Now, the question arises: How can I be sure that my application is actually calling the Web Service? It is simple to test. Stop your Web server so that the Web Service cannot be contacted. Now, run the WinApp application. It will fire a run-time exception. Now, start the Web server again. It should work. Great, isn't it?

Downloads

Download tutorial source code - 2 Kb


Comments

  • дуслар татарский портал знакомств

    Posted by griegosic on 06/28/2013 07:10am

    То были Дюгем и его люди: они поспешили на помощь, услышав выстрелы, обошли Сульмону и напали на Пронио с тыла. Но больше не проси ни за кого: все места заняты. [url=http://kotlas-znakomstva.ded-of.ru.com/neformali-chat-znakomstva.php]неформалы чат знакомства[/url] Но следов, которые спускались бы к дороге, там не осталось. О Роза, дочь моя, тебе, конечно, виднее, но, судя по запаху, твой ягодный пудинг пригорает. Можете на меня рассчитывать - я найду Клинка Света и передам ваше письмо. Он работал неделями, но, несмотря на все свои старания, так ничего и не добился, и цилиндр не стал двигаться быстрее. Энергия последнего предсмертного вздоха копится, тут он показал на грудь Хардвина, и придает Ему сил. Николай, видя мое горе, попытался утешить меня. Сначала я думал, что мне удалось спастись, но моя рана оказалась серьезней, чем я полагал. [url=http://samarskie-znakomstva.ded-of.ru.com/anketa750.php]глухие американские знакомства[/url] Последний был человеком добрым на свой грубоватый манер. Такую борьбу вела эта девушка, достойная хвалебной песни.

    Reply
  • Do You Know the most important Dangers concerning Counterfeit Oral Drug for Erectile Dysfunction Treatment?

    Posted by agieffifielm on 06/21/2013 07:54pm

    Erectile Dysfunction Products - The Ones That Move the Best? Though this is a cheaper drug, the decision is still your own [url=http://rxhealth.pw ] is viagra bought on the internet safe [/url] read a lot more The causes of erectile dysfunction

    Reply
  • tdk1naf cigar

    Posted by grwastqz on 05/21/2013 08:52pm

    k1aj4shk kcekc71m f54yewr4t536 igh4abu7 thlu3axx

    Reply
  • fv0lhx4 cigar

    Posted by grwastqz on 05/21/2013 08:04am

    a6fdp595 pkc6cw2v f54yewr4t536 m69xfchp zq3fy4nv

    Reply
  • 5l067ic cigar

    Posted by grwastqz on 05/21/2013 02:52am

    slvqluta sbs1y4j0 f54yewr4t536 y0wj6tvp b5ogyu3k

    Reply
  • .net

    Posted by Owais Qureshi on 04/02/2013 01:40pm

    First of fall assalam-o-alaikum i like .net and then mea yeh or sekhna chata hu plz help me.

    Reply
  • .net

    Posted by Owais Qureshi on 04/02/2013 01:38pm

    First of fall assalam-o-alaikum and then i like .net and or mea yeh sekhna chata hu plz help me.

    Reply
  • Heal Can Gout Cause Plantar Fasciitis

    Posted by joipsyrillips on 04/01/2013 12:59pm

    1 Does Overpronation Cause Plantar Fasciitis surgery for plantar fasciitis Treatment For Plantar Fasciitis Exercises Cultural anthropologist, Angeles Arrien, suggested that she is connected to the new socks I bought a home incredibly easy. Length Of Time For Plantar Fasciitis To Heal plantar fasciitis strapping Heal Plantar Fasciitis Current Diagnostic Modalities And Treatments Real Property Law Deeds Covenants of Title Plantar Fasciitis Foot Drop Remedy plantar fasciitis massage Plantar Fasciitis Cavus Foot

    Reply
  • RHAZte Tf pY zSH lWlf Qu

    Posted by hrwdoyqXdQ on 04/01/2013 05:08am

    buy tramadol cod tramadol high blood pressure - buy tramadol cash on delivery

    Reply
  • GHD Hair Straighteners Questionnaire Cheap Online with free streaming Transport

    Posted by on 03/11/2013 02:43am

    lSowvzQdup ghd lSjxqrFofk ghd straighteners rGnybbFnxc ghd online mHjryfGrya http://cheapghdaustraliasale.webs.com/ sEtwbyEgon ghd tGisxzLwtn ghd sale vQgmsfAqal ghd straightener cheap jOwedjHxhj www.cheapghdaustraliasale.webs.com/ jPsadsLxkr ghd gSjwqiDwdk ghd straighteners wFclqvVvix ghd straightener cheap wFubzjCtwr www.cheapghdaustraliasale.webs.com/

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • The proliferation of cloud computing options has begun to change the way storage is thought about, procured, and used. IT managers and departments need to think through how cloud options might fit into and complement their onsite data infrastructures. This white paper explains cloud storage and backup, providing advice about the tools and best practices for its implementation and use. Read this white paper for some useful takeaways about how to take advantage of cloud storage for high availability, backup and …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds