C#Builder WebMethod (Service) and Consumer (Client) Tutorial by Clay Shannon

By: Clay Shannon

Abstract: Step-by-step guide to creating web services (AKA "web methods") and clients to "consume" them using C#Builder.

Web Services are cool; web methods are all the rage. But are they just another cool technology du jour, a flash-in-the-pan? If we ignore them long enough, will they just go away? No, this technology has staying power written all over it. It is not just hype. Web services are a genuinely useful blade in your Swiss Army Knife of development techniques. In what way?

Leveraging web services, you don't need to reinvent the wheel for functions that are rare enough to not be part of your programming language's built-in functions or development tool's rtl, but are nevertheless common enough to be useful to many--or at least several--developers. Also, in many cases the return values of web services are dynamic, such as the weather at a given zip code, the current time, prices for this or that item, road conditions, etc. In cases like these you will need to access some source of dynamic information anyway (read "the Internet"), so there are little or no performance drawbacks in consuming a web service that has already been created to provide the information your application needs.

In this example, we will create a web service (in .NETspeak, a "web method") that returns the day of the week for any given date. We will also create a WinForm client that passes the requisite year, month, and day values to the web method.

Creating the Web Method/Service

Let's jump right in. Select File | New | Other | ASP.NET Web Service Application

Change Name to "DOW" (no, not after the actor who portrayed The Beaver's older brother Wally (Tony Dow), but for Day Of the Week)).

Two files are created for you: WebService1.asmx, and WebService1.asmx.cs. Select File | Save As, and save WebService1.asmx as DOW.asmx. This will also change the *.cs file to DOW.asmx.cs.

If you try to run the project at this point, you'll get the error message "unable to attach to ASP.NET process (typically aspnet_wp.exe)." Right-click DOW.asmx in the Project Manager and select "Set as start page". Now if you run it, you will get a page in IE like this:

Change the default name of your Web Method (WebService1) in both the *.asmx and the *.asmx.cs file to DOW. Also, add the following attribute (replacing my name with yours) above

public class DOW: System.Web.Services.WebService:

[WebService(Namespace="http://www.ClayShannon.com"]

Remove the placeholder web methods (commented out) in the DOW.asmx.cs file, and add the following method and attribute at the bottom of the unit:


[WebMethod]
public string GetDow(int intYear, int intMonth, int intDay)
{
  DateTime d8 = new DateTime(intYear, intMonth, intDay, new GregorianCalendar());
  GregorianCalendar gregCal = new GregorianCalendar();

  return gregCal.GetDayOfWeek(d8).ToString();
}

Also, add the following at the top of the unit:

Using System.Globalization;

That's all there is to it. Now, when you run the app, you will see this screen in your web browser (IE in my case):

Clicking ServiceDescription displays the SOAP XML behind the web method:

Clicking GetDow displays this page:

If that isn't slick, I don't know what is: C#Builder allows you to test your web method from within the web method/service itself. You don't have to create a client first to test it-what a time-saver, since otherwise you might have to switch back and forth between this project and the client project!

Here's a screenshot of the results I got after entering some test data and then selecting the Invoke button:

BTW, www.ClayShannon.com is a bogus URL (it is just a placeholder in the WebService NameSpace attribute shown above). Fortunately, though, C#Builder doesn't give three continental derns about the bogusality of that URL-it still returns the correct result.

The web method/service has been successfully created. DOW.dll has been created in C:InetpubwwwrootDOWbin. Now, let's write a simple client to call the method.

Creating the Client

Select File | New | C# Application. A WinForm will display in the designer.

Select Project | Add Web Reference The UDDI browser dialog will display:

Enter the following into the URL edit box at the top of the dialog:

http://localhost/DOW/DOW.asmx

Select the "Go" (right-arrow) button to the left of the URL edit box. The progress bar and its affiliated label at the Southwest corner of the UDDI dialog will let you know it's opening that page. It will then show you the same HTML page as seen previously in your web browser:

Select the Add Reference button. This adds some files to your project. You can see this in the Project Manager-expand the References, Web Reference, and Local Host nodes to view what has been created and added to your project for you. System.XML.dll has been added as a child to the References node, DOW.wsdl as well as Reference.map have been added to the localhost node, and the Reference.cs source code file has been added below Reference.map.

Now let's get GUI and add three Label components, three Text Box components, and a Button component to the WinForm. As with Delphi-and probably other Borland development tools-you can shift-click a component in the tool palette so as to drop as many of that type of component on the form as you want. After you are through with that particular type of component, click the North-by-Northwest pointing arrow at the top of the tool palette to deselect that component.

Change the text property of the Label components to Year, Month, and Day, respectively. Change the text property of all the Text Box components to an empty string and their names to tbYear, tbMonth, and tbDay as appropriate. Change the Button component's Layout.Size.Width property to 100. Change the form's Layout.Size.Height property to 220. Tidy up the components so they align with each other and look more-or-less orderly (not slap-dashed together, as they actually sort of were). Your form should now look something like this at design-time:

Add the Web method you created earlier to your client application's References by selecting Project | Add Reference | Project References, and then selecting the Browse button to navigate to the DOW.dll file. Now add using DOW; to the using clause of your main form (named WinForm.cs by default).

Finally, 2-click the Button and add the following code to its Click event:


private void button1_Click(object sender, System.EventArgs e)
{
  int AYear = Convert.ToInt32(this.tbYear.Text);
  int AMonth = Convert.ToInt32(this.tbMonth.Text);
  int ADay = Convert.ToInt32(this.tbDay.Text);

  try
  {
    DOW localdow = new DOW();
    MessageBox.Show(localdow.GetDow(AYear, AMonth, ADay));
  }
  catch (Exception x)
  {
    MessageBox.Show(x.Message, 
      "Something is rotten in Denmark!");
  }
}

}

When you add valid entries to the Text box components and select the Button, you will get a message back from the GetDOW web method, telling you which day of the week the date you entered corresponds to (or will be, in the case of a future date):

It may take a few seconds for the result to return the first time you call the web method, but subsequent calls return faster than you can spit and holler howdy-probably much faster, in fact.

We know have a working web method/service and a client that uses, or "consumes" it. Beyond the scope of this article is the next obvious step of publishing, or exposing the web method on a Web Service hosting site such as www.xmethods.com.

Also, before going "prime time", code should be added to test the arguments passed to the web method, namely to assure that they are valid positive integers in the appropriate range (such as 1..12 for month, 1..31 for day). For this simple example, though, we are assuming that the users (you, dear readers) will never enter bogus values such as "yabba dabba doo", "-7", "3.14", etc.

Clay Shannon is a Borland and PDA-certified Delphi developer and the author of "Tomes of Delphi: Developer's Guide to Troubleshooting" (Wordware, 2001) as well as the novel he claims is the strangest one ever written, "the Wacky Misadventures of Warble McGorkle" (see Wacky Warble, etc. for more information on the 4 Novels application, which contains this and three other novels he has penned).

You can find out more about Clay at: http://hometown.aol.com/bclayshannon/myhomepage/index.html
You can look into Clay's shareware and determine his current availability at:
http://hometown.aol.com/bclayshannon/myhomepage/business.html
You can contact him at:
BClayShannon@aol.com

Server Response from: SC2