Skip to main content

Microsoft Silverlight

Answered Question How to use the XMLHttpRequest() "AJAX method" in SilverLightRSS Feed

(0)

anilk_goel2009
anilk_go...

Member

Member

2 points

12 Posts

How to use the XMLHttpRequest() "AJAX method" in SilverLight

Hi,

I am new in SilverLight. I have created an AJAX application to check the status code (404, 200 etc...). Now I want to do the same functionality with the silverlight application. Can please anyone tell me how can I do this in the SilverLight application. For reference the AJAX applcation is given below:

 

html>
<head>
<title>Updating status page using Ajax</title>
<script type=text/javascript language=javascript>
<!-- Hide Javascript on old browsers

function aboutlang() {

/* Get back the server status */

        var xmlhttp=false;

  try
  {
   xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch (e)
  {
   try {
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (E)
    {
     xmlhttp = false;
    }
  }

  if (!xmlhttp)
  {
   try
   {
    xmlhttp = new XMLHttpRequest();
   }
   catch (e)
   {
    xmlhttp=false;
   }
  }

  xmlhttp.open('GET',"http://localhost/ajax/time.asp",false);
  xmlhttp.send(null);

  if (xmlhttp.readyState==4)
  {
   if (xmlhttp.status==200){
    alert("Success - It is a 200!");
   }
   else if (xmlhttp.status==401){
    alert("Credentials required!");
   }
   else if (xmlhttp.status==403){
    alert("Access denied !!!");
   }
   else if (xmlhttp.status==302){
    alert("It's a redirect !!!");
   }
   else if (xmlhttp.status==404){
    alert("It's a 404");
    
   }
   else{
    alert("Status is "+xmlhttp.status);
   }
  }

        return false;
}
</script>
</head>
<body onload="aboutlang()">
</body>
</html>

MarkMonster
MarkMonster

Contributor

Contributor

5124 points

1,038 Posts

Re: How to use the XMLHttpRequest() "AJAX method" in SilverLight

In Silverlight you're able to make use of HttpWebRequest. Please take a look at the example on this page: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(VS.95).aspx

Mark Monster - MCPD Enterprise
http://mark.mymonster.nl
Silverlight and Expression Insiders UG

Dont forget to click "Mark as Answer" on the post that helped you.

anilk_goel2009
anilk_go...

Member

Member

2 points

12 Posts

Re: How to use the XMLHttpRequest() "AJAX method" in SilverLight

Please tell me RequestState class is present in which library. Is it a custom class?

MarkMonster
MarkMonster

Contributor

Contributor

5124 points

1,038 Posts

Re: How to use the XMLHttpRequest() "AJAX method" in SilverLight

Yes the RequestState mentioned in the example is a custom class. And looks probably something like this:

 
class RequestState
{
    public HttpWebRequest request;      // holds the request
    public HttpWebResponse response;      // holds the response
}
  

Mark Monster - MCPD Enterprise
http://mark.mymonster.nl
Silverlight and Expression Insiders UG

Dont forget to click "Mark as Answer" on the post that helped you.

anilk_goel2009
anilk_go...

Member

Member

2 points

12 Posts

Re: Re: How to use the XMLHttpRequest() "AJAX method" in SilverLight

Thanks a lot. Here I succesfully  writing a code to get all the information from the requested header. I successfully get all the information into string variable but when I try to copy the string to textbox (here i use the messagebox in following code) it gives the exception ("Invalid cross thread error"). please can u tell me here what can I do. the code sniped in given below:

private void Button_click(object sender, RoutedEventArgs e)

{

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://localhost:53347/ab.htm"));

req.BeginGetResponse(getResponse, req);

}

void getResponse(IAsyncResult ar)

{

HttpWebRequest req = (HttpWebRequest)ar.AsyncState;

HttpWebResponse res = (HttpWebResponse)req.EndGetResponse(ar);

String ResponseHeaders = "ContentType : " + res.ContentType.ToString() + "\n";

ResponseHeaders += "ContentLength : " + res.ContentLength.ToString() + "\n";

ResponseHeaders += "Response URI : " + res.ResponseUri.ToString() + "\n";

ResponseHeaders += "Status Code : " + res.StatusCode.ToString() + "\n";

ResponseHeaders += "Status Description : " + res.StatusDescription.ToString() + "\n";

ResponseHeaders += "Response Method : " + res.Method.ToString() + "\n";

MessageBox.Show(ResponseHeaders);

 

if (res.StatusCode == HttpStatusCode.OK)

{

string baseurl = "http://localhost:53347/ab.htm";

Uri uri = new Uri(baseurl, UriKind.Absolute);

WebClient client = new WebClient();client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);

client.DownloadStringAsync(uri);

}

}

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)

{

if (e.Error == null)

{

string s = e.Result.ToString();MessageBox.Show(s);

}

else

outputBlock.Text += e.Error.ToString();

}

MarkMonster
MarkMonster

Contributor

Contributor

5124 points

1,038 Posts

Answered Question

Re: Re: How to use the XMLHttpRequest() "AJAX method" in SilverLight

This basically because the response coming to you on a different thread. To manipulate UI elements, like MessageBox, you need to be on the UI-Thread. For detailed information you can take a look at my article on getting back to the UI Thread.

if(Dispatcher.CheckAccess())
{
   Dispatcher.BeginInvoke(()=>MessageBox.Show(s));
}
 

 

Mark Monster - MCPD Enterprise
http://mark.mymonster.nl
Silverlight and Expression Insiders UG

Dont forget to click "Mark as Answer" on the post that helped you.

anilk_goel2009
anilk_go...

Member

Member

2 points

12 Posts

Re: Re: Re: How to use the XMLHttpRequest() "AJAX method" in SilverLight

Thanks a lot. Now I successfully getting the values in the messagebox.

Now, i am facing a new problem that is, when the html page that I have request is exists (HttpStatusCode = "OK") then everything is working fine. But when the page is not exists then I got an runtime error (Exception) in the code. Also, please tell me how I access the another URLs not in the same domain.

HttpWebResponse res = (HttpWebResponse)req.EndGetResponse(ar);

The code sniped is given below:

private void Button_click(object sender, RoutedEventArgs e)
{
 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://localhost:53347/ab.htm"));
 req.BeginGetResponse(getResponse, req);
}

void getResponse(IAsyncResult ar)
{

 HttpWebRequest req = (HttpWebRequest)ar.AsyncState;
 HttpWebResponse res = (HttpWebResponse)req.EndGetResponse(ar);

 if (res.StatusCode == HttpStatusCode.OK)
 {
  string ResponseHeaders = "ContentType : " + res.ContentType.ToString() + "\n";
  ResponseHeaders += "ContentLength : " + res.ContentLength.ToString() + "\n";
  this.Dispatcher.BeginInvoke(delegate()
  {
   myTextBox.Text = ResponseHeaders;
  });
 }
}

 

MarkMonster
MarkMonster

Contributor

Contributor

5124 points

1,038 Posts

Re: Re: Re: How to use the XMLHttpRequest() "AJAX method" in SilverLight

First of all, you will need to add proper handling of exceptions. So please add Try/Catch blocks.

To access URLs on a different domain you will have to take into consideration Cross Domain problems.

If the other domain has a file like "clientaccesspolicy.xml" or "crossdomain.xml" in the root of it's domain it might be possible, if it doesn't have this kind of CrossDomain Access file and you're not able to put such a file on that domain, you will have to take a different approach.

This approach could be to communicate with your own trusted server which can in that case also serve as a proxy between you and the domain that cannot be crossed using Silverlight.

Mark Monster - MCPD Enterprise
http://mark.mymonster.nl
Silverlight and Expression Insiders UG

Dont forget to click "Mark as Answer" on the post that helped you.

anilk_goel2009
anilk_go...

Member

Member

2 points

12 Posts

Re: Re: Re: Re: How to use the XMLHttpRequest() "AJAX method" in SilverLight

Thanks a lot !!! 

Now, everything is working fine. But here with "WebRequest" or "WebClient" object I am able to identify only the "HTTPStatusCode - 404 or 200". Please tell me how I identy the "HTTPStatusCode - 401". If you have any sample code sniped than please share it.

MarkMonster
MarkMonster

Contributor

Contributor

5124 points

1,038 Posts

Re: Re: Re: Re: How to use the XMLHttpRequest() "AJAX method" in SilverLight

Sory, I haven't got any more details on those statuscodes. Does it not work the same like 404 and 200?

Mark Monster - MCPD Enterprise
http://mark.mymonster.nl
Silverlight and Expression Insiders UG

Dont forget to click "Mark as Answer" on the post that helped you.
  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities