Archive

Archive for January, 2010

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:

Lightweight Task Scheduling Library for .NET / Silverlight

January 9th, 2010

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

Features:

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

 

Download library and sample

Current Version: 1.0.2, 2010.01.12

 

What Does it Do?

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

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

private Scheduler scheduler = new Scheduler();

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

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

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

 

Silverlight

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

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

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

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


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

 

image

 

Jobs

 

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

Read more…