Archive

Archive for the ‘Silverlight’ Category

A Parser for Formatted Text in WPF / Silverlight

November 5th, 2010

I finally got round to implement on-the-fly text formatting for Sketchables, which will  allow you to define text formatting while typing (similar to wikis or forum posts). Sketchables will parse such strings and format them on the fly for you:

the star renders *bold* text

I didn’t rely on regular expressions here, but wrote a simple forwarding parser to process markup text. As it makes a pretty neat tool, I extracted it into a little sample app that shows a possible use for it. The presented implementation just creates nested text blocks, but you should be able to easily adjust it to your needs.

 

image

Latest Update:  2010.11.07 – Fixed issue with single character chunks.

Download Sample Application

Sketchables 0.9 – Public Preview Release

July 20th, 2010

I wanted to officially release Sketchables weeks ago, but business just got in the way – and it turned out that my plan to just working at night / on weekends didn’t work either because, well, business got in the way there, too.

However, my deadline ends in little more than a week (and I’ll have quite some time at my hands in August), so I’ll be able to finally package Sketchables, record some more videos, and of course add a few goodies. For now, I’ve prepared a preview release of the package which already works quite solid:

 

Sketchables Preview

 

If you compare this package to the contents in the YouTube video, the most prominent addition is built-in navigation support which gives you point-and-click navigation, and allows you to trigger other actions for a Sketchable’s items:

(Click on screenshot to show in full size)

image

 

As always, critical feedback is appreciated – happy sketching! 🙂

Author: Categories: Open Source, Silverlight, Sketchables, WPF Tags:

An Abstraction Layer for Temporary Data in .NET and Silverlight

April 15th, 2010

Up until now, I’ve dealt with temporary data in my .NET applications using local files and FileInfo instances.  This worked just fine – until I needed a solution that works under both .NET and Silverlight.

The problem: In Silverlight, you can’t just create a temporary file on the file system for security reasons. Instead, there’s the concept of isolated storage that provides you with the means to store data in files and directories. The API is very similar to working with the local file system, but it doesn’t use the FileInfo class. As a result, I needed to get rid of the (proprietary) concept of FileInfo in my temporary file handling and came up with a simple yet generic solution.

 

Download Sample Project

 

Here’s a sample usage of the API. This code transparently creates temporary storage, and works in both .NET and Silverlight:

private void Foo(ITempStreamFactory factory)
{
  using (Stream stream = factory.CreateTempStream())
  {
    //write to the stream, read from it
  }

  //once we get outside the "using" block, temporary data has been discarded
}

 

The snippet above relies on a factory of type ITempStreamFactory that returns a simple Stream instance. I do not need to know anything about this returned stream – it’s the factory’s responsibility to return a Stream instance that will clean up after itself once it is being disposed.

Read more…

Author: Categories: C#, Silverlight Tags: ,

A Custom Text Encoding Generator For Silverlight

March 30th, 2010

Unlike the .NET platform, Silverlight only provides two text encodings out of the box: UTF-8 (UTF8Encoding class) and UTF-16 (UnicodeEncoding class).

Accordingly, if you find yourself in a situation where you need to encode or decode data with another encoding (e.g. iso-8859-1), you’ll have to write your own Encoding class (or delegate the work to a server-side service).

I found myself in this exact situation yesterday, and came up with a little tool which automates the process. The Encoding Generator is a WPF application which takes the name or code page of a well known encoding, and generates source code for a custom Encoding class which compiles under Silverlight.

 

Get Source Code

 

Get Compiled Executable

Current version: 1.0.0, 2010.03.31, requires .NET 3.5 SP1 or higher

(You can subscribe to the RSS feed or follow me on Twitter in order to get notified about updates and bug fixes)

 

image

 

 

How Does It Work?

 

Specifying the Encoding

In order to specify the encoding you want to use, you can either enter the name or numeric code page of a well-known encoding. As soon as you enter a valid value, some information for the encoding is being displayed in the right hand border you can see on the screenshot.

As a sample for valid encoding names or code pages, here’s some values you can enter in order to tell the tool to generate an iso-8859-1 encoder (see screenshot):

  • iso-8859-1 (name)
  • latin1 (name)
  • 28591 (code page)
    A list of encodings can be found here.

Fallback Character

The tool gives you the option to specify a fallback character value, which is used as a default in case a character or byte value is being processed during encoding/decoding. In case you don’t specify the character, the encoding class will crash at runtime should it receive data that cannot be properly encoded or decoded.

Single-Byte Encoding Limitation

The generated class only works if a single byte can be translated into a single character and vice versa. Accordingly, if you try to generate code for an encoding that uses several bytes per (e.g. utf-8) character, the generator shows an error message.

Byte Range

You need to specify the byte range of the encoding. For example, ASCII supports only 128 characters, and therefore has a byte range of 128 bytes. Most other encodings support a byte range of 256 bytes, though. 256 is the maximum value that can be specified, as a single byte cannot deliver more values (the byte data type covers a numeric range from 0 – 255).

Testing

The generator also creates an NUnit test class that compares the results of the generated class against the original encoding. Accordingly, this test class is supposed to run in a regular .NET environment, not in Silverlight (if the original encoding that is used in the test was available in SL, you wouldn’t have to generate a custom encoding class in the first place…).

Internals

At runtime, the following is happening: Basically, the generator maintains mapping tables to do the encoding and decoding from characters to bytes and vice versa. Fore every request, it just looks up the translation tables for every supported character/byte value of the encoding.

The generator creates these translation tables on the fly in the form of a static array and dictionary.

Performance

The library doesn’t contain any performance tweaks and performs much slower than the built-in encodings that rely on all sorts of black magic. However, as long as you don’t have to encode or decode huge amounts of data, this shouldn’t be noticeable.

Here’s the results from my machine for 10000 iterations:

  • Encoding the whole character table to a byte array (256 characters)
    • 17 milliseconds with the built-in encoding
    • 94 milliseconds with the generated encoding
  • Decoding the bytes back into a string
    • 2 milliseconds with the built-in encoding
    • 46 milliseconds with the custom encoding

REST Client Library for Silverlight

February 8th, 2010

I’ve been doing some hackery and ported the client libraries of the WCF REST Starter Kit to Silverlight. The library greatly simplifies things when it comes to accessing and consuming RESTful services and resources in your Silverlight application.

Here’s a sample for a simple GET using the HttpClient class:

public User GetUser(string userId)
{
  //init client with base URI
  HttpClient client = new HttpClient(http://localhost:56789/users/);

  //send a HTTP GET request for a given resource
  HttpResponseMessage response = client.Get(userId);

  //parse the received data on the fly
  return response.Content.ReadAsDataContract<User>();
}

 

Or, in order to send a DTO via HTTP POST:

public void PostUser(User user)
{
  //init client with base URI
  HttpClient client = new HttpClient("http://localhost:56789/");

  //serialize user object
  HttpContent content = HttpContentExtensions.CreateDataContract(user);

  //post to user service
  HttpResponseMessage response = client.Post("/user", content);
}

 

I have removed a few bits, but most of the functionality should be there, and I added “NOTE” comments to all the sections that I had to modify. I haven’t used this port in-depth but managed to access my RESTful resources as expected so far, and I hope it will work just fine as in most scenarios that are covered in the original Starter Kit. Of course, given the Starter Kit itself is prerelease software, this applies to this release even more.

 

Blocking vs. Async Operations

If you try to initiate a blocking request to your REST service on the UI thread, an InvalidOperationException is thrown due to synchronization issues. Accordingly, a snippet as the one above should always be invoked on a worker thread (which is a best practice anyway).

However, in order to simplify things, I’ve added a bunch of XXXAsync extension methods for the HttpClient class that allow you to invoke HTTP operations such as GET, POST, PUT etc. directly on the UI thread, and have the result delivered back to you through a simple callback action. Here’s the same snippet as above, this time using the GetAsync method of the HttpClient class:

public void GetFolder()
{
  HttpClient client = new HttpClient("http://localhost:56789/root");

  //you can invoke the GetAsync method on a worker thread
  client.GetAsync(response =>
    {
      VirtualFolder folder = response.Content.ReadAsDataContract<VirtualFolder>();
    });
}

 

Note that the callback action will be invoked on a worker thread, so you might have to switch back to the UI thread if you want to modify your UI.

 

Oh yes: Use at your own risk 😉

 

Download REST Starter Kit for Silverlight

Current Version: 1.0.3, 2010.02.14

Author: Categories: REST, Silverlight Tags: ,

A GetResponse Extension for Synchronized Web Requests in Silverlight

February 8th, 2010

Unlike its CLR counter part, Silverlight’s HttpWebRequest does not provide a synchronous GetResponse method that allows to receive an HTTP response in a blocking operation. As a result, you are forced to use the asynchronous BeginGetResponse method, and handle the results on a callback method.

This makes sense if the response is requested on the UI thread (otherwise, it would freeze the UI), but it might be a problem in certain scenarios (e.g. if you want to submit multiple requests in an orderly fashion).

However, you can get around the issue by using wait handles, which allow you to easily block a running operation. I encapsulated the required functionality in a simple extension method that brings GetResponse method back into Silverlight.

The usage is simple – you just invoke the GetResponse() extension method with an optional timeout. Here’s a sample that submits five synchronous HTTP requests:

private void RunRequests()
{
  for (int i = 0; i < 5; i++)
  {
    Uri uri = new Uri("http://localhost/users?user=" + i);
    HttpWebRequest request = 
      (HttpWebRequest)WebRequestCreator.ClientHttp.Create(uri);

    //get response as blocking operation which times out after 10 secs
    HttpWebResponse response = request.GetResponse(10000);
  }
}

 

You will run into timeout issues if you run execute this method on the UI thread because internally, the requested response accesses the UI thread (for whatever reasons). Only invoke this extension method on background threads!

 

Here’s the implementation:

public static class RequestHelper
{
  /// <summary>
  /// A blocking operation that does not continue until a response has been
  /// received for a given <see cref="HttpWebRequest"/>, or the request
  /// timed out.
  /// </summary>
  /// <param name="request">The request to be sent.</param>
  /// <param name="timeout">An optional timeout.</param>
  /// <returns>The response that was received for the request.</returns>
  /// <exception cref="TimeoutException">If the <paramref name="timeout"/>
  /// parameter was set, and no response was received within the specified
  /// time.</exception>
  public static HttpWebResponse GetResponse(this HttpWebRequest request,
                                            int? timeout)
  {
    if (request == null) throw new ArgumentNullException("request");

    if (System.Windows.Deployment.Current.Dispatcher.CheckAccess())
    {
      const string msg = "Invoking this method on the UI thread is forbidden.";
      throw new InvalidOperationException(msg);
    }

    AutoResetEvent waitHandle = new AutoResetEvent(false);
    HttpWebResponse response = null;
    Exception exception = null;

    AsyncCallback callback = ar =>
       {
         try
         {
           //get the response
           response = (HttpWebResponse)request.EndGetResponse(ar);
         }
         catch(Exception e)
         {
           exception = e;
         }
         finally
         {
           //setting the handle unblocks the loop below
           waitHandle.Set(); 
         }
       };


    //request response async
    var asyncResult = request.BeginGetResponse(callback, null);
    if (asyncResult.CompletedSynchronously) return response;

    bool hasSignal = waitHandle.WaitOne(timeout ?? Timeout.Infinite);
    if (!hasSignal)
    {
      throw new TimeoutException("No response received in time.");
    }

    //bubble exception that occurred on worker thread
    if (exception != null) throw exception;

    return response;
  }
}
Author: Categories: Silverlight Tags: