Executable Specification


Background

Recently I was listening to a podcast on Hanselminutes which is hosted by Scott Hanselman. The podcast aimed at getting some insights into BDD, Cucumber, Gerkin and SpecFlow which are the tools mainly used for acceptance tests in many DotNet projects. You can download and listen to the podcast from http://www.hanselminutes.com/default.aspx?showID=267.
While listening to the podcast something immediately struck me. I was able to relate to it. It reminded me of two separate instances which I had encountered on two different projects. One wherein lack of Acceptance tests had caused us a lot of headache and the other one where a possible situation was avoided by having a simple acceptance test in place. I would like to share both these instances here. The point to note here is that in both the cases we were working in distributed teams in different geographic locations.

Case one without Acceptance tests in place

During this project my team was developing a client application which was customer facing. We were consuming a service developed by another team. At the start of development both the teams had agreed on the contract of the service and both sides had developed their pieces of functionality. Both teams were following Agile and had done a thorough unit testing of their code. These tests were working fine on either side. We had all the unit tests in place which were ran with the every check in as part of the continuous integration process.
At the time of integration a strange thing happened.  On the client side which was the code developed by my team we were expecting a field from the service of 2 characters in length. We had built the client code assuming that we will always get 2 characters from the service. Instead what we got was a long string of many characters. There was some error in the service code and as a result instead of passing the required code down to the client the service was sending the namespace of the object which was holding the code. When we saw a long cryptic namespace appearing in place of a simple code it was not a good sign. It was a small error and took very little time to fix it. But it was really embarrassing for the teams because it was identified at a very late stage in the project during integration phase. Luckily for us the change was very minor.
There have been cases in the past where substantial code changes had to be made and lot of time was wasted redoing stuff. On many occasions lot of time was spent debugging things to make things work.

Case two with Acceptance tests in place

In my current project we are using Fitnesse as a Acceptance testing tool. I will not go into the details of what is Fitnesse and how to use it because there is already lot of material available on the Internet. This time also the situation was similar that a service was providing the data to a client. All the code had been unit tested. As part of definition of done we also had to ensure that all the tests are passing. These tests include not just the unit tests but also the acceptance tests developed in Fitness. The Business Analysts in our team maintain a set of Fitnesse tests for each user story.
While running the Fitnesse tests all but one test was failing for a particular scenario. Myself and the BA who had written the story started investigating the reasons for failure. It turned out that one of the value stored in the reference tables in database was wrong. As per the acceptance test in Fitnesse BA had written an expectation that the service should return a value say “ABC XYZ”. When the service call was made the actual value returned was “ABC  XYZ”. There was an additional space between the two words. After fixing the spacing issue everything was passed and the user story was marked as Done.

Conclusion

As we can see from the above instances, it can be really helpful to have a suite of acceptance tests to validate your functional requirements. Many times people think that a good code coverage by means of unit tests is enough. But there are scenarios where unit tests might not be able to give you 100% coverage. Also because the dependencies are always mocked in unit tests you are most likely to miss scenarios which will pop up during the integration tests. Acceptance tests provide  a good way of doing integration testing and validating the user requirements.
I remember having a brief discussion with Colin Bird the founder of Ripple-Rock while I was in India about acceptance testing. Colin's view was that we need not write acceptance test for each and every scenario because there is steep learning curve involved in learning something new like Fitness or any other acceptance testing tool. Instead we can identify scenarios which are very critical to the success of the project and turn them into acceptance test. While doing this we should ensure that the tests which we have cover almost 80% of the scenarios. If those scenarios are passed we can say that all the minimum marketable features or must have use stories from the product backlog have been successfully completed.
Acceptance tests give us an early feedback during the development of user stories. We need not have to wait till the integration stage.  They can also be run as part of automated build process and provides a level of regression suite as well. It is true that writing acceptance test and also executing them takes a lot of time compared to unit testing. But overall the benefits of having acceptance tests are much more than the time spent on developing and maintaining them. Having ripped the befits of using Acceptance tests I would recommend them for all types of projects wherever applicable and possible.
If you happen to listen to the podcast Scott makes a point that your user stories which might be written on index card or word documents cannot be executed. There is no way to validate a word document and say that the user story is working as per the specification. Specification tests is one way of making the functional specification as executable entities and validate the functionality. Another advantage I feel is that when a Business Analyst writes an acceptance test it can actually help him validate his own understanding with the business users. Many a times we see things lost in translation where in the business users expects something and the business analysts interprets them differently. These kind of mismatches can be rectified early in the development cycle as the business analyst can demonstrate to the business users their understanding before a single line of code has been developed by the developers. It can save a lot of time for developers because they can assume that whatever the Business Analyst have created in the fitnesse tests is what is expected by the business users and the end users.
Fitness is just one option. In the podcast Scott Hanselman also discusses other tools like Cucumber and SpecFlow. All these tools basically help you in doing the same thing. Fitnesse seems to be the one which is widely used. In my previous company I know that some folks were using Cucumber as well as SpecFlow. Its really a personal choice. You can pick and choose what suites you and your team needs.
Until next time Happy Programming Smile
spacer

Interesting links for 29th January 2011

 

ASP.NET / ASP.NET MVC

 

EF / ORM

 

Silverlight / WP7

 

Agile

 

Miscellaneous

spacer

Interesting links for 27th January 2011

 

Silverlight

 

ASP.NET / ASP.NET MVC

 

Agile

 

Miscellaneous

spacer

Interesting links for 26th January 2011

 

Wishing all the Indian readers of this post a very Happy Republic day.

Silverlight / WP 7

 

Agile

 

ASP.NET

 

Miscellaneous

spacer

Interesting links for 25th January 2011

spacer

Interesting links for 24th January 2011

spacer

Interesting links for 22nd January 2011

 

Agile

 

Silverlight

 

Miscellaneous

spacer

Basic Controls in Silverlight – Part II

 

Background

In the previous post we looked at some of the basic controls in Silverlight. In this post I am going to demonstrate few other basic controls which come bundled with the Silverlight framework. Without wasting too much time lets start.

Silverlight controls

Run

On many occasions we need to highlight a portion of the text differently compared to the rest of the text in the same line. Usually if you are working on a web application you can do so using something like a Span tag and then giving a different style to one of the span tag. I am not aware if such a feature exists in any Winforms controls. But in Silverlight we can use the Run control to give different styles to a section of text. Let take an example

        <TextBlock>
            <Run Text="This is normal Text"/>
 
           
<Run FontWeight="Bold" Text="This is bold text"/>
            <Run Foreground="Red" Text="This is displayed in Red" />
        </TextBlock
>

All the above render text in the same line. But the first Run renders a normal text, second one renders a bold text and third one with red colored text. I don’t think this can be done so easily in a Windows forms application. If you were to do the same in Windows application, you’ll need separate label controls and set different properties on them accordingly. You’ll need to take care of the alignment of each label etc.


Border


A border element is similar to a group box control in HTML. It is used to logically group various controls under one container. Creating a border is very simple.

        <Border BorderThickness="2" Width="300" BorderBrush="Blue">

I have fixed the width of border to 300 and thickness to 2. Also the border color is set to Blue.


Canvas


A Canvas is useful when we want to position the elements at absolute position. Normally almost all the container controls in Silverlight use the relative positioning to position the child controls. In certain cases we need to position controls in absolute positions and we can do it using Canvas as shown below

        <Canvas Background="Crimson">
            <TextBlock Canvas.Left="10" Canvas.Top="10" Text="This is inside the canvas positioned at 10,10"/>
            <TextBlock Canvas.Left="50" Canvas.Top="50" Text="This is inside the canvas positioned at 50,50"/>
        </Canvas
>

The most commonly used elements as the parent controls in Silverlight are the Grid, StackPanel and Canvas.


ProgressBar


Almost all the applications now a days have the need to do some asynchronous operation.As a best practice the user should not wait for the operation to finish and the screen should not be frozen. People usually tend to show a busy indicator or a progress bar. Silverlight has a built in progress bar control which can be used as follows

        <ProgressBar Value="10" Minimum="0" Maximum="100" Height="20" Width="200" IsIndeterminate="True"/>

In an ideal world you’ll set the Value property of the progress bar to indicate the change in value based on some timer or some other criteria. In this case I am using the IsIndeterminate property to display a continuous progress bar.


PasswordBox


It’s a very basic requirement in any application which handles security and authentication to display a password box. The contents of the textbox are masked. In HTML we can do this by using a normal textbox control and setting its mode to password. In windows applications also its similar. We set a property on the normal textbox controls to mask the input. But Silverlight has a dedicated password box control.

        <PasswordBox Width="100" />

 


Conclusion


In this post we saw few basic controls available in Silverlight apart from the ones we saw in the previous post. There are other controls like Rectangle, Line etc. which are mainly used for drawing graphics. From a line of business applications point of view these are used very rarely. Hence I have not demonstrated them here. In the next post I’ll be talking about the additional controls available as part of Silverlight toolkit controls like Accordion, date picker, numeric up down etc. Keep watching this space for more on that later. Here is a screenshot of the controls that I demonstrated in todays post.


image


The complete source code is available for download  from dropbox.


Until next time Happy Programming Smile

spacer

Interesting links for 21st January 2011

 

Silverlight / WPF / WP 7

ASP.NET / ASP.NET MVC

Agile

Miscellaneous

spacer

Basic controls in Silverlight – Part I

 

Background

In the previous post we looked at the preliminary step of building a new Silverlight 4 application. We also briefly touched upon the controls like TextBox, TextBlock, Grid and Button. Silverlight has almost all the controls required for building a windows based application like checkbox, combo boxes, tree views, menus etc. Apart from these basic controls you also get special purpose controls like the expander control and slider control. In this post I am going to demonstrate some of the built in controls available in Silverlight.

Some of the basic controls available in Silverlight

Stackpanel

Last time we looked at the Grid control which is good for laying out controls in a tabular form. But sometimes we just want to add controls in horizontal or vertical direction. Stackpanel can be used for this purpose. Following is the markup related to adding controls to stack panel

    <StackPanel>
        <TextBlock Text="This is first text block."/>
        <TextBlock Text="This is second text block."/>
        <TextBlock Text="This is third text block."/>
    </StackPanel
>

We can specify the direction in which the stacking has to happen. The default is the vertical stack. Using the Orientation property we can stack the controls in horizontal direction as well as follows

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="This is first text block."/>
        <TextBlock Text="This is second text block."/>
        <TextBlock Text="This is third text block."/>
    </StackPanel
>

Combo box or drop down list


This control is used to present a list of items and select one among the available options. This is a standard control used in web or windows applications. Its very easy to add combo box using xaml

        <ComboBox>
            <ComboBoxItem Content="India"/>
            <ComboBoxItem Content="South Africa"/>
            <ComboBoxItem Content="England"/>
            <ComboBoxItem Content="Australia"/>
        </ComboBox
>

Here I have added four countries to the list of items of which only one can be selected at a time.


Checkbox


A Checkbox is used where a boolean condition is applicable. We can use check box to represent true or false state. By default we can also mark a checkbox as checked as shown below

        <CheckBox Content="Is Valid" />
        <CheckBox Content="Is Eligible" IsChecked="True"
/>

Radio Button


Radio button control is used when you have mutually exclusive controls and you can choose one of the values. This is similar to a dropdown control but is represented differently on the screen. You’ll use drop down or combo box control when you have many choices and want to use one of the values. Here is a small usage of radio button

        <RadioButton GroupName="Gender" Content="Male" IsChecked="True"/>
        <RadioButton GroupName="Gender" Content="Female"
/>

Note that the group name is same in the above two radio button controls. That is how we make them mutually exclusive to one another. If we don’t set this property we’ll be able to select both the radio buttons. You can test this by removing the GroupName property from either the first or second radio button. Also you can initially set the checked state of the radio button using the IsChecked property as shown above.


ScrollViewer


We can use the scroll viewer when there is limited screen estate available and the amount of contents that needs to be displayed is more. We can fix the height or width or both of the scroll viewer and anything that can’t be fitted in those bounds will be displayed using a scroll bar.

    <ScrollViewer Height="100">

For clarity purpose I haven’t copied the complete code here. But I have fixed the Height to 100 in the above code and created controls within the scroll viewer which exceed that area. You can download the complete source code to check the working code. ScrollViewer is another container control which can contain other child controls like the Grid or StackPanel. One of the things I like in Silverlight and WPF is that you mix and match the container controls. You can have a stack panel inside a grid or a grid inside a stack panel or any other container control. It essentially acts as a parent for other controls which helps you in building appealing visuals.


Slider


Another interesting control that comes built in Silverlight is the Slider control. We can use slider to limit a range of values as shown below

            <Slider Minimum="30" Maximum="45" Value="35" Background="Red"/>

In this case I  have set the minimum limit for the slider to be 30 and maximum to 45. I have also set the default value of 35. I have also given a red background to the slider to identify it easily.


Here is a partial screenshot of the output of what we have built


image


Conclusion


These are the controls I’ll be making use of in the sample application which will be built very soon. my intention here was to get familiarized with the basic controls.If you have worked on windows programming before using Microsoft technologies you’ll find one major difference between Silverlight and earlier versions of Microsoft based languages. Many of the controls use the Content property instead of Text to display text on the screen. I’ll talk about it in more detail in future post but just make a note of it for the time being. 


Each of these controls have numerous properties which allows us to customize the behavior of the controls as per our needs. You can play around with the properties to see how it impacts the behavior of each control. In the future post I’ll demonstrate the commonly used and freely available controls like date picker, auto complete textbox, busy indicator etc. which are not part of the core controls but are available as part of controls toolkit.


As always I have uploaded the complete working solution to dropbox which can be downloaded.


Until next time happy programming Smile

spacer

Interesting links for 20th January 2011

 

Agile

Silverlight

Miscellaneous

spacer

Agile ways to reduce technical debt

 

Background

After a long time I thought of sharing my views about managing technical debt in an Agile project. The views expressed here are not only limited to Agile and I believe they can be used in any methodology. A debt is anything that we incur over a period of time. This could be due to various reasons like formation of a new team, people leaving the team, new technology etc. These are mainly related to the technical aspects. There could be a functional debt occurring due to similar reasons. Since Agile teams tend to time box their iterations there is always that extra pressure to deliver the next increment within the iteration cycle. In order to achieve the iteration goals  team members try to take shortcuts due to time and at times peer pressure to come up with shortcuts which starts building the debt.

 

Various reasons for building technical debt

Lets look at some of the common scenarios which are responsible for building the technical debt.

  • Formation of a new team

One of the most common reason is when the new project teams are formed. You have people from different parts of the same organization of different organizations coming together. As the team takes time to understand the dynamics of working together, there could be different styles of working between different team members. There might not be a agreed coding standard to which all the team members can confirm to. These things surely improve as the teams gel together. But it might take some time and effort to re do things which were done initially.

  • New members joining the team

I have found it one of the most difficult thing to get started on a new project with an existing team. It takes quite sometime to understand the ways of working of the team. If you are new to the domain then it is even more time consuming to understand the functional as well as technical side of things. For the experienced and seasoned professionals it might be little bit easier to bridge the gap. When it comes to new recruits it can be a big task specially in those places where the difference between the practicality and academic studies are quite contrasting.

  • People leaving project or organizations

Organizations all around the world have hard time  retaining the same team over a long period of time for the complete duration of the project. It is quite normal for people to choose to move into a new team within the same organization or even change organizations due to various reasons. If a person has worked on a project for a long duration then obliviously he or she is bound to have acquired a lot of functional as well as technical knowledge about the project. As part of the handover managers usually ensure that this key knowledge is transferred to some other individual but very rarely does it happen that all the knowledge is transferred as expected. Many teams use a wiki to share knowledge among team members. My personal experience says that creating design documents and any other lengthy documents under the name of process is of no use. First and foremost its very difficult to keep these so called design documents in sync with the changing software. And secondly the way they are interpreted by different people is also different. I tend not to give too much importance to these documents. Their relevance is lost fairly quickly.

  • Time constraints

One of the most common excuse people have for increasing the technical debt is “Time”. Almost all the customers want everything to be delivered as the highest priority from their product backlog. This might not allow the development team to concentrate on the technical excellence. My experience says that this leads to things like not making use of proper patterns like Design patterns or enterprise patterns while building solutions, lack of unit tests, skipping integration tests, lack of automated tests.

  • Lack of knowledge / skills

Not always do developers have control over the choice of tools and technologies that are used for developing software. You might end up working with a team where everything that you see and hear is new for you. Just to give you an example if you have joined a new team which uses Silverlight technology for building line of business application, NHibernate as ORM, WCF as service layer and SQL Server 2008 as database server, MS Test as unit testing framework and Rhino Mocks as mocking framework. In most likelihood you’ll have people with different skillsets in these technologies. Someone might be a beginner while some other person might be an expert. As a result the way both the people might approach the same problem with different mindsets. 

  • Lack of standardized practices and processes

In order to build quality code the team needs to have a agreed set of guidelines which all team members need to follow. These are basic things like coding standards document, agreed definition of done, inclusion of quality metrics like code coverage as well as automated code analysis.

 

Different methods of reducing technical debt

You will find symptoms of  one or more above debts in almost every project. There is no sure shot solution to any of these problems. What works for one team might not really work for others. We can only try and reduce the debt and make sure that it is kept to minimum at every level. Lets look at some of the ways which might help to reduce these debts.

  • Formation of new teams

One of the common thing to do at the time of forming a new team is to go slow in the beginning and ensure that everyone understands what's going on around them. At the beginning of the project there is lot of work needed to be done on infrastructure side like setting the build, creating the project structure, choosing the tools or third party dll’s, setting up the source control etc. The team as a whole can work on these tasks. For e.g. this helps in ensuring that everyone is aware of why a certain folder or file was created in a certain place. You need not go about asking the person who created it and why is it needed. If there are multiple choices available and you are required to choose one among them then may be two or three people can evaluate things together so that the decision which is taken is not biased and based on an individuals analyzing skills.

  • People leaving the team or organization

In my opinion this is the most difficult thing to manage as part of debt. Agile doesn’t support much of documentation. The best thing to do  is to avoid having the knowledge confined to a single individual. Obliviously you can’t satisfy each and every individual in your team. There comes a time when you need to let go the best people within the team whether you like it or not. To be honest every time I hear someone say that so and so individual is very important to a project I can sense that there might be lot of technical debt in that project. The moment you reduce that dependency you secure yourself from one man show and ensure greater success for your team.

Its not just limited to people leaving the organization. There could be extreme cases where a person has gone out of town or city or country and a critical bug arises in the production environment. You definitely don’t want only one person in the team to know about the functionality which is breaking. Think of another extreme scenario where one of the team mate has to go on a month long vacation may be for medical leave or for something special like marriage. You don’t want to disturb someone when he’s lying on a hospital bed or enjoying with his or her better half on a honeymoon trip Smile

  • Time constraints

Most of the times when I discuss with people why they did some things in a certain way and not the other way round, the standard answer is due to lack of time. In a hurry to complete something in a short duration people skip some steps and take shortcuts. Many times things which could have been refactored and implemented in a simple way get neglected due to lack of time. People always say we’ll finish this and then refactor everything at the end of the project or at a later point of time. Trust me 99% of the time it never happens. If you can’t refactor today there is very little chance that you’ll do it later. And those big bang refactoring steps are always more dangerous than the smaller ones. Once again refactoring is a very huge topic and there are dedicated books and blogs written about it. If I was the scrum master or project manager or a person in a position to take a decision I would rather spend little bit of time now to fix things as they are instead of piling on them and trying to fix everything together. The downside of taking shortcuts is that you might be able to finish things on time but the quality of the output that your team is producing is bound to be affected. My personal opinion is that no one cares how fast you deliver something but how well you deliver what you have delivered. Customers and clients would be much more happy to see 3 of the 5 requested functionalities working fully rather than 4 of 5 functionalities delivered but only 2 of them working as expected.

  • Lack of knowledge

One of the best ways to reduce the skill gap is by using pair programming. Pair programming helps in reducing technical debt to a great extent. In my opinion almost every line of production code should be written by a pair. People normally tend to think that when two people work together the productivity goes down as one persons man hours are not accounted. It is proven and from my personal experience I can confirm that this is not true. You get some of the best results when two brains are working together on the same problem. (Provided both the partners who are pairing contribute). If there are any issues found during testing or some enhancement needs to be done then potentially there are two people capable of handling it. You also get some of the best ideas while discussing with your pair. You might come to a solution to a complex problem much faster if two people are working compared to a single individual working on the same. I’ll leave it for another post because pair programming is very close to my heart Smile

  • Lack of standardized practices and processes

It is very useful to have a standard way of developing different components within the same team. Hence a coding standard needs to be followed so that its easier for everyone to work within the team. The team also needs to decide upon the different metrics they are going to use to gauge the quality of their code. Some of the things which I have used during my career are the percentage of code coverage for unit test, various code matrices like cyclomatic complexity and maintainability index etc. We as developers have too much confidence in our code. But its always advisable to run code analysis tool to make sure the code confirms to industry standards. I personally like FxCop and StyleCop for dynamic and static code analysis. There will be things which these code analysis tools suggest or treat as errors or warnings. But they might be valid as per the teams conventions. In such cases these tools provide facilities to customize the default settings. I recommend that these tools should be integrated the build process itself. Some of the teams I have worked with had these tools integrated into continuous build and would even fail the build if things like code coverage was not met. If there is a way to enforce the standard or a process it should be done right from the beginning. 

 

Conclusion

Its always a herculean task to ensure that the team is self organizing and has what it needs to do its job on a given day. Many a times things are totally out of our control and we can only make an attempt to get things back from going from bad to worse. Technical debts keeps occurring during development every now and then. The more they increase the more dangerous they are for the maintenance of the project. But one of the motive behind the Agile moment is that we deliver quality software. If your team is serious about practicing Agile then you should aim for a quality product and not the quantity. People always remember how well you did a job and not how fast you finished it off. I believe in software craftsmanship and delivering quality with everything I do. I am sure there are many more techniques to reduce the debts. I would like to know about them. If you know any please drop me a comment.

Until next time happy programming Smile

spacer

Interesting links for 17th January 2011

 

Agile

 

Silverlight / WPF / WP7

spacer

Interesting links for 16th January 2011

 

Agile

 

Silverlight / WPF / WPF 7

 

ASP.NET / ASP.NET MVC

 

Miscellaneous

spacer

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

spacer