Wednesday 12 September 2007

Silverlight Client Update without Polling part 2

Following up from my previous post which i posted at Mix UK.

Here is some of the specifics on how it works:

1) You should host your asmx file within the same web project you deploy your silverlight app on (to avoid cross domain issues)
2) remember to mark your class as [System.Web.Script.Services.ScriptService] so you can access it via json within silverlight

This is a sample of the web service code:



[WebMethod]
public bool PerformCalc()
{
//_startCalc = false;

while (!_startCalc)
{
System.Threading.Thread.Sleep(1000);
}

// Start the calc
return true;
}

[WebMethod]
public bool StartCalculation()
{
_count = 0;
_startCalc = true;
return true;
}


Essentially we have two web methods

1) One method Kicks off the calculation (i.e update the client)
2) The other method is called asynchronously, and essentially blocks until we kick off the calc.

This has the effect that the client will accept the update at anypoint without polling.

Here is the client code:



private void RegisterForCalc()
{
_request = new BrowserHttpWebRequest(new Uri(serviceUri));
//_request = new BrowserHttpWebRequest(new Uri("http://www.chrishay.com/Silverlight/Mesh/MeshService.asmx"));
IAsyncResult iar = _meshWS.BeginPerformCalc(new AsyncCallback(OnPerformCalc), _request);
}

public void OnPerformCalc(IAsyncResult iar)
{
_meshWS.EndPerformCalc(iar);
for (Int64 i = 0; i < 10000; i++ )
{
// do nothing
string blah = "blah" + i.ToString();
}
_meshWS.IncrementCount(10000);
tbCalcCount.Text = string.Format("Local Count: {0}, Total Count {1}", 10000, _meshWS.GetCount());
//RegisterForCalc();
}


Essentially this post shows that, we call the web service asynchronously, and then we perform some code client side, when we receive a repsonse from the web service.

Essentially you can use the code todo a lot of things you can't do just now (until sockets comes along)

For example:

Messenger
Stock Ticker
etc.

2 comments:

Anonymous said...

No, I wouldn't let you run that on my server.

chrishayuk said...

I think you miss my point.

As i have said in my other posts on this subject, this code is not production code. I wrote this lot in less than an hour after a very long day.

The point is that we can get around the limitations of lack of socket support in Silverlight by use of other techniques.

I wouldn't run this code on my server either in its current form.

This is all about proof of concept. As I clearly state in this series of posts.