hardcodet.nethttp://www.hardcodet.net
Confessions of a Code AddictSat, 02 Apr 2016 07:07:50 +0000en-UShourly1https://wordpress.org/?v=4.9.3Subscribe with My Yahoo!Subscribe with NewsGatorSubscribe with My AOLSubscribe with BloglinesSubscribe with NetvibesSubscribe with GoogleSubscribe with PageflakesSubscribe with PlusmoSubscribe with The Free DictionarySubscribe with Bitty BrowserSubscribe with NewsAlloySubscribe with Live.comSubscribe with Excite MIXSubscribe with Yourminis.comSubscribe with Attensa for OutlookSubscribe with WebwagSubscribe with netomat HubSubscribe with Podcast ReadySubscribe with FlurrySubscribe with WikioSubscribe with Daily RotationIn order to import the feed into your mail client, just click on the "View Feed Xml" button.WPF NotifyIcon 1.0.8 releasedhttp://www.hardcodet.net/2016/04/wpf-notifyicon-1-0-8-released
http://www.hardcodet.net/2016/04/wpf-notifyicon-1-0-8-released#commentsFri, 01 Apr 2016 18:09:13 +0000http://www.hardcodet.net/?p=941I just published a maintenance release of my WPF NotifyIcon control. The update fixes an issue with potential null references during initialization.

Links and downloads as usual on the control’s project page. Happy coding!

]]>http://www.hardcodet.net/2016/04/wpf-notifyicon-1-0-8-released/feed2WPF NotifyIcon 1.0.6 releasedhttp://www.hardcodet.net/2016/03/wpf-notifyicon-1-0-6-released
http://www.hardcodet.net/2016/03/wpf-notifyicon-1-0-6-released#commentsMon, 21 Mar 2016 09:34:22 +0000http://www.hardcodet.net/?p=937I just published a maintenance release of my NotifyIcon control, which addresses a potential null reference issue, and optionally removes the double-click delay, which allows the NotifyIcon to react to single clicks immediately.

Links and downloads as usual on the control’s project page. Happy coding!

My work at Vistaprint is focused on the UI architecture of the distributed software system that runs in our factories. Today, we process more than 120,000 individually customized pieces in over 70,000 shipments per day, with diverse human-machine interaction taking place while produced items are making their way through the plant. This includes desktops, touch panels, handhelds, or dashboards. And we are currently trying to rethink the way our UIs should work – which is where YOU come in: A brilliant UI designer, XAML wizard, UX geek, who wants to make a difference and join us in implementing an exciting, cutting edge UI infrastructure that will support both our stakeholders on the factory floor as your fellow developers all around the globe. Recognize yourself? Come join us in our beautiful, and slightly chaotic Winterthur office in Switzerland!

Take the wording on the posting with a grain of salt. We really are looking for a Blend wizard more than a Visual Studio crack. This is all about creating exciting user interfaces, and evangelizing / teaching UI goodness to a globally distributed team.

]]>http://www.hardcodet.net/2014/03/ui-developer-spring-2014/feed0WPF NotifyIcon 1.0.5 Releasedhttp://www.hardcodet.net/2013/11/wpf-notifyicon-1-0-5-released
http://www.hardcodet.net/2013/11/wpf-notifyicon-1-0-5-released#commentsMon, 25 Nov 2013 12:52:37 +0000http://www.hardcodet.net/?p=893I just published a maintenance release of my NotifyIcon control, which addresses a few (long due) issues, most notably for applications that target more recent versions of the .NET framework, or x64 applications.

Source code and samples can be downloaded via the control’s project page. Alternatively, there’s now also an official NuGet package for the control (binaries only) that contains builds for .NET 3.5 up to 4.5.1.

What’s next?

I already started working on a new version of the control. The most important feature will be interactive tooltips (so you can hover over them and interact with clickable content), along with a few minor new features. Check back in a few days/weeks, or follow me on Twitter in order to get the update once it’s released. Also, if you have specific feature requests, let me know!

]]>http://www.hardcodet.net/2013/11/wpf-notifyicon-1-0-5-released/feed12Updated ToolTips Libraryhttp://www.hardcodet.net/2013/11/updated-tooltips-library
http://www.hardcodet.net/2013/11/updated-tooltips-library#commentsThu, 21 Nov 2013 23:16:32 +0000http://www.hardcodet.net/?p=870I just uploaded an updated version of the clickable ToolTips library I released this month. The changes add string formatting for bindings, plus the option to disable ToolTips via a the bindable boolean IsEnabled flag. You can download the current version 1.0.1 here.

A few years ago, I posted an article that leveraged markup extensions to quickly show localized ToolTips with minimal effort. Fast forward to 2013: I still like ToolTips, but interactive / clickable ones would be nice, and there’s Blend Behaviors that provides developers with a great design-time experience. As a result, I wrote a simple control and a complementary Blend Behavior that get’s me quite a bit of flexibility with minimal impementation effort.

The behavior allows you very easily create simple ToolTips like this:

However, it doesn’t stop there. The following Blend Behavior generates an error ToolTip:

Also, unlike the built-in ToolTip service, the behavior supports interactive/clickable ToolTips. As the ToolTip takes arbitary XAML or a user control for Content or Header properties, you can display arbitrary controls on the popup.

Features at a glance:

Blend Behavior with design-time support – you can setup rich ToolTips within Blend in a matter of seconds.

Unlike regular ToolTips, those are clickable – you can put interactive content such as buttons or Hyperlinks on them.

Built-in header / content support.

Data Binding and MVVM-friendly.

Content and header not limited to text.

Built-in themes: You can show a ToolTip as an information, warning, or error.

If bound to strings, values can be formatted on the fly using the HeaderStringFormat and ContentStringFormat properties.

Disabling ToolTips through a bindable IsEnabled flag.

Some final notes: I didn’t make everything configurable – that would have been overkill for the scope of a ToolTip. Instead, I recommend you to tweak the control styles to your needs. Things you might want to change:

When being displayed, ToolTips are slightly transparent – full opacity is only set if you hover over them. You can easily adjust this in the animation that fades in the control.

If you shorten the delay in which the ToolTip is being displayed remarkably, you should also adjust animations (fade-in / fade-out in order to not cut them off.

Placement of the ToolTip’s popup (near Mouse pointer) is currently hardcoded in the Behavior class.

Happy coding

]]>http://www.hardcodet.net/2013/11/quick-and-dirty-but-nice-tooltips-revisited-and-interactive/feed4Understanding the “yield” keyword in 120 Secondshttp://www.hardcodet.net/2011/04/understanding-yield-in-120-seconds
http://www.hardcodet.net/2011/04/understanding-yield-in-120-seconds#respondSun, 17 Apr 2011 10:11:51 +0000http://www.hardcodet.net/?p=828I’m about to release my own take on coroutines, and as a complementary app, I created a very simple sample that lets developers (hopefully) experience the fundamental behavioral difference of returning a sequence of values through the yield keyword.

There’s a lot of great material that can be read about iterator blocks (Google is your friend), and I’m not planning to add another article on top of that. So, stop reading and:

]]>http://www.hardcodet.net/2011/04/understanding-yield-in-120-seconds/feed0A Parser for Formatted Text in WPF / Silverlighthttp://www.hardcodet.net/2010/11/parser-for-formatted-text-in-wpf-and-silverlight
http://www.hardcodet.net/2010/11/parser-for-formatted-text-in-wpf-and-silverlight#commentsFri, 05 Nov 2010 20:46:17 +0000http://www.hardcodet.net/2010/11/parser-for-formatted-text-in-wpf-and-silverlightI 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.

]]>http://www.hardcodet.net/2010/11/parser-for-formatted-text-in-wpf-and-silverlight/feed10Back in Switzerlandhttp://www.hardcodet.net/2010/09/back-in-switzerland-sept-2010
http://www.hardcodet.net/2010/09/back-in-switzerland-sept-2010#commentsFri, 03 Sep 2010 08:24:35 +0000http://www.hardcodet.net/2010/09/back-in-switzerland-sept-2010The blog (and myself) has been dormant a while – I’ve been literally working my *** off (doing over 600 hours in just two months isn’t too healthy) and have rewarded myself by travelling the US for three weeks. However, I’m back in Switzerland now and will try to reply to pending posts and questions asap (read: once I get rid of my current sleep deprivation), along with an update on Sketchables.
]]>http://www.hardcodet.net/2010/09/back-in-switzerland-sept-2010/feed2Sketchables 0.9 – Public Preview Releasehttp://www.hardcodet.net/2010/07/public-sketchables-preview-release
http://www.hardcodet.net/2010/07/public-sketchables-preview-release#commentsTue, 20 Jul 2010 21:28:01 +0000http://www.hardcodet.net/2010/07/public-sketchables-preview-releaseI 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:

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)

As always, critical feedback is appreciated – happy sketching!

]]>http://www.hardcodet.net/2010/07/public-sketchables-preview-release/feed33Announcing Sketchables – Rapid Mockup Creation with SketchFlowhttp://www.hardcodet.net/2010/05/announcing-sketchables
http://www.hardcodet.net/2010/05/announcing-sketchables#commentsMon, 24 May 2010 17:48:08 +0000http://www.hardcodet.net/2010/05/announcing-sketchablesSketchFlow 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:

…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

]]>http://www.hardcodet.net/2010/05/announcing-sketchables/feed34An Abstraction Layer for Temporary Data in .NET and Silverlighthttp://www.hardcodet.net/2010/04/temp-files-in-net-and-silverlight
http://www.hardcodet.net/2010/04/temp-files-in-net-and-silverlight#commentsThu, 15 Apr 2010 09:22:29 +0000http://www.hardcodet.net/2010/04/temp-files-in-net-and-silverlightUp 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.

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

privatevoid 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.

In the snippet above, disposal happens implicitly through the using statement. But of course, the stream can also be disposed explicitly:

Factories

Factory implementations are very simple – they just need to create a Stream class that can be used. Here’s the interface:

/// <summary>/// Responsible for the creation of stream instances/// which can be used to read and write temporary data./// </summary>publicinterface ITempStreamFactory
{
/// <summary>/// Creates a stream that automatically cleans up after itself./// </summary>
Stream CreateTempStream();
}

TempStream Base Class

So basically, the convention is that ITempStreamFactory returns streams that clean up after themselves. In order simplify the implementation of such streams, I created an abstract base class called TempStream. TempStream itself derives from Stream, and applies the Decorator pattern. All stream-related methods just forward requests to an underlying (decorated) stream. As an example, here’s the implementation of the Write method:

However, besides just forwarding request to a decorated stream, the TempStream class provides two abstract methods that need to be implemented by deriving classes:

The CreateTempDataStream method is invoked in order to create that decorated stream.

The DiscardTempResources method is invoked during disposal. When invoked, implementing classes should clean up (e.g. delete temp files).

/// <summary>/// Creates the underlying stream. This method is being invoked on the first/// request of the <see cref="DecoratedStream"/> property./// </summary>/// <returns>A temporary stream that supports seeking.</returns>protectedabstract Stream CreateTempDataStream();
/// <summary>/// When invoked (which happens during disposal), implementing classes/// should clean up temporary resources. Note that at the time this/// method is being invoked, the <see cref="DecoratedStream"/> has/// already been disposed./// </summary>protectedabstractvoid DiscardTempResources();

Implementations for Local Files / Isolated Storage

Local File System

In order to handle temporary files on the local file system, I implemented the TempFileStream class that takes a reference to a temporary file. The CreateTempDataStream method opens a stream to that file, and the DiscardTempResources deletes the file once it’s no longer required.

This is a simplistic implementation for the sample – the one I’ll be using in production code also deals with a temporary root directory and so forth. But the concept is the same.

TempFileStream instances can be acquired via the TempFileStreamFactory, which implements the ITempStreamFactory interface. Here’s a simplistic implementation (the one in the attached project is a little smarter):

Silverlight / Isolated Storage

In order to handle temporary files in the Silverlight sample, I implemented the IsolatedStorageTempStream class that creates and deletes a temporary file in isolated storage. The CreateTempDataStream method creates the stream using a GUID as a temporary name, and the DiscardTempResources override removes the data from isolated storage once it’s no longer required.

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.

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

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

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.

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.

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 --><TextBoxText="{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 --><TextBoxText="{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:

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:

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.

A Problem: Where to get the Bound Property?

Josh’s focus helper library uses the binding between the UI and the View Model in order to observe the View Model for a change on a relevant property.

Accordingly, the Blend Behavior needs to determine the bound property somehow in order to submit it to the FocusController class. Basically, there’s two solutions:

Write control-aware Behaviors that implicitly use the correct property.

Write a Behavior that lets you specify the bound property at design time.

I decided to support both approaches. The sample application consists of three classes:

An abstract base class that wires up the control in order to take part in focus control.

A generic Behavior class that allows to specify the bound property manually.

A exemplary Behavior that can be used on TextBox controls without having to do any further configuration. You will see that you can create similar classes for other controls in a matter of seconds.

The FocusBehaviorBase Class

This abstract base class takes care about wiring up the associated UI element with the FocusController of Josh’s focus helper library:

As you can see in the snippet above, the base class delegates the job to resolve the bound property via the abstract GetSourceProperty method. This property, along with the associated object, is then forwarded to the FocusController class which takes care of the rest.

Generic but Complex Behaviors

The first working Behavior implementation is a generic version that lets you specify the bound property yourself. As such, the class exposes a BoundSource property, which takes an arbitrary DependencyProperty. The GetSourceProperty method then just returns that property:

This class is already sufficient to cover any binding scenarios, but it requires you to specify the property yourself with a rather unusual binding expression (you are not binding to a property value, but a dependency property itself):

The advantage of this generic Behavior is that you can bind to arbitrary properties. On the other hand, it’s obvious that this approach isn’t exactly designer friendly, which is why I’d recommend to simplify things for common controls with custom Behaviors.

Controls Specific Behaviors

The FocusBehaviorBase class expects only one thing from an implementing class: Information about a bound property. This makes it extremely simple to create control-aware behaviors. The sample application contains one example that can be used with TextBoxes, called TextBoxFocusBehavior. The implementation is trivial:

A behavior like this requires no additional configuration if you are working in Blend. Just drag and drop the behavior on the control and be on your way. And of course, nothing stops you from writing your own behavior classes.

As an additional example, here’s a behavior that covers all controls of type ToggleButton, which includes checkboxes and radio buttons:

You could also write a Behavior that looks at the AssociatedObject before returning a property, or one that takes a string argument and resolves the dependency property via reflection. Basically, there’s no limits here. However, I assume you will probably only have to write a few behaviors to cover your whole application – accordingly, I’d recommend you to write simple behaviors such as the TextBoxFocusBehavior.

Conclusion

Behaviors are a very convenient way if you are working in Blend. Just dropping a few behaviors on your controls is more comfortable than tampering with XAML, and the bindings remain untouched, so you can edit them in Blend at any time.

On the other hand, if you’re working with Visual Studio, or if you are used to set up your bindings directly in XAML anyway, just using the markup extension is the faster and leaner choice.

In my opinion, the two approaches complement themselves. Both are just means to wire up your controls with the View Model, so the outcome is the same. In the end, it’s about preference.

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:

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:

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.

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).

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:

The façade, which implements IFileSystemProvider.

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

]]>http://www.hardcodet.net/2010/02/remote-file-access-in-vfs-part-1/feed4REST Client Library for Silverlighthttp://www.hardcodet.net/2010/02/wcf-rest-starter-kit-for-silverlight
http://www.hardcodet.net/2010/02/wcf-rest-starter-kit-for-silverlight#commentsMon, 08 Feb 2010 16:49:08 +0000http://www.hardcodet.net/2010/02/wcf-rest-starter-kit-for-silverlightI’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 flyreturn response.Content.ReadAsDataContract<User>();
}

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:

]]>http://www.hardcodet.net/2010/02/wcf-rest-starter-kit-for-silverlight/feed16A GetResponse Extension for Synchronized Web Requests in Silverlighthttp://www.hardcodet.net/2010/02/blocking-httpwebrequest-getresponse-for-silverlight
http://www.hardcodet.net/2010/02/blocking-httpwebrequest-getresponse-for-silverlight#commentsMon, 08 Feb 2010 11:40:55 +0000http://www.hardcodet.net/2010/02/blocking-httpwebrequest-getresponse-for-silverlightUnlike 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:

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!

]]>http://www.hardcodet.net/2010/02/blocking-httpwebrequest-getresponse-for-silverlight/feed14A Simplistic Random String Generation Snippethttp://www.hardcodet.net/2010/01/simple-random-strings
http://www.hardcodet.net/2010/01/simple-random-strings#commentsMon, 25 Jan 2010 12:27:00 +0000http://www.hardcodet.net/2010/01/simple-random-stringsThis is just a little snippet that generates a random string, containing both upper and lower case characters and special chars, so there’s a range of 93 possible characters, taken from the UTF-8 character table. I thought I’d post it as the snippets I’ve seen after a quick search usually just generate strings with characters ranging from ‘A’ to ‘Z’, or do not work with properly initialized seeds.

Note that this method uses a static int field (seedCounter) when in comes to creating a random seed. This counter is incremented in a thread safe manner every time the method is being invoked. This simple trick is a simple workaround to the notoriously unreliable Random class, and effectively prevents double seeds (and thus: duplicate “random strings”) if the GetRandomString method is being invoked several times immediately. As an alternative, you could also use a static Random field, which would only have to be initialized once. My implementation has the smaller footprint (and integer variable), while a Random field would perform much better (currently, every invocation calculates a seed and creates a new Random instance). The better choice depends on the context I guess:

]]>http://www.hardcodet.net/2010/01/simple-random-strings/feed2Lightweight Task Scheduling Library for .NET / Silverlighthttp://www.hardcodet.net/2010/01/lightweight-task-slash-job-scheduling-with-silverlight-support
http://www.hardcodet.net/2010/01/lightweight-task-slash-job-scheduling-with-silverlight-support#commentsSat, 09 Jan 2010 20:35:59 +0000http://www.hardcodet.net/?p=727I’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.

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:

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:

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.

Creating Jobs

Creating a job is pretty easy, and can be configured through a fluent interface (optional, you can also set the properties the traditional way). Jobs may run once, several times, or indefinitely – you can configure intervals, an optional expiration time, or a maximum number of executions. Here’s a few configuration samples:

//run the job every second until we manually cancel it
Job job = new Job();
job.Run.Every.Seconds(1);

The Scheduler Class

Jobs are being submitted to the Scheduler class, which provides a very simple API. Most methods should be pretty self-explanatory, and they are well documented.

Callback Actions

If you add a Job to the Scheduler through one of the SubmitJob overloads, you have to submit a callback action that is being invoked whenever the job runs. Depending on whether you use Job or Job<T>, a different callback delegate may be used:

Cancelling or Pausing a Job

If you want to cancel or pause a job, you can do this either via the Scheduler class, or directly on the Job instance that is submitted to you whenever the job runs. Note that canceling the job is a terminal operation – a canceled job cannot be resumed.

Actually, doing these operations directly via the Job class is the preferred mechanism – if you use the scheduler’s methods, the scheduler needs to lock its internal list and search for the job itself, which costs you processing power.

Exception Handling

An exception that occurs during the execution of a job does not affect the scheduler – all jobs are being executed on worker threads taken from the .NET thread pool. However, in order not to miss any exceptions, you can instruct the Scheduler class to supervise executing jobs, and forward any unhandled exceptions to a single exception handling routine. All you need to do is registering a callback action to the JobExceptionHandler of the Scheduler class:

Performance

The library could surely be tweaked, but it performs pretty well. Running 10000 jobs, each with an interval of 100 ms (that’s around 100 jobs per millisecond) keeps the CPU busy (at around 25% on my machine), but neither eats away your memory nor freezes the PC. Bigger intervals aren’t a problem at all because the scheduler is sleeping most of the time.

Reacting to System Time Change Events

Assume the following:

The current time is 21:00, your job is scheduled to run at 22:00

The user changes the computer’s time to 21:30

Now, depending on your needs, you might want the scheduler to adjust itself based on two strategies:

A: If you want the job to run at a fixed time (22:00), you expect the job to run in 30 minutes. This is the scheduler’s default behavior.

B: If you want the job to run based on relative times, you still expect the job to run in an hour, so the execution time would have to be change to 22:30.

In order not to miss such an event, the scheduler performs a quick self test with a fixed configurable interval from time to time – even if no jobs are up for execution. Per default, the scheduler’s SelfTestInterval property is set to two minutes, but this can be configured should you need more (or less) accurate re-scheduling.

If you want the scheduler to just readjust its internal schedule and keep fixed times (A), you don’t have to do anything. However, if you want the scheduler to reschedule its jobs if a system time change was detected (B), you can do by setting the SystemTimeChangeRescheduling property of the Scheduler class, which takes an enum value of type ReschedulingStrategy:

As you can see, you can choose not to reschedule at all (default), only reschedule the next execution time (the next time the job runs), or even shift the expiration time of your jobs.

Fixed vs. Relative Rescheduling Depending on Jobs

What if you have a few jobs that should run on a fixed time, while others should be rescheduled?

I decided against making the API more complicated by allowing jobs to be individually configured. As an alternative, I’d suggest to just use two scheduler classes with individual configurations. You could even write a wrapper class that just maintains two schedulers, and forwards all job submissions to the correct one. Here’s a quick but working implementation:

Persisting Jobs

Persisting jobs is not part of the library, but could be done by subclassing the Scheduler class. The class gives you protected access to all its internals, including its job list. Job is a very simple component, so it should be fairly easy to store and reload all jobs.

However, from an architectural point of view, I’d probably not persist any jobs at all, but rather recreate them during initialization based on persisted business data. A job does execute in a given context, because of “something”. Let’s assume this “something” is a reminder flag in a calendar application:

User sets a reminder on a calendar entry.

Calendar application updates database record of the calendar entry, then creates a job with the scheduler.

User turns off application – the scheduler and running jobs are being disposed.

User restarts application.

The application retrieves all reminders from the database and schedules jobs for them.

This approach is simple, and clearly defines the responsibilities of the components in your application. It also minimizes dependencies on the scheduling system.

Implementation Notes

Creating a Fluent Interface

The library provides a fluent API that allows you to chain configuration settings:

//job starts at a given start time, repeats until expiration time
Job myJob = new Job();
myJob.Run.From(startTime).Every.Seconds(1.5).Until(expiration);

The fluent API is optional – a job can also be configured via traditional properties setters. However, the corresponding declaration is more verbose:

DateTime, DateTimeOffset, and SystemTime

SystemTime Pattern

With a scheduler, everything is about time. However, time-related code is very hard to test, which is why the scheduler does not directly access the current system time, but makes use of Ayende’s SystemTime. This is an awesome pattern, and I highly recommend using it whenever timestamps play an important role in code.

DateTimeOffset vs. DateTime

You might have noticed that usually, the code works with DateTimeOffset rather then the commonly known DateTime struct. DateTimeOffset is basically an alternative to DateTime, but operates on UTC which makes it an ideal candidate for most time-related scenarios. You can read more about it at MSDN or at the BCL team blog.

However, you can even still use DateTime in your code if you feel more comfortable with it:

Job List, Timer and Pooled Execution

Job List

Internally, the Scheduler class uses a very simple mechanism: All jobs are being cached in a sorted list, which allows the scheduler to easily determine the next execution time. If a new job is being submitted, the scheduler only has to check whether the new job runs before the next scheduled job or not. If yes, the scheduler adjusts its next execution. If no, the job is just added to the end of the list, and a flag is set that reminds the scheduler to reorder the list once the next job was done. This approach has a big advantage: Even if many jobs are being submitted, reordering takes only place once the next job runs.

publicvoid SubmitJob(Job job, Action<Job> callback)
{
//[validation omitted for brevity]
JobContext context = new JobContext(job, callback);
lock(syncRoot)
{
//if this job is going to be the next one, we need to reconfigure//the timer. Do not reschedule if the next execution is imminentif (NextExecution == null || context.NextExecution <= NextExecution.Value)
{
//insert at index 0 –> makes sure the job runs first on next timer event
jobs.Insert(0, context);
//only reschedule if the next execution is not imminentif (NextExecution == null || NextExecution.Value.Subtract(SystemTime.Now())
.TotalMilliseconds > MinJobInterval)
{
//no sorting required, but we need to adjust the timer
Reschedule();
}
}
else
{
//add at end of the list and mark list as unsorted//the job will be sorted and rescheduled on the next run (which is before//this job's execution time)
jobs.Add(context);
isSorted = false;
}
}
}

Timer and Rescheduling

In order to trigger the execution, a single Timer is used to wake up the scheduler once jobs are due. The timer is set to one of those values:

If the scheduler has no jobs at all, the timer is disabled.

If jobs are pending, the next interval is the execution time of the next pending job.

If the self test interval is lower than the execution time of the next job, the scheduler will run an evaluation at this time (which ensures that a changed system time does not cause the scheduler to oversleep).

Conclusion

This is a neat little helper library, and its small footprint makes it a viable alternative to handling timers yourself even for small applications. Happy coding

]]>http://www.hardcodet.net/2010/01/lightweight-task-slash-job-scheduling-with-silverlight-support/feed35Announcing VFS, the Virtual File Systemhttp://www.hardcodet.net/2009/12/vfs-virtual-file-system-announcement
http://www.hardcodet.net/2009/12/vfs-virtual-file-system-announcement#commentsTue, 29 Dec 2009 10:00:52 +0000http://www.hardcodet.net/2009/12/vfs-virtual-file-system-announcementI’ve been working on a new project of mine for a while now, and opened the project at CodePlex: VFS, the Virtual File System, is basically an abstraction to arbitrary hierarchical resources, which can be handled like a file system.

VFS comes with a set of file system providers and clients (including Silverlight support), and allows you to easily write your own providers (e.g. to expose the contents of a ZIP file on a remote server). Additional offerings are flexible security (e.g. to access your Azure blobs via VFS in order to plug-in a custom authorization scheme), auditing and reliable file transfers.

VFS is currently in early Alpha, but I’m working full steam ahead. Comments and wish lists are appreciated! For a more detailed introduction and a few code snippets, visit the project home: http://vfs.codeplex.com

]]>http://www.hardcodet.net/2009/12/vfs-virtual-file-system-announcement/feed6Convert WCF Service Exceptions into Faults using Lambdashttp://www.hardcodet.net/2009/12/convert-service-exceptions-to-wcf-faults
http://www.hardcodet.net/2009/12/convert-service-exceptions-to-wcf-faults#commentsTue, 08 Dec 2009 14:25:02 +0000http://www.hardcodet.net/2009/12/convert-service-exceptions-to-wcf-faultsInteroperability in WCF is a great thing, but it requires us to rethink our exception handling strategy: The simple paradigm of throwing exceptions whenever something goes wrong doesn’t cut it with distributed systems.

Thankfully, WCF allows us to communicate errors (or faults) through FaultExceptions. We can just convert internal exceptions into a FaultException, and WCF will take care about everything else. However: This conversion strategy is tedious and error prone, especially if you want to do more sophisticated exception handling. Even a simplified example as the one below mainly consists of exception handling code:

I’m currently finding myself having to write a set of WCF services, and I didn’t want to go through try/catch blocks all the time just in order to wrap up the same exceptions over and over again. Accordingly, I wrote helper methods that do the exception handling for me.

SecureAction is used by service methods that do not have a return value.

SecureFunc<T> is used by service methods that do have a return value.

These helper methods allow me to easily delegate the exception handling from all my service methods, and if anything goes wrong, I can trust that the internal exception is safely converted into a FaultException. Here’s is the rewritten Foo method from above, now remarkably smaller:

Below is the (simplified) snippet with the helper methods. Do note that the above sample methods are just starting points. My productive helper methods provide a more sophisticated exception handling than shown above (they build detailed FaultContracts which are specific to my application) and come with a few overloads.

Furthermore, you might think about adding additional parameters to your helper methods (such as fault IDs) in order to customize the generated faults.

]]>http://www.hardcodet.net/2009/12/convert-service-exceptions-to-wcf-faults/feed2NetDrives 1.0.2 Releasedhttp://www.hardcodet.net/2009/12/httpwwwhardcodetnet200909netdrives-update-102
http://www.hardcodet.net/2009/12/httpwwwhardcodetnet200909netdrives-update-102#respondMon, 07 Dec 2009 17:09:21 +0000http://www.hardcodet.net/2009/12/httpwwwhardcodetnet200909netdrives-update-102I just released a minor update for NetDrives, which fixes an issue that caused settings not to be persisted correctly. NetDrives is a Windows utility that helps you manage your network shares and mapped network drives.

This is an introductory tutorial on SLF, the Simple Logging Façade. This tutorial covers the basics, which will be all you’ll ever need in most projects. I’m planning on writing a second tutorial that will show custom factories and resolvers soon.

Downloading SLF

To get started, visit http://slf.codeplex.com and download the latest release. Source code is available as a Visual Studio 2008 solution, but if you’re working with VS2005, there’s also precompiled binaries for .NET 2.0 available (.NET 1.0 or 1.1 is not supported).

Sample Projects

SLF comes with a lot of samples, all organized as independent projects that discuss a specific use case. As you will see, most scenarios only require a few lines of code. We are planning to extend this section over time, based on your feedback.

ILogger

The central interface in SLF is ILogger. ILogger provides a versatile API to log information to a specific logging framework. You could roughly say there’s three “categories” of loggers:

A few simple implementations directly in the SLF core library (e.g. ConsoleLogger or DelegateLogger) that cover common scenarios.

Façades for logging frameworks that are currently supported (e.g. log4net). A façade is usually an independent DLL.

Custom loggers that you implement yourself. You can do that very easily, usually by extending a simple base class. Creating fancy custom loggers will be covered in the second part of this tutorial.

Here’s a first snippet, that creates a ConsoleLogger, which is part of the core library:

ILogger logger = new ConsoleLogger();
logger.Info("hello world");

This produces the following output

However, rather than creating your loggers all over the place, you will usually use LoggerService to obtain your logger(s):

Logging a LogItem

Apart from the the above mentioned Info(), Warn(), Error(), Fatal() and Debug() methods, there’s also the Log method, which expects an parameter of type LogItem. LogItem is a simple class that encapsulates information that belongs to a given log entry:

Working with LogItem is not as straightforward as using the other methods, but it may be useful if you want to submit more detailed logging information. Here’s a sample that logs a warning along with an event ID:

Setting up Logging in Code

Do it Yourself: Storing a Reference to ILogger

Basically, the simplest possible implementation to use SLF is to just store an ILogger instance somewhere and be on your way. The sample below uses the BitFactory logger façade, which internally forwards log messages to the BitFactory logging framework:

LoggerService

LoggerService is a static repository you can use in different ways. It provides support for declarative configurations (taken from app.config), lets you just plug in a single logger, or completely customize and plug in advanced logger resolution strategies.

Lets have a look at a simplistic example: Create the above ConsoleLogger and make it available through LoggerService. Again, this is as simple as it gets:

Good to Know: LoggerService Never Returns Null

LoggerService guarantees you to always return a valid ILogger instance. If no logger is configured, it will just return you a NullLogger instance. NullLogger is a special implementation of the ILogger interface, which just discards everything you throw at it. You could say that NullLogger switches off logging without requiring any changes in your code.

Thanks to NullLogger, you never have to check for null references when retrieving a logger. Look at the snippet below: This code will not result in an exception, because GetLogger will not return null, but a NullLogger instance:

//you can explicitly assign a null reference…
LoggerService.SetLogger(null);
//…and the service will return you a NullLogger
ILogger logger = LoggerService.GetLogger();
//NullLogger will just discard this message, so no real logging happens
logger.Info("This message will be discarded");

Setting up Logging Declaratively (App.config)

Per default, LoggerService analyzes the application’s configuration file (app.config) in order to detect configured loggers. So if you want to go the declarative route, you don’t have to write a single line of code – it just works.

Here’s a sample app.config file that makes SLF write anything to the console through a ConsoleLogger:

Declarative configurations often make sense in more complex scenarios, especially if you use more powerful logging frameworks such as log4net. Here’s a complete configuration file that makes SLF use log4net. This app.config file contains two sections:

The slf section tells SLF to forward all logging data to log4net.

The log4net section is a standard log4net configuration (it has nothing to do with SLF). In this example, log4net is configured to write everything into a single log file.

<?xmlversion="1.0"encoding="utf-8" ?><configuration><configSections><sectionname="log4net"type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/><sectionname="slf"type="Slf.Config.SlfConfigurationSection, slf"/></configSections><slf><factories><!-- configure single log4net factory, which will get all logging output --><factorytype="SLF.Log4netFacade.Log4netLoggerFactory, SLF.Log4netFacade"/></factories></slf><!-- configures log4net to write into a local file called "log.txt" --><log4net><appendername="MainAppender"type="log4net.Appender.FileAppender"><paramname="File"value="log.txt"/><paramname="AppendToFile"value="true"/><layouttype="log4net.Layout.PatternLayout"><conversionPatternvalue="%date - %message %newline"/></layout></appender><root><levelvalue="ALL"/><appender-refref="MainAppender"/></root></log4net></configuration>

If you configure SLF through app.config, you don’t have to write any code, because SLF will detect the configuration on its own. Accordingly, just get the logger through LoggerService and log away:

Do note that if you plug in a custom logger through LoggerService.SetLogger, this will override any declaratively configured loggers. You can, however, always reset LoggerService through the LoggerService.Reset method.

Working With Loggers and Façades

Using the Built-in Loggers

SLF comes with a number of built-in loggers that implement ILogger, which you can use to quickly add logging functionality to your application. There’s the usual suspects such as ConsoleLogger, DebugLogger, or TraceLogger, as well as a few more fancy implementations (e.g. DelegateLogger or DecoratorLogger) and base classes you can use to quickly create your own logger implementations.

There’s a lot of samples that demonstrate the loggers and possibilities, all wrapped into individual projects. However, here’s a few samples:

Delegating Logging through DelegateLogger

DelegateLogger is a simple logger that allows you to quickly plug in some custom logic through a delegate or lambda expression. Here’s dummy sample for a WinForms application, which just shows a message box for every item that is logged to SLF.

Formatting Logging Output

The first snippet in this tutorial wrote “hello world” to the console, which looked like this:

Now, a lot of loggers derive from FormattableLoggerBase. This base class provides a Formatter property, which takes an instance of ILogItemFormatter. ILogItemFormatter is a very simple interface, which has only one task: Converting a given LogItem into a string.

Accordingly, if you wanted to change the format of the above message, you could just write a custom formatter and assign it to your logger. Here’s an alternative for a simple XmlFormatter:

The above snippet produces the following output, that renders a LogItem as an XML element:

Directing Trace Output To SLF

If you have an existing codebase that logs through the Trace class, and you would like to make use of SLF, you don’t necessarily have to change the existing code. The SLF core library contains the SlfTraceListener class which just redirects trace messages to SLF.

SLF comes with a sample that shows how to declare SlfTraceListener declaratively via app.config. But you can do this also programmatically:

Your own Logger: Extending the Logger Base Classes

If you want to create your own ILogger implementation, you can either create a new class that implements ILogger, or extend either LoggerBase or FormattableLoggerBase.

ILogger is not a complex interface, but there’s a lot of boilerplate code to implement. So in most cases, it’s probably more convenient to extend one of the base classes. Both require you to override just one method:

Sample: Implementing a ColoredConsoleLogger

The class below is a custom console logger which writes colored output to the console, depending on the LogLevel of the logged item. The class derives from FormattableLoggerBase in order to allow you to plug in a custom message formatter.

If you log through this ColoredConsoleLogger, a logged Info is displayed in green now:

Working with Available SLF Façade Libraries

SLF comes with a few façade libraries you can use to forward to a given logging frameworks. Currently, there is support for the following commonly known frameworks:

log4net

NLog

Enterprise Library

BitFactory Framework

…and if you would like to use SLF along with a framework that is not listed yet, writing your own façade is pretty easy!

We’ve provided samples and sample configurations for all these façades. Accordingly, you can just find the sample that suits you, and copy/paste the configuration code into your application.

Named Loggers

The “Named Loggers” feature allows you to define several loggers (programmatically or in code), and then access them through their names. You can even direct logging instructions to different logging frameworks based on logger names!

In order to get a named logger, just use the overload of LoggerService.GetLogger that takes a string parameter:

The downloadable SLF solution contains sample applications that show how to configure loggers with different names both programmatically or via configuration files.

The Hierarchical Lookup Process

When requesting a named logger, you don’t have to submit a name that exactly matches the name of a configured logger. Instead, named loggers are organized in a hierarchical manner. As soon as a named logger is being requested, SLF will just resolve the closest match and return you a matching logger instance:

In the above sample, SLF was configured with a total of eight loggers. You can see, that the logger names form a hierarchy. With this setup in place, the closest match will be returned on every request.

Accordingly, LoggerService.GetLogger("Foo.AAA") would return a logger of type Foo (closest match). And LoggerService.GetLogger("Foo.XXX.AAA") would return a logger of type Foo.XXX (closest match again).

Here’s some more samples, matching the above hierarchy:

Requested Logger Name

Returned Logger Type

Name of Returned Logger Instance

"Foo"

Type declared for "Foo"

"Foo"

"Foo.XXX"

Type declared for "Foo.XXX"

"Foo.XXX"

"Foo.XXXXXX"

Type declared for "Foo.XXX"

"Foo.XXXXXX"

"Foo.X"

Type declared for "Foo"

"Foo.X"

"FooXXX"

Type declared for "Foo"

"FooXXX"

"Bar.XXX"

Type declared for "Bar.XXX"

"Bar.XXX"

"Bar.ZZZ"

Type declared for "Bar"

"Bar.ZZZ"

"XXX"

Type declared for Default Logger

"XXX"

"XXX.Foo"

Type declared for Default Logger

"XXX.Foo"

"TEST"

Type declared for Default Logger

"TEST"

""

Type declared for Default Logger

""

null

Type declared for Default Logger

""

Fallback to Default Logger

The lookup for a logger will always fall back to the default logger type if no matching named logger was found. This should not come as a surprise. After all, the default logger is just a logger with the name [String.Empty].

And don’t forget – LoggerService always returns a valid logger instance and never a null reference. If no unnamed logger was configured at all, you would just receive an instance of NullLogger.

Exceptions to Named Logger Resolving

Hierarchical lookups work out of the box, but they are not guaranteed if you customize LoggerService:

If you inject a single ILogger instance into LoggerService via LoggerService.SetLogger, all requests will of course return this specific logger instance, regardless of the requested logger name.

If you inject a custom resolver into LoggerService by setting the LoggerService.FactoryResolver property, you gain full control over the lookup and logger creation process. Accordingly, you can completely change this behavior.

Configuring Named Loggers in Code or Declaratively

The sample projects show how to set up named loggers in code, or via the application configuration file (app.config).

Filtering

Currently, SLF provides not built-in filtering mechanism, but leaves that to the underlying logging frameworks. The reason for this is that we just wanted to provide a very lean interface to get started with.

However, we’ve already opened a topic on CodePlex’ discussion board, so please express your opinion. If we feel there is a demand for built-in filtering, we will provide the functionality in a matter of days:

Tutorial Part 2

The next part of this tutorial will discuss Resolvers, Factories, and creating your own logging façades. It will cover simple scenarios (you can plug-in factories with a single line of code) and more complex resolution scenarios for those among you who happen to deal with challenging logging situations. Stay tuned

Release days are good days – Colin Eberhardt and I are very happy to announce SLF 1.0!

SLF is a framework with a simple but ambitious mission: To provide every developer with the means to easily plug in logging functionality into her application. As such, it aims at two fundamental goals:

Simplicity: SLF allows you to plug in solid logging functionality into your application with literally one line of code, while providing you with an upgrade path to complex logging scenarios at any time.

Flexibility: SLF provides you with a common interface that decouples the logging framework of your choice (e.g. log4net or NLog) from your code. This eliminates dependencies on a given framework, thus allowing you to switch (or even combine!) frameworks at any time. Furthermore, SLF’s modular architecture allows you to plug-in custom logging strategies very easily.

When working with SLF, you’re usually dealing with the ILogger interface. There’s a few built-in implementations of this interface directly in the SLF core library (e.g. ConsoleLogger), but in productive environments, your ILogger implementation usually is a class that forwards logging instructions to a proprietary logging framework such as log4net, or a custom logging facility you wrote yourself. Hence the name façade:

From your application’s point of view, there is no dependency on the underlying façade and logging framework – you are always logging through the ILogger interface of the SLF core library. This allows you to easily exchange the underlying proprietary mechanism without having to change any of your code that performs the actual logging.

SLF also allows you to directly control the logger resolution process (the process that eventually leads to an ILogger instance). We will cover this in a later tutorial.

But why should we replace dependencies on logging framework X with dependencies on SLF?

You probably won’t worry about that, as SLF really just forwards logging information, and can be easily adjusted. However: There’s a simple pattern to get rid of that dependency, too. If you download SLF, you will find a sample project that implements a wrapper for SLF itself:

SLF in a Fictitious Sample: The Lifecycle of an Application.

I’ll try to outline the benefits of logging, and the role SLF can play in the context of a fictitious software project. We assume the following:

The application will contain various modules (plug-ins). The modules will be developed individually by separate teams.

All modules should log important information. These modules log through SLF, so they have no idea about the underlying logging framework.

Parts of the logged data should be sent back to the development team as soon as the first beta versions have been deployed.

Week 1: Setting Up Logging

Developers have other things in mind than thinking about logging frameworks. They do, however, set SLF in place with two simple steps:

Set a reference to the SLF core library.

Configure a logger within the main initialization routine of the application. For starters, all logged data is written to Visual Studio’s debugger by plugging a DebugLogger instance into the global LoggerService:

Actually, the first line of code in the application is related to logging:

Note that modules have no idea about the underlying logging strategy that was plugged into SLF (currently the DebugLogger from Week 1). They just know how to request a logger (ILogger interface) from LoggerService. What kind of logger they are dealing with is of no interest to them.

Week 3: Writing Logged Data to a File

There’s a lot of modules by now, which all direct logging information towards SLF. Currently, all this logged messages are being written to the debug window (as configured on Week 1). However, the developers would also like to have the data persisted in a file, while keeping the debug output at the same time.

Accordingly, the initialization routine from Week 1 is slightly altered:

//create two independent loggers
ILogger debugLogger = new DebugLogger();
ILogger fileLogger = BitFactoryLogger.CreateSingleFileLogger("log.txt");
//CompositeLogger will redirect all its logging data to the two loggers…
ILogger composite = new CompositeLogger(debugLogger, fileLogger);
//…so plug it into LoggerService
LoggerService.SetLogger(composite);

There’s now 3 loggers in play:

The initial DebugLogger that logs to the debug window.

The BitFactory façade was used to quickly set up logging to a file. The BitFactory façade is a library that comes with SLF (just like the NLog façade library or the log4net façade library) and makes use of the BitFactory logging framework. This SLF façade library is now referenced by the main application, but not the independent module libraries.

CompositeLogger (part of the core library) is then used as a channel that logs output to both the DebugLogger and the new BitFactoryLogger:

These four lines of code changed the logging behavior of the whole application. Even if there are now literally hundreds of logging instructions in various modules, they don’t need to be changed at all. Everything will now be logged to both the file and the debugger.

Week 4: Switching to Declarative Configurations and log4net

The integration team decides to plug in their logging framework of choice, which happens to be log4net. Furthermore, they want to get rid of programmatic initialization, and switch to declarative configuration. This requires two steps:

Configuring SLF and log4net in the application’s configuration file (app.config)

Remove all the code (initialization of LoggerService) from Weeks 1 and 3.

Actually, the above SLF configuration could have been written shorter, but the verbose version is recommended for readability. This would be a shorter, but equivalent version of the slf section:

<slf><factories><!-- this default factory is used for every logging instruction --><factorytype="SLF.Log4netFacade.Log4netLoggerFactory, SLF.Log4netFacade"/></factories></slf>

Week 5: Working with Named Loggers

One of the teams develops a module that logs very important data, and they would like to gather this data separately. It is therefore decided that this output will be logged through a named logger called LABDATA. This LABDATA logger should store this information separately.

Accordingly, a lot of logging instructions in this team’s module use SLF’s capability to work with named loggers:

This code was written by an independent team, and they haven’t changed the configuration of the main application. Accordingly, the logged information will still be routed through the default logger, because a logger that matches the name “LABDATA” just isn’t available yet.

So currently, “LABDATA” output will be logged to the same file as all other logging information.

But the important thing is: The mechanism is in place and SLF still works without errors!

Week 6: Declaratively Configuring the “LABDATA” Logger

During integration of the new module, SLF’s configuration is changed in order to support custom logging instructions for the LABDATA module.

Because log4net is used, which also supports named loggers out of the box, the SLF configuration does not need to be changed at all! Only the log4net section is being updated:

The adjustments in the application configuration file are specific to log4net:

Week 7: Using Another Logging Framework for the LABDATA Loggers

So far, the generated LabData logging file was manually sent to the development team of the new module, which proved to be tedious (somebody had to manually send a mail every day).

Accordingly, a team developed a simple custom logging façade for SLF. This façade uses WCF to send logged data directly to the team.

As a result, there are now two logging façades in play. We have a new situation:

Regular logging data should be logged to a file via log4net (same as before).

Logging data for LABDATA should be handled by the new WcfLogger.

Fortunately, integration of the new façade library is easy! It can be plugged into SLF declaratively through the application’s configuration file:

log4net configuration: The appender for the LABDATA logger is being removed.

SLF configuration: The new WcfLogger is declared, and configured to handle all LABDATA output. SLF allows us to inject arbitrary configuration information into the declaration. For the WCF logger, this is address information and credentials.

Again, only the configuration file was changed – the code in the modules was not touched at all.

Week 8 – Unit Testing Logging Instructions

The developers of the LabData module notice they didn’t cover all code in their unit test: Actually, they don’t know whether their logging instruction are properly executed or not.

In order to unit test their module, they just replace the configured loggers at runtime: They plug in TestLogger classes into LoggerService. TestLogger is a simple logger which just stores all logging input it receives.

This is how the initialization code of their unit test class looks like:

The above snippet installs a TestLoggerFactory. This factory will return TestLogger instances for every logger request that is made through LoggerService. This allows to test whether input was logged through the correct loggers.

Conclusion and Further Links

I hope the above scenario gave you an impression about how easily you can set up and adjust your logging environment with SLF. For more information, please visit the project page, check out the tutorials, or leave a feedback. Happy logging

]]>http://www.hardcodet.net/2009/10/wpf-disciples-resources-updated/feed0Windows Live Writer: Plug-ins to Format Content through CSS Classeshttp://www.hardcodet.net/2009/09/live-writer-plugins-to-format-content-through-css-classes
http://www.hardcodet.net/2009/09/live-writer-plugins-to-format-content-through-css-classes#commentsWed, 30 Sep 2009 20:12:15 +0000http://www.hardcodet.net/?p=637I like using CSS classes to format specific content of my blog posts, in order to keep my formatting centralized. I prefer HTML that looks like this over inline styles:

If you invoke the <spanclass="code">GetData</span> method, ...

Quickly inserting CSS directives is something you can’t easily do with Windows Live Writer. This started to annoy me while writing an article, so I came up with two simple plug-ins that do just that: Formatting selected text through CSS classes.

Plug-in 1: Quick-Insert a Predefined CSS Class

This is a very simple plug-in that stores one (1) single CSS class name, and applies it to the selected text with a single click. This is a fastest possible way to format several junks of your post with the same CSS class.

The simple assignment comes has a price, however: It takes some more work to reconfigure the used CSS class. Therefore, it mainly makes sense if you have quite a lot of similar content to format at once. Otherwise, the second plug-in is probably the better choice.

Using the Plug-in

Once the plug-in is installed (instructions at the end of the article), you’ll notice an additional entry on the side bar and the Insert menu of the tool bar, saying “Quick CSS…”:

All you have to do is selecting the portion of text you’d like to format, and click on the plug-in. The configured CSS class name will be immediately applied to the selected text.

First invocation / configuration

The first time you click on the plug-in, there is no formatting happening. Instead, the plug-in displays its options dialog because no CSS class has been configured yet. This dialog allows you to quickly set the CSS class that should be applied:

Subsequent clicks on the plug-in directly apply the class name you configured – this dialog is only opened automatically the first time.

Changing the Class Name

You can change the name of the used CSS class at any time. This requires a bit of work though, as you’ll have to go through Live Writer’s options dialog:

Plug-in 2: Selecting a CSS Class from a List of Class Names

This is a more flexible plug-in. It takes two clicks to format your text with a given CSS class, but it maintains a configurable list of CSS class names, and allows you to quickly select the class name to be applied from a popup.

Using the Plug-in

Once the plug-in is installed (instructions below), you will find a new entry saying “CSS Format…” on the side bar and Live Writer’s Insert menu. Clicking the plug-in (which causes a short delay the first time) opens a popup that lists your CSS classes in alphabetic order. In order to apply a CSS class to the selected text, just double-click a class name:

Most Recently Used Items

Note that if you have configured 10 or more CSS class names, the popup will display two lists, of which the upper list contains the 5 most recently used class names.

(I could make that feature configurable in a subsequent release, if requested.)

Configuring / Importing CSS Class Names

The plug-in allows you to quickly configure class names through a custom configuration dialog, and also supports importing class names directly from a CSS Style Sheet. You can open the dialog through the Popup by clicking the “Options” button:

Style Sheet Import

Clicking the Import Style Sheet button opens a file dialog that allows you to select a style sheet (probably the one you’re also using on your blog). Once selected, the plug-in imports all new class names from the style sheet.

Live Writer Bug: Reformatting Span-Tags

It appears that Live Writer has a bug when it comes to reformatting already formatted text spans. There’s currently no simple fix for this bug, so keep this in mind:

Imagine you have a preformatted junk of text that looks like this:

<spanclass="foo">hello</span>

Now, if you select the word “hello”, and try to assign it another CSS class (bar), you’d expect the new markup to look like this:

<spanclass="bar">hello</span>

Instead, Live Writer just keeps the old span, and wraps it into a second one.

Source Code Download for Developers

]]>http://www.hardcodet.net/2009/09/live-writer-plugins-to-format-content-through-css-classes/feed9Making WPF Popups Work in Windowless Applicationshttp://www.hardcodet.net/2009/09/activating-wpf-popups-ensures-controls-are-enabled
http://www.hardcodet.net/2009/09/activating-wpf-popups-ensures-controls-are-enabled#commentsWed, 23 Sep 2009 10:08:24 +0000http://www.hardcodet.net/2009/09/activating-wpf-popups-ensures-controls-are-enabledI’ve first encountered this issue with my WPF NotifyIcon, and now again while writing a plug-in for Windows Live Writer: If you try to display a WPF popup without any Windows open (the Popup is the only UI component there is), certain controls such as TextBox, ListView, or ListBox don’t receive proper mouse and/or keyboard input, and cannot be selected.

The reason for this issue is buried in the WPF framework, and how it interacts with Windows. Fellow WPF Disciple Andrew Smith pointed me in the right direction:

…because a Popup’s HWND has the WS_EX_NOACTIVATE so the WPF framework will not attempt to actually focus the associated hwnd (because its usually used with a window and you don’t want to deactivate the window when you focus something in the popup).

Accordingly, you’ll have to fiddle with Windows Interop to make things work. Here’s the snippet:

]]>http://www.hardcodet.net/2009/09/netdrives-update-101/feed0Snippet Time: Helper Libraries for C# / WPFhttp://www.hardcodet.net/2009/09/common-helper-libraries
http://www.hardcodet.net/2009/09/common-helper-libraries#respondMon, 14 Sep 2009 19:23:35 +0000http://www.hardcodet.net/?p=601I just made a few minor updates to two libraries which assemble as set of helper classes for C# and WPF and thought: Why not share them? The libraries aren’t really intended to be used directly in your code, but you might find one or another helper method or snippet that might make a nice addition to your own toolbox