Archive

Posts Tagged ‘Silverlight’

Announcing Sketchables – Rapid Mockup Creation with SketchFlow

May 24th, 2010

SketchFlow is a great addition to Blend, but I was missing the ability to create quick mockups of user interfaces. I’m a huge fan of productivity tools such as Balsamiq, and I was sorely missing its ease and speed in SketchFlow.

Meet Sketchables. Sketchables is a simple framework complemented by a set of controls that allow you to quickly create common controls in a matter of seconds. Here’s a screenshot from one of the samples, which was created in just a few minutes:

image

 

…and here’s a complementary recording that shows how the above mockup was created:

 

 

 

Sketchables will be free software, requires Blend 4 RTM and fully supports both WPF and Silverlight SketchFlow projects. Version 1.0 is approaching completion, so I hope I’ll be able to release it as soon as Blend 4 goes live.

Still time for you to slip in some last-minute feature requests though 😉

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:

Lightweight Task Scheduling Library for .NET / Silverlight

January 9th, 2010

I’m currently working on VFS, a virtual file system. For running transfers, VFS internally maintains locks that do have expiration time. Accordingly, I found myself in need for a job scheduling mechanism in order to properly release expired locks. I looked around for a few alternatives, but eventually ended up writing my own lightweight version.

Features:

  • Simple scheduling and callback mechanisms
  • Silverlight compatible
  • Lightweight
  • Fluent API
  • Detection of system time changes with optional rescheduling
  • Optional forwarding of exceptions during job execution
  • Open Source (Ms-PL)

 

Download library and sample

Current Version: 1.0.2, 2010.01.12

 

What Does it Do?

Basically, the library allows you to create a job, and submit that job to a scheduler, along with a callback action. This callback action is invoked as soon (or every time) the job is due.

Before going into the details, here’s a first code snippet that creates a simple Job that is supposed to run repeatedly (every 1.5 seconds) for a minute. Once the job is created, it is submitted to a Scheduler instance which processes the job and makes sure the submitted callback action is being invoked every time the job is due:

private Scheduler scheduler = new Scheduler();

public void RunOnce()
{
  //define a start / end time
  DateTime startTime = DateTime.Now.AddSeconds(5);
  DateTime endTime   = startTime.AddSeconds(60);

  //configure the job
  Job consoleJob = new Job();
  consoleJob.Run.From(startTime)
                .Every.Seconds(1.5)
                .Until(endTime);

  //submit the job with the callback to be invoked
  scheduler.SubmitJob(consoleJob, j => Console.Out.WriteLine("hello world"));
}

 

Silverlight

The project provides class libraries for .NET 3.5 and Silverlight 3, along with a Silverlight sample application that shows how to add scheduling functionality to your SL application with just a few lines of code.

While long-term scheduling isn’t probably something you need to do in a Silverlight application, the scheduler simplifies the management of periodic jobs, such as polling a server for updates. Below is a snippet from the Silverlight sample application. This job starts immediately, and runs indefinitely with an interval of 2 seconds:

private void CreateJob2()
{
  //create job
  Job<int> job = new Job<int>("Job 2");
  job.Data = 0;
  job.Run.Every.Seconds(2);

  //submit to scheduler
  scheduler.SubmitJob(job, LogJobExecution);
}


private void LogJobExecution(Job<int> job, int data)
{
  //updates user interface
}

 

image

 

Jobs

 

A job is a simple configuration item for the scheduler. There’s two built-in job types: Job and Job<T>. The only difference between the two is that the latter provides a Data property which allows you to attach state information directly to the job and have it delivered back to you when the job runs.

Read more…