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.

Advertisement

Crossdomain.xml – Flex

When accessing the web services in Flex you need a crossdomain.xml file in the root of the web server which hosts the web service. In the file you can mention whether to accept the connections from all the domains or the connections from the specific domains to be accepted.

Here the sample for a crossdomain.xml file which allows the access from all the domains.

   1: <?xml version="1.0" ?>

   2: <cross-domain-policy>

   3:    <allow-access-from domain="*" secure="false" />

   4:    <site-control permitted-cross-domain-policies="all"/>

   5:    <allow-http-request-headers-from domain="*" headers="*"/>

   6: </cross-domain-policy>

For .NET guys, this is the exact similar version of the clientaccesspolicy.xml file we deploy in the root of the web server when working with Silverlight.

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.

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.

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

x64 Microsoft Strategy

I write this post after a real piss off, by the Microsoft’s x64 strategy. They announced that in future all of their applications will be working on x64 architecture. As to the statement SharePoint 2010, Windows Server 2008 R2 and some other came in x64 bit only mode.

Even I did a clean format of my PC and installed x64 Windows 7 in order to run SharePoint 2010 and other as well. But what’s the problem ?

They are not clean in their x64 policy. It is totally messed up with x86 applications. Even in x64 bit Windows 7, Windows Media Player runs in 32 bit mode. And Visual Studio 2010 runs in x86 and there is no x64 version of that. (The reason for that, they say is the difficult of development and the application grows bulky)

And every time I start IE is get starts in the x86 mode. There is another x64 version of browser as well in the list. I was wondering why it is not used as default. After wondering I made my IE9 x64 version as the default browser. That gave me the real piss !@#

In the IE9  x64 bit release  (the modern browser) Silverlight cannot run. When ever I reach a website with the Silverlight content it asks me to install the Silverlight.

When I click the link this is the message that I get.

image