Creating and Calling ASP.NET AJAX Web Service

Hi,

First we will create a new ASP.NET Ajax web site(Visual Studio 2005)
or ASP.NET web site (version 3.5) if we are using Orcas(Visual studio 2008)

Through Add New Item, add a new web service WebService.asmx in the website.

1) Add this in webservice.cs

using System.Web.Script.Services;


2) Add a ScriptService attribute to our webservice class

[ScriptService]
[WebService(Namespace = “http://tempuri.org/”)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

3) We’ll use the default Hello World web service. So just save the web service and view it in browser to test it.

Now change the url of the webservice in browser and append “/js” to it
i.e.
Change
http://d-0824/AjaxinAction/WebService.asmx
to
http://d-0824/AjaxinAction/WebService.asmx/js

Press enter it will ask you to save the file,
just save and open it in notepad

We will see something like this

var WebService=function() {
WebService.initializeBase(this);
this._timeout = 0;
this._userContext = null;
this._succeeded = null;
this._failed = null;
}
WebService.prototype={
_get_path:function() {
…………………………
……………………….

This is a javascript proxy class which the our client side ajax library will use to make call to our web service.

4) Add a script manager control to our default.aspx page ( if not already there), and add the reference to our web service

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
<Services>
<asp:ServiceReference Path=”WebService.asmx” />
</Services>
</asp:ScriptManager>

5) Now add a simple html text control on the default.aspx page. We will be calling our web service and fill the text box value returned from the webservce (“Hello World”).

<input id=”Text1″ type=”text” />

6) Put this script on your default.aspx page

<script type=”text/javascript”>

function pageLoad()
{
WebService.HelloWorld(onSuccess);
}

function onSuccess(result)
{
$get(“Text1”).value=result;
}

</script>

7) Now just view the page in browser we should see the textbox filled with “Hello World” string returned from our web service.

8) Or if we want to call it in the click of the button. add a html button control.

<input id=”Button1″ type=”button” value=”button” />

9) Replace the above script with this one

<script type=”text/javascript”>
var myButton=null;
function pageLoad(sender,e)
{
myButton=$get(“Button1″);
$addHandler(myButton,”click”,btn_click);
}

function btn_click(sender,e)
{
WebService.HelloWorld(onSuccess);
}

function onSuccess(result)
{
$get(“Text1”).value=result;
}
</script>

In the above example we saw a client centric approach, the same thing can be done very easily by making use  of server centric approach in ASP.NET AJAX framework.

https://nishantrana.wordpress.com/2007/11/06/creating-a-simple-hello-world-aspnet-ajax-web-page/

Bye

 

Advertisements

Javascript and Asp.net

Let’s see how we can use javascript with our server side controls with very simple examples

1) One way is using

controlname.attributes.add(string key,string value);

Let’s see an example

1. Create a new webpage

2. Add a textbox to it.

<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

3. Now let us add some javascript for onMouseOver event so that whenever mouse is over the textbox it should alert Hello World message.

4. For this add this code on page_load event handler

protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Attributes.Add(“onMouseOver”,”alert(‘Hello World’);”);
}

OnMouseOver is the name of the JavaScript event followed by our javascript code to run on occurence of that event.

5. If small code of javascript is there than we can write it over directly in attributes.add but otherwise it’s better we write the code within our script block and put the name of the function over there

<script type=”text/javascript”>
function mHover()
{
alert(‘Hello World’);
}
</script>

and

protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Attributes.Add(“onMouseOver”, “mHover()”);
}

Normally we can insert javascript by adding attributes to the control.

But for our button server control we can use OnClientClick property for handling button clicks with Javascript code

<asp:Button ID=”Button1″ runat=”server” Text=”Button” OnClientClick=”return confirm(‘Post back to the server?’);”/>

Whatever is written on OnClientClick fires first followed by the postback event.

In above case if the method returns false i.e. user clicks cancel no post back occurs.

Some common javascript events which we can use inside attributes.add are

onChange, onClick, onMouseOver, onMouseOut, onKeyUp, onKeyDown, onSelect, onFocus, onBlur,onAbort, onError, onLoad ,onUnload

In asp.NET we can make use of Page.ClientScript property for managing script blocks

RegisterClientScriptCallBlock() : It writes the script block right after the <form runat=server> tag

RegisterStartupScript() : It writes the script block right before closing </form> tag

We will modify the textbox example we first created

1: Remove the script section from the aspx page and put it on the page load like this

protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Attributes.Add(“onMouseOver”, “mHover()”);
string script=@”<script type=’text/javascript’>
function mHover()
{
alert(‘Hello World’);
}
</script>”;
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),”onMO”,script);
TextBox1.Attributes.Add(“onMouseOver”, “mHover()”);
}

2: Now run the web page and see the source we will find the script added just after the <form> start tag

3: Now replace

Page.ClientScript.RegisterClientScriptBlock(this.GetType(),”onMO”,script);

with

Page.ClientScript.RegisterStartupScript(this.GetType(),”onMO”,script);

4: We will be able to see the script added just before the </form> tag

Bye

Using Ajax in ASP.NET application -3 (JSON)

As we saw in our previous post

https://nishantrana.wordpress.com/2007/10/25/using-ajax-in-aspnet-application-2/ 

How easy it becomes to parse the response and the values if it is in the XML rather than plain text.

But that is not the only way there is something called JSON as well

What is JSON?

JSON – Javascript object notation is a format for sending and recieving data similar to XML.

It’s a lightweight data fomat that’s easy to work with in JavaScript.

Check this site for more info http://json.org/

Let’s understand it by an example

We’ll here again modify the application created in our previous post to make use of JSON in place of XML

This time we will be returing an Object to our javascript code in JSON as response.

Let’s say we have on class like this which we would like to return as response to our calling ajax scripts

public class Emp

{

public Emp(){}

private string firstName;

public string FirstName{get { return firstName; } set { firstName = value; }}

private string lastName;

public string LastName{ get { return lastName; } set { lastName = value; }} 

private string[] skills = new string[3]; 

public string[] Skills{ get { return skills; }set { skills = value; }

}} 

To convert it to JSON let’s make use of a library.

We’ll make use of LitJSON here.

We can find all the information and the library for LitJSON here http://litjson.sourceforge.net/doc/manual.html 

(add reference to LitJson.dll in the project) 

Now make this change in our Default2.aspx page’s page Load

protected void Page_Load(object sender, EventArgs e)

{

Emp emp = new Emp();

emp.FirstName = “Donald”;

emp.LastName = “Duck”;

emp.Skills[0] = “ASP.NET”;

emp.Skills[1] = “WCF”;

emp.Skills[2] =”WPF”;

string json_Emp = JsonMapper.ToJson(emp);

Response.Write(json_Emp); 

}

Response.Write(json_Emp) will give us this

{“FirstName”:”Donald”,”LastName”:”Duck”,”Skills”:[“ASP.NET”,”WCF”,”WPF”]}

The changes that we need to make in our Default.aspx page are again in doUpdate function 

function doUpdate()

{

if(xmlHttp.readyState==4)

 {

//{“FirstName”:”Donald”,”LastName”:”Duck”,”Skills”:[“ASP.NET”,”WCF”,”WPF”]}

 var jsonData=eval(‘(‘+xmlHttp.responseText+’)’);

var firstName=jsonData.FirstName;

var lastName=jsonData.LastName; 

var skill1=jsonData.Skills[0];

var skill1=jsonData.Skills[1];

}}

This way we can parse the recieved as JSON which seems much easier comapred to XMLDOM. 

Bye 

Using Ajax in ASP.NET application -2

In part 1 of this post we saw our response returning us a simple text which was holding a single value.

But what if it is returing multiple values and it using some characters like | (pipe) or say semicolon for separating one value from another.

In this case, we need to make use of javascript string functions to get each and every value.

Here then our application should understand what ; and | or say , mean and what if their order changes.

So now we can have our responses send as XML so that we can make use of XMLDOM to parse through the response. Which infact would be quite easy and efficient.

Let’s update our application

https://nishantrana.wordpress.com/2007/10/25/using-ajax-in-aspnet-application/

Things we need to change are

1)  Change doUpdate function

function doUpdate()

{

if(xmlHttp.readyState==4)

{ // replacing reponseText with responseXML to get the xml DOM tree reference 

var xmlDoc=xmlHttp.responseXML; // parsing through the response using dom methods

var firstName=xmlDoc.getElementsByTagName(“first”)[0].firstChild.nodeValue;

var lastName=xmlDoc.getElementsByTagName(“last”)[0].firstChild.nodeValue;

document.getElementById(“lblInfo”).firstChild.nodeValue=firstName+” “+lastName; }

 }

In the above case the response we are recieving from server is this, which is in xml

<?xml version=”1.0″?>
<name>
<first>Mickey</first><last>Mouse</last>
</name>

2) Now we will change Default2.aspx to send us response back in xml.

protected void Page_Load(object sender, EventArgs e){ // this will inform our webpage about responses being sent as XML and not text

 Response.AddHeader(“Content-Type”, “text/xml;charset=UTF-8”);

Response.Write(“<?xml version=\”1.0\” encoding=\”utf-8\”?><name><first>Mickey</first><last>Mouse</last> </name>”);  

}

Now we can run our application and see our label’s text changing to Mickey Mouse. 

Bye

Using Ajax in ASP.NET application -1

Hi,

Here we’ll change the small application that we had written to get reponse from ASP.NET webpage rather than a webservice.

https://nishantrana.wordpress.com/2007/10/18/calling-aspnet-webservice-from-javascript-ajax/

Here we are using a label server control whose value we will be replacing with response from our asp.net web page through ajax call

1)  Create a new ASP.NET WebApplication  

2)  Put a label control on the form (Default.aspx)

<asp:Label ID=”lblInfo” runat=”server” Height=”49px” Text=”Label” Width=”209px”>ReplaceIt</asp:Label>

 3) Put this script code in the head section of the aspx page

var xmlHttp;

function getMessage()

{

xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);

xmlHttp.open(“post”, “Default2.aspx”, true);

xmlHttp.onreadystatechange=doUpdate;

xmlHttp.send();  return false; }

function doUpdate() { if(xmlHttp.readyState==4)

{

var exch; exch=xmlHttp.responseText;document.getElementById(“lblInfo”).firstChild.nodeValue=exch;

}

}

4) Call the getMessage function in the body’s onLoad eventHandler

 <BODY onload=”getMessage()”>

5) Create another page Default2.aspx which will return us  the “Hello World” repsonse.

6) Write this in our Default2.aspx’s page load event

protected void Page_Load(object sender, EventArgs e)

{

Response.Write(“Hello World”);

}

7) Now comes the most imp part i.e. Deleting all the html tags  from our Default2.aspx leaving only this, otherwise the html will also come as a part of response. But we need only the Hello World text.

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default2.aspx.cs” Inherits=”Default2″ %>

8- Now run the application, we should see our label’s text changing to “Hello World”

Bye

Configuring ASP.NET Web Service

Hi,

Well today i created a webservice which would fetch me some data from oracle database. The method signature was something like this

public DataSet getEmpInfo

{,,,,,,,,,,,,,}

I was calling this webservice within form’s onLoad inside the a custom entity of Microsoft Dyanmics CRM3,0. 

I deployed it in my machine and when i was opening the my custom entity form inside CRM in my machine, i was able to see the values fetched using ajax calls to webservice.

But for other machines i was getting an internal server error for my ajax call.

Finally the error got resolved when i included this inside the web.config for my webservice

<webServices>
    <protocols>     
        <add name=”HttpPost”/> 
        <add name=”HttpGet”/>  

 </protocols>
</webServices>

By the way, I was using POST in my xmlHttpRequest object Open method.

Plzz check out these links to better understand web services.

Configuration Options for XML Web Services Created Using ASP.NET 

http://msdn2.microsoft.com/en-us/library/b2c0ew36(vs.80).aspx

How to: Disable Protocol Support for Web Services 

http://msdn2.microsoft.com/en-us/library/9hdd3w8c(VS.80).aspx

Top Five ASP.NET Web Services Tips

http://www.ondotnet.com/pub/a/dotnet/2002/10/07/webservices.html

Bye

Calling Asp.NET web service from javascript (Ajax)-(Passing Parameter-POST)

Hi,

Now we will modify the application that we developed in the previous post to work with POST parameter

https://nishantrana.wordpress.com/2007/10/22/calling-aspnet-web-service-from-javascript-ajax-passing-parameter/

We have changed the get to post as we are now not passing the value for Name by appending it in the url.

Only make changes to the function getMessage()

function getMessage()

{

var name=’Nishant’;

xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);

xmlHttp.open(“POST“, “http://localhost/WebService1/Service1.asmx/HelloWorld&#8221;, true);

xmlHttp.onreadystatechange=doUpdate;

xmlHttp.setRequestHeader(“Content-Type”,”application/x-www-form-urlencoded”);

xmlHttp.send(“name=”+escape(name));

return false;

}

Let’s understand the changes that we have made

First of all we have change the method of passing data to POST from GET.

But still we need to pass the name’s value which our web service method needs.

For that we’ll modify our Send() method

xmlHttp.send(“name=”+escape(name));

We are using the same name/value pair in send()  which we used at the end of the request URL in the GET version

escape()-It makes sure that the values are valid values i.e. no tricky characters are there.

But this is not enough that is why we added this line

xmlHttp.setRequestHeader(“Content-Type”,”application/x-www-form-urlencoded”);

Here the server doesn’t know what kind of data it can expect or is coming from our application.

We are making use of setRequestHeader function to tell the server about the content type we are going to send.

The server can get this information from request’s header that it recieves.

Content-Type  -> Name of the header

application/x-www-form-urlencoded -> http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1

Bye

Calling Asp.NET web service from javascript (Ajax)-(Passing Parameter-GET)

Hi,

Now we will modify the application that we developed in the previous post to work with parameters

https://nishantrana.wordpress.com/2007/10/18/calling-aspnet-webservice-from-javascript-ajax/

1) First we will modify the default Hello World service to accept a parameter like this

[WebMethod]

public string HelloWorld(string Name)

{

return “Hello “+Name+”!”;

}

2) Add the html textbox control in the webform

<INPUT type=”text” id=”Info”>

3) Add the following in the body

<BODY onload=”getMessage()”>

4) Put the following script in our webpage.

<script language=”javascript”>

var xmlHttp;

function getMessage()

{

xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);

xmlHttp.open(“get”, “http://localhost/WebService1/Service1.asmx/HelloWorld? name=’Nishant'”, true);

xmlHttp.onreadystatechange=doUpdate;

xmlHttp.send(); return false;

}

function doUpdate()

{

if(xmlHttp.readyState==4)

{

var xmlDoc=xmlHttp.responseXML;

var responseElement=xmlDoc.getElementsByTagName(“string”)[0];

var respText=responseElement.firstChild.nodeValue;

document.forms[0].elements[‘Info’].value=respText;

}

}

</script>

5) We have changed the method of passing the data to server from post to get as we are passing the value for Name by appending it in the url.

6) Right now if we run the application it will give us error as “object not found”.

7) The reason for the error is that we have to make our web service configured for get method.

8- We need to open web.config of our web service and add the following line inside system.web section

<webServices>

<protocols>

<add name=”HttpGet”/>

</protocols>

</webServices>

9) We need to build the service again

10) This time our application should work without any error.

Bye

Calling Asp.NET web service from javascript (Ajax)

Here we will be calling the default helloworld webservice that is already created for us when we open a asp.net webservice project template in Visual Studio.

We’ll just have a textbox(html control) which will display us the Hello World! response returned from the web service.

This is the step we need to follow

1) Create a new ASP.NET WebApplication

2) Put a html textbox control on the form

<input type=”text” id=”info”/>

3) Put this script code in the head section of the aspx page

<script language=”javascript”>

var xmlHttp;

function getMessage()

{

xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);

xmlHttp.open(“post”, “http://localhost/WebService1/Service1.asmx/HelloWorld&#8221;, false);

xmlHttp.onreadystatechange=doUpdate;

xmlHttp.send();

return false;

}

function doUpdate()

{

if(xmlHttp.readyState==4)

{

var startTag = “<string xmlns=\”http://tempuri.org/\”>”;

var endTag = “</string>”;

var exch;

var valueStart = 0;

var valueEnd = 0;

valueStart = xmlHttp.responseXML.xml.indexOf(startTag, valueEnd) + startTag.length;

valueEnd = xmlHttp.responseXml.xml.indexOf(endTag, valueEnd+1);

exch = xmlHttp.responseXML.xml.substring(valueStart, valueEnd);

document.forms[0].elements[‘Info’].value=exch;

}

</script>

4) Call the getMessage function in the body’s onLoad eventHandler

<BODY onload=”getMessage()”>

5) Run the applicaton. We’ll see the HelloWorld! text in our textbox(‘info’)

Now let us understand what is happening inside the javascript code

xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”)

This line of code creates the XMLHttpRequest object. This object sends request to the server and processes the responses from it.

The above code creates the object specific to Internet Explorer( <=6.o).

It is implemented as Active X for IE. However in IE 7 XMLHttpRequest will come as native JavaScript object.

For other browsers we can write

xmlHttp=new XMLHttpRequest();

or best we can write this

if(window.ActiveXObject)

{

xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);

}

else if (window.XmlHttpRequest)

{

xmlHttp=new XMLHttpRequest();

}

xmlHttp.open(“post”, “http://localhost/WebService1/Service1.asmx/HelloWorld&#8221;, false);

The open method initializes the connection to the server and informs the xmlHttp object how to connect to the server.

post- it indicates how we want to send the data. It can be “get” as well

url- comes the url where we are connecting

false- this means we are making a synchronous call. To make asychronous call simply set it to true

xmlHttp.onreadystatechange=doUpdate;

This specifies the name of the function to be called whenever the state of the xmlHttpRequest changes

xmlHttp.send();

Send method than makes the request to server. This method would return immediately in case of asynchronous call and it would block until the synchronous response is received from the server.

if(xmlHttp.readyState==4)

It tells about the current state of the request

0- uninitialized

1- loading

2- loaded

3-interactive

4-complete

xmlHttp.responseXML.xml

It returns the current response from server in XML=

<?xml version=”1.0″?>

<string xmlns=”http://tempuri.org/”>Hello World !</string>

Than we are using some javascript functions to get the Hello World! and remove everything else.

document.forms[0].elements[‘Info’].value=exch;

Finally assigning the value to our textBox.

The function doUpdate() can be written differently so that we don’t have to make use of any string functions.

function doUpdate()

{

if(xmlHttp.readyState==4)

{

// Here the server is returning us XML in response so we can make use of responseXML

// Here the browser creates a DOM tree to represent that XML and puts a reference to that DOM tree

// in the request’s (xmlHttp) object’s responseXML

var xmlDoc=xmlHttp.responseXML;

var responseElement=xmlDoc.getElementsByTagName(“string”)[0];

var respText=responseElement.firstChild.nodeValue;

document.forms[0].elements[‘Info’].value=respText;

}

 

However creating a ASP.NET AJAX webservice is little different than our normal ASP.NET web service, and calling them using the ASP.NET AJAX client library is also a bit different

https://nishantrana.wordpress.com/2007/11/06/creating-and-calling-aspnet-ajax-web-service/

Bye

Finding no of users online ASP.NET

To do this,
1) Add a new item global.asax in your website.
2) Put the following code in it

void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
Application[“UsersOnline”] = 0;
}

void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Application.Lock();
Application[“UsersOnline”] = (int)Application[“UsersOnline”] + 1;
Application.UnLock();
}

void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
Application.Lock();
Application[“UsersOnline”] = (int)Application[“UsersOnline”] – 1;
Application.UnLock();
}

3) In the webpage where the no of online users have to be displayed make use of this application object

protected void Page_Load(object sender, EventArgs e)
{
Response.Write(“The no of users online are ” + Application[“UsersOnline”].ToString());
}



That’s it