Tuesday, December 29, 2009

Expression evaluation in Silverlight using eval

One of the previous posts in my general programming blog talks about evaluating the arithmetic expressions using the DataColumn and DataTables.The requirement was simple.You are given with an arithmetic expression say “(2+2)*3” as string. May be a user entered expression.You need to evaluate the given expression and show the answer.

In .Net it is easier.Use a DataColumn with the given expression and it will calculate the result for you.But when we come to Silverlight the things get harder.There is no concept of DataSet or DataTable in Silverlight.Rather the ADO.Net is not there.So what can we do?

One solution is to have a WCF server call which accepts the expression as string and use the ADO.Net DataColumn at server-side and return back the result.Obviously you can achieve that since the server is just a .Net application with ADO.Net support.But is that the better solution? I will say No because we have another alternative.

Its nothing but the famous eval function of javascript.I think all of you know how Silverlight can communicate with Javascript.If not please read this post about the same.

Here goes the solution.Get your expression.Pass it to the eval method of HtmlWindow.Use the return value properly.

private double Evaluate(string expression)
object obj = HtmlPage.Window.Eval(expression);
return Convert.ToDouble(obj);

Wednesday, December 16, 2009

Referring Silverlight 4 DLLs in WPF

Finally MSFT did it.Now we can use Silverlight assemblies in WPF without recompilation.In the older days we have to link the files to other solution and compile for Silverlight and WPF separately.Now that is over.Share your assemblies…

See what the CLR team says about this.

Tuesday, December 8, 2009

Finding Memory Leak in Silverlight

Finally one of my colleague opened the door to the Silverlight debugging using WinDbg and after a through google I was able to find out a great article by Delay regarding the same.


This blog tells about so many commands while debugging.So you may obviously in one question.What are the other commands? Here is the list of commands.

Enjoy debugging and stop the leaks in your application.

Monday, September 28, 2009

Lambda expression in Silverlight 3 Databinding

First of all let me thank to M. Orçun Topdağı for pointing out a useful cs file in the samples provided by Microsoft.You may get those samples in the below location.

[Install drive]:\Program Files\Microsoft Visual Studio 9.0\Samples

The file is Dynamic.cs which provides a bunch of functionality to work more with Lambda expressions.That sample was written for .Net 3.5 and I was afraid whether I can use that in my Application since I am working in Silverlight 3. But I was able to use the same classes for Silverlight and a sample which takes Lambda Expression from xaml and executes through converter is attached with this post.

How to specify a Lambda expression in XAML data-binding

I am using the ConverterParameter to get the lambda expression.The no of parameters to Lambda expression is limited because we can pass only one value to the converter.
<UserControl x:Class="SL_LambdaInConverter.MainPage"
        <local:LambdaConverter x:Key="lambda" />
    <Grid x:Name="LayoutRoot">
            Text="{Binding Converter={StaticResource lambda},ConverterParameter='dt=>dt.ToString()'}" />
In the above sample I have set DateTime.Today as DataContext of the UserControl in the constructor.So it will take that value into the converter.Here is the converter code.

Option Strict On
Imports System.Windows.Data
Imports System.Linq.Expressions
Imports System.Linq.Dynamic
Public Class LambdaConverter
    Implements IValueConverter
    Dim _delegate As [Delegate]
    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        If Me._delegate = Nothing Then
            ConstructOperation(value, targetType, CType(parameter, String))
        End If
        Return Me._delegate.DynamicInvoke(value)
    End Function
    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New InvalidOperationException("Convert back operation is not supported")
    End Function
    Sub ConstructOperation(ByVal value As Object, ByVal t As Type, ByVal lambdaString As String)
        Dim opi As Integer = lambdaString.IndexOf("=>")
        If (opi < 0) Then Throw New Exception("No lambda operator =>")
        Dim param As String = lambdaString.Substring(0, opi)
        Dim body As String = lambdaString.Substring(opi + 2)
        Dim p As ParameterExpression = Expression.Parameter(value.GetType(), param)
        Dim lambda As LambdaExpression = DynamicExpression.ParseLambda(New ParameterExpression() {p}, t, body, value)
        Me._delegate = lambda.Compile()
    End Sub
End Class

Now you might wonder where is the System.Linq.Dynamic ? Here comes the importance of Dynamic.cs which I had mentioned at the beginning.You may find all those classes there.

Download and enjoy the sample here.

Sunday, September 27, 2009

Silverlight 3 in Windows Mobile 7

Any developer who takes programming as a passion, would always like to see his application running in different plat forms.The code need to be same ,but runs every where.

.Net & Java did this by introducing an intermediate language to which every code compiles to and before running, it convert in to the native code.

When I entered into Silverlight it felt like I am writing code only for Browser.Prism has introduced a solution where we can use same code base for Silverlight as well as WPF.Now we have got much more support in extending our Silverlight code to different plat forms. 

Yes.The support is in Mobiles. Microsoft has announced that their next Mobile operating system Windows Mobile 7 Will support Silverlight 3.They are planning to release Windows Mobile 7 in 2010.So plan your application accordingly,because it has to run in mobiles by next year.

Some links


Tuesday, September 22, 2009

The need for ModuleBase class in Prism

When I started a sample application in Prism, I came to some situations where I need ModuleManager and all.After a small google I came to know that if we specify some arguments in the constructor of Modules we could get lot of useful objects such as ModuleManager,RegionManager etc...We can hold them for future uses.

Instead of having properties in each module to hold these objects, it is always better to have an abstract base class which holds all these objects.Then I did a trial an error method to find out what are all the objects which we can get and it came around 4 objects.

  • IModuleManager
  • IRegionManager
  • IUnityContainer
  • IRegionViewRegistry

And the base class implementation is as follows.
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Practices.Composite.Modularity;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Unity;
namespace Prism.Core
    public abstract class ModuleBase : IModule
        IModuleManager _modulemanager;
        public IModuleManager ModuleManager
            get { return _modulemanager; }
            set { _modulemanager = value; }
        IRegionViewRegistry _regionViewRegistry;
        public IRegionViewRegistry RegionViewRegistry
            get { return _regionViewRegistry; }
            set { _regionViewRegistry = value; }
        IRegionManager _regionManager;
        public IRegionManager RegionManager
            get { return _regionManager; }
            set { _regionManager = value; }
        IUnityContainer _container;
        public IUnityContainer Container
            get { return _container; }
            set { _container = value; }
        public ModuleBase(IModuleManager moduleManager, 
            IRegionManager regionManager,
            IUnityContainer container, 
            IRegionViewRegistry reg)
            ModuleManager = moduleManager;
            RegionManager = regionManager;
            Container = container;
            this.RegionViewRegistry = reg;
        #region IModule Members
        public abstract void Initialize();
The same thing is applicable in the case of Views too.

Saturday, September 19, 2009

Is it DRM which we really need in Silverlight 4?

From some news sites and also from Microsoft's press pass I could know that there will be DRM support in Silverlight 4.DRM is a nice feature which I would like to be in Silverlight.

But I wonder why they are not telling about other features, which as a developer we are waiting for from the Silverlight 1.0 days itself.I came from the WPF environment so I will really look for the below features first instead of DRM.

  1. Full implementation of Commands.Silverlight 3 doesn't have Button.Command property.Do we need to relay on interactions provided by blend 3?
  2. FindAncestor for RelativeSource binding
  3. InputBindings in UIElement.
  4. Attached events.
  5. Triggers or equivalent implementation in DataTemplates
  6. Option to create custom mark-up extensions.
  7. XPS support.
  8. Printing.
  9. More bindings in WCF such as TCP.

A huge wish list is here in Silverlight forum.Hope Microsoft will address our these small issues along with rocking new features.

Wednesday, September 2, 2009

Specify Modules in XAML

When I first started PRISM my thought was how to specify the modules through a xaml file or an xml fille.The existing code is written as like something hard coded in the Bootstraper.cs.

protected override Microsoft.Practices.Composite.Modularity.IModuleCatalog GetModuleCatalog()
    var catalog = new ModuleCatalog();
    return catalog;

We can easily setup an xml file and create module objects using reflection.But I was sure, there will be an implementation of same somewhere in the framework.

After spending some time, I got a new way to implement my scenario.Why don't I have a new xaml file derived from ModuleCatalog and make the entries in xaml ? Yes that did the trick.

I added a new file which derives from ModuleCatelog and added my module entries.The xaml looks as below.

        ModuleType="Students.StudentsListModule, Students, Version=" />
        ModuleType="Students.MarkModule, Students, Version=" />

Make sure that the code behind class should inherit from ModuleCatalog.

Now you can Rewrite the Bootstraper.GetModuleCatalog() as follows

protected override Microsoft.Practices.Composite.Modularity.IModuleCatalog GetModuleCatalog()
    return  new StudentsModuleCatalog();
This makes the code more neat and we can easily add or remove modules.

Tuesday, September 1, 2009

Microsoft SSRS viewer in Silverlight

Some time back we had a scenario of showing reports in Silverlight.Our first though was to create reports in ASP.Net and show that as popup window from Silverlight.But in the research we found out a great tool from Perpetuum softwares which renders the SSRS report inside Silverlight.

Main advantages were it capability to leverage features of Silverlight such as Vector graphics.We can zoom the report without losing it's clarity.

Online demo is available here .You need to install only Silverlight 3 in order view the report.

Basically it works by adding a component at the server side which makes the report compatible with their Silverlight viewer.Currently it supports SQL Server Reporting Services 2005 only.

Good work Perpetuum guys.Keep it up.

Saturday, August 15, 2009

WCF service from Silverlight with Windows credentials

Last week this was our major research item.How to make Silverlight call a WCF service which needs Windows authentication?

In the ideal scenario ,if the user is already logged in with right windows credentials the system(here Silverlight) should not ask for user name and password again.Silverlight should recognize the user and pass those credentials automatically into the WCF service.We implemented the WCF service with Windows credentials and made the hosting ASP.Net application's authentication to Windows.But it was asking for the user name and password when we call the service from Silverlight.Really that dialog is ugly when comparing to the rich UI of Silverlight.The reason for this is under normal circumstances Silverlight can't access the windows credentials of user.

Avoiding the windows login dialog box

After a tough research, one of my colleague find out a solution to get rid of this windows authentication dialog.The solution is simple.Just add the name of website where the service is hosted, into trusted sites collection of browser.

But this solution has a draw back.The end user has to do this configuration in browser.We can't always expect them to do this setting.So the better way is to create a Silverlight authentication page which accept the windows credentials and call a login service to authenticate the user using the provided credentials.Once we get the user name and password we can easily authenticate the user by calling some native methods.

So if the user has setup the browser settings the Silverlight won't show the authentication dialog.Else show the Silverlight dialog and ask user to enter his windows login details again.

Again another question comes, whether the user will/can trust the website which asks for his windows credentials ? In that scenario forget the rich UI of Silverlight show them the native windows login dialog box...

Some references

Happy Independence day to all My Indians.

Saturday, August 8, 2009

Some useful links to Prism

What is Prism

According to my understanding about prism ,it is nothing but a framework which implements a modularized environment for different application blocks or UI components. We can develop modules separately and plug into the different regions in UI.

Hope I can add my own articles when I the project starts.

Saturday, July 11, 2009

Silverlight 3 released

Download tools from here and enjoy...

Wednesday, July 8, 2009

Added F# support in Silverlight

According to wikipedia F# is a multi-paradigm programming language, targeting the .NET Framework, that encompasses functional programming as well as imperative object-oriented programming disciplines.
Now Silverlight also can take advantages of F# from F#'s May CTP onwards .

First you have to download and install the F# May CTP from here

Then install the templates from here

More details

Thursday, May 21, 2009

Whether Silverlight 3 application is running online or not

Just check the below mentioned property to know the network status of Silverlight application.We can do operations according to that.

There are 5 possible states which are defined in System.Windows.ExecutionStates

// Summary:
// Defines constants that indicate the state of an application that can run
// offline.
public enum ExecutionStates
// Summary:
// The application is running within its host Web page.
RunningOnline = 0,
// Summary:
// The application is in the process of detaching from its host Web page.
Detaching = 1,
// Summary:
// The application is running in offline mode, detached from its host Web page.
Detached = 2,
// Summary:
// The application is running in offline mode, but a newer version of the application
// has been downloaded and will be used the next time the application is launched.
DetachedUpdatesAvailable = 3,
// Summary:
// The application could not be detached from its host Web page.
DetachFailed = 4,

Tuesday, May 19, 2009

RoutedEvents for Silverlight 3

It is my pleasure to inform you that my colleague Andrew Whiddett at Identitymine has developed and released code for implementing Routed events in Silverlight 3.The code is available in Codeplex.See the below link.



Monday, March 30, 2009

Silverlight 3 Beta Local Messaging among Silverlight islands

If you have read my previous post about inter silverlight communication design you might seen how difficult it is to accomplish communication between 2 silverlight applications hosted in same page.But in Silverlight 3 Microsoft has introduced a new technique to do the communication.It is nothing but 2 classes.LocalMessageSender & LocalMessageReceiver.Now it is very easy to accomplish communication between islands of Silverlight contents.

Implementing Local messaging between silverlight applications
As like in other communication scenarios here also there should be a source and destination which sends and receives respectively.LocalMessageSender class sends a string message and LocalMessageReceiver receives the same.At the time of sending we should specify the name of the receiver.Also at the time of listening for message we should give the name of receiver.ie it denotes which messages it should capture based on the receiver name.
LocalMessageSender : The constructor of this class accepts the receiver name.To send the message we have to use the method SendAsync.The SendCompleted event is fired after completion of sending process.
LocalMessageReceiver : The constructor of this class also got a parameter to specify the receiver name.MessageReceived is the event which will fire when a message comes with the corresponding receiver name.After subscribing into this event the Listen Method need to be called in order to start listening.

Creating Visual Studio Solution structure
Here I have used 3 projects 2 Silverlight projects one is source and next is destination,and one asp.net application which hosts these 2 Silverlight applications.


<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div  style="height:100%;">
<asp:Silverlight ID="Silverlight1" runat="server" 
Source="~/ClientBin/LocalMessagingSource.xap" MinimumVersion="3.0.40307.0" 
Width="400" Height="100"/>
Your html contents goes here..
<h3>Sub heading</h3>
<div  style="height:100%;">
<asp:Silverlight ID="Silverlight2" runat="server" 
Source="~/ClientBin/LocalMessagingDestination.xap" MinimumVersion="3.0.40307.0" 
Width="400" Height="100" />

 MainPage.xaml in project LocalMessageSource

<UserControl x:Class="LocalMessagingSource.MainPage"
<Grid x:Name="LayoutRoot"
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<TextBlock Grid.ColumnSpan="2"
HorizontalAlignment="Center">I am sender</TextBlock>
<TextBlock Grid.Row="1">Message</TextBlock>
<TextBox Grid.Row="1"
Text="" />
<Button Grid.Row="2"
Click="Button_Click" />
<TextBlock x:Name="txtStatus"
Grid.Column="1" />

MainPage.xaml.cs in project LocalMessageSource

private void Button_Click(object sender, RoutedEventArgs e)
LocalMessageSender msgSender = new LocalMessageSender("receiver");
msgSender.SendCompleted += new EventHandler<SendCompletedEventArgs>(msgSender_SendCompleted);

void msgSender_SendCompleted(object sender, SendCompletedEventArgs e)
txtStatus.Text = "Send";

MainPage.xaml.cs in project LocalMessageDestination

<UserControl x:Class="LocalMessagingDestination.MainPage"
<Grid x:Name="LayoutRoot"
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<TextBlock Grid.ColumnSpan="2"
HorizontalAlignment="Center">I am receiver</TextBlock>
<TextBlock Text="Received messag"
Grid.Row="1" />
<TextBox x:Name="txtMessage"
Grid.Column="1" />

MainPage.xaml.cs in project LocalMessageDestination

public MainPage()
LocalMessageReceiver receiver = new LocalMessageReceiver("receiver");

receiver.MessageReceived += new EventHandler<MessageReceivedEventArgs>(receiver_MessageReceived);

void receiver_MessageReceived(object sender, MessageReceivedEventArgs e)
txtMessage.Text = e.Message;

Sample can be downloaded from here.

There are so many options with this messaging APIs such as domain blocking etc.You can send to some specific domains by using these options.More details later…

NB:This post is written using Silverlight 3 Beta.Things may change in Actual release.