WCF Services and Silverlight

After looking at WPF the other week I thought being a web developer it would be beneficial to look at Silverlight.  One of the first things I was interested to try was to access the server’s file system from the Silverlight application. I quickly found out that this wasn’t possible so I decided to create a WCF service hosted in the web application running my Silverlight application to access the file system for me.

To use a WCF service in Silverlight it must use basicHttpBinding. In Visual Studio you can add a ‘Silverlight-enabled WCF Service’ from the Silverlight category which creates a service using basicHttpBinding as default.

I created a simple service method called GetDirectories which returns an array of directory names within a given location.

 

public string[] GetDirectories()
{
    string path =  ConfigurationManager.AppSettings["GalleryDir"];
    IList<string> directories = new List<string>();

    foreach (string directory in Directory.GetDirectories(path))
        directories.Add(directory);

    return directories.ToArray();
}

After adding my service reference and creating an instance of my proxy I noticed that it did not contain the method GetDirectories. Instead I have GetDirectoriesAsync and an event called GetDirectoriesCompleted. This is cool as all service calls with Silverlight are asynchronous.

 

public Directories()
{
    InitializeComponent();

    GalleryContractClient proxy = new GalleryContractClient();
    proxy.GetDirectoriesCompleted += new EventHandler<getDirectoriesCompletedEventArgs>(proxy_GetDirectoriesCompleted);
    proxy.GetDirectoriesAsync();
}

void proxy_GetDirectoriesCompleted(object sender, GetDirectoriesCompletedEventArgs e)
{
    foreach (string directory in e.Result)
        tvDirectories.Items.Add(directory);
}

The Result property of GetDirectoriesCompleteEventArgs has the response from the request.

Posted on by Joe in Silverlight, WCF

Add a Comment