Archive

Archive for the ‘.NET’ Category

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

Input Focus from the View Model – Configured via Blend Behaviors

March 17th, 2010

Background / Focus of this Article

WPF wizard and fellow WPF Disciple Josh Smith published an article yesterday that showed how to control input focus from View Model objects using attached properties and a custom binding extension. Prior to the article, there was a discussion in the Disciples group, during which I looked into using Blend behaviors as an alternative configuration approach to Josh’s markup extension – this article here discusses this approach.

Accordingly, this posting is not about controlling input focus. Josh did all the legwork there, and you should check out the article on his blog. Everything that goes beyond the Behavior classes is Josh’s work, not mine  – I merely discuss a different approach regarding the declaration of focus control on the UI using Blend Behaviors.

 

Download Source Code and Sample Application

 

Differences

Let’s start by looking at the difference from a developer’s point of view. Assume you have a simple TextBox control that is bound to a FirstName property on the View Model:

<!-- simple textbox -->
<TextBox Text="{Binding FirstName}" />

 

Markup Extensions – One for the XAML Guys / Gals

Josh’s approach using a markup extension is a very lean way to wire up your control with the focus controller. If you’re used to coding in XAML, this is pretty much the quickest way to get things running. Note that only the Binding keyword was replaced by a the custom FocusBinding markup extension:

<!-- simple textbox -->
<TextBox Text="{jas:FocusBinding FirstName}" />

 

If you’re working in Visual Studio, this is the way to go (even more so if you have ReSharper to take care of the namespace declarations for you). It might become tedious, however, if’ you’re working in a Blend environment: For one thing, there’s the namespace declarations. And then, you can no longer wire up your bindings directly in Blend on the designer surface.

 

Blend Behaviors – Designer’s Flavor

The Blend Behaviors don’t require you to write any XAML at all. The data binding itself remains unchanged, and the TextBoxFocusBehavior was just dragged/dropped on the TextBox in Blend. Accordingly, you can set up both binding and input focus control with a few mouse clicks without having to leave the designer surface:

image

 

If you look at XAML source, you’ll notice that the Behavior above actually produces substantially more markup – this isn’t something you’d want to type in manually:

<TextBox Text="{Binding FirstName}" >
    <i:Interaction.Behaviors>
        <FocusVMLib_Behaviors:TextBoxFocusBehavior/>
    </i:Interaction.Behaviors>
</TextBox>

 

In order to compare the two approaches, just download the attached sample and have a look at the two Window classes. Window1 is the original implementation (using the markup extension), Window2 uses the Blend behaviors. The end result is the same – the only difference is the different declaration approaches.

 

The Behavior Classes

The rest of this blog post discusses the implementation of the behavior classes, and suggests an approach to support different control types.

Read more…

Author: Categories: WPF Tags: ,

Remote File Access in VFS using OpenRasta – Part 1 (Introduction)

February 14th, 2010

This lose series of articles will cover the implementation of a file system façade that allows transparent remote file system access in VFS.

The series will cover the following topics:

  • Introduction and basic concept (this article)
  • Implementing a RESTful file system proxy service with OpenRasta (coming soon)
  • Unit testing the OpenRasta proxy service (not yet published)
  • General tutorial: Streaming binary data in Silverlight
  • Implementing VFS client libraries for both .NET and Silverlight (not yet published)

VFS File System Providers

VFS abstracts access to arbitrary file systems through so-called “File System Providers”, which expose a common interface (IFileSystemProvider) that allows you to browse and modify the file system. The interface is not exactly lean, but easy to understand:

image

Now, common file system providers directly operate on some kind of hierarchical data. Here’s a few examples:

  • The “Local File System Provider” allows you to access your local machine, or the contents of a dedicated directory.
  • The “ZIP File System Provider” works upon a single ZIP file, and allows you to transparently access and modify its contents.
  • An “FTP File System Provider” connects to a given FTP server and gives you access to the server’s files through the VFS API.

So basically, an application uses a VFS provider, which in turn directly accesses the exposed file system:

image

 

Tunneling Façades

There is, however, a special family of file system providers that do not access any files. Instead, they forward file system requests to another file system provider, thus creating a tunnel to another file system. Basically, these file system providers are façades to another, arbitrary file system provider.

image

 

Here’s an exemplary scenario that uses a façade in order to access a ZIP file that is exposed through a ZIP file provider (click on the UML diagram in order to see it in full size).

 Tunnelling

 

The interesting point here: From the client’s perspective, there is no difference in accessing the file system. The façade itself implements the IFileSystemProvider interface – it provides exactly the same API as any other provider.

As you can see from the diagram above, a façade is usually complemented by some kind of proxy that receives the forwarded requests, so in order to implement the pattern, there’s two components to be written:

  1. The façade, which implements IFileSystemProvider.
  2. The proxy that takes the forwarded requests, forwards them its own file system provider, and eventually returns the requested data. This proxy is not a VFS component, and you don’t have to implement any VFS interfaces.

As you can guess, tunnels come in handy in order to access remote data. Here’s a few scenarios:

  • Run a local file system provider on a server that provides a download service. Clients don’t have direct access to the files, but use a tunnel to access the files that are exposed through the provider that runs on the server.
  • Allow a Silverlight client to browse the contents of a ZIP file on the server, without having to download the whole ZIP file first (sample coming).
  • Host a cloud file system provider within a WCF service, and expose parts of the cloud’s data to clients. Like this, clients don’t have direct access to the cloud data.

A RESTful Façade Implementation

Every façade itself is an independent file system provider – so tunneling is rather a pattern than an API, and you can write your own façade should you wish to (actually, contributions will be most welcome!).

However, VFS 1.0 will ship with a single façade implementation that uses HTTP/REST to create a tunnel to a remote file system. It is built upon the following libraries:

  • On the server side, OpenRasta was used to expose file system access as RESTful services. OpenRasta is a lightweight, but powerful framework that comes with a API.
  • On the client side, the WCF REST Starter Kit was used for both .NET and Silverlight clients (the Silverlight library hacked together by myself). The starter kit’s client libraries allow for simple access to RESTful resources, even if there is no WCF involved.

 

The upcoming articles will walk you through the implementation of the both the client and service libraries, and will also be complemented by a preview release of VFS. Stay tuned 🙂

Author: Categories: REST, VFS Tags:

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: ,