Archive

Archive for the ‘C#’ Category

Understanding the “yield” keyword in 120 Seconds

April 17th, 2011

I’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:

  • Download the sample (VS2010).
  • Quickly glance at the few lines in the code-behind of the window.
  • Run the app.
  • Bow in front of the power of iterators 😉

image

 

Download Sample Application

Author: Categories: C# Tags: ,

An Abstraction Layer for Temporary Data in .NET and Silverlight

April 15th, 2010

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

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

 

Download Sample Project

 

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

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

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

 

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

Read more…

Author: Categories: C#, Silverlight Tags: ,

A Simplistic Random String Generation Snippet

January 25th, 2010

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

 

/// <summary>
/// A counter that is being incremented with every invocation of
/// <see cref="GetRandomString"/>.
/// </summary>
private static int seedCounter = (int)DateTime.Now.Ticks;


/// <summary>
/// Generates a random string of a given length, which consists
/// of characters taken from the UTF-8 table (0x21 - 0x7e).
/// </summary>
/// <param name="length">The length of the random string.</param>
/// <returns>Random characters.</returns>
public static string GetRandomString(int length)
{
  const int lower = 0x21;
  const int upper = 0x7e;

  StringBuilder builder = new StringBuilder();

  //increment thread-safe
  seedCounter = Interlocked.Increment(ref seedCounter);

  //create random with the seed (make sure it's not int.MinValue)
  Random rnd = new Random(seedCounter %int.MinValue);

  for (int i = 0; i < length; i++)
  {
    builder.Append((char) rnd.Next(lower, upper));
  }

  return builder.ToString();
}

 

Accordingly, invoking the method like this:

string random = GetRandomString(10);

 

…generates you a string comparable to this one: 2#,R`6>Cz{

Author: Categories: C# Tags:

Convert WCF Service Exceptions into Faults using Lambdas

December 8th, 2009

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

//Simplified example
public string Foo(string userName)
{
  try
  {
     Bar.FooBar(userName);
  }
  catch(ArgumentException e)
  {
    //convert exception into a WCF friendly FaultException
    throw new FaultException("Info about specific error");
  }
  catch(Exception e)
  {
    //convert exception into a WCF friendly FaultException
    throw new FaultException("Info about unspecific error");
  }
}

 

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:

public string Foo(string userName)
{
  return SecureFunc(() => Bar.FooBar(userName));
}

 

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.

public static void SecureAction(Action action)
{
  try
  {
    action();
  }
  catch (Exception e)
  {
    //productive code provides more specific
    //exception handling, but you should get the idea...
    throw new FaultException(e.Message);
  }
}

public static T SecureFunc<T>(Func<T> func)
{
  try
  {
    return func();
  }
  catch (Exception e)
  {
    //productive code provides more specific
    //exception handling, but you should get the idea...
    throw new FaultException(e.Message);
  }
}
Author: Categories: C#, WCF Tags:

An Introduction to SLF, the Simple Logging Façade

December 2nd, 2009

slf 

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:

  1. 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.
  2. 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.

Read more…

Author: Categories: C#, Open Source, SLF Tags: ,

Snippet Time: Helper Libraries for C# / WPF

September 14th, 2009

I 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 🙂

 

Hardcodet.Commons (C#, .NET 3.5)

Common helper classes and snippets (simple base classes, file management, weak events, extension methods etc.)

 

Hardcodet.Wpf.Commons (C#, .NET 3.5)

Stuff I commonly use in WPF projects, such as checking for design time, base classes for commands and converters, data binding helpers and other stuff.

 

I’ll keep these libraries up-to-date, version history will be posted here.

 

History:

2009.09.14  Initial blog release

Author: Categories: C#, Open Source, WPF Tags: , ,