Silverlight is a cross platform plugin which works with all the popular browsers.

What is covered in the tutorial:

  • How to use Visual Studio and Expression Blend to create and edit your applications.
  • What’s new with XAML and how simple it has made application development with Silverlight.
  • Silverlight Panels
  • Silverlight Controls
  • How to add media and images to a Silverlight page
  • Animation and Storyboard
  • Templates
  • Dependency property and development concepts

Silverlight brings the power of the real desktop apps to browser applications. Now Microsoft is also working on the HTML5 framework keeping the future of web in mind. Silverlight can be considered as Microsoft’s platform for developing and deploying Rich internet Applications.

Silverlight 5 has

–          Great Media Support

–          Helps building Line of Business applications

–          3D support (through XNA 3D integration)

–          GPU accelerated video encoding.

–          Open Fonts type support

–          Text Improvements

–          Binding, debugging and other improvements.

–          Animation , Binding, Skinning and more

Silverlight is a native application and it runs on the computer but the default configuration is to run Silverlight as a browser plugin. It helps you write awesome cross browser application that can run either on PCs or MACs. You would be really excited to know that Silverlight is installed on 67% of the Internet connected devices (http://www.Statowl.com/custom_ria_market_penetration.php).  You can program in Silverlight using your favourite .NET language like C#, VB or Dynamic languages like python or ruby.

 

How To Get Your Development Environment Ready

–          Install Visual Studio (Professional, Premium and Ultimate). You can get it at http://www.microsoft.com/visualstudio/

–          Install Silverlight 5 Tools for Visual Studio 2010. It will configure VS for creating Silverlight 5 projects using Visual studio.  It also enables VS o use the latest WCF RIA Services (SP1). You can get it at http://www.microsoft.com/download/en/details.aspx?id=28358

–          Install Expression Blend Preview for Silverlight 5. You can get it at http://www.microsoft.com/download/en/details.aspx?id=9503

–          Install XA Game Studio 4.0 for game development. http://www.microsoft.com/download/en/details.aspx?id=23714

–          Install Microsoft Toolkit (Optional). You can get it at http://silverlight.codeplex.com

Silverlight Application Start up process for an Application

 

The key players in this case are Application manifest file and the Silverlight plugin. The steps are as follows:

  1. User requests an HTML page from the server.
  2. The Browser downloads the page and detects that there is a Silverlight content in the page. It does this by seeing that there is an <object> tag on the page.
  3. The Browser loads the Silverlight Plugin using the mime type.

Once you have built a Silverlight 5 project you will see the files in the Bin folder something like the below image:

Silverlight App Bin folder

Silverlight App Bin folder

Now when we open StartingUPTestpage.html it looks like something as below:

 

Silverlight App TestPage

Silverlight App TestPage

 

Silverlight App TestPage

Silverlight App TestPage

Now You can see the object tag (in the form section à div) that I was taking about. This will cause the Silverlight plugin to load.

Once the Silverlight Plugin is loaded the Browser goes back to the server and asks for the xap file.

Then the browser opens the xap file which is nothing but a zip file. It then reads the AppManifest.xaml file.The AppManifest.xaml file looks something like below:

 

Appmanifest.xaml

Appmanifest.xaml

You can see that the Manifest file contains the assemblies to load.

The Silverlight plugin then loads the runtime and then loads these assemblies.

Next it goes the Manifest and reads the information about the startup. As you can see in the Deployment part in the image above the EntrypointAssembly is StartingUP. Then it will find the class StartingUP.app which is mentioned as the EntryPointType. Now this Class is shown in the image below:

 

App.xaml.cs

App.xaml.cs

 

App.xaml.cs

App.xaml.cs

As you can see there is App Class in the StartingUP namespace. You can see in the Application_Startup method we have the RootVisual (Startup Page) as MainPage.

Now once this page loads the application is running and will run till either there is an unhandled exception or the user navigates away or the browser is closed.

Hey guys. Today i am going to discuss about the MediaElement in Silverlight and see how we can put it in use in Silverlight and WPF applications. We can integrate media into our Silverlight pages and WPF UserControls.

 

MediaElement Objects

To add media to the Silverlight page just add a MediaElement to your XAML and provide a URI (Uniform Resource Identifier) to the media to play. The code below will show you how to create a MediaElement and set its Source proprty to URI of a video file. You can add the video file to Visual Studio project also and then set its property to Resource and the MediaElement will begin playing when the page loads.

XAML

<StackPanel Width="300" Height="300">
  <MediaElement x:Name="media" Source="xbox.wmv" Width="300" Height="300" />
</StackPanel>

Note – The MediaElement object can play WMV (Windows Media Video), WMA (Windows Media Audio), MP3 Files.
MediaElement Properties
The MediaElement object provides several media-specific properties. The following list describes the commonly used properties.

  • AutoPlay: Specifies whether the MediaElement should begin playing automatically. The default value is True.
  • IsMuted: Specifies whether the MediaElement is silenced. A value of True mutes the MediaElement. The default value is False.
  • Stretch: Specifies how video is stretched to fill the MediaElement object. Possible values are None, Uniform, UniformToFill, and Fill. The default is Fill.
  • Volume: Specifies the volume of the MediaElement object’s audio as a value from 0 to 1, with 1 being the loudest. The default value is 0.5.

In addition to its media-specific properties, MediaElement also has all the properties of a UIElement, such as Opacity and Clip.

Controlling Media Playback

You can control media playback by using the Play, Pause, and Stop methods of a MediaElement object.

XAML

<Grid>
   <Grid.ColumnDefinitions>
         <ColumnDefinition Width="*" />
         <ColumnDefinition Width="*" />
         <ColumnDefinition Width="*"/>
     </Grid.ColumnDefinitions>
     <Grid.RowDefinitions>
         <RowDefinition Height="*" />
         <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <MediaElement x:Name="media" Source="xbox.wmv" Width="300" Height="300" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="3" />
    <!-- Stops media playback.-->
     <Button Click="StopMedia" Grid.Column="0" Grid.Row="1" Content="Stop" />
    <!-- Pauses media playback. -->
     <Button Click="PauseMedia" Grid.Column="1" Grid.Row="1" Content="Pause" />
    <!-- Begins media playback. --> 
    <Button Click="PlayMedia" Grid.Column="2" Grid.Row="1" Content="Play" />
</Grid>

 

C#

private void StopMedia(object sender, RoutedEventArgs e)
{
     media.Stop();
}
private void PauseMedia(object sender, RoutedEventArgs e)
{
    media.Pause();
}
private void PlayMedia(object sender, RoutedEventArgs e)
{
    media.Play();
}

Visual Basic

Private Sub StopMedia(ByVal sender As Object, ByVal e As RoutedEventArgs)
     media.Stop() End Sub
Private Sub PauseMedia(ByVal sender As Object, ByVal e As RoutedEventArgs)
     media.Pause() End Sub
Private Sub PlayMedia(ByVal sender As Object, ByVal e As RoutedEventArgs)
     media.Play() End Sub

Video Player Sample with Code

The following example illustrates typical features of a video player including playback control, a progress/seek slider, and full screen toggling.

Smooth Streaming

Smooth Streaming is an IIS (Internet Information Services) technology that enables adaptive streaming over HTTP to Silverlight clients.  Smooth Streaming breaks video feeds into small fragments which enables it to quickly alter the quality of the video, depending on the current bandwidth of the client.  This creates a high-quality viewing experience that scales massively on content distribution networks.   For more information on Smooth Streaming, see the IIS Smoothing Streaming site.

For an indepth example of Smooth Streaming, see the Microsoft Silverlight Media Framework CodePlex project.

 

Extending your Silverlight 4 Application with Controls

We could not only use and extend the controls present in the visual studio toolbox for Silverlight but also there are multiple providers offering additional controls for Silverlight framework.

Extending XAML

XAML stands for eXtensible Application Markup Language and hence it’s possible to add import external elements into a document without breaking rules.

Mapping a Prefix to CLR Namespace

Now we can define a set XML namespace (xmlns) in XML and can map a unique identifier to a prefix so that the XML parser can use additional rules while loading the document.

For Example

Lets say we want to add double value in the document resources. Now as you would know that XAML is by default configured for User Interface elements, the default XML namespaces will not map to Double types so we have to add the line of code shown in Bold in your XAML other than the normal code.

 

<UserControl x:Class="DoubleInResources.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

xmlns:sys="clr-namespace:System;assembly=mscorlib"

mc:Ignorable="d"

d:DesignHeight="300" d:DesignWidth="400">

<UserControl.Resources>

<sys:Double x:Key="ButtonsWidth">200</sys:Double>

</UserControl.Resources>

<Grid x:Name="LayoutRoot" Background="White">

<Button Width="{StaticResource ButtonsWidth}" Height="{StaticResource ButtonsWidth}" Content="Click Me!!" />

</Grid>

</UserControl>

 

So we are including the mscorlib namespace which contains the Double type definition and then referencing the same in UserControl.Resources and then we have referenced the same as a static resource.

Note

When we are working with XAML we encounter two types of namespaces

CLR Namespaces – Used in .NET code to group the classes logically.

XML Namespaces – Used to extend XML document with additional declarations.

Prefix is not always needed

Silverlight elements are defined into two namespaces. The first one is a Unique Resource Identifier (URI) mapped to the default xmlns (http://schemas.microsoft.com/winfx/2006/xaml/presentation).

 

In fact, multiple CLR namespaces (such as System.Windows.Controls, System.Windows.Shapes, and so on) are mapped to this URI. This allows us to use all the types within these namespaces without having to use a prefix. For example, we write <Button Click=”Button_Click” /> and not <anyPrefix:Button Click=”Button_Click” />. Note that this URI is not a website’s address, and entering it into a web browser will not lead you anywhere. It is just a Unique Resource Identifier, a unique name.

 

The other namespace used by Silverlight by default is http://schemas.microsoft.com/winfx/2006/xaml, another URI, which is mapped to the x prefix. Inside this namespace are defined additional properties that can be applied to any element.

 

How to add a namespace to any element

You can a namespace mapping to a control as well as shown below:

<Button xmlns:controls=”clr-namespace:MyApplication.Controls”>

<controls:MyControl />

</Button>

 

How to define your own CLR and Mapping CLR Namespaces

We can map our own URI to a group of namespaces and this is useful because we can consolidate multiple CLR namespaces into one single URI and also this would hide the CLR namespaces that our code is using. And later when we decide to move some classes to different CLR namespaces we don’t need to change the XAML code. This is also very useful in creating data objects and it also makes data binding easier.

For Example:

Add the following code to the AssemblyInfo.cs

 

[assembly: XmlnsDefinition("http://www.mycompany.com", "DoubleInResources")]

[assembly: XmlnsDefinition("http://www.mycompany.com", "DoubleInResources.Controls")]

[assembly: XmlnsDefinition("http://www.mycompany.com", "DoubleInResources.DataAccess")]

 

And then after building the solution we can reference it as shown below:

What is a Control?

I know you would say that you know what it is but lets start with a formal definition of Control. A Control is an element of software, encapsulating some functionality related to user interface. Now in Silverlight there are two kinds of controls User Control and Custom Control.

User Controls

A user control is a logical group of other controls. It is typically used to separate a user interface in smaller parts that are easier to code and design. In fact, in Silverlight, all the pages of an application are user controls.

The App class (defined in App.xaml and App.xaml.cs) is the main point of entry for the Silverlight application. This is also where the MainPage control is created and assigned.

The Application_Startup Event Handler in App.xaml.cs is as follows:

 

 

 

If you rename the MainPage control to a different name, you must also change the name in the RootVisual assignment, or else your application will not compile anymore.

 

Custom Controls

The custom controls are made of code only as against XAML (Front End) and a code behind file. All controls build in Silverlight are lookless. The custom control file defines only the controls functionality i.e. Properties and methods and its behavior is defined by its states and parts.

For the controls to be visible, a XAML front end must be defined, though. An invisible control is not very usable! One control can have multiple appearances, defined in as many control templates. We talk out a separation of concerns: The control’s code defines its functionality; the control’s template defines its appearance. Typically, a developer implements the control, whereas a designer styles and templates it.

 

Design a Custom Control

 

Let’s take the example of a Custom with the following functionality:

 

  • The user defines a threshold and a value, both of type Double.
  • If the value is higher than the threshold, the control is in High state.
  • If the value is lower than the threshold, the control is in Low state.
  • If the value is equal to the threshold, the control is in Equal state.
  • Both the threshold and the value can change dynamically, be data bound, animated, and so forth.
  • The user can click one part of the control to increment the value by one unit, and another part to decrement by one unit.
  • The control can be disabled, in which case clicking does not change the value.

 

Now as you see we have the functionality of the custom control but not how the control will look so the developer can start working the designers can do the designing part simultaneously.

 

Let’s get started:

 

  1. In Visual Studio, select File, New, Project from the menu.
  2. In the Add New Project dialog, in the Silverlight category, select Silverlight Class Library.
  3. Enter the name CustomControlsLibrary and click OK. Make sure that you select Silverlight 4 in the next dialog. This creates an assembly, a library that can be referenced in multiple applications but cannot be run on its own.
  4. Delete the file Class1.cs in the Solution Explorer (because will not use it).
  5. Right-click the CustomControlsLibrary project in the Solution Explorer, and select Add, New Item from the context menu.
  6. In the Add New Item dialog, select the Silverlight, and then select a Silverlight Templated Control.
  7. Enter the name ThresholdControl.cs and click Add.

Defining the Parts and States

These steps create a C# code file, a folder named Themes, and a XAML file named

Generic.xaml. We will investigate this last file later; for now let’s declare the parts and

states for this control:

  1. Open the file ThresholdControl.cs.
  2. According to the requirements, the control has two state groups. We will call these the Common states (Normal, Disabled) and the Threshold states (High, Equal, Low). Note that the states within a state group are mutually exclusive; that is, the control cannot be simultaneously in Normal and in Disabled state. However, it can be Normal and High, or Normal and Low, and so forth. Defining the states and states groups is done with the TemplateVisualState attribute on the class.
  3. The requirements also state that the control has two parts with a special meaning: Clicking them increments or decrements the value. Here too, we use an attribute to define the parts on the class: the TemplatePart attribute.

 

The ThresholdControl.cs should look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace CustomControlsLibrary
{
    [TemplatePart(Name = "IncrementPart", Type = typeof(UIElement))]
    [TemplatePart(Name = "DecrementPart", Type = typeof(UIElement))]
    [TemplateVisualState(GroupName = "Common", Name = "Normal")]
    [TemplateVisualState(GroupName = "Common", Name = "Disabled")]
    [TemplateVisualState(GroupName = "Threshold", Name = "High")]
    [TemplateVisualState(GroupName = "Threshold", Name = "Equal")]
    [TemplateVisualState(GroupName = "Threshold", Name = "Low")]
    public class ThresholdControl : Control
    {
        public ThresholdControl()
        {
            this.DefaultStyleKey = typeof(ThresholdControl);
        }

        public double Value
        {
            get
            {
                return (double)GetValue(ValueProperty);
            }
            set
            {
                SetValue(ValueProperty, value);
            }
        }

    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(ThresholdControl), new PropertyMetadata(0.0, OnValueChanged));

    public double Threshold
    {
        get
        {
            return (double)GetValue(ThresholdProperty);
        }
        set
        {
        SetValue(ThresholdProperty, value);
        }
    }

    public static readonly DependencyProperty ThresholdProperty = DependencyProperty.Register("Threshold", typeof(double), typeof(ThresholdControl), new PropertyMetadata(0.0, OnValueChanged));

    private static void OnValueChanged(object s, DependencyPropertyChangedEventArgs e)
    {
        var sender = s as ThresholdControl;
        if (sender != null)
        {
            sender.GoToThresholdState(true);
        }
    }

    private void GoToThresholdState(bool useTransitions)
    {
        if (Value > Threshold)
        {
             VisualStateManager.GoToState(this, "High", useTransitions);
        }
        else
        {
            if (Value < Threshold)
            {
                 VisualStateManager.GoToState(this, "Low", useTransitions);
            }
            else
            {
                 VisualStateManager.GoToState(this, "Equal", useTransitions);
            }
       }
    }
    
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        var incrementPart = GetTemplateChild("IncrementPart") as UIElement;
        if (incrementPart != null)
        {
            incrementPart.MouseLeftButtonDown += new MouseButtonEventHandler(IncremementPartMouseLeftButtonDown);
        }
        var decrementPart = GetTemplateChild("DecrementPart") as UIElement;
        if (decrementPart != null)
        {
            incrementPart.MouseLeftButtonDown += new MouseButtonEventHandler(DecremementPartMouseLeftButtonDown);
        }
        GoToThresholdState(false);
    }

    void IncremementPartMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        Value++;
    }
    void DecremementPartMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        Value--;
    }
    }
}

 

And the Generic.xaml should look like this:

<ResourceDictionary

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:local="clr-namespace:CustomControlsLibrary">

<Style TargetType="local:ThresholdControl">

<Setter Property="Template">

<Setter.Value>

<ControlTemplate TargetType="local:ThresholdControl">

<Border Background="{TemplateBinding Background}"

BorderBrush="{TemplateBinding BorderBrush}"

BorderThickness="{TemplateBinding BorderThickness}">

<VisualStateManager.VisualStateGroups>

<VisualStateGroup x:Name="Threshold">

<VisualState x:Name="High">

<Storyboard>

<DoubleAnimationUsingKeyFrames

Storyboard.TargetProperty="(UIElement.Opacity)"

Storyboard.TargetName="EqualTextBlock">

<EasingDoubleKeyFrame

KeyTime="0" Value="0" />

</DoubleAnimationUsingKeyFrames>

<DoubleAnimationUsingKeyFrames

Storyboard.TargetProperty="(UIElement.Opacity)"

Storyboard.TargetName="LowTextBlock">

<EasingDoubleKeyFrame

KeyTime="0" Value="0" />

</DoubleAnimationUsingKeyFrames>

</Storyboard>

</VisualState>

<!--...-->

</VisualStateGroup>

</VisualStateManager.VisualStateGroups>

<Grid>

<Grid.ColumnDefinitions>

<ColumnDefinition Width="30" />

<ColumnDefinition Width="*" />

<ColumnDefinition Width="30" />

</Grid.ColumnDefinitions>

<Border Background="Blue" x:Name="DecrementPart"

Cursor="Hand">

<TextBlock Text="-" />

</Border>

<StackPanel Grid.Column="1"

Orientation="Vertical"

Margin="10">

<TextBlock Text="{Binding

RelativeSource={RelativeSource TemplatedParent},Path=Value}" />

<TextBlock x:Name="HighTextBlock"

Text="&gt;" />

<TextBlock x:Name="EqualTextBlock"

Text="==" />

<TextBlock x:Name="LowTextBlock"

Text="&lt;" />

<TextBlock Text="{Binding

RelativeSource={RelativeSource TemplatedParent},Path=Threshold}" />

</StackPanel>

<Border Background="Red"

x:Name="IncrementPart"

Grid.Column="2"

Cursor="Hand">

<TextBlock Text="+" />

</Border>

</Grid>

</Border>

</ControlTemplate>

</Setter.Value>

</Setter>

</Style>

</ResourceDictionary>

 

 

You can find the complete Source Code at http://min.us/mKwMNIhKq

Hey guys,

While searching for .NET posters on internet i came across this one. This has most of the .NET Framework 3.5 commonly used types and namespaces.

 

net-framework-3_5-types-and-namespaces-poster

 

I just want to share knowledge and do not intend any copyright infringements.

Feedback, comments and questions are most welcome.

 

Hello Everyone.

With the launch of Windows 8 Microsoft has reached new hights in User Interface. But though the UI has changed from good (windows 7) to wicked cool (Windows icon cool Windows 8 : How to Change the Number of Apps Rows in Windows 8 Metro Start Screen the same amount of learning curve is required. As you wont find the options so easily as you do on windows 7. So thats why i have started this WINDOWS 8 HOW TO series to help everyone find there way through windows 8.

So this time i will start off with tips on how to pin and unpin apps from Metro Start Screen.

If you want to pin an app on the Metro Start Sceen just follow the steps below:

1. Hover your mouse over the bottom most and left most corner of your screen. Click on search. ALternatively you can press Windows key + F.

Start Click

Start Click

 

2. Select apps from search list on the right and find the app you want o pin.

3. Now if you don’t see you rapp listed here then you need to go to the start menu folder (hidden by default) and create a shortcut form the app’s .exe file in the Start Menu folder and the trying searcing for the app again. The folders to see for Start Menu items are :

For Your Account Only:
C:\Users\User-Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs

For All User Accounts: (must be administrator)
C:\ProgramData\Microsoft\Windows\Start Menu\Programs

New Shortcut
New Shortcut

4. You will see the app now.

Pin App
Pin App

5. You can right click on the app to pin it to the start screen.

Pin App
Pin App

7. Now you can see you app on the Metro Start Screen.

Pinned App Metro Start Screen
Pinned App Metro Start Screen

Unpin An App Metro Start Screen

To Unpin an app from the Metro Start Screen simply search the app (Windows KEy + F ) and right click on it and it will be unpinned from the Metro Start Screen .
Hope this was helpful. Will soon be back with another Windows 8 How To. Comments and feedback are always welcome.