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.
    http://www.silverlight.net/learn/overview/what'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 data.ie 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)
    {
    SendMessage("joy\0George");
    }
    private void SendMessage(string serialized)
    {
    MessageBox.Show("Length:"+serialized.Length.ToString());
    LocalMessageSender sender = new LocalMessageSender("TestPoint");
    sender.SendCompleted += new EventHandler<SendCompletedEventArgs>(sender_SendCompleted);
    sender.SendAsync(serialized);
    }
    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
    receiver.Listen()
    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 proxies.ie 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.

    Thursday, December 30, 2010

    TestComplete now supports Silverlight 4

    Today I got chance to work with TestComplete to automate a Silverlight application.

    http://www.automatedqa.com/blogs/post/10-12-09/TestComplete-8-10-Enhanced-Support-for-Silverlight-4-Applications.aspx

    If you need to get the support for Silverlight object recognition you need to patch your xap with a TestComplete utility. The patch just adds 2 dlls into your xap and updates the AppManifest.xaml file.

    We have an application which uses same code base for WPF as well as Silverlight .Hope our WPF test scripts will execute for testing Silverlight version as well.

    Monday, November 22, 2010

    Silverlight training - some questions

    After a while I had to conduct training in my company.Earlier it was WPF and now the topic is Silverlight.I dont know whether Silverlight training is relevant now because of HTML 5.According to me next version of ASP.Net may be 5.0 or 6.0 will emit html5 which may reduce the need of Silverlight in the RIA world.But in other context Silverlight is valuable because of Windows 7 mobile development.

    Anyway I have started training and conducted one small test in order to evaluate my students.I am not going to share their scores but some questions I have asked.

    • Which code snippet determines whether the Silverlight application is running inside browser or OOB?
      1. App.GetState()
      2. System.Windows.Application.Current.IsRunningOutOfBrowser
      3. System.AppDomain.CurrentDomain.IsRunningOutOfBrowser
      4. Silverlight.IsRunningOutOfBrowser
    • Can we create folder in IsolatedStorage? (Yes/No)
    • Can we redirect the browser to a ASPX/HTML page from Silverlight?(Yes/No)
    • What is possible in OOB without using COM objects?
      1. Access registry
      2. Access file from C: drive
      3. Access file from MyDocuments
      4. All
    • Is it possible to refer a WPF 4.0 dll in Silverlight? (Yes/No)
    • Where we normally specify the window less mode?                           
      1. Hosting HTML page
      2. App.xaml.vb
      3. MainPage.xaml.vb
      4. None of the above                           
    • Where is isolated storage located?
      1. Main memory of server
      2. Hard disk of client
      3. Main memory of client
      4. Database
    • Can <Resources> tag in a xaml page contain a boolean value?(Yes/No)
    • Can we write code behind of ABC.xaml in XYZ.vb? (Yes/No)
    • Can Silverlight application access ASP.Net Session variable?
    • How Silverlight application gets values from its browser host at initialization time?                               
      1. Through constructor of App class                               
      2. Through Environment.CommandLine property                               
      3. Using ProvideInitValues event                               
      4. None of the above
    • How to add a resource programatically?
      1. Me.Resources.Add(1, New SolidColorBrush(Colors.Green))
      2. Me.Resources.AddResource(1, New SolidColorBrush(Colors.Green))
      3. Me.AddResource("mycolor", New SolidColorBrush(Colors.Green))
      4. None of the above
    • What is the base class of UserControl class?                           
      1. Control
      2. UIElement
      3. DependencyObject
      4. UserControlBase      
    • How Silverlight application can access SQL database ?
      • Through SQLDataAdapter
      • Through ODBC connection
      • Using WebService
      • Using Windows service     
    • Last question was to create a simple <Grid> based layout of a login page.

    If you are a Silverlight developer you may feel that some questions are silly or too simple.But my students are in different categories.Some had projects in Silverlight others are hearing word Silverlight for the first time.So its a mix and people can just start learning concepts even if they are not able to answer.

    Hope I don’t have to provide answers to these questions since all are known.Let me know if anybody needs clarification.

    NB: These are not Silverlight interview questions and I think nobody will ask these type of questions in interview.

    Tuesday, October 5, 2010

    Why it is asking to update Silverlight version

    So  many times I have seen this type of messages in dev environment.Now understood what was the reason..I was doing the same without knowing the actual facts.

    http://timheuer.com/blog/archive/2010/09/28/keeping-your-silverlight-dev-environment-stable-through-service-releases.aspx

    Monday, September 27, 2010

    Getting Silverlight version

    Here is the post which gives you how to get the Silverlight version through Javascript.
    http://www.kunal-chowdhury.com/2010/09/how-to-detect-installed-silverlight.html

    If you want to get the Silverlight version inside Silverlight code you may invoke this function as follows.
    http://silverlightedweb.blogspot.com/2008/05/silverlight-javascript-communication.html

    Saturday, September 18, 2010

    Silverlight security aspects

    The below link explains the security aspects of Silverlight. ie differences among the Transparent code,Safe critical code and Critical code along with the theory of user initiation.

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

    Monday, September 13, 2010

    Using dynamic keyword in browser interaction

    In my general code blog I talked about usage of dynamic keyword in Silverlight browser interaction applications.Here is the sample with source.

    Generally the browser interaction is used to communicate with the browser elements from Silverlight application.Its not at all type safe.So we use the general methods like SetProperty to talk to the com objects.

    The 'innerText' property isn't defined at compile-time - it's a Javascript property on the div. The way to do this without the dynamic keyword is:

    var myDiv = HtmlPage.Document.GetElementById("myDiv");
    myDiv.SetProperty("innerText", "Text was replaced!");


    We can replace the SetProperty as the real property usage if we use the dynamic keyword.

    dynamic myDiv = HtmlPage.Document.GetElementById("myDiv");
    myDiv.innerText = "Text was replaced!";


    Download the sample from here

    Sunday, August 8, 2010

    Single window F1 help in Silverlight

    I know the title is confusing.You will know why I gave this title when you read further.When we talk about the Rich Internet Application we could see that they are half desktop and half web.The UI resembles a desktop application but they behave like web applications.

    As we know all the desktop applications comes with a help.We all would like to have a help popup on F1 key when we are struck on a desktop’s functionality. The same applies to RIA.Due to its richness like desktop we should have a F1 help window.This post talks about implementing a F1 help window for Silverlight applications.

    Basically we need to capture the F1 key and show a popup.I don’t think people expects a huge hlp file on F1 because this is web and downloading a big file will take time.So better we can choose html or asp.net based help which are context based and easy to load. Now the things are simple just show a html popup on F1 press.

    Here I am adding one good feature of Silverlight.Attached properties. This extends one class by introducing a new property implemented in another class.I am not going into details of attached properties.We can write a HelpProvier class which holds the attached property so that we can set the help source as follows from anywhere in our application.

    <UserControl x:Class="F1Help.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:F1Help">
    <Grid x:Name="LayoutRoot" Background="White" local:HelpProvider.Source="help.htm">
    <TextBox Text="Enter the datas here"></TextBox>
    </Grid>
    </UserControl>


    Lets see how the HelpProvider is processing the F1 key.

    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 System.Windows.Browser;

    namespace F1Help
    {
    public class HelpProvider
    {
    public static Uri GetSource(DependencyObject obj)
    {
    return (Uri)obj.GetValue(SourceProperty);
    }
    public static void SetSource(DependencyObject obj, Uri value)
    {
    obj.SetValue(SourceProperty, value);
    }
    public static readonly DependencyProperty SourceProperty =
    DependencyProperty.RegisterAttached("Source", typeof(Uri), typeof(HelpProvider), new PropertyMetadata(OnSourcePropertyChanged));
    public static void OnSourcePropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
    if (e.NewValue != null && e.NewValue is Uri)
    {
    FrameworkElement element = sender as FrameworkElement;
    element.KeyDown+=new KeyEventHandler(element_KeyDown);
    }
    }
    static void element_KeyDown(object sender, KeyEventArgs e)
    {
    if (e.Key == Key.F1)
    {
    e.Handled = true;
    e = null;
    if (GetSource(sender as DependencyObject) != null)
    {
    ShowHelpFile(GetSource(sender as DependencyObject));
    }
    }
    }
    private static void ShowHelpFile(Uri source)
    {
    HtmlPage.Window.Navigate(source, "new");
    }
    }
    }


    The code is self explanatory.In the property changed method we are subscribing to the keydown event of the UIElement which requested help implementation.The event handler shows the htm file in a popup.Simple…

    But you can see yourself this is not as simple as we thought when you run the app.F1 will show our help as well as browser help.The user needs our help only when he is in our application.So we need to avoid browser help at any cost.What to do? I know what everybody thinking as web developers.Yes Javascript…


    function HideHelp() {
    document.onhelp = function () { return (false); }
    window.onhelp = function () { return (false); }
    }


    Call this function on document.onload.This is tested only in IE 8.Sample can be downloaded from here.

    Monday, May 17, 2010

    Location of OOB xap file in local file system

    Everybody knows that there is Out of browser support in Silverlight 3 and Silverlight 4.Basically how it is working? Its simple.It downloads the xap file into a local folder and runs the xap from that location as similar to in browser.But with some more privileges.

    All that are fine.So to which location the xap files is getting downloaded in my local machine? It’s very easy to find out.Right click on the OOB application icon in desktop and get select properties.You can get the application id.Using that application id you can find the application folder in the Out-of-browser cache in the below location.

    C:\Users\<login id>\AppData\Local\Microsoft\Silverlight\OutOfBrowser

    Saturday, April 24, 2010

    Silverlight 4 RichTextBox lab

    Got the below lab when I was looking for the usage of RichTextBox in Silverlight 4.This gives an idea how to use RichTextBox.

    http://channel9.msdn.com/learn/courses/Silverlight4/NewFeatures/RichTextBox/

    More labs here

    Wednesday, April 21, 2010

    Parser internal error: Object writer 'xClassNotDerivedFromElement'

    If you are a Silverlight developer there is a chance that you may get the exception “Parser internal error: Object writer 'xClassNotDerivedFromElement'” very rarely which is difficult to track.Even you can’t put break points to track this.As a developer you will google the same.But most probably you will not get any results.

    Only thing went wrong here is the namespace.But this is not at all mentioned in any of the exception details.ie The project which you are working on will not have a namespace or somebody in the project might forgot put the namespace in XAML or code files.

    So make sure that there is namespace present in the project and the xaml files are correctly mapped to the corresponding code files in the x:Class attribute.

    Note : We cannot have Silverlight projects without namespace.

    I came to see this exception when one of my colleagues tried to write code which should  compile in both Silverlight 4 and WPF 4.

    Saturday, March 20, 2010

    Creating WCF proxy without reference

    The problem : Creating WCF proxy in Silverlight without using the add service reference and it’s auto generated code

    It was a debate that whether we can call a WCF service from Silverlight without using “Add Service Reference” menu item.In WPF or in the other .Net environments it is easy.We just need to refer the contracts dll and write a class which inherits from ClientBase.But this is Silverlight - A different runtime.

    A Normal WCF service reference with all the generated code files

    There were 3 opinions.Not at all possible,Possible with less amount of code,Possible if we create all those classes by our own.Just avoid the last one because that doesn’t give us any benefit as it is just making the process manual.

    One of my Colleagues started research on that and was able to achieve the same.I am just sharing the idea.

    Solution : We can achieve the same using contract interface,proxy class and a custom eventargs class

    First of all there are no changes at the server side.Only 3 types we are going to write at client side which will be present in the reference.cs file if you create the proxy using “Add Service Reference” Dialog.

    There will be a question for sure.Why are we writing the code which is being auto generated ? Why don’t we create a reference using the dialog and copy paste the reference.cs code?

    The answer for both the questions is same.You can create reference using the dialog and get the code from reference.cs.That is enough.

    Advantages

    • Can avoid huge amount of code which is auto generated.
    • This is acting as a separate layer and can encapsulate operations here in future.

    Implementation steps

    Lets take example of implementing a DataService with one method GetData which returns a string.Don’t bother about the server side.Use the same.Below are the steps to perform at client side ie Silverlight side.

    1. Create interface IDataService
      1. Decorate with ServiceContract attribute.
      2. Add method BeginGetData.Decorate it with OpertionContract and Set AsyncPattern to True.
      3. Add Method EndGetData.
        Imports System.ServiceModel

        <ServiceContract()> _
        Public Interface IDataService
        <OperationContract(AsyncPattern:=True)> _
        Function BeginGetData(ByVal callback As System.AsyncCallback, ByVal asyncState As Object) As System.IAsyncResult
        Function EndGetData(ByVal result As System.IAsyncResult) As String
        End Interface





    2. Create eventArgs class deriving from System.ComponentModel.AsyncCompletedEventArgs


      1. Add required properties to pass values.

        Public Class GetDataCompletedEventArgs
        Inherits System.ComponentModel.AsyncCompletedEventArgs

        Private results() As Object

        Public Sub New(ByVal results() As Object, ByVal exception As System.Exception, ByVal cancelled As Boolean, ByVal userState As Object)
        MyBase.New(exception, cancelled, userState)
        Me.results = results
        End Sub

        Public ReadOnly Property Result() As String
        Get
        If Me.results IsNot Nothing Then
        Return CType(Me.results(0), String)
        End If
        Return Nothing
        End Get
        End Property
        End Class




    3. Create class DataServiceProxy derived from ClientBase which Implements IDataService.Write constructors.Implement methods.Write delegates and event which communicate back to the caller.



    Public Class DataServiceProxy
    Inherits ClientBase(Of IDataService)
    Implements IDataService
    #Region " Constructors"
    Public Sub New()
    MyBase.New()
    End Sub

    Public Sub New(ByVal endpointConfigurationName As String)
    MyBase.New(endpointConfigurationName)
    End Sub

    Public Sub New(ByVal endpointConfigurationName As String, ByVal remoteAddress As String)
    MyBase.New(endpointConfigurationName, remoteAddress)
    End Sub

    Public Sub New(ByVal endpointConfigurationName As String, ByVal remoteAddress As System.ServiceModel.EndpointAddress)
    MyBase.New(endpointConfigurationName, remoteAddress)
    End Sub

    Public Sub New(ByVal binding As System.ServiceModel.Channels.Binding, ByVal remoteAddress As System.ServiceModel.EndpointAddress)
    MyBase.New(binding, remoteAddress)
    End Sub
    #End Region

    #Region "GetData"
    Private onBeginGetDataDelegate As BeginOperationDelegate
    Private onEndGetDataDelegate As EndOperationDelegate
    Private onGetDataCompletedDelegate As System.Threading.SendOrPostCallback
    Public Event GetDataCompleted As System.EventHandler(Of GetDataCompletedEventArgs)

    Public Function BeginGetData(ByVal callback As System.AsyncCallback, ByVal asyncState As Object) As System.IAsyncResult Implements ServiceContracts.IDataService.BeginGetData
    Return MyBase.Channel.BeginGetData(callback, asyncState)

    End Function

    Public Function EndGetData(ByVal result As System.IAsyncResult) As String Implements ServiceContracts.IDataService.EndGetData
    Return MyBase.Channel.EndGetData(result)
    End Function

    Private Function OnBeginGetData(ByVal inValues() As Object, ByVal callback As System.AsyncCallback, ByVal asyncState As Object) As System.IAsyncResult
    'Dim engID As String = CType(inValues(0), String)
    'Dim libraryID As String = CType(inValues(1), String)
    'Dim folderName As String = CType(inValues(2), String)
    'Dim parentFolder As PathInfo = CType(inValues(3), PathInfo)
    'Dim folderGeneralProperties As FolderGeneralProperties = CType(inValues(4), FolderGeneralProperties)
    'Dim additionalProperties As System.Collections.Generic.Dictionary(Of String, String) = CType(inValues(5), System.Collections.Generic.Dictionary(Of String, String))
    Return CType(Me, IDataService).BeginGetData(callback, asyncState)
    End Function

    'Private Function GetData() As String Implements IDataService.GetData
    'Return MyBase.Channel.GetData()
    'End Function

    Private Function OnEndGetData(ByVal result As System.IAsyncResult) As Object()
    Dim retVal As String = CType(Me, IDataService).EndGetData(result)
    Return New Object() {retVal}
    End Function

    Private Sub OnGetDataCompleted(ByVal state As Object)
    'If Not (GetDataCompleted Is Nothing) Then
    Dim e As InvokeAsyncCompletedEventArgs = CType(state, InvokeAsyncCompletedEventArgs)
    RaiseEvent GetDataCompleted(Me, New GetDataCompletedEventArgs(e.Results, e.Error, e.Cancelled, e.UserState))
    'End If
    End Sub

    Public Overloads Sub GetDataAsync()
    If (Me.onBeginGetDataDelegate Is Nothing) Then
    Me.onBeginGetDataDelegate = AddressOf Me.OnBeginGetData
    End If
    If (Me.onEndGetDataDelegate Is Nothing) Then
    Me.onEndGetDataDelegate = AddressOf Me.OnEndGetData
    End If
    If (Me.onGetDataCompletedDelegate Is Nothing) Then
    Me.onGetDataCompletedDelegate = AddressOf Me.OnGetDataCompleted
    End If
    MyBase.InvokeAsync(Me.onBeginGetDataDelegate, New Object() {}, Me.onEndGetDataDelegate, Me.onGetDataCompletedDelegate, Nothing)
    End Sub
    #End Region
    End Class



    Uploaded a sample which does the same.

    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.

    Tuesday, March 2, 2010

    Add Reference is empty in Silverlight 4 Beta

    As I told in the last post ,I have started with the Silverlight 4 research using Visual Studio 2010 beta 2 .The first thing I noted is the add reference box in Silverlight project is empty.

    According to Microsoft this is a bug and has fixed.
    Workaround
    In the add reference dialog manually browse the dll from the folder [Install Drive]:\Program Files\Microsoft SDKs\Silverlight\v4.0\Libraries\Client

    https://connect.microsoft.com/VisualStudio/feedback/details/520040/missing-list-of-components-from-add-reference-in-silverlight-4-0-projects
    http://forums.silverlight.net/forums/p/150240/335233.aspx

    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. 

    Friday, January 29, 2010

    Silverlight Media Framework v1.1 Released

    This open source framework will make developer’s work much easier when they develop a media player for Silverlight.

    More details in codeplex along with videos shows how to use it.