Create a Web service with C# as project type, and enter http://localhost/Security/AppendixE/Calculator as the location of your project. Write a Web method named Calculator that accepts three arguments: first operand operation (+, - , *, /, Pow), second operand, and gives the result as double, as shown in the following code. [WebMethod(Description="Simple Calculator Web Service.")] public double Calculator(System.Double a,string c, System.Double b) { switch (c) { case "+": return a + b; case "-": return a - b; case "/": if (b == 0) { return 0; } return a /b; case "*": return a * b; case "Pow": return Math.Pow(a, b); default: return 0; } } Test the Web service in the test form and check the results. EXAMPLE: ASYNCHRONOUS PROGRAMMING (METHOD 1)To illustrate the asynchronous programming of method 1, we look at a simple Windows example. Open a new Windows application and add a Web reference to the Web service http://localhost/Security/AppendixE/Calculator/Service1.asmx . In this method, the Callback function is passed with the Begin method, and it will be called by the proxy when the Web method has completed processing and returns the result to the proxy. In the following example we show the asynchronous programming of method 1. [View full width]
Figure E-13 shows the output of Calculate.cs . Figure E-13. Output of Calculate.cs (asynchronous method 1).
EXAMPLE: ASYNCHRONOUS PROGRAMMING (METHOD 2)To illustrate the second method of calling the End method, let us look at a simple Web example. Open a new ASP.NET Web application and add a Web reference to the Web service http://localhost/Security/AppendixE/Calculator/Service1.asmx . Include the namespace System.Threading . You will require this namespace to access the WaitHandle class. In this method the client waits for the method to complete, using one of the methods of the WaitHandle class. After asynchronously calling the desired Web service or Web services, the WaitHandle class waits for
In the following example we show the asynchronous programming of method 2. private void Button1_Click(object sender, System.EventArgs e) { localhost.Service1 proxy = new localhost.Service1(); double s1,s3,a; string s2; s1=Convert.ToDouble(TextBox1.Text); s2 = TextBox2.Text; s3=Convert.ToDouble(TextBox3.Text); IAsyncResult ar = proxy.BeginCalculator(s1,s2,s3,null,null); /*Do any Useful further works and then wait for the output from Web Service.*/ ar.AsyncWaitHandle.WaitOne(); a=proxy.EndCalculator(ar); TextBox4.Text=a.ToString(); } Figure E-14 shows the output of Calculate.aspx . Figure E-14. Output of Calculate.aspx (asynchronous method 2).
|