Silverlight Stock Rates Rotator


Introduction

Silverlight is a rich framework that works in web browsers using a browser plug-in, just like Flash, but with it, you can interact more easily with .NET libraries. Silverlight has the same code-behind model that exists in ASP.NET, and operates under a modified light version from the .NET framework. With Silverlight, you can build Flash-like applications with full .NET server side code integration. Now, I’ll go through how to build a stock rates rotator with Silverlight and embed it into an ASPX page, step by step. First, you have to download the Silverlight Tools Beta 2 For Visual Studio 2008.

Using the code

Open Visual Studio 2008, and open a new project, select the Silverlight node under Visual C#, and select Silverlight Application:

NewProject

Click OK to proceed to the following screen:

SelectWeb

Select the first option to add a new web site to test your Silverlight controls, and click OK.

Solution

Notice these files in you solution:

  • App.xaml: The entry point for your application that tells which control to begin with, and within it, you can declare the shared variables.
  • Page.xaml: A Silverlight control which will hold the XAML and has a code-behind file “Page.xaml.cs” which holds the server side code.

Now, I’ll start developing the email form in “Page.xaml”:

<canvas xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns="http://schemas.microsoft.com/client/2007">
        <canvas.triggers>
            <eventtrigger routedevent="Canvas.Loaded">
                <beginstoryboard>
                    <storyboard repeatbehavior="Forever"
                           storyboard.targetproperty="(Canvas.Left)" x:name="animation">
                        <doubleanimation duration="0:0:10" to="-820"
                               from="0" storyboard.targetname="txtResult">
                    </doubleanimation>
                </storyboard>
            </beginstoryboard>
        </eventtrigger>
        <border opacity="1" background="Red">
            <textblock text=" Updating stock rates ...... please wait "
                       foreground="Wheat" x:name="txtLoading" />
        </border>
        <textblock x:name="txtResult">
</textblock></canvas.triggers></canvas>

I made the animation to rotate the “txtResult” textblock from right to left forever. This is a very simple animation; also, I added another textblock to simulate the loading effect. Now, I’ll code the web service which will provide the stock rates to the Silverlight control.

[WebMethod]
public string GetStockData()
{
    // Just to see the loading effect
    System.Threading.Thread.Sleep(2000);

    StringBuilder stockData = new StringBuilder();
    Random randomRate = new Random();

    stockData.Append("USD " + randomRate.NextDouble() + "   |   ");
    stockData.Append("KD " + randomRate.NextDouble() + "   |   ");
    stockData.Append("GBP " + randomRate.NextDouble() + "   |   ");
    stockData.Append("EGP " + randomRate.NextDouble() + "   |   ");
    stockData.Append("AUD " + randomRate.NextDouble());

    return stockData.ToString();
}

It’s a very simple web method just to return the required string. Now, we must code calling the web service from the Silverlight control.

public partial class Page : UserControl
{
    # region "Public members"
    DispatcherTimer timer;
    BasicHttpBinding bind;
    EndpointAddress endPoint;
    // Change this to your local URL
    const string WebServiceUrl =
      "http://localhost:11545/StockRotatorWeb/services/StockData.asmx";
    WebServices.StockDataSoapClient stockService;
    # endregion

    public Page()
    {
        InitializeComponent();

        // Initialize timer
        timer = new DispatcherTimer();
        timer.Interval = new TimeSpan(0, 0, 10);
        timer.Tick += new EventHandler(timer_Tick);
        // Initialize the web service proxy and add the event handler
        bind = new BasicHttpBinding();
        endPoint = new EndpointAddress(WebServiceUrl);
        stockService = new WebServices.StockDataSoapClient(bind, endPoint);
        stockService.GetStockDataCompleted += new
          EventHandler<stockrotator.webservices.getstockdatacompletedeventargs>(
          stockService_GetStockDataCompleted);
        stockService.GetStockDataAsync();
        // Start the timer
        timer.Start();
    }
    // Invoked when the calling completed or timed out
    void stockService_GetStockDataCompleted(object sender,
         StockRotator.WebServices.GetStockDataCompletedEventArgs e)
    {
        try
        {
            // Update the result
            txtResult.Visibility = Visibility.Visible;
            txtResult.Text = e.Result.ToString();
        }
        catch (Exception ex)
        {
            // Display the error
            txtResult.Text = ex.InnerException.Message;
        }
        finally
        {
            // Hide the loading textbloxk and restart the timer
            txtLoading.Visibility = Visibility.Collapsed;
            timer.Start();
        }
    }

    void timer_Tick(object sender, EventArgs e)
    {
        timer.Stop();
        txtLoading.Visibility = Visibility.Visible;
        txtResult.Visibility = Visibility.Collapsed;
        // Make the async call to the web service
        stockService.GetStockDataAsync();
    }
}

And this is the test page in action:

Loading....

And, this with the data displayed:

Loaded

Sample project

I hope that helped

Ahmed

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s