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

Eight Key Practices for ASP.NET Deployment

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg This
his article presents some best practices that you can follow to deploy ASP.NET applications in production mode. These practices help you avoid problems both during and after deployment.1. Version Your Assemblies
Make sure you have a solid versioning policy in place. You can apply a version stamp using the AssemblyVersion attribute at compile time, for example:

 [assembly: AssemblyVersion("1.0.12.34")] 

It’s usually best to apply the same version number to all the assemblies in an application during the build process.

2. Give Assemblies Strong Names
An assembly is the smallest unit of versioning, security, deployment, version control and reusability of code in .NET. Each assembly contains:

  • Assembly Identity information (name, version, etc.)
  • Manifest and metadata information
  • MSIL code
  • Type and security information
  • Resources

An assembly with a strong name can be uniquely identified by a combination of its assembly version, culture information, and a digital signature.

You can create a strong name for your assembly using the strong name utility (sn.exe) provided by the .NET framework. The utility requires you to provide the name of a strong name key file as a parameter. The resulting file is called a “strong-named” file. You can use the sn.exe tool from the command line to create a strong-named key file as follows:

 sn --k MyCompany.snk 

When you execute the preceding command, you’ll see the output shown in Figure 1.

 
Figure 1. Creating a Strong-Named Key File: Running the <i>sn.exe</i> file from the command line as shown creates a strong-named key file.

When you create a project in Visual Studio, you’ll see a default file called AssemblyInfo.cs that you can use to specify the related attributes. Here is how you can specify the strong name information in the AssemblyInfo.cs file.

 [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyKeyFile("MyCompany.snk")] 

3. Obfuscate Your Assemblies
It’s good practice to obfuscate your assemblies before you deploy them; obfuscation makes assemblies more difficult to decompile, and impedes reverse-engineering efforts, thus protecting your source code to some degree from potential threats. In addition, obfuscation reduces the size of your assemblies; thereby boosting the application’s performance. You can learn more about obfuscation here.

4. Deploy Shared Assemblies to the GAC
You should deploy assemblies used by multiple applications to the Global Assembly Cache (commonly known as the GAC), which allows them to be shared by all applications that use the assembly. Deploying an assembly to the GAC improves its load performance compared to assemblies not located in the GAC. Strong-named assemblies load faster from the GAC because they’re verified at install time rather than at runtime—the .NET framework skips verification at runtime for GAC-loaded assemblies. The runtime always checks strong-named assemblies to verify their integrity. .NET refuses to load assemblies that are not trusted or that may have been tampered with. Note that you must provide a strong name for assemblies you want to install in the GAC.

You place an assembly into the GAC using the GACUtil tool. The following command places MyProject.dll into the GAC, thus making it globally accessible.

 GacUtil /i MyProject.dll 

To uninstall the assembly from the GAC, you would use:

 GacUtil /u MyProject.dll 

Note that you can even make your strong-named assembly globally accessible without placing it in the GAC. For this, you need to deploy your assembly using the XCOPY command.

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