Si tepershtasimatributinWebmethodsipaskerkesave
Le tekontrollojmekarakteristikat e Web metodave duke perdoruratributet.
You've seen how easy it is to generate a Web service by using Visual Studio .NET,
simply by marking published methods with the WebMethodattribute. But there are also a
number of ways to customize your Web service by adding properties to that attribute.
Table 4.1 shows the properties that you can use to customize the WebMethodattribute
Table 4.1. Properties of the WebMethodAttribute
Property Meaning
BufferResponseIndicates whether the response should be buffered. If set to true
(the default) the entire response is buffered until the message iscompletely serialized and is then sent to the client. If set to false,the response is sent to the client as it is serialized.
CacheDurationSpecifies the number of seconds that ASP.NET should cacheresults on the server. The default is 0, which disables caching.
Description Supplies a description for the Web method.
EnableSessionIndicates whether the session state should be enabled. The defaultis false.
MessageNameSpecifies the name by which the method will be called in SOAPmessages. The default is the method name.
TransactionOptionIf set to TransactionOption.RequiredorTransactionsOption.RequiredNew, enables the Web method toparticipate as the root object of a transaction. The default isTransactionOption.Disabled.
In the Step-by-Step 4.4, you'll see how you can use several of these properties to
customize a Web method..
Customizing a Web Service
Ushtrimi 1
1. Open the StringProcWeb Service project that is created.
3. [WebMethod(CacheDuration = 60,
4. Description = "Method to demonstrate caching")]
5. public String CachedString(intintInput)
6. {
7. return "The time is " +
8. DateTime.Now.ToLongTimeString();
9. }
10.
11. [WebMethod(Description = "Method without caching")]
12. public String UncachedString(intintInput)
13. {
14. return "The time is " +
15. DateTime.Now.ToLongTimeString();
16. }
17.
18. [WebMethod(EnableSession = true,
19. Description = "Store a value in session state")]
20. public String SetSession(intintInput)
21. {
22. Session["StoredInt"] = intInput;
23. return "Value " + intInput +
24. " stored in session state";
25. }
26.
27. [WebMethod(EnableSession = true,
28. MessageName = "Get Session",
29. Description=
30. "Retrieve a value from session state")]
31. public String GetSession()
32. {
33. if (Session["StoredInt"] != null)
34. {
35. intintOutput = (int) Session["StoredInt"];
36. return "Value " + intOutput +
37. " retreived from session state";
38. }
39. return "";
40. }
41. Run the project. This opens the test page shown in Figure 4.10. Notice that
the test page displays the description property of each Web method.
Figure 4.10. The test page for a Web service displays the Web method with
its description, if the Web method attribute has the Description property
defined.
42. Click on the UncachedStringlink to open a test page for the
UncachedString() method.
43. Enter a value for the input parameter and click Invoke. You should see a
return message with the current time.
44. Click Invoke again. You should now see the updated current time.
45. Click the link to return to the complete list of operations.
46. Click on the CachedStringlink to open a test page for the CachedString()
method.
47. Enter a value for the input parameter and click Invoke. You should see a
return message with the current time.
48. Click Invoke again. You should now see the same current time. That's
because the result from the CachedString() method is cached for sixty
seconds. ASP.NET returns the cached value during that time without calling
the original method.
49. Change the input parameter and click Invoke again. You should see a return
message with the current time. When an input parameter changes, ASP.NET
does not use the cached result.
50. Click the link to return to the complete list of operations.
51. Click the link for the SetSession() method.
52. Enter an input value and click Invoke. You should see a confirmation
message.
53. Click the link to return to the complete list of operations.
54. Click on the link for the GetSession() method. Notice that this link uses the
MessageNameproperty of the WebMethodattribute rather than the name of the
underlying method.
55. Click Invoke. You should now see the value retrieved from the session state.
Step-by-Step 4.4 demonstrates all the WebMethodattribute properties except for
BufferResponseand TransactionOption. The only time that you'll want to set
BufferResponseto true is when you're returning more than 16KB of data, and that data
is being constructed on the fly—for example, when you are retrieving and formatting
records from a database.
WARNING
Be Wary of Session State You should be cautious about using session state in a Web
service. Session state can tie up server resources for an extended period of time. If you
use session state with a popular Web service, you will apply heavy demands to Random
Access Memory (RAM) on your Web server.
Ushtrimi 2
A web service which performs Domain Name Lookups
[WebService(Namespace="
Description="<b>A web service which performs Domain Name Lookups.</b>")]
publicclassDNSLookupService: System.Web.Services.WebService
{
[WebMethod(MessageName="LookupDNS",
Description="Get an IP address for a given hostname string")]
publicstringGetIPForHostname(stringstrHostname)
{
IPHostEntryhostInfo = Dns.GetHostByName(strHostname);
returnhostInfo.AddressList[0].ToString();
}
}
Ushtrimi 3
Create a Visual C# .NET Windows Application in the Visual Studio .NET IDE.
2. Right-click the References folder in Solution Explorer and select Add Web
Reference. The Add Web Reference dialog box appears.
Type in the
Address bar of the Add Web Reference dialog box and press Enter. This connects
you to the StringProcWeb service and creates the appropriate proxy classes.
4. Click the Add Reference button.
5. Add a new Windows form to your Visual C# .NET project.
6. Place a Label control, a TextBoxcontrol (txtCode), a Button control
(btnGetWeather), and a Listboxcontrol (lbResults) on the form. Refer to
Figure 4.2 for the design of this form.
7. Double-click the Button control and enter the following code to invoke the Web
service when the user clicks the Get Weather button:
8. private void btnGetWeather_Click(
9. object sender, System.EventArgs e)
10. {
11. // Declare the Web service main object
12. com.capescience.live.AirportWeather aw=
13. newcom.capescience.live.AirportWeather();
14.
15. // Invoke the Web service.
16. // This may take some time, so
17. // call it asynchronously.
18. // First, create a callback method
19. AsyncCallbackwcb = new AsyncCallback(
20. WebServiceCallback);
21. // Initiate the asynchronous call
22. aw.BegingetSummary(
23. txtCode.Text, wcb, aw);
24. }
25. // This method will get called
26. // when the Web service call is done
27. public void WebServiceCallback(
28. IAsyncResultar)
29. {
30. // Retrieve the state of
31. // the proxy object
32. com.capescience.live.AirportWeather aw=
33. (com.capescience.live.AirportWeather)
34. ar.AsyncState;
35.
36. // Call the End method
37. // to finish processing
38. com.capescience.live.WeatherSummaryws=
39. aw.EndgetSummary(ar);
40.
41. // And display the results
42. lbResults.Items.Clear();
43. lbResults.Items.Add(ws.location);
44. lbResults.Items.Add(
45. "Wind " + ws.wind);
46. lbResults.Items.Add(
47. "Sky " + ws.sky);
48. lbResults.Items.Add(
49. "Temperature " + ws.temp);
50. lbResults.Items.Add(
51. "Humidity " + ws.humidity);
52. lbResults.Items.Add(
53. "Barometer " + ws.pressure);
54. lbResults.Items.Add(
55. "Visibility " + ws.visibility);
56. }
57. Insert the Main() method to launch the form. Set the form as the startup object for
the project.
58. Run the project and enter a four-digit ICAO airport code. Click the Get Weather
button. Wait a few moments; you will see the current weather at that airport in the
list box. Note that while you're waiting, you can still drag the form around the
screen, which shows that it is not blocked by theWeb service call.
If you compare the code for this exercise with the code that you saw in Step-by-Step 4.1,
you'll find some significant changes. In the .NET Framework, asynchronous Web service
calls are managed by callback methods. When you add a Web reference, the proxy class
includes Begin and End methods for each Web method. In this case, those are the
BegingetSummary() and EndgetSummary() methods.
The Begin method takes all the same parameters as the underlying Web method, plus two
others. The first is the address of a callback method, and the second is an object whose
properties should be available in the callback method. When you call the Begin method,
the .NET Framework launches the call to the Web service in the background. When the
Web method call completes, the callback method is invoked. The code in this exercise
shows how you can then retrieve the original object and use its End method to finish the
work of using the Web service.
Perdoriminga Web Aplikimi
7. Double-click the Button control and enter the following code to invoke the Web
service when the user clicks the Get Weather button:
8. private void btnGetWeather_Click(
9. object sender, System.EventArgs e)
10. {
11. // Declare the Web service main object
12. com.capescience.live.AirportWeather aw=
13. newcom.capescience.live.AirportWeather();
14.
15. // Invoke the service
16. // to get a summary object
17. com.capescience.live.WeatherSummaryws=
18. aw.getSummary(txtCode.Text);
19.
20. // And display the results
21. lbResults.Items.Clear();
22. lbResults.Items.Add(ws.location);
23. lbResults.Items.Add("Wind " + ws.wind);
24. lbResults.Items.Add("Sky " + ws.sky);
25. lbResults.Items.Add(
26. "Temperature " + ws.temp);
27. lbResults.Items.Add(
28. "Humidity " + ws.humidity);
29. lbResults.Items.Add(
30. "Barometer " + ws.pressure);
31. lbResults.Items.Add(
32. "Visibility " + ws.visibility);