Consuming CurrencyConverter web service through JavaScript

Hi,

For getting the currency conversion rate we could use the following web service provided by Generic Objects Technologies Ltd.

Check out the web services provided by them

http://www.webservicex.net/WCF/webServices.aspx

To consume their currency converter web service

http://www.webservicex.net/CurrencyConvertor.asmx we could use the following JavaScript code

var xmlHttp;
function SoapCall() {
// creatng the xmlHttp object
xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
// Calling the web service using post and true means asynchronous call
xmlHttp.open(“post”, “http://www.webservicex.net/CurrencyConvertor.asmx”, false);
// Setting the request header to let the web service identify the soap request we would be sending

xmlHttp.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”);

xmlHttp.setRequestHeader(“SOAPAction”, “http://www.webserviceX.NET/ConversionRate”);

var soapRequest = “<?xml version=’1.0′ encoding=’utf-8′?> ” +
“<soap12:Envelope xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance&#8217; xmlns:xsd=’http://www.w3.org/2001/XMLSchema&#8217; xmlns:soap12=’http://www.w3.org/2003/05/soap-envelope’>&#8221; +
” <soap12:Body>” +
”   <ConversionRate xmlns=’http://www.webserviceX.NET/’>&#8221; +
”     <FromCurrency>USD</FromCurrency>” +
”    <ToCurrency>INR</ToCurrency>” +
”  </ConversionRate>” +
“</soap12:Body>” +
“</soap12:Envelope>”;

xmlHttp.send(soapRequest);
alert(xmlHttp.responseText);

}


Bye..

Nice reference card for quick revision

Hi,

Yesterday while browsing encountered the following site

http://refcardz.dzone.com/

The site has got nice reference material written by experts.

Do check out this site !!

Bye …

Understanding and Using AJAX

Suppose this is our simple ASP.NET page i.e. MyPage.aspx which would be called using AJAX

Code for MyPage.aspx.cs

protected void Page_Load(object sender, EventArgs e)

{

// no data is passed

if (Request.QueryString[“myGetData”] == null)

{

Response.Write(“Hello World”);

}

// if GET method is used to call this page

else if (Request.QueryString[“myGetData”] != null)

{

Response.Write(“Hello “ + Request.QueryString[“name”].ToString());

}

// if POST method is used to call this page

else if (Request.Form[“myPostData”] != null)

{

Response.Write(“My Post Data is “ + Request.Form[“myPostData”].ToString());

}

}

Delete everything from MyPage.aspx page just keep the page directive otherwise html tags would also be sent as a part of response.

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

Now the javascript code to call the page asynchronously using AJAX. Comment/Uncomment the particular section of code to test the functionality

<script type=”text/javascript”>

var request=null;

function CreateRequest()

{

try

{

// create a new object to talk HTTP with a web server.

// XMLHttpRequest – works on Safari,Firefox, Mozilla, Opera , IE 7 and most other browsers

request=new XMLHttpRequest();

}

catch(trymicrosoft)

{

try

{

// Msxml2.XMLHTTP – Most version of IE support this

request=new ActiveXObject(“Msxml2.XMLHTTP”);

}

catch(othermicrosoft)

{

try

{

//Microsoft.XMLHTTP – but for some, we’ll need this other type

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

}

catch(failed)

{

request=null;

}

}

}

if(request==null)

alert(‘Error creating request object’);

else

{

// i.e. space with %20

// if no data is to be send

var url=“MyPage.aspx”;

// open-initialize the connection

// GET – specify how to send data to the server

// url- url to send the request

// asynchrounous – true

request.open(“GET”,url,true);

// telling the browser what to do with the server’s response

// i.e. the function to be called when response is received

// onreadystatechange- this property affects every ready state not just the one indicating

// that the server is finished with request

request.onreadystatechange=updatepage;

// send the request

// no data is required so send null

// for using send() to pass data to a server requires POST method for the request and need to specify content type

request.send(null);

// if data is to be send using GET i.e. as query string

var name=“MyName”;

// escape() function replaces characters like space with something that will work as a part of a request URL.

var url=“MyPage.aspx?myGetData=”+escape(name);

request.open(“GET”,url,true);

request.onreadystatechange=updatepage;

request.send(null);

// if more data is to be send than use post

var name=“MyName”;

var url=“MyPage.aspx”;

request.open(“POST”,url,true);

request.onreadystatechange=updatepage;

//setRequestHeader()- allows us to add information to the request usual intended for use by the server

// Content-Type – is the name of the request header

// application/x-www-form-urlencoded – the value of the request header

// this tells the server that the data is encoded like it would be in a request URL

// for passing XML content replace “application/x-www-form-urlencoded” with “text\xml”

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

// specify the data to be send

// escape() function replaces characters like space with something that will work as a part of a request URL.

request.send(“myPostData=”+escape(name));

}

}

// updatepage – this function will get run every time the ready state changes

function updatepage()

{

// readyState=this property of the request object stores the current state

// if 4 means server is done with the request

// if 0 i.e uninitialized

// if 1 i.e open, the object has been created but the send method has not been called

// if 2 i.e. sent, the send method has been called.

// if 3 i.e. receiving , responseText is not available but some data has been received

// if 4 i.e. loaded, all the data has been received, responseText is available

if(request.readyState==4)

{

// check for the status send by the server

// if 200 i.e. everything is fine

// if 404 i.e. if the page specified in the url is not found

if(request.status==200)

{

var myResponse=request.responseText;

alert(myResponse);

}

else

{

alert(“Error! Request status is “ +request.status);

}

}

}

</script>

<input id=”Button1″ type=”button” value=”button” onclick=”CreateRequest()”/>

Bye…

Calling a asp.net webservice from an asp page

Say we have created a simple web service like this

[WebMethod]
public string Hello(String name) {
return “Hello “+name ;
}

Now we want to call the web service from inside our asp page,

for this we can make use of the following code

<%
Dim myPostData
Dim name
name=”Mickey Mouse”
myPostData=”name=” & name
Dim xmlhttp
Dim postUrl
postUrl = “http://servername/MyService/Service.asmx/Hello&#8221;
Set xmlhttp = server.Createobject(“MSXML2.XMLHTTP”)
xmlhttp.Open “POST”,postUrl,false
xmlhttp.setRequestHeader “Content-Type”,”application/x-www-form-urlencoded”
xmlhttp.send strWebServideDetails
Response.Write(“<b>This is the message i recieved</b>” +xmlhttp.responseText)

%>

Bye

Creating a simple Hello World ASP.NET AJAX web page.

Hi,

Here we will create a simple ASP.Net Ajax webpage having a button and textbox control in it.
On the click of button we will fill the textbox with “Hello world” string returned from the server without refreshing our webpage.

1) 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)

2) Add a ScriptManager control in the page( if it isn’t there)

3) Add button and textbox server side control.

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

<asp:Button ID=”Button1″ runat=”server” Text=”Button” />

4) Add this event Handler for button click event

protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text=”Hello World”;
}

4) Now to make our page AJAX enabled the only thing we need to add is

<asp:UpdatePanel id=up1 runat=server>
<ContentTemplate>

<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Button” />

</ContentTemplate>
</asp:UpdatePanel>

Just wrap our server side controls inside update panel control’s content template.

5) That’s it. Now run the application and click on the button the textbox should get filled with Hello World string without any refresh of the page.

Right now what we saw was a server-centric approach using updatePanel control.

We can do the same thing using client-centric approach using ASP.NET AJAX client library. Check this post

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

Bye.

 

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/&#8221;)]
[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

 

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