Archive for April, 2009

Silverlight Navigation : Browser Navigation Overview

Silverlight does not provide built in direct navigation system not it provides integration with browser navigation system but Silverlight provide some other features that can be used for navigation while developing Silverlight applications. There is two type of navigation is possible in Silverlight application

Browser Navigation

Browser navigation means Silverlight application can directly point to pages that are outside of your application domain or applications. Like you can use browser navigation for redirecting user to some other web page. To enable user navigation to other web pages Silverlight provides a user control called HyperLinkButton and by setting it’s Navigateuri. There is one more important property HyperLinkButton has called TargetName means whether url will be opened in a new windows or in same window. It’s Content property is display the text of HyperLinkButton Control.

<HyperlinkButton x:Name="hpb" Content=" All About ASP.Net" NavigateUri="" TargetName="_blank"></HyperlinkButton>

The above example is simple static browser navigation example but browser navigation can also be done programmatically by manipulating HTML DOM objects through the HtmlPage class.

<HyperlinkButton Content="Go to Silverlight Website" Click="GoToSilverlight" />
Imports System.Windows.Browser

Partial Public Class HomePage
    Inherits Page

    Public Sub New()
    End Sub

    'Executes when the user navigates to this page.
    Protected Overrides Sub OnNavigatedTo(ByVal e As System.Windows.Navigation.NavigationEventArgs)

    End Sub
    Protected Sub GoToSilverlight(ByVal sendar As Object, ByVal e As System.Windows.RoutedEventArgs)
        If (HtmlPage.IsPopupWindowAllowed) Then
            HtmlPage.PopupWindow( _
                New Uri(""), Nothing, Nothing)
            HtmlPage.Window.Navigate(New Uri(""))
        End If

    End Sub
End Class

Abstract class V/S Interface

Abstract Class

Abstract classes are classes that cannot be instantiated and are partially implemented or not implemented. Members that are implemented can still be overridden in the implementation class. A class can only inherit only one abstract class or any other type of class. Abstract classes provide elements of inheritance and interface.


Interfaces are definitions how a class needs to respond. An interface describes methods, properties (applicable to Visual Basic .Net) and events that a class needs to implement and type of parameters each member receive and return, but leaves the specific implementation of these members up to the implementing classes. A class may implement more then one interface.

The choice of whether to design an abstract class or an interface sometimes can be difficult. Both interface and abstract class is useful for component integration. Some points that help you to whether to choose an abstract class or interface

  1. If you are creating multiple versions of component then use abstract class. By updating the base class all the inheriting classes are automatically updated with changes. Interfaces cannot be changed once they are created. If new version of interface is required, you must create a new version of interface.
  2. If the functionality you are creating will be useful across a wide range of disparate objects, use an interface.
  3. Abstract classes should be use for primarily for objects that are closely related whereas interfaces are used where common functionality is required to unrelated classes.
  4. If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
  5. If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members

ASP.Net Exception Handling-Part I

.Net languages support structured exception handling means when ever an exception occurs .Net framework creates an exception object, this exception object represents complete information about the exception. You can catch this exception object using the try catch block code if your application failed to catch the exception then you see a error page like this

Exception Handling

Structured Exception Handling Features

  • Exceptions are objects means each exception wrapped with significant amount of useful information about exception instead of just plain text explaining the exception message or cause of exception. These exception objects also support an InnerException property that allows you to wrap a generic error over the more specific error that caused it. You can even create and throw your own exception objects.
  • Exception can be caught based on their type means you can catch specific type of exception following code show an example of this
    IO.File.Open("F:\testfile.text", IO.FileMode.Open)

Catch ex As IO.FileNotFoundException
    Console.WriteLine("File Not found")
Catch ex As IO.PathTooLongException
    Console.WriteLine("File Path is to long")
End Try

  • Exception handlers can also be used in layered manner means you can always create exception handlers on top of other exception handlers for different section of code to handle their exception separately.
  • Exceptions are generic part of .Net framework.


Exception Class Overview

Exception class is base class for all exception classes. Exception class defines two type of exceptions

  • SystemException: This class provides a means to differentiate exception caused by system or application. SystemException does not provide information about the cause of exception and try to avoid throwing instance of this class , if there are cases when you want to throw or created object of this class , a human readable message describing the error should be passed to the constructor.
  • ApplicationException: The ApplicationException class differentiates between exceptions defined by applications versus exceptions defined by the system. If you are creating your own exception class then it is always advised to derive custom exception class from Exception class. Deriving custom exception class from ApplicationException class does not add any significant value to derived class.

Exception Class Properties

Exception includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: StackTrace, InnerException, Message, HelpLink, HResult, Source, TargetSite, and Data.

In Next article we will discuss more about exception class members and how to write a exception handling block.

Silverlight Plug-in Lifecycle

Silverlight Application class provides several services that commonly required by Silverlight application, so when you create a Silverlight you must create a class that is being derived from Silverlight Application class. Application class represents Entry point for your Silverlight application.

Silverlight Plug-in Lifecycle

Silverlight plug-in lifecycle starts with opening a web page that host a Silverlight plug-in. If Silverlight plug-in is not present then web page ask you to install Silverlight browser plug-in. Then web browser activates the Silverlight plug-in and start downloading application package. Silverlight plug-in load Silverlight core services, followed by Silverlight CLR (Common Language Runtime) which creates application domain for your application. After downloading application package CLR creates object of Application class and raise Application Startup event. Application constructor can also be used to initialize application task but generally its a good practice to use Application Startup event handler for most application initialization task.

Silverlight Plug-in Lifecycle

There can be only one Application instance in a Silverlight-based application. After startup, the Application instance provides several services that applications commonly require. You can access these services from any code in your application by retrieving the Application instance from the static Application.Current property.

Silverlight Application Lifetime Management

Silverlight Application class provides a number of features to developers and Application Lifetime management is one feature that is being offered by Silverlight Application class. You can add code to your application class that runs at the following points in the application lifetime:

The application class constructor

Application class constructor can be used for basic initialization of variables and attaching event handlers. Application class constructor typically includes a call to InitializeComponent method which is responsible for merging of XAML and code behind file. Generally your application classes are defined using XAML markup and a code-behind file.

public Sub New()
End Sub

The application Startup event

Silverlight plug-in raises Application Startup event after loading application package. At this point of time all application package assemblies are loaded and available for use. Application Startup event can be used for

  • Process data that you retrieve at startup, such as initialization and URL parameters, or data stored in a previous application session.
  • Display the application user interface (UI).
  • Begin asynchronous downloads of additional resource files or assemblies.
Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
    Me.RootVisual = New MainPage()
End Sub

Application Exit

The Application.Exit event occurs when one of the following actions takes place:

  • The user closes the Web page hosting the Silverlight plug-in.
  • The user refreshes the host Web page.
  • The user navigates the browser away from the host Web page.
  • The host Web page uses JavaScript and the HTML DOM to remove the plug-in from the page.
  • The user logs off or shuts down the operating system.

One common use for the Application.Exit event is to save application settings by using the IsolatedStorageSettings class. For more information, see How to: Store and Retrieve Application Settings Using Isolated Storage.

Private Sub Application_Exit(ByVal o As Object, ByVal e As EventArgs) Handles Me.Exit

End Sub

ASP.NET State Management Overview

As HTTP is stateless, meaning the connection to the server does not remain open. When ever page is post back to server a new instance of the class is created this means there is a overhead of loading all the values associated with controls that are present on the page because http is a stateless protocol and each round trip to the server causes controls to loose their values. To overcome the inherent limitation of http protocol ASP.NET includes several options that help you preserve data on both a per-page basis and an application-wide basis. These features are as follows:

View state

View state is the method that the ASP.NET page framework uses to preserve page and control values between round trips. When the HTML markup for the page is rendered, the current state of the page and values that must be retained during postback are serialized into base64-encoded strings. This information is then put into the view-state hidden field or fields.

Control state

Control state is used to store the state information specific to control. This property is very useful when you are creating custom control and want to know the current state of control.  AS compare to view state property which can be turned off by developer at page level and that can cause your control to break, in case of control state property that can not be turned off like view state.

Hidden fields

Hidden fields are controls that provide a way to store information and at the same time they are not visible to the user. When a page is submitted to the server, the content of a hidden field is sent in the HTTP form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you want to store directly in the page. It is easy to see and modify the hidden field value so it is always recommend that never store sensitive information in Hidden field.


Cookies are basically small text files that are used to store small amount of data on client file system. Cookies can also be stored in clients main memory. Cookies can be temporary (with specific expiration times and dates) or persistent. Generally cookies are used to store information about a particular client, session or application. When a client send a request to the server, browser also sent the cookie to the server, Server then extracts value from the cookie. Typically cookies are encrypted and used for storing user authentication information and user profile preferences.

Response.Cookies("destination").Value = "CA"
Response.Cookies("destination").Expires = DateTime.Now.AddDays(1)

Query strings

Query String is a key value pair that is appended at the end of url with a question mark (?). Query string is a very simple way to send information to the server but it is highly browser dependant. Different browsers have different length for query string. Information passed through query string is easily viewed by the client so query string is not a good option for sending sensitive information to the server.

View state, control state, hidden fields, cookies, and query strings all involve storing data on the client in various ways.

Application state

Application state is a data repository available to all classes in an ASP.NET application. Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and sessions. Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another. Application state is stored in an instance of the HttpApplicationState class. This class exposes a key-value dictionary of objects. The HttpApplicationState instance is created the first time a user accesses any URL resource in an application. The HttpApplicationState class is most often accessed through the Application property of the HttpContext class.

Application("WelcomeMessage") = "Welcome to the Contoso site."

Session state

ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET applications.

Session("FirstName") = FirstNameTextBox.Text
Session("LastName") = LastNameTextBox.Text

Profile Properties

Profile property is a new feature in that allow you to store user specific data this some thing like session but profile information is not lost when a user session is expire. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner.

Profile.PostalCode = txtPostalCode.Text

You must define the PostalCode property in the Web.config file by using the following markup:

      <add name="PostalCode" />

Application state, Session state, and profile properties all store data in memory on the server.

We will discuss each of the state management feature in more detail in upcoming articles. some of the definitions are taken from MSDN

The Acropolis Client Application Framework

The Acropolis Client Framework makes it easy to build flexible and powerful Windows Presentation Foundation (WPF) applications. Learn how to tap into the power of Acropolis and how it can help you deliver the next generation of client applications. In this session, we first describe the basic Acropolis" features and how you can use them to build rich WPF applications. We then move onto some of the more advanced features and show you how to leverage the frameworks flexibility to add rich navigation, theming, commanding, and supporting services to your applications.

Install Silverlight

How to Build A WPF Standard Application

This video shows how you can you build a WPF standard Application.

Silverlight Application and Programming Model

Application that are written for targeting Silverlight 2.0 platform using managed code uses Silverlight Application model. Application model refers to application packaging and the common functionality encapsulated by the Application class. The application model helps you to develop both simple applications and complex, extensible applications that can share resources across a network. Silverlight offers two different programming model for developing Silverlight applications.

  • The managed API for Silverlight
  • The JavaScript API for Silverlight

You can not use both these programming models at same time with in the single application. Managed API model provides more functionality as compare to JavaScript model because application using managed API model can also access lightweight .Net framework classes.

Silverlight Layout Container Panel: Grid

Grid is one of the Silverlight container layout panel that enable complex layout. By default grid contains one row and one column. RowDefinations and ColumDefinations collections also be used to define more rows and columns in Grid. RowDefination and ColumnDefination objects are used to define the size of each row and column inside Grid. In Silverlight Grid is designed to use for your application it is not design for displaying the data, it’s not like GridView in Visual Studio.

Grid.Column and Grid.Row properties are used to position objects in specific cells.

For scenarios that require application layout that is not possible using any of the predefined Panel elements, custom layout behaviors can be achieved by inheriting from Panel and overriding the default measure and arrange behavior by using the MeasureOverride and ArrangeOverride methods. For more information


<UserControl x:Class="SilverlightApplication3.MainPage"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="#DCDCDC" Width="400" Height="300" ShowGridLines="True">
            <ColumnDefinition Width="250" />
            <ColumnDefinition Width="150" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="2*" />
            <RowDefinition Height="*"/>
        <TextBlock Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="1" Margin="10" FontWeight="Bold"  Foreground="Blue"  Text="Silverlight Grid Demo" HorizontalAlignment="Center" VerticalAlignment="Center" />
        <Grid x:Name="FormLayoutGrid" Grid.Row="1" Grid.Column="0" ShowGridLines="True">
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
            <TextBlock Grid.Row="0" Grid.Column="0" Text="First Name" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Center" />
            <TextBox Grid.Row="0" Grid.Column="1" Margin="10" />
            <TextBlock Grid.Row="1" Grid.Column="0" Text="Last Name" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Center" />
            <TextBox Grid.Row="1" Grid.Column="1" Margin="10" />
            <TextBlock Grid.Row="2" Grid.Column="0" Text="Address" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Center" />
            <TextBox Grid.Row="2" Grid.Column="1" Margin="10" />
            <TextBlock Grid.Row="3" Grid.Column="0" Text="Email Address" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Center" />
            <TextBox Grid.Row="3" Grid.Column="1" Margin="10" />


Silverlight Grid Demo