Showing posts with label Silverlight 3. Show all posts
Showing posts with label Silverlight 3. Show all posts

Wednesday, March 3, 2010

Silverlight Installation issues I faced

Here are some details about the installation issues which I faced when tried to setup my machine for Silverlight 4 with Visual studio 2010. No need to read further, if you are able to setup your machine with Silverlight 3 + VS 2008 and Silverlight 4 + VS 2010 without issues ;-)

After the completion of previous project which is done in VSTS 2008 and Silverlight 3 we decided to port the same to Silverlight 4.According to my knowledge it is difficult to have 2 versions of Visual studio if any version of them are in beta.Here to work with Silverlight 4 we need Visual studio 2010 beta 2.So normally I uninstalled Silverlight 3 and  started uninstalling VS 2008.

Everything went fine until my onsite counterpart called and asked me to setup my machine with VS 2008 + Silverlight 3and VSTS2010 beta 2 + Silverlight 4 beta .The reason was simple.We may need to support client for the previous project.The good news was he setup his machine with the above mentioned configuration.

So I stopped the uninstallation of VSTS 2008.Seems the problems started here.Started installation of Silverlight 3.Got the simple error message.Not able to complete the installation.Log says a previous version of Silverlight is there.Tried with different versions of Silverlight 3 which were available with colleagues.Hours passed with Uninstallations, Installations and reboots.Finally downloaded the Silverlight 3 version from net and tried.That too not worked out.

As usual I asked Google what is this error message by pasting the installation log in search box.Got a good link with Silverlight error messages and their solutions.

Silverlight 3 installation Error messages : http://blogs.msdn.com/amyd/archive/2009/03/19/silverlight-tools-installation-error-codes.aspx

I figured out that there are 2 patches which are stopping me from installation.They are KB967143 and KB956453 and the solution was to manually uninstall those.But when I tried uninstalling it said “Update removal was disallowed by policy”.What policy ? Its My machine and my login with admin privileges.I haven’t set any policy.

After a google I came to know more things about the patches.There are different types of patches and these patches fall into UNINSTALLABLE patch category.The only solution was to reinstall the application without applying those patches.

Uninstallable patches:http://msdn.microsoft.com/en-us/library/aa372102%28VS.85%29.aspx

Again uninstalling and installing VS 2008.Then Silverlight 3.Next series was VS 2010 beta 2 and Silverlight 4 beta.Tested whether the old project is running or not in VS 2008 and creation of Silverlight 3 and 4 projects in VS 2008 and VS 2010 respectively.Overall cost - a weekend and 2 week days.

Sometimes I am getting error message “VB.Net compiler is not responding” when I compile Silverlight 3 projects in VS 2008.But not consistent.Other than that everything works perfect.

Saturday, February 27, 2010

Return of the blogger

I was not able to blog more after joining my current company because of an important project.That project was in Silverlight 3 to show an existing big business application can be ported to Silverlight 3 and runs properly.

We achieved our goal this week and the client accepted the same.According to my small experience that project will be the biggest business application ever built using Silverlight or even RIA technologies.Sorry I am not in a position to tell any more details about that application due to NDA.

Anyway we are progressing to port the same to Silverlight 4 and the research for that is already started. Thats it for now.Stay subscribed for more news. 

Sunday, January 17, 2010

Performance optimization in Silverlight 3

Just now got a good link in MSDN for performance optimization in Silverlight 3 applications.

http://msdn.microsoft.com/en-gb/library/cc189071%28VS.95%29.aspx

Don’t know when can I get a chance to apply this in my current project :-(

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"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:SL_LambdaInConverter">
    <UserControl.Resources>
        <local:LambdaConverter x:Key="lambda" />
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot">
        <TextBlock 
            Text="{Binding Converter={StaticResource lambda},ConverterParameter='dt=>dt.ToString()'}" />
    </Grid>
</UserControl>
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

http://www.silverlight.net/learn/mobile/
http://en.wikipedia.org/wiki/Windows_Mobile#Windows_Mobile_7

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();
    catalog.AddModule(typeof(MarkModule));
    catalog.AddModule(typeof(StudentsListModule));
    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.

<modularity:ModuleCatalog 
    x:Class="Students.StudentsModuleCatalog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:modularity="clr-namespace:Microsoft.Practices.Composite.Modularity;assembly=Microsoft.Practices.Composite">
 
    <modularity:ModuleInfo 
        ModuleName="StudentsListModule"
        ModuleType="Students.StudentsListModule, Students, Version=1.0.0.0" />
    <modularity:ModuleInfo 
        ModuleName="MarKModule"
        ModuleType="Students.MarkModule, Students, Version=1.0.0.0" />
 
</modularity:ModuleCatalog>

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.

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.

Samples
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...

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.
Application.Current.ExecutionState

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,
}

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.

Default.aspx

<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"/>
</div>
<div>
Your html contents goes here..
<h1>Heading</h1>
<h3>Sub heading</h3>
<p>contents</p>
</div>
<div  style="height:100%;">
<asp:Silverlight ID="Silverlight2" runat="server" 
Source="~/ClientBin/LocalMessagingDestination.xap" MinimumVersion="3.0.40307.0" 
Width="400" Height="100" />
</div>
</form>


 MainPage.xaml in project LocalMessageSource


<UserControl x:Class="LocalMessagingSource.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid x:Name="LayoutRoot"
Background="AliceBlue"
Height="100"
Width="400">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.ColumnSpan="2"
HorizontalAlignment="Center">I am sender</TextBlock>
<TextBlock Grid.Row="1">Message</TextBlock>
<TextBox Grid.Row="1"
x:Name="txtMsg"
Grid.Column="1"
Text="" />
<Button Grid.Row="2"
Content="Send"
Click="Button_Click" />
<TextBlock x:Name="txtStatus"
Grid.Row="2"
Grid.Column="1" />
</Grid>
</UserControl>


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);
msgSender.SendAsync(txtMsg.Text); 
}

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


MainPage.xaml.cs in project LocalMessageDestination


<UserControl x:Class="LocalMessagingDestination.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400"
Height="100">
<Grid x:Name="LayoutRoot"
Background="LightGoldenrodYellow">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.ColumnSpan="2"
HorizontalAlignment="Center">I am receiver</TextBlock>
<TextBlock Text="Received messag"
Grid.Row="1" />
<TextBox x:Name="txtMessage"
Grid.Row="1"
Grid.Column="1" />
</Grid>
</UserControl>


MainPage.xaml.cs in project LocalMessageDestination

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

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

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.

Saturday, March 28, 2009

Silverlight 3 Beta Deep linking using Navigation application

The main disadvantage of earlier RIA technologies like Flash and Silverlight 2 was the absence of Deep linking.ie we can’t maintain a link to a specific screen or page in the RIA application.We can see just same URL even we change screens or pages in RIA application.Hence we can’t give a specific url to somebody or book mark that screen by url.Each time when the RIA application loads we have to navigate again to reach a specific page.That is very much time consuming.
Eg: If we want to have a profile page in our application how will we handle that in ASP.Net ? it’s simply addressed by using a page called profile.aspx with querystring ?id=10
This was not possible in Silverlight until the release of Silverlight 3 and it’s Navigation application support.With the introduction of navigation support we can maintain constant links to specific screens in the Silverlight RIA application.Hence we can distribute that link and bookmark that Silverlight page.

Creating a deep linked address book application using Silverlight
Since the main aim is to demonstrate deep linking ,I am using a simple Person class with properties Id ,Name and Address.The data storage is an Xml file.Here is the Person class.

public class Person
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }


Designing Data access
The PersonDataContext class provides the required Data.AllPersons and GetPersonById are the members which returns collection of all persons and Person by id respectively.


public class PersonDataContext
{
    XDocument _doc;
    private XDocument XmlDoc
    {
        get
        {
            if (_doc == null)
            {
                 _doc = XDocument.Load("Persons.xml");
            }
            return _doc;
        }
    }
    public IEnumerable<Person> AllPersons
    {
        get
        {
            return from li in XmlDoc.Root.Elements()
                   select new Person()
                   {
                       ID = Convert.ToInt32(li.Attribute("Id").Value),
                       Name = li.Attribute("Name").Value,
                       Address = li.Attribute("Address").Value
                   };
        }
    }
    public Person GetPersonById(int id)
    {
        XElement ele= XmlDoc.Root.Elements().First(s => s.Attribute("Id").Value == id.ToString());
        Person person=null;
        if(ele !=null)
        {
            person = new Person()
            {
                ID = Convert.ToInt32(ele.Attribute("Id").Value),
                Name = ele.Attribute("Name").Value,
                Address = ele.Attribute("Address").Value
            };
        }
        return person;
    }
}


Building User Interface

We are using a ListBox to display the list of persons in the HomePage.xaml.The ItemTemplate of the ListBox contains a hyperlink button and its NavigateUri is binded to Person object using a converter named Person2UriConverter.We are using a converter because the NavigateUri expects a object of type Uri.One more thing is that we don’t have path to details page in Person class.So we used a converter which combines the page url with the newly created name value pair.

HomePage.xaml


<navigation:Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
                 xmlns:local="clr-namespace:AddressBook"
                 x:Class="SilverlightApplication1.HomePage"
                 xmlns:conv="clr-namespace:AddressBoook.Converters"
                 Title="HomePage Page">
    <navigation:Page.Resources>
        <conv:Person2UriConverter x:Key="p2uri" />
        <local:PersonDataContext x:Key="PersonDataContextDataSource" />
        <DataTemplate x:Key="personDT">
            <StackPanel>
                <HyperlinkButton Content="{Binding Name}" NavigateUri="{Binding Converter={StaticResource p2uri}}"></HyperlinkButton>
            </StackPanel>
        </DataTemplate>
    </navigation:Page.Resources>
    <Grid x:Name="LayoutRoot" Background="White" >
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <ListBox DataContext="{Binding Source={StaticResource PersonDataContextDataSource}}"
                 ItemsSource="{Binding Mode=OneWay, Path=AllPersons}"
                 ItemTemplate="{StaticResource personDT}" Grid.Row="1" />
        <TextBlock Text="Home" Style="{StaticResource HeaderTextStyle}"/>
    </Grid>
</navigation:Page>



Person2UriConverter.cs


public class Person2UriConverter:IValueConverter
    {
        #region IValueConverter Members
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Person person = value as Person;
            string localpath = System.Windows.Browser.HtmlPage.Document.DocumentUri.LocalPath;
            return new Uri(localpath+"#/Views/Person.xaml?id="+person.ID,UriKind.RelativeOrAbsolute);
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        #endregion
    }


Now we made the display of listbox with all persons.Now when run and click on the person link we can see the new url as http://localhost:61838/SilverlightApplication1TestPage.aspx#/Views/Person.xaml?id=1.It won’t display anything since there is no Person.xaml.Create the Person.xaml page which is going to be the detail view.

Creating detail page Person.xaml

Here the idea is to get the query string parameter id and load the Person class.This Person class is set as DataContext of the newly created a Page called Person.xaml where it is going to display the details.DataContext is setting on the overriden method OnNavigateTo.

Person.xaml.cs


// Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            int personId = Convert.ToInt32(this.NavigationContext.QueryString["id"]);
            this.DataContext = new PersonDataContext().GetPersonById(personId);
        }


Person.xaml

<navigation:Page x:Class="SilverlightApplication1.Views.Person" 
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
           xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           Title="Person Page">
    <Grid x:Name="LayoutRoot"
          Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TextBlock Text="ID" />
        <TextBox Grid.Column="1"
                 Text="{Binding ID}" />
        <TextBlock Grid.Row="1"
                   Text="Name" />
        <TextBox Grid.Row="1"
                 Grid.Column="1"
                 Text="{Binding Name}" />
        <TextBlock Grid.Row="2"
                   Text="Address" />
        <TextBox Grid.Row="2"
                 Grid.Column="2"
                 Text="{Binding Address}" />
    </Grid>
</navigation:Page>



Now when we click on the Person link we will get the detail page Person.XAML.Now you can distribute the URL to your friends and you can yourself use that as bookmark in your browser.

Sample can be downloaded from here.