Friday, January 14, 2011

Silverlight getting started

Background

This is the first part of the Silverlight learning series. As mentioned in the earlier post I am planning to incrementally build an application and implement some of the best practices as per my knowledge so far. I have had prior experience of building enterprise application using WPF in which we had used Model View Presenter (MVP) pattern for separating the concerns. Both WPF as well as Silverlight have very good support for data binding. Due to this we can use advanced data binding concepts to write applications which are fully testable using automated unit tests by separating the concerns related to the business logic and user interface. I’ll come to that in the future posts which will talk more in details about the Model View View Model aka MVVM pattern. The objective of this post is to kick start the series and get a basic idea about the application I am trying to build.

Getting started with Silverlight 4

This is the first time I am working with Silverlight technology. Current version of Silverlight is 4.0. Having missed the earlier 3 versions I think it’s a good starting point to start with the latest version. Lets see the steps needed to build and run the first Silverlight application.

Fire up the Visual Studio IDE and select new Project. Depending the tools and addons installed on your system you’ll get the available templates for various types of projects that you can create using Visual Studio IDE. I am using VS 2010. Following is a screenshot of what I get upon choosing new project

image

Select Silverlight under the left menu and select Silverlight Application from the available templates on the right hand side. As you can see there are few other options available as well apart from Silverlight Application. Silverlight class library is for creating reusable Silverlight controls which can be used as a library in other applications. Silverlight Business Application and Silverlight Navigation Application are similar to a basic Silverlight application but have additional templates which reduce the task on developers part to add few references. We can easily enhance a simple Silverlight application into a business application or navigation application. So I’ll start with the basic one. Fill in the other details like the name of the project, location, solution name etc and hit Ok button. On my machine I did not have the latest Silverlight runtime and had to install an update from Microsoft site.

Once we have selected the project name and the output directory the wizard prompts us to choose the type of host for the Silverlight application. We can either host the application  in a new website or we could choose not to do so. As can be seen from the screenshot below if we decide against hosting it in a web application then a test page will be generated which can be used to test the application.

image

In case we decide to host the Silverlight application in a web application we can choose among the following types of projects

  • ASP.NET Web Application Project
  • ASP.NET Web Site
  • ASP.NET MVC Web Project

image

We’ll choose the default which is the ASP.NET Web Application project. You can also choose the Silverlight version. By default its Silverlight 4. If you have other runtimes installed those will be shown here. And the last option is to enable WCF RIA Services. Right now we’ll go with the default and choose not to enable RIA services. I n one of the future posts I would like to demonstrate this feature as well.

Once we hit the OK button the wizard produces two projects. One is the Silverlight application and the other one is the Web project. The web project is set up as the startup project and contains a test page to test the Silverlight application. This is required because Silverlight needs a container or a parent to run. It cannot run on its own. Since Silverlight is a browser pluginn the HTML or ASP.NET web page acts as the container for the Silverlight app.

image

We can examine the contents of both GettingStartedWithSilverlightTestPage.aspx and GettingStartedWithSilverlightTestPage.html. They both are almost same especially the JavaScript and the object tag that is rendered by the code generator. The boilerplate code generated by the template is standard html and JavaScript code.

At this point we can hit F5 and see that everything works fine. You should be able to see the browser pop up and open the GettingStartedWithSilverlightTestPage.aspx on the local server with an auto generated port. Lets start adding some controls to the user interface.

Lets spend some time understanding the structure of the Silverlight application. There are two file which are generated for us. App.xaml and MainPage.xaml. Like me if you have worked in WPF before this would sound similar to you. Look at the contents of App.xaml and its almost empty. There are no controls or any other code in the .xaml file. This file acts as the bootstrapper of the Silverlight application. Look carefully at the code behind of App.xaml which is App.xaml.cs. We find that the constructor wires up various events like StartUp, Exit and UnhandledException. This again is the boilerplate code generated for us by the codegen. The point of interest here is the StartUp event which fires the Application_Startup method.

        private void Application_Startup(object sender, StartupEventArgs e)
        {
           
this.RootVisual = new MainPage();
        }

This is where the MainPage is assigned as the startup page by assigning it to the RootVisual property. Lets turn our attention to the MainPage.xaml. You can see that it contains a empty Grid control with a white background. The Grid control is one of the container controls in Silverlight which can be used to add other controls. The Grid is similar to the HTML table which allows us to add controls in a tabular format like in rows and columns. But the syntax is completely different in HTML and XAML. Lets add a simple text box to the grid and display the contents of what is entered by the user in another label with the help of a button. Following is the markup required to display these elements in the grid.

<Grid x:Name="LayoutRoot" Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
       
       
<TextBlock Text="Enter the text to update the label contents" Grid.Row="0" Grid.Column="0"/>
        <TextBox Grid.Row="0" Grid.Column="1" x:Name="txtInput"/>

        <TextBlock Text="Your contents will be displayed here" Grid.Row="1" Grid.Column="0"/>
        <TextBlock Grid.Row="1" Grid.Column="1" x:Name="txtOutput"/>
       
       
<Button Grid.Row="2" Grid.Column="0" Content="Update"/>
        <Button Grid.Row="2" Grid.Column="1" Content="Clear"/>
    </Grid
>

As can be seen from the above code snippet there is start contrast in the way an HTML table is constructed and an Silverlight grid is constructed. Here we need to define the columns and rows using ColumnDefinitions and RowDefinitions collection properties of Grid. I have defined two columns and 3 rows above. Then we can place the controls in any order within the grid and associate those controls with a particular cell of the grid using the Row and Column attached properties of the grid. I’ll talk about attached properties in later posts. For the read only text I have used TextBlock control available in Silverlight. This is similar to the Label control in WPF and windows forms. Also note that to display the text on the button controls we use the Content property of the button control and not the text property. There is a concept of content controls and item controls in Silverlight which I would cover in the future posts. With this much of markup we have our user interface elements. Lets run the application and see the output.


image


If you look at the output it looks odd. All the controls are there but their sizes are very big. If you have worked in WPF before you probably know the reason for this. This happens due to the fact that both WPF and Silverlight render resolution independent graphics. This helps you in designing user interfaces which proportionately appear the same on different resolutions. To understand what I am trying to explain resize the browser to different sizes and see the shape and size of these controls. It will always remain in proportion. Here is screenshot where I have resized the IE window to a very small size.


image


You can clearly see the difference between the two screenshots. If we want to fix this issue we can specify the height and width for different controls. I am going to fix this by specifying the column width as 250 and row height as 50.

<Grid.ColumnDefinitions>
            <ColumnDefinition Width="250"/>
            <ColumnDefinition Width="250"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition Height="50"/>
            <RowDefinition Height="50"/>
        </Grid.RowDefinitions
>

Run the application and notice the change in the dimensions of the controls. If you click on the Update of Clear buttons nothing happens at this point. Like we always do in any application to associate the click event of the button with the delegate, we need to wire up the event handler code to handle the button click. You can do so by double clicking on the button which will generate the event handler in the code behind file. Double click on both the buttons and put the following code in the methods which are generated

private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            txtOutput.Text = txtInput.Text;
        }

       
private void Button_Click_1(object sender, System.Windows.RoutedEventArgs
e)
        {
            txtInput.Text =
string
.Empty;
            txtOutput.Text =
string.Empty;
        }

The first method updates the text from what is entered into the input textbox to the output one. And the second method is used to clear the contents of both the text boxes. This is the same code that we would have written in other applications like WPF, windows forms or even APS.NET.


Conclusion


This is a very basic Silverlight app. Like I mentioned in the earlier post I would be building on these small steps to come up with a sample app. Before starting with the app I believe its important to understand the basic concepts in Silverlight. We briefly touched upon few controls like Grid, TextBlock and Buttons here. I’ll cover some of the new controls in the next post.


As always I have uploaded the complete source code to dropbox which you can download and play around with. Until next time Happy Programming Smile

No comments:

Post a Comment

Submit Apache Spark job from Command Line to HDInsight cluster

Background This is the 3rd part of the Step by Step guide to run Apache Spark on HDInsight cluster. The first part was about provisioning t...