Category Archives: Silverlight

Embedding Resources in Silverlight

This post explains how to embed a resource file in Silverlight and use it. For the example we’ll consider embedding a CSV file and using it.

Copy the file inside the project under the appropriate path. In the properties of the file set the Build Action as Embedded Resource.

The below sample code shows how to access an embedded CSV file.

   1: Stream shareInfo = typeof(ShareInformationManipulation)

   2:                    .Assembly

   3:                    .GetManifestResourceStream("data.csv");

You can read any type of embedded resource as  a Stream.

UI Updates – Part 2

ASP.NET

ASP.NET UI updates are handles using Ajax. In this example it is described how to use the ASP.NET Ajax for the updates.

In ASP.NET Ajax we can have update panel and make the updates via Ajax calls. Prepare your ASPX markup like below.

   1: <body>

   2:     <form id="form1" runat="server">

   3:         <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

   4:         

   5:         <div>

   6:             <asp:Button ID="BtnPostback" runat="server" Text="PostBack" OnClick="BtnPostback_Click" />

   7:         </div>

   8:  

   9:         <div>

  10:             <asp:UpdateProgress ID="UpdateProgress1" runat="server">

  11:                 <ProgressTemplate>

  12:                     <asp:Label Text="Working..." ID="LblBusyIndicator" runat="server"></asp:Label>

  13:                 </ProgressTemplate>

  14:             </asp:UpdateProgress>

  15:         </div>

  16:  

  17:         <div>

  18:             <asp:UpdatePanel ID="UpdatePanel1" runat="server">

  19:                 <ContentTemplate>

  20:                     <asp:Label ID="Label1" runat="server" Text=""></asp:Label>

  21:                 </ContentTemplate>

  22:                 <Triggers>

  23:                     <asp:AsyncPostBackTrigger ControlID="BtnPostback" />

  24:                 </Triggers>

  25:             </asp:UpdatePanel>

  26:         </div>

  27:  

  28:     </form>

  29: </body>

Code behind..

   1: private void PerformTask()

   2: {

   3:     // job time 4 - 10 seconds

   4:     int time = new Random().Next(4, 11);

   5:     Thread.Sleep(1000 * time);

   6:     Label1.Text = String.Format("Hello from worker - ran for {0} seconds", time);

   7: }

   8:  

   9:  

  10: protected void BtnPostback_Click(object sender, EventArgs e)

  11: {

  12:     PerformTask();

  13: }

 

Silverlight

Silverlight the platform itself is asynchronous. And we can have the same mechanism we used in WPF for the UI updates, but little different.

Read the Silverlight Dispatcher for the Silverlight UI updates

Accessing a WCF Service WinRT vs Silverlight

Hi, last few days I got some questions from few folks that they are confused on how to call a WCF service in WinRT (Windows 8). This confusion occurs mainly if you are Silverlight dev or Windows Phone 7.5 dev and you are used to the traditional async method and the CompletedEvent.

In Silverlight these two are very handy and generated by the VS.

Think a very simple WCF service that you get once you create a WCF Application project in the Visual Studio. It comes with a simple method GetData which accepts an int and returns a string.

In Silverlight, VS generates the async method and the async CompletedEvent method for us. so we can simply call the service and get the results like this.

private void Button_Click_1(object sender, RoutedEventArgs e) { Service1Client proxy = new Service1Client(); proxy.GetDataCompleted += (GetDataSender, Ev) => { TxtName.Text = Ev.Result; }; proxy.GetDataAsync(10); }

 

But in WinRT if you try do the same thing you soon will find that you are missing the CompletedEvent.

This is handled differently using the await and async keywords in C# 5.0 Read it in detail here.

Here’s the implementation detail of how you can call a WCF service in WinRT. Click to enlarge the image.

image

As you see the GetDataAsync method generated by the VS returns an awaitable Task. So it is simple than Silverlight, this what you have to do. Simple at its best.

Capture1 

But it is better to know how things work, but that is beyond the scope of this article and you can learn about it here

But what if you need to have a separate Application logic layer and wants to do some processing in the data returned by the service. (more often you need that)

Here’s a way to get the CompletedEvent architecture from Application logic and notifying it to the UI. I’m having my own even handler here.

Create a Class1 (your application logic layer)

class Class1 { public event EventHandler<MyWebServiceEventArgs> DataProcessed; public void HandleMethod(int value) { ProcessData(value); } private async void ProcessData(int value) { Service1Client proxy = new Service1Client(); string result = await proxy.GetDataAsync(value); DataProcessed(null,new MyWebServiceEventArgs(result)); } }

Create MyWebServiceEventArgs derived from EventArgs

public class MyWebServiceEventArgs : EventArgs { private string _myVar; public string MyProperty { get { return _myVar; } set { _myVar = value; } } public MyWebServiceEventArgs(string result) { _myVar = result; } }

 

In your UI layer do this

private void BtnClick_Click(object sender, RoutedEventArgs e) { Class1 c1 = new Class1(); c1.DataProcessed += c1_DataProcessed; c1.HandleMethod(10); } void c1_DataProcessed(object sender, MyWebServiceEventArgs e) { TxtName.Text = e.MyProperty; }

 

Open-mouthed smile I brought the Silverlight CompletedEvent model to WinRT.

But you can simply live a happy life with async and await keywords.

Microsoft’s confuzzled.

You might wonder what this confuzzled is. It’s a word I heard in a movie or in a TV series (don’t remember exactly where) as a combination of confused and puzzled. Hot smile Cool isn’t it ? But it perfectly suits the current situation of the Silverlight.

Silverlight is a good platform, no one can deny that. MS released it as a RIA plugin for the web. (initially to battle against Adobe Flash and Java FX) then Microsoft realized that HTML 5 is  great and started the promising of open web.

They started campaigning Silverlight is not meant for the web. At that time Mango was in a hype. So Silverlight got a safe shelter under the Mango tree. Island with a palm tree

Microsoft also announced the Lightswitch, which is based on Silverlight. (out of the browser feature).

Lightswitch has its own attention from some ISV’s and has been growing, but not much popular in a broader market. Though it is a pleasing platform to develop applications deployment of a Lightswitch app is little hard.

But now Silverlight got a very serious problem. It doesn’t know where to go and where to exactly fit in ? Because of the new boss – WinRT. Just kidding

We all know that Windows 8 apps are running on top of WinRT, and the Windows phone 8 is also a WinRT platform. No more  Silverlight in Windows phone.

Poor Silverlight it lost one of its major safe houses. Sick smile

So as of now Lightswitch is the only guaranteed place for Silverlight to rest in peace.

But you might wonder still we use the XAML in WinRT, so how come we loss the Silverlight. XAML is a powerful UI standard created for WPF and then ported to Silverlight and now being used in WinRT.

So still you can use the XAML skills you’ve got on layout, user interaction, data binding and so and so in the WinRT, but Silverlight is no longer there. That’s it.

So what about the existing WP7 (Mango) apps written in Silverlight, MS promised an automatic recompile of the apps in the marketplace to WinRT.

And since XAML is there, Silverlight devs no need to panic much, because they can still use the XAML and other features like Command model, Converter model and other patterns in WinRT. ( I think the dependency property is still there, not so sure)

Silverlight also has the promises of BI 2.0 but again in a very limited scope. In SQL Server 2012 the power view has some sort of a Silverlight touch.

So when calculating all the formulas, I think Silverlight 5 would be the last version. Party smile

Styles and Templates in Silverlight

Styles

This post has very short code snippets to explain the styles and templates in Silverlight.

Styles are used to set the properties of a UI control. For example this shows the inline style setting of a Button control.

<Button Content="Direct Styling" Height="30" Margin="12,73,298,197" Width="90"> <Button.Style> <Style TargetType="Button"> <Setter Property="Background" Value="DarkOrange"/> <Setter Property="BorderBrush" Value="Blue"/> </Style> </Button.Style> </Button>

This is not interesting, because you can do this without using a Style tag by directly setting the Background and BorderBrush properties of a Button.

It is very useful when you declare the style definition as a resource. Then you name the style and can use across different Button controls as shown below.

Here you can notice for the Background property I have used the attached properties. It is possible since Value is an attached property of Style.

<UserControl.Resources> <Style TargetType="Button" x:Name="colorfulButtonStyle2"> <Setter Property="BorderBrush" Value="Red"></Setter> <Setter Property="BorderThickness" Value="5"></Setter> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0" EndPoint="1,0"> <GradientStop Color="DarkRed"></GradientStop> <GradientStop Color="Chocolate" Offset="1"></GradientStop> </LinearGradientBrush> </Setter.Value> </Setter> </Style> </UserControl.Resources>

Usage

<Button Style="{StaticResource colorfulButtonStyle2}" Content="I'm Colorful" Width="90" Margin="12,12,298,257" Click="Button_Click" Height="30" />

In the above Style declaration I have named the style as ‘colorfulButtonStyle2’. If you do not use a name then all the Buttons in the page will use the style automatically without the need of explicitly setting the Style. (In some applications it is useful mainly if you want all your buttons look same)

Styles also support inheritance. Though it is not recommended you can inherit a Style who’s TargetType is different from the one who inherits.

If you have a style defined for TextBox where it sets the BorderBrush, you can inherit this from a different style who’s TargetType is Button. This is possible because both the TextBox and the Button have the BorderBrush property.

Inheritance will raise errors only if the controls do not have the matching properties. But as a matter of a convention / good practice inheritance of Styles between two different types is not recommended.

Inheritance is done via BasedOn tag.

<Style TargetType="Button" x:Name="anotherStyle" BasedOn="{StaticResource colorfulButtonStyle2}"> <Setter Property="Background" Value="Green"></Setter> </Style>

Here the child will override the styles of the parent.

Templates

Templates allow you to change the visual “face” of any common control. In other words, if
you can’t get the custom appearance you want by tweaking properties alone (and often you
can’t), you can almost certainly get it by applying a new template.

And although creating custom templates is more work than just setting control properties, it’s still far simpler and more flexible than developing an entirely new custom control, which many other programming frameworks force you to do

In Silverlight every control has a way to be rendered. Controls are consist of other basic controls. Example Button is a complex control which consists of Rectangale, Border and other basic controls. This is known as Control Template.

<ControlTemplate x:Key="RawButtonTemplate" TargetType="Button"> <Border BorderBrush="BlueViolet" BorderThickness="3" CornerRadius="4" Background="Red"> <TextBlock Text="Custom Button Template"></TextBlock> </Border> </ControlTemplate>

Above we have defined the Control Template for the Button. You can see in Template we have the flexibility to go beyond the control’s properties and customize them.

<Style x:Key="ButtonStyle" TargetType="Button"> <Setter Property="Background" Value="Green"/> </Style>

 

We have a defined a style as well. Let’s see what happens when we apply these two to a Button. Because both the template and the style set the Background property.

<Button Content="Button" Height="46" HorizontalAlignment="Left" Margin="20,26,0,0" Name="button1" VerticalAlignment="Top" Width="166" Style="{StaticResource ButtonStyle}" Template="{StaticResource RawButtonTemplate}" Click="button1_Click" />

Output image

 

 

Few things to notice here, first it is obvious Style is rejected. Next we have set the Content property of the Button as ‘Button’. And it is overridden by the Control Template’s TextBlock control. And if you run the code you can notice that, Button would have lost it’s total Buttonness Open-mouthed smile ( I invented this word).

You can notice that Button would do its work and fires a click event, but you no longer see the visual transition and the hover effect of a typical button.

This is the way template is defined. It overrides all the properties.

But there’s a way to handle that, using the Content Presenter and Template Binding. Template Binding takes the property values from the control and pass it to the Template (Control Template)

<ControlTemplate x:Key="ContentPresenterButtonTemplate" TargetType="Button"> <Border BorderBrush="BlueViolet" BorderThickness="3" CornerRadius="4" Background="{TemplateBinding Background}"> <ContentPresenter Margin="{TemplateBinding Padding}"></ContentPresenter> </Border> </ControlTemplate>

It is used in a Button like this

<Button Content="Button" Height="41" HorizontalAlignment="Left" Margin="20,101,0,0" Name="button2" Style="{StaticResource ButtonStyle}" Template="{StaticResource ContentPresenterButtonTemplate}" VerticalAlignment="Top" Width="166" Padding="10" /

Output

image

You can see the value set on the Style is applied for Background. And Content Presenter wraps the content of a control which also used Template Binding, so the Content value in the Button is used.

Silverlight Dispatcher

Threading in Silverlight is simple and have very few classes and limited functionality.

In Silverlight we rarely go for the threading since the platform itself is asynchronous. Click to read how to do asynchronous programming in C# 5.0

In Silverlight the  main thread is incorporated with the Dispatcher, and we can use the BeginInvoke method of the Dispatcher class to update the UI from a different thread. According to the MSDN documentation Dispatcher in Silverlight is intended for the UI updates.

I’m using a dummy method which returns a string reversed of its input. And let’s assume it takes 4 seconds to complete the task.

So we need a thread to do the work, without blocking the UI. Once the task completed we have to display the string in the UI.

Here’s my simple and the dirty UI, a TextBox, a Button and a TextBlock to show the output.

image

Here’s the code goes under the Button click event , you can do the work in a thread and return the updates to the UI safely using Dispatcher.

{
string name = textBox1.Text;
Thread thread =new Thread(() =>
{  _reversedString = ReverseString(name);
   this.Dispatcher.BeginInvoke(() =>
     {
              textBlock1.Text = _reversedString;
     });
});
thread.Name =Reverse String Thread;
thread.Start();
}

When hitting the debug and break point we can ensure that our thread is really started and running.

1

Code for the ReverseString method

private string ReverseString(string input)
{
     char[] array = input.ToCharArray();
    Array.Reverse(array);
    Thread.Sleep(4000);
    return new String(array);
}

Let’s discuss how Dispatcher can communicate across threads.

You can clearly notice that, I got the Dispatcher object using this.Dispatcher. This gives the Dispatcher of the Page (MainPage).

Dispatcher is a member of the DependencyObject class. So all the elements mainly UI controls have the Dispatcher property.

Silverlight is a Single Threaded Apartment (STA) Model. And as mentioned earlier it is incorporated with the main thread of the Silverlight. It is the thread responsible of the creation of the UI elements.

Trying to create UI elements from custom threads will throw thread exceptions as they try get the one and only Dispatcher from a different thread.

Here I compare the difference Dispatcher obrtained. First I got the Dispatcher of the RootVisual. Second the TextBlock control. Third I get the Dispatcher reference of the Deplyoment.

System.Windows.Threading.Dispatcher appDisptcher = Application.Current.RootVisual.Dispatcher;
System.Windows.Threading.Dispatcher textBlockDispatcher = textBlock1.Dispatcher;
System.Windows.Threading.Dispatcher deploymentDispatcher = System.Windows.Deployment.Current.Dispatcher;
if (appDisptcher.Equals(textBlockDispatcher))
{
    MessageBox.Show(Root Visual Dispatcher is same as TextBlock Dispatcher);
    
    if (appDisptcher.Equals(deploymentDispatcher))
    {
          MessageBox.Show(All three are same indeed);
    }
}

You can see that all Dispatchers equal. So Dispatcher works from one golden rule that is Silverlight is Single Threaded Apartment (STA) model where with that main thread Dispatcher is incorporated.

Rajini Style App

 

Hi, I never thought of writing a post today. But this website made me to do so. http://www.desimartini.com/​allaboutrajni.htm

A tribute for the creativity of those guys, it’s simply cool. So what is it to have a Silverlight version of the Rajini style app.

No big worries here’s the code. I named it as Rajini Style app. The code is not a matter here, but I salute the creativity of those guys who really made us think.

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;
using System.Net.NetworkInformation;

namespace RajiniStyleApp
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
        }

        void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                textBlock1.Text = "You need to switch off the Internet \n in order to view the content";
            }
            else
            {
                textBlock1.Text = "Disconnected ... Runs on Rajini power >> \n visit :: http://www.desimartini.com/​allaboutrajni.htm ";
            }
        }
    }

 

You have to add the System.Net.NetworkInformation namespace.

Windows Phone All in One Kick Start => Meet Jack Sparrow

Hi this is a quick and simple WP7 application, which demonstrates some of the advanced features within very few steps.

If you are already familiar wit h WCF and Silverlight then WP7 development is very easy for you.

This application explains the following features.

  • Accessing the WCF service from the WP7 application.
  • Handling Cross reference threads in Wp7 and create responsive UI.

Application

The application asks you simple question, and if you answer correct then you will be taken to meet Jack Sparrow. If you do not answer correctly, then the application asks another question and this process repeats.

WCF service is responsible for generating the questions and evaluating the answer. Thread is used to load the web browser.  Browser object is in the Collapsed Visibility mode, and the thread used to navigate the page, and bind the delegate of Navigated event.

Since the web browser is created in the main thread and accessed in another thread, this creates the cross thread reference problem. It is solved using the traditional way of the BeginInvoke() call. But the BeginInvoke() call is made from the Dispatcher object of the current thread.

Code Implementation

In my WCF service I have 2 operational contracts. One is to generate the question and the other one is for evaluate the answer. (Read the comments within the code blocks)

Code for my IService1.cs

image

Code implementation of those methods are mentioned here, You can download the complete solution here

As like Silverlight we have to call the WCF service through asynchronous method calls and binding a delegate to that. But we do not have to worry much since VS generates the Async methods for us.

Build the service, and the reference of the Service to the WP7 application.

The below image shows my WP7 application interface in the design mode.

image

 

In the MainPage.xaml.cs file we have code logic of the application.

Here is the code for calling a service in WP7. It is 100% similar to Silverlight applications. (Read the comments ..)

image

Once the Method call is returned from the service, the following method will be fired. (Note that GetQuestion() is the method we created. GetQuestionAsync() is generated by VS. We have to simply call that. (If you are familiar with Silverlight then this is not a big deal for you)).

image

The following method handles the cross thread reference problem, and provides a responsive UI. (Note that I didn’t code any explicit Threads. In .NET you can do this with simple delegates, .NET handles the thread for you).

image

Notice that in the BeginInvoke() I’m again making a call to my main thread for the Navigated event.

After the application completes it happily displays Jack Sparrow Winking smile

 

image