Working with Events in Silverlight

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg This

It’s no secret that today’s applications require a high-level of interactivity between user actions and application code. It’s critical for developers to know what actions a user performs so that they can call the appropriate code to show and hide content, hit a database or perform other tasks. Although each of today’s more modern languages handles events differently, they all provide the ability to attach events to event handlers.

Silverlight 1.0 provides a rich event-driven development model that can be used to detect when users perform specific actions or when Silverlight objects complete various tasks or operations. This can be useful when users interact with objects on a Silverlight canvas, to detect a file’s download progress or when you need to be notified that a canvas has loaded and is available to use. Silverlight events can be defined in XML Application Markup Language (XAML) files and handled using JavaScript. In this article, you’ll see how to work with Silverlight events and see how they’re similar in many ways to HTML events.

Comparing HTML Events and XAML Events

Working with events in Silverlight is quite similar to working with events in HTML. Events are defined using a declarative language (markup language) and handled using a programming language. HTML provides a simple way to embed events and event handler references into various elements contained within a page. For example, to handle a button’s click event you could add the following code:

1
2
<input type="button" id="btnSubmit" value="Click Me" 
  onClick="btnSubmit_Click" />

JavaScript embedded in the HTML page (or stored externally) could then handle the event:

1
2
3
4
5
function btnSubmit_Click()
{
    var outputDiv = document.getElementById("divOutput");
    outputDiv.innerHTML = "You clicked the button!";
}

Although this is very simple example, the same overall concept applies to Silverlight applications. Events and their associated references are defined in XAML and handled using JavaScript. An example of embedding events into an XAML document is in Listing One.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<Canvas xmlns="http://schemas.microsoft.com/client/2007" Loaded="ShowLoad">
    <Canvas.Triggers>
        <EventTrigger RoutedEvent="Canvas.Loaded">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation AutoReverse="True"  
                      From="80" To="200" Duration="0:0:3" 
                       Storyboard.TargetName="tbHello"
                 Storyboard.TargetProperty="(Canvas.Top)"
                       RepeatBehavior="Forever"/>
            </Storyboard>
               </BeginStoryboard>
        </EventTrigger>
    </Canvas.Triggers>
    <Canvas Canvas.Left="10" Canvas.Top="10" Height="300" 
      Width="300" Background="#efefef">
        <Canvas.RenderTransform>
            <TransformGroup>
              <RotateTransform Angle="25"/>
                <SkewTransform AngleX="25"/>
        </TransformGroup>
      </Canvas.RenderTransform>
      <Rectangle Name="Rect" Canvas.Top="25" Canvas.Left="25" 
        Width="200" Height="150" Fill="Yellow" Loaded="ShowLoad" 
        MouseEnter="MouseEnter" MouseLeave="MouseLeave"
        MouseLeftButtonDown="MouseClick"/>
      <TextBlock Name="tbHello"
        Canvas.Left="36" Canvas.Top="80"
        Foreground="Maroon" FontFamily="Verdana" 
          FontSize="24" FontWeight="Bold"
          Text="Hello From Silverlight!">
      </TextBlock>
    </Canvas>
</Canvas>
Listing One: Embedding events and event handler references into XAML code.

Table 1 summarizes the events defined in the XAML shown in Listing One.

 

Event

 

Description

 

Loaded

 

 

 

Called when the canvas object loads.

 

MouseEnter

 

 

 

Called as the mouse enters an object’s area.

 

MouseLeave

 

 

 

Called as the mouse exits an object’s area.

 

MouseLeftButtonDown

 

 

 

Called as the left mouse button is clicked on an object.

 

Table 1

The Loaded event defined on the root canvas notifies you when the canvas has loaded so that you know when to interact with it and its children. It’s similar to the onLoad event that can be added to an HTML body tag. The XAML Canvas object exposes several other events as well such as GotFocus, KeyDown, KeyUp, LostFocus, MouseEnter, MouseLeave, MouseLeftButtonDown, MouseLeftButtonUp, and MouseMove.

When the canvas is loaded a JavaScript function named ShowLoad() is called. The ShowLoad()function is shown next:

1
2
3
4
5
6
7
var _Control = document.getElementById('slControl');
var _TB = null;        
function ShowLoad(sender,eventArgs)
{
   if (sender == "Canvas") _TB = _Control.Content.FindName("tbHello");
   alert("Object Loaded.  Sender = " + sender);
}

If you program in VB.NET or C#, the parameter signature on the ShowLoad() event handler should look familiar. When the event is raised the sender of the object is passed (the Canvas object) as well as event argument data. ShowLoad() checks to see if the sender is a Canvas object and then locates a TextBlock object named tbHello using the FindName()method.

The XAML in Listing One also defines several mouse events including MouseEnter, MouseLeave, and MouseLeftButtonDown. hese events fire as the user enters, leaves or clicks a Rectangle object defined in the Silverlight application. The Rectangle object also defines a Loaded event that calls the ShowLoad()method discussed earlier. The JavaScript code that handles the enter, leave and left button down events is in Listing Two. Looking through the code you’ll see that all of the methods have the same parameter signature which allows for a consistent way to handle events and event data.

1
2
3
4
5
6
7
8
9
10
11
12
function MouseEnter(sender,eventArgs)
{
   _TB.Text = "Mouse entered " + sender;
}
function MouseLeave(sender,eventArgs)
{
   _TB.Text = "Mouse left " + sender;
}
function MouseClick(sender,eventArgs)
{
   _TB.Text = sender + " clicked!";
}
Listing Two: Handling different mouse events in Silverlight.

Silverlight 1.0 doesn’t provide a built-in way to know when the right mouse button has been clicked unfortunately. Hopefully that functionality will make it into a future version of Silverlight.

In addition to the events in Listing One, you’ll also find a special tag named EventTrigger that can be used to route events and perform actions defined in the XAML. In this example, EventTrigger handles the root Canvas object’s Loaded event. It does this using the RoutedEvent attribute. As the Canvas object’s Loaded event fires, the EventTrigger will play a storyboard animation that changes the TextBlock‘s Top property to move the TextBlock object up and down on the canvas. Because the animation’s RepeatBehavior attribute is assigned a value of Forever, the animation will play until the application is closed.

Although a complete discussion of routed events is beyond the scope of this article, it’s important to understand the overall role they play in XAML and how they can be used to route events to actions. You’ll find additional details about event triggers and routed events in the Silverlight 1.0 SDK available at www.silverlight.net.

 

A rich event-driven development model that can be used to detect when users perform specific actions

Using Events to Download Files

Silverlight events can also be used in other ways that don’t involve require user interaction. In Silverlight you can use a built-in Downloaderobject to download files used by an application on-the-fly. This functionality is useful when you need to download several images as an application initializes or need to download XAML fragments or other file types on demand as a user performs an action.

The Silverlight Downloaderobject exposes three events as in Table 2.

 

Event

 

Description

 

Completed

 

 

 

Fires when a download completes.

 

DownloadFailed

Fires when a download fails due to no content being returned.

DownloadProgressChanged

Fires as a download progresses and provides the percentage of the file that has been downloaded.

 

Table 1

Listing Three provides an example of using the Silverlight Downloader object and handling its events. The code starts by creating the Silverlight object instance using the standard Silverlight.createObjectEx() method. Within this method the onLoad event is hooked to an event handler of the same name. The onLoad() event handler creates the Downloader control using the CreateObject() method and then wires its events to their respective event handlers using the AddEventListener() method. Once the events are wired up it then defines the file to download and calls Send()to start the download.

As the file is downloaded the onDownloadProgressChanged() event handler is called which is used to get the download progress. The code then updates a TextBlock object’s Text property with the percentage of the download that has completed. When the file download completes the onCompleted()event handler is called which provides the user with an updated status.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var _TB = null;
function CreateSilverlight()
{
  Silverlight.createObjectEx(
    {
      source: "MyApp.xaml",
      parentElement: document.body,
      id: "slControl",
      properties: { width: "100%", height: "100%", version: "1.0" },
      events: { onLoad: onLoad, onError: null }
    }
  );
}
function onLoad(control, context, rootElement)
{
    _TB = control.Content.FindName("tbProgress");
    var downloader = control.CreateObject("downloader");
    downloader.AddEventListener("DownloadProgressChanged", 
     onDownloadProgressChanged);
    downloader.AddEventListener("Completed", onCompleted);
    downloader.AddEventListener("DownloadFailed", onDownloadFailed);
    downloader.Open("GET", "MyFiles.zip?" + new Date()); 
    downloader.Send();
}
function onDownloadProgressChanged(sender, eventArgs)
{
    var percentComplete = sender.DownloadProgress * 100;
    _TB.Text = Math.floor(percentComplete) + "%";
}
function onCompleted(sender, eventArgs)
{
    _TB.Text = "Download complete!";
    //Access files that were downloaded
}
Function onDownloadFailed(sender, eventArgs)
{
    //eventArgs will always be null in this event handler
    alert("Download failed");
}
website designing delhi,website designing india,website designing,website design,websitedesignin.org,seo,search engine optimization,seo articels,website design delhi,website design india

ASP.NET MVC and Web Forms — Shaping the Future of the Web

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg This
Ever since the release of ASP.NET MVC there is a constant buzz to evaluate its features and compare it with traditional Web Forms development. This article compares both these frameworks to help the developer community decide the use of appropriate framework while working on actual projects.

Introduction

ASP.NET Web Forms development is a rich and matured technology for web development on the Microsoft platform. It allows quick development, rich user interface and rapid adaptability by naïve developers. Developers get WYSIWYG kind of designer support right in the development environment. But this ease of usage brings certain issues from maintainability, testability and performance-related point of views. Due to new expectations from web applications and better control over the content, Microsoft’s focus has changed a little bit, and now we have an alternative.

ASP.NET MVC is a new programming paradigm in web application development and is as revolutionary as ASP.NET itself was a decade ago. The first version of the MVC 1.0 was released in March 2009 where it was a separate installer. Microsoft is so backing on to MVC as the next big thing in the web development arena that they have not only made MVC 2 part of .NET framework 4.0, but also made it open source, http://aspnet.codeplex.com/releases/view/41742, like the AJAX toolkit. So you can download the MVC source code and suggest improvements and at the same time have custom implementation, since you have the power of entire source code. The latest preview of MVC 3 is available @ http://aspnet.codeplex.com/releases/view/50092

Before it gets too complicated for an Introduction part, let’s get on with understanding more about ASP.NET MVC.

Diagram 1: Parallel existence of Web Forms and MVC.

What is ASP.NET MVC?

MVC stands for Model, View, Controller, is a design pattern used for software development that supports separation of business logic from the user interface and application input. There is nothing new in this pattern that Microsoft has re-invented. The design pattern was there since long back and pretty much used in web arena also, but as stated earlier, Microsoft’s focus has changed recently and is a new addition to ASP.NET.

  Diagram 2: ASP.NET MVC Components. 

Controller

The Controller is the one that receives the input and initiates Model to reflect the correct state of the application. For example, the Controller handles the user interaction request and selects appropriate action handler to execute and passes the query string values to the Model, which in turn can query database based on information received from Controller.

View

View is the MVC component that displays the application’s user interface (UI). Usually, Model data is used to render the UI. Example would be an editable view of a Products table that displays text boxes, drop down lists, and check boxes based on the current state of a Product object. View renders any change in the UI. View does not contain any business logic and receives information from Controller.

Model

Model represents the state aspect of the application and passes the information back to Controller. Model generally interacts with database, web services and NHibernate etc. Controller sends the Model information to View. In small to medium applications, the Model is often a theoretical separation instead of an actual one. For example, if the application only reads a dataset and sends it to the View, the application does not have a physical Model layer and associated classes. In that case, the dataset takes on the role of a Model object. Hence it’s an optional component in MVC.

ASP.NET MVC is a web variation of the standard MVC design pattern and in this there is no direct link between the model and the View. This is done in order to have clear separation between Model and View.

MVC or Web Forms?

Since MVC is just an alternate to Web Forms development and not a replacement, there always remain a big question that when should we go for MVC and when should we stick to Web Forms.

MVC scores over Web Forms in most of the areas, especially when it comes to out of the box options. Features that require explicit effort in Web Forms are available right from the ground up in MVC. Next sections discuss all these points in detail.

Separation of Concerns

MVC assigns clear responsibility to all the 3 involved components. While Controller handles the HTTP request, Model holds the business logic, data access layer. View ensures data validation and display the application’s user interface (UI). As per this architecture, Controller will never try to access database directly or for that matter View will not hold any business logic in it. This is different from a Web Form where controller and view are just about combined and gives fake sense that code behind is separated from the view, whereas in reality they are tightly coupled and requires explicit extra efforts to introduce separations.

Separation of concern can lead to significant productivity improvement since this lets you implement the code in parallel. While one of the team is working on Data Model design and implementation, we can have Views and Controllers developed in parallel. This separation also results into better code maintenance, extensibility and adaptability.

Separation of concerns also lets you implement DRY principle (Don’t Repeat Yourself). DRY idea is to code it once and that’s all. A DRY design removes the code redundancy, which makes projects faster to compile and easier to maintain. For example, validations using Data Annotations can be implemented within Model which ensures that no matter where you use the Model; all validations will still be enforced. Generally, Create and Edit pages use the same kind of View layout. MVC provides the flexibility to define “partial view” that can be used to encapsulate view rendering logic for a sub-portion of a page. This provides a powerful way to define logic once, and then re-use at multiple locations.

Conventions over Configuration

The thought is pretty simple, stick to the conventions and avoid too much configurations. We all know how big those web.config files get when we do standard ASP.NET Web Form application development. Also, we always need to mention specific details of the method while calling. However, in MVC if we follow certain naming conventions for classes, files and folders we can avoid many of the configurations and explicit settings. For example:

 Diagram 3: Conventions over Configuration.

Simple statements like return View(); can automatically reference the Index.aspx view in the Home (name of the Controller) folder under the Views folder. This avoids specifying the view name explicitly and keeps the code simpler and cleaner. There are various other places where conventions can really ease the job during development and helps improve the productivity. For example, you can create a View straight from the Controller by right-clicking and Visual Studio will prompt about the type of View you would want to create and framework will accelerate in creating a View pretty fast for you.

website designing delhi,website designing india,website designing,website design,websitedesignin.org,seo,search engine optimization,seo articels,website design delhi,website design india
website designing delhi,website designing india,website designing,website design,websitedesignin.org,seo,search engine optimization,seo articels,website design delhi,website design india