Sunday, December 25, 2011

How to get unrestricted access in Silverlight 5

As you all know Silverlight 5 released with unrestricted access in InBrowser mode which gives full control to the Silverlight developers in the client machine. This post is to describe what are the changes you need to do at the server side as well as client side to leverage the trusted application feature.
  • Server side
    1. Make the IB elevated from project properties
    2. Sign the xap using certificate.

    1. Client side
      1. Install the cert into “trusted publishers”
      2. Change the reg key “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Silverlight\AllowElevatedTrustAppsInBrowser” to 1
      3. The “Protected mode” of browser should be turned off for the zone.
    The above steps are mainly for Silverlight 4 to Silverlight 5 conversion and want to get the full trust support. If you just upgrading your projects there is no need to do above items. Just open in Visual Studio 2010 after installing the SL 5 tools.It will show the conversion wizard and just follows that. One thing you need to make sure is the reference path to Sl 5 assemblies.

    Steps to setup Silverlight 5 application to have unrestricted access in IB using elevated trust mode

    Ok.Now lets look at details of how we can create new SL project which access a file from c:\ in the In-Browse mode.First as usual create a Silverlight 5 Application. Then place a Button inside and wire the Click event handler.Write the below code in the handler to write a file to c:\

    private void btnWriteToCDrive_Click ( object sender, RoutedEventArgs e )
        File.WriteAllText(@"c:\FromSL5.txt","This is written from Silverlight 5 web application in InBrowser mode");

    Giving Elevated trust to SL 5 application

    Just to go to the Silverlight 5 project properties and in the Silverlight tab check the “Require elevated trust when running in-browser” check box.See the below screen shot for reference.

    Signing the xap

    Next step is to sign the xap file with a certificate. Just goto Silverlight project properties and check the “Sign the Xap File” check box.If you don’t have any certificate just create a new one using the “Create Test Certificate” button.

    Disable the browser protected mode

    The above changes are mainly for the server side. You need to do some at client side as well.The first one is to disable the protected mode in browser.Goto the internet options and disable it.

    Change registry entry

    As mentioned above just change the registry entry as it is.If you cant find the key just add a DWORD and set to 1. Still I am not sure how this step is carried out in other platforms such as MAC and Linux.

    That’s it.Now run your application.It will create a file inside c:\ from in browser.Just uploaded the sample by removing the certificate as it give some information about my company laptop Smile

    Welcome to my general coding blog.

    Most probably this will be my last post in this Silverlight technology blog. It’s a hard decision to stop this blog and use my general coding blog for all the programming related posts. Still I don’t know why I started separate blogs for each technology.May be my knowledge in SEO at that time lead me to have a new blog with technology name in the URL.Anyway changes are needed and I think this is the time to afford that. If possible I will post a last good bye post .Anyway you can start following me in my coding blog where my new Silverlight posts will come soon and it is.
    Joymon v/s Code

    Sunday, December 11, 2011

    Silverlight 5 released !! more access or security threat

    Finally it is released. Earlier than expected.'s-new-in-silverlight-5

    Nobody said that this is the final version in the Silverlight line as a web technology.But it can be because  Microsoft as a product company started promoting HTML 5.Look at their new OS windows 8. We can even write native windows applications using HTML5 and javascript.

    For the developers who still think that Silverlight will be available for long as a web technology, I have a small story .No its not a story its the history of web applications which brought RIA.

    The History of RIA

    Long long ago when speed of the internet connectivity was in single digit Kb/s, developers created browsers and people started using it. The job of the browser was simple. Get a server address known as URL from the user then retrieve some text from that URL address using socket and port, mainly port 80 and show that text to the user. If the retrieved text contains any markup tags, format the text between the start and end tag according to a name of the tag. That tagging or formatting language known as HTML.

    Later there came a scripting language which is executed by the browsers .This make people embed some code which will understand the page and even can modify the web page during runtime. But different browsers supported the language in different ways which made it difficult to write programs.

    Years passed .The speed of internet connection started expressing in double digits and at some places the unit Kb/s changed to Mb/s along with the fall of connection cost. Then people started thinking about the shortcomings of the HTML. They figured that if they want to draw a curve there is no inbuilt option to draw other than putting an image which adds load to the downloading content.This also reduce the quality when the same page is opened in big screens with high resolution.Another scenario they faced was lack of an option to refresh small portion of page. This demanded the HTML to support more tags and specifications. The people / panel who decides on HTML told changing the HTML specs is a long process. We cannot change it overnight. It will takes years to evolve. You need to continue using the technology as is.

    Some smart people effectively utilized this scenario .They didn't go to change the HTML specifications or the way browser deals with the tags and javascript. They created their own system which has it own run time independent of browser ,programming language, designer applications etc...They just asked browser "Can we get some space in your page?" The browser agreed and in the borrowed space they started playing.

    Wow...That was the first impression from people who saw these plug-ins in their browser. Its great,lets put it everywhere.This made a good competition in RIA.RIA is the name given to this technology and it stands for Rich Internet Applications. Investments on RIA technology increased rapidly. Even some people started creating their entire application in RIA excluding the HTML. But one day..

    As agreed earlier the governing body of HTML, planned to release specs on new version called HTML 5. This has enough tags to support short comings of old HTML, specification for javascript and much more. The RIA world got panic first but after that it settled down and one of them said that they are stopping their RIA and you can have a tool which will convert your RIA applications to HTML 5. Another RIA vendor said you can even create desktop applications using HTML 5 and Javascript.

    Everybody accepted and the world became ready for HTML 5 .Isn't it?

    What is next with Silverlight 5

    Now Silverlight web developers can directly access so many resources at client side even in the InBrowser mode. From the application developer's view its a great help,but just think from the system admin's / security personal's  view. They need to open up machine to an outside web application which may take up anything from the system or do anything to the system. I agree that there are certificates and other security measures. But don't know why I can't fully agree with this which makes it less different than a desktop application.

    I guess in near future if Silverlight as web technology survives HTML 5 ,we can hear about Silverlight VIRUS or some threat which may make it unacceptable. But as a developer I love Silverlight as it is the technology in Windows Phone :-)

    Monday, August 29, 2011

    Silverlight local messaging issues with ‘\0’

    When we want to communicate between 2 Silverlight applications locally, we have a framework way to accomplish the same.Its nothing but 2 classes LocalMessageSender and LocalMessageReceiver.Recently we had faced an issue with local messaging system of Silverlight.The problem was LocalMessageSender sends a message without any exception but when LocalMessageReceiver receives the message, it is not the same message. Its not incorrect data, but the length itself reduced.
    We first checked the size of the message which we are sending.It not exceeding 40KB limit as per Microsoft.Then we started digging into the project specifics and could see that the data passed is binary it’s the data got from a BinarySerializer which is just using the BinaryWriter Class to make the data as binary.The investigation continued to find the character which says the end of the message at the receiver side. After couple of hours I got the character which is nothing but our famous ‘\0’ which was used in C & C++ to denote as end of string.
    Our binary serializer was adding this character while serializing the objects. Since the serializer internally uses BinaryWriter, this happens by the BinaryWriter when serializing numbers. I have checked .Net string specification and it says the string is represented using its length rather than the old ‘\0’ style. But don’t know why in local message sending, this is happening.
    You can reproduce it simply.Try to send the message "Joy\0George" it will transmit or receives only ‘Joy’.I am not sure which communication end is cutting the message.

    private void btnJSON_Click(object sender, RoutedEventArgs e)
    private void SendMessage(string serialized)
    LocalMessageSender sender = new LocalMessageSender("TestPoint");
    sender.SendCompleted += new EventHandler<SendCompletedEventArgs>(sender_SendCompleted);
    void sender_SendCompleted(object sender, SendCompletedEventArgs e)
    if (e.Error != null) MessageBox.Show(e.Error.ToString());

    Here is the receiving end.

    Private Sub ListenForMessage()
    Dim receiver As New LocalMessageReceiver("TestPoint")
    AddHandler receiver.MessageReceived, AddressOf Received
    End Sub
    Private Sub Received(ByVal sender As Object, ByVal e As MessageReceivedEventArgs)
    MessageBox.Show("Length " + e.Message.Length.ToString())
    DirectCast(sender, IDisposable).Dispose()
    End Sub

    Don’t confuse with the C# and VB.Net code.All will compile into same ILCode Smile.At the sending side the length will be 10 and receiving end the length will be 3 if we send the above mentioned string which has ‘\0’. 

    I can guess that Microsoft uses unmanaged modules to accomplish the communication which takes ‘\0’ as end of string. Anyway I have posted in Silverlight forums.

    Monday, August 22, 2011

    Adding custom EndPoint Behavior at client side ServiceReferences.ClientConfig

    A custom Endpoint behavior which implements IEndpointBehavior can be added for many purposes. That depends upon your requirements and the nature of the application you are working on. But interesting thing is you cannot add the EndpointBehavior through config in Silverlight 4. But supports addition of custom Endpoint Behaviors through code .ie after creating the proxy you may add the behavior to the Endpoint.Behaviors collection of proxy.As you know, here proxy is a derived class of ClientBase<T> and this class has the property Endpoint.

    Passing ClientBase<T> objects as method arguments
    Next question comes how to make the code to add end point more generic in order to reuse the code for all the WCF service we need to write a method which accepts ClientBase<T>.This is little tricky at first look .But please don’t go for dynamic keyword or object where we have a typed way.Here is the small code snippet to use ClientBase<T> as method parameter type in C#.

    private void CreateProxy()
    TestServiceReference.TestServiceClient client = new TestServiceReference.TestServiceClient();
    AddMyEndpointBahavior < TestServiceReference.ITestService>(client);
    private void AddMyEndpointBahavior<T>(ClientBase<T> client) where T :class
    client.Endpoint.Behaviors.Add(new MyEndpointBehavior());

    For VB.Net version see my general coding blog where I posted this first since it is more related to generics.

    Monday, August 15, 2011

    Changing Application.RootVisual at runtime

    If you are a Silverlight Island programmer, this will not applicable to you because you will never face a situation which demands to change the Application.RootVisual property. Don’t confuse the word Island programmer ,it simply refers to the programmers who are creating small sized Silverlight applications mainly with some animations to fit into a small portion of HTML page which may be static or emitted by technologies such as ASP.Net or PHP.

    Sometimes I feel that the Silverlight is more suited to Island programs than full window business apps. There are so many reasons.One is its rich user interface capabilities.This is more needed for glazy island apps than business apps. When we talk about great user experience there is always some cost attached to it which reduces performance. The performance is more important when we come to business apps than the user interface. In some of the tests we could see that the UI rendering takes more time than the WCF service in the whole display cycle. This happens when the data elements are huge in number but small and has complex data templates.

    Ok.Coming back to changing Application.RootVisual multiple times at runtime. There may be scenarios where you need to show your authentication UI first and then load your application XAPs and the actual UI pages. In this case you need to change the RootVisual for sure.But this is not supported by the Silverlight runtime. First of all if you simply change, it will not change.You will get the below exception when you try to set null first and assign another visual after that.

    Invalid value set for application's RootVisual

    ie the below code will result into System.InvalidOperationException' in System.Windows.dll

    'This will result in System.InvalidOperationException occurred in System.Windows.dll
    Application.Current.RootVisual = Nothing
    Application.Current.RootVisual = New TextBox With {.Text = "changed"}

    So what is the simple solution.Keep a ContentControl as your RootVisual and set your Login UI and Application UI pages as its content.In the Application_Startup event set a ContentControl as your RootVisual then add initial UI to that. Later cast the RootVisual as ContentControl and change its Content property.

    Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
    'Initial UI.Here its button
    Dim btnChangeRootVisual As New Button() With {.Content = "Change RootVisual"}
    AddHandler btnChangeRootVisual.Click, AddressOf btnChangeRootVisual_Click

    'ContentControl as RootVisual
    Me.RootVisual = New ContentControl() With {.Content = btnChangeRootVisual}
    End Sub
    Private Sub btnChangeRootVisual_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    'Get the ContentControl and assign new UI to its content property
    Dim rootContentControl As ContentControl = DirectCast(Application.Current.RootVisual, ContentControl)
    rootContentControl.Content = New TextBox With {.Text = "changed"}
    End Sub

    This is just a hack for real business application programmers of Silverlight.