Archive

Posts Tagged ‘Web Service’

Testing and Monitoring WCF Service using soapUI and Fiddler

September 3, 2011 Leave a comment

This article is not about understanding the details of .Net WCF service, soapUI and Fiddler as all these three are quite popular things among .Net developers. And tools like soapUI and Fiddler may already be in the arsenal of many web developers and QA engineers. Those who are new to these two tools should refer to following articles.

However, we will take a look into how Fiddler can be used to Monitor SOAP Request and SOAP Response transmitting behind the soapUI.

Let’s start with a simple WCF service in place. No need to have a WCF .Net Client as of now to test and monitor HTTP traffic of WCF service calls.

1. Open soapUI and set the following settings. Make sure the service’s wsdl path is correct.

Loading wsdl definition

2. After loading the definition of WSDL, service definitions will appear like shown below.

Service requests definitions

3. Double click on Request # node and navigate to the request window on the right.

Submitting the request

4. Fill the method parameters denoted by “?”.

5. Open Fiddler and make sure it is ready to capture HTTP(S) traffic.

6. Submit request to the specified endpoint and SOAP Response can be seen on the right pane.

Service Request-Response in soapUI

7. If you see the Fiddler window, there is no traffic captured. This is really frustrating if you have been testing your services using soapUI when you do not see the underlying details of the SOAP Request and SOAP Response in the wire.

8. All you need to do following proxy settings in the soapUI File –> Preferences –> Proxy Settings window.

soapUI Proxy Settings

9. Re-submit web service request on soapUI.

10. Now you see WCF Request-Response traffic in the Fiddler window Smile. You are now all in your territory to view the details of service request-response headers, body, and many more!

SOAP Request-Response view in Fiddler

But why did we add Port No. 8888 in the proxy settings of soapUI? It is because Fiddler by default listens on port no. 8888.

Fiddler default listening port no.

If you have configured your Fiddler proxy tool to listen on some other port no., then you should use that one.

I hope you enjoyed this testing tip. No need to reiterate how blissful it is to test web services using soapUI and Fiddler if you are a web service developer/provider to remote clients.

jQuery, JSON and ASP.Net Web Service

Today we will see a simple example of jQuery, JSON and ASP.Net Web Service. We will mainly see how to consume ASP.Net web service web methods using both jQuery and JavaScript and see how to handle DateTime object result. Also, how jQuery can be used to call a web method by passing arguments values.

We know JSON type lacks Date/Time literal because JavaScript too does not have Date/Time literal directly. I think JavaScript author was smart enough to leave Date/Time literal! As Date/Time is a complex subject, that should be better left for programmers who write code to interact with servers that have different running time zones, and we know JavaScript is a client-side scripting language.

Let’s see how to handle this with examples. Write a simple web service as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml.Serialization;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
namespace JsonAndScriptSvc
{
/// <summary>
/// Summary description for WebServerDate
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script,
// using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebServerDate : System.Web.Services.WebService
{
//
private JsonDateSez objJson = null;
public WebServerDate()
{
objJson = new JsonDateSez();
}
[WebMethod]
public object GetServerDate()
{
JavaScriptSerializer serz = new JavaScriptSerializer();
return serz.Serialize(objJson);
}
[WebMethod]
public Int32 GetSumResult(Int32 xValue, Int32 yValue)
{
return (xValue + yValue);
}
}

public class JsonDateSez
{
public DateTime JsonSerzDate
{
get { return new DateTime(2009, 9, 17); }
}
}
}

Then, add one Default.aspx page whose mark-up code looks like this:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”JsonAndScriptSvc._Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>JavaScript and JavaScriptSerializer</title>
<script type=”text/javascript” language=”javascript” src=”JSWebService.js”></script>
</head>
<body>
<form id=”frmJson” runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePageMethods=”true”>
<Services>
<asp:ServiceReference Path=”~/WebServerDate.asmx” />
</Services>
</asp:ScriptManager>
<div>
<input id=”BtnFetchDate” type=”button” value=”Check Server Date” onclick=”ServerDate();”/>
<br />
</div>
</form>
</body>
</html>

The onClick() event of BtnFetchDate button will call ServerDate() method in JSWebService.js file. This js file has two methods as:

function ServerDate() {
JsonAndScriptSvc.WebServerDate.GetServerDate(ReceivedDate);
}
function ReceivedDate(result) {
var svrdt = Sys.Serialization.JavaScriptSerializer.deserialize(result);
alert(“Result in Json Format: ” + result + “\n” + “Result desired: ” + svrdt.JsonSerzDate);
}

Once clicked, we may see result as shown in figure below.

JSON-WebService

We saw how JavaScriptSerializer class helped to get the desired date-time result.

Similarly, we can see jQuery based example similar to above one. Let’s add another JQryPage.aspx page whose mark-up may look like this:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”JQryPage.aspx.cs” Inherits=”JsonAndScriptSvc.JQryPage” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>JQuery and Web Service</title>
<script type=”text/javascript” language=”javascript” src=”jquery-1.2.3.min.js” />
<script type=”text/javascript” language=”javascript” src=”JSWebService.js”></script>
<script type=”text/javascript” language=”javascript”>
/* jQuery calling webmethod to fetch server date-time values */
function JQueryWebMethod() {
$.ajax({
type: “POST”,
url: “WebServerDate.asmx/GetServerDate”,
data: “{}”,
contentType: “application/json;charset=utf-8″,
dataType: “json”,
success: function(result) {
alert(“Result in Json Format: ” + result.d);
},
error: function(request, status, throwerror) {
alert(status);
}
});
}
/* jQuery calling webmethod by passing two arguments */
function JQuerySumResultWebMethod() {
$.ajax({
type: “POST”,
url: “WebServerDate.asmx/GetSumResult”,
data: “{‘xValue’:’10′,’yValue’:’15′}”,
contentType: “application/json;charset=utf-8″,
dataType: “json”,
success: function(result) {
alert(result.d);
},
error: function(request, status, throwerror) {
alert(status);
}
});
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePageMethods=”true”>
<Services>
<asp:ServiceReference Path=”~/WebServerDate.asmx” />
</Services>
</asp:ScriptManager>
<div>
<input id=”BtnJQry” type=”button” value=”jQry Check Server Date” onclick=”JQueryWebMethod();”/>
<br /><br />
<input id=”BtnSumResult” type=”button” value=”jQry Sum Result” onclick=”JQuerySumResultWebMethod();”/>
</div>
</form>
</body>
</html>

Run this page, click BtnJQry button to see the result of Date/Time. We may see the same raw result that we received in JavaScript before deserializing ‘result’ object using JavaScriptSerializer class. Click other button called BtnSumResult will get the sum result from web method by passing two arguments values.

The documentation of $.ajax() global method can be found at http://docs.jquery.com/Ajax/jQuery.ajax. However, we should remember type, url, data, contentType and dataType key values when constructing parameters for $.ajax() global method.

Thus, we saw jQuery, JSON and ASP.Net Web Service example.

ASP.Net Ajax Callbacks to: Web Service and ASP.Net Page’s Web Methods

Today we will see how ASP.Net Ajax callback feature can help us call methods defined in Web Service and ASP.Net page. ScriptService and ScriptMethod are two new attributes in ASP.Net Ajax framework library that helps calling web service and web page web methods respectively.
Let’s see it one by one in the following examples.

First, create a simple web service project called ASPAjaxService.asmx. Define a web method as given below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace ASPAjaxService
{
/// <summary>
/// Summary description for ASPServiceMethods
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script,
// using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class ASPServiceMethods : System.Web.Services.WebService
{
//
[WebMethod(true)]
public string WebServiceMethod()
{
return “Example: Consuming a web service using ASP.Net Ajax.”;
}
}
}
See the ScriptService attribute that is applied to Class declaration ASPServiceMethods. This indicates that a web service can be invoked from script. In fact, it provides a JavaScript proxy class corresponding to the web service in order to call the web service web methods. Now to test this service, let’s view our *.asmx in browser. Probably, we may see url as: http://localhost:49487/ASPAjaxService.asmx. The port number may vary, but we are now ready to test  WebServiceMethod web method. Before this, change the url as: http://localhost:49487/ASPAjaxService.asmx/js and hit [Enter]. It will return a proxy code of JavaScript. We may save it to our project folder to see its details. This is result of ScriptService attribute.

Now, create a simple ASP.Net application and add this existing web service project to this application. Modify the Default.aspx markup as:

<head runat=”server”>
<title>ASP.Net Ajax CallBack</title>
<script type=”text/javascript” language=”javascript” src=”javascript_ajax_asp_net.js”></script>
</head>
<body>
<form id=”form1″ runat=”server”>
<asp:ScriptManager runat=”server” ID=”ScriptManager1″ EnablePageMethods=”true”>
<Services>
<asp:ServiceReference InlineScript=”false” Path=”~/ASPAjaxService.asmx”/>
</Services>
</asp:ScriptManager>
<div>
[Invoke Web Method] – Make a call to Web Method in web service: ASPAjaxService.asmx<br /><br />
<input type=”button” id=”BtnCallWebMethod” value=”Invoke Web Method” onclick=”return CallWebServiceMethod();” /><br /><br />
[Invoke Web Method defined in UI.Page] – Make a call to Page Method in Default.aspx<br /><br />
<input type=”button” id=”BtnPageMethod” value=”Invoke Web Method defined in UI.Page” onclick=”return CallPageMethods();” />
</div>
</form>
</body>
</html>

See the <asp:ScriptManager/> tag section. ServiceReference registers the web service mentioned in Path attribute for use in a web page.  Path can only point to local web service, i.e.; in the same domain.

InlineScript value can be either true or false. Toggle its value, view Default.aspx in browser, view its html source and save it. Compare the size of two files. You will see a remarkable difference. When InlineScript is set to true, the proxy javascript code is generated and rendered directly in the page for each request. Due to this, the page can not be cached for similar request and page size is also larger.

But in our example, we have set this property to false and added src=”javascript_ajax_asp_net.js”.  It has required functions to fulfil our purpose. But one may compare and see both the proxy and current *.js file. In this case, we can definitely benefit from browser caching and shorter page load time!

The javascript file has following code.

//Webservice web methods
function CallWebServiceMethod() {
ASPAjaxService.ASPServiceMethods.set_timeout(1000);
ASPAjaxService.ASPServiceMethods.WebServiceMethod(onSuccess, onFailed, “Caller Context”);
}
function onSuccess(result, usercontext) {
alert(result + ” – ” + usercontext);
}
function onFailed(result, usercontext) {
var failed_message = “Some error occured while calling the web method.”;
alert(failed_message + ” : ” + usercontext);
}
//PageMethods
function CallPageMethods() {
PageMethods.WebMethodInPage(onSuccessfulPageCall, onFailed, “Caller Context:System.Web.UI.Page”);
}
function onSuccessfulPageCall(result, usercontext) {
alert(result + ” – ” + usercontext);
}
We have not done yet.  We are still one step away from calling a web method in ASP.Net page.

Add this method in code behind of our ASP.Net page as given below.

[WebMethod(true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static string WebMethodInPage()
{
//
return “I am in Page Method.”;
}
Run the page and call each web method.  We are able to call ASP.Net page method due to ScriptMethod attribute for WebMethodInPage() method and EnablePageMethods=”true” in ScriptManager class property. ScriptManager.EnablePageMethods property when set to true enables public static web method in page to be called by javascript.

That’s all! Happy coding!

Follow

Get every new post delivered to your Inbox.