Posts Tagged “c-sharp”

Follow


My DateTime serialization practices

  

Show me your date

When sending DateTimes as string across the wire, it is quite useful to use ISO 8601 date formatting. For one, it holds all required info (including timezone offset specified), it is easy to infer the Kind of the DateTime (UTC, Local or Unspecified), it is widely and commonly used across most (if not all) platforms, and if omitting milliseconds, is lexicographically ordered, which makes it useful for indexed storage as well (for example on the filesystem, or as keys in a string based Key Value stores such as Azure Table Storage)

During the many times I had to deal with serialization implementations, while working on one of the many web frameworks I’ve been involved with, or with serialization libraries, I keep getting back to be needing to remember what I did last time, so this post is to serve as a future reminder to self on how I want it to be done.

Serializing a DateTime to a string:

string Serialize(DateTime value) {
    const string ISO8601Format = "o"; // this is a terrific little gem!

    return value.ToString(ISO8601Format);
}

Did you notice the “o” format specifier? This is a much better than typing “yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss.fffffffK”, which I’ve been doing until recently.

For lexicographically ordered version, we would only go so far to the seconds, and be sure to force the input datetime kind to UTC (otherwise order is difficult to maintain…):

string SerializeOrdered(DateTime value) {
    const string OrderedUniversalFormat = "u";
    return value.ToUniversalTime().ToString(OrderedUniversalFormat);
}

What’s the deal with Kind and Timezone offset?

The ‘K’ specifier will render the following:

The interesting bit here is that there is a difference between 2013-09-03T10:00:00-00:00 and 2013-09-03T10:00:00Z. They refer to the same point in time, however the former refer to the Local time where the offset is 0 (e.g. London, UK at winter time – a lovely picture), while the latter refer to the UTC time. This knowledge allow us to infer the actual datetime kind when parsing the result. How do we do that you may rightfully ask?

Deserializing DateTimes from a string:

DateTime DeserializeDateTime(string value) {
    return DateTime.Parse(value, null, DateTimeStyles.RoundtripKind);
}

That’s it. The trick is in the DateTimeStyles.RoundtripKind bit. I keep forgetting that, and this (and the “o” specifier) is the reason for this post.

When Deserializing ordered DateTimes, the former deserialization code would end up with a DateTime of Unspeficied kind, so it would be better to do that:

DateTime DeserializeOrderedDateTime(string value) {
    return DateTime.Parse(value, null, DateTimeStyles.AssumeUniversal).ToUniversalTime();
}

Fetching from many urls concurrently - the right way

  

I’ve recently bumped into a post describing how to access a bunch of urls. The post was describing usage of Parallel.ForEach as a mean to parallelize such code.

It goes down to describe the the improvement over the iterative, single threaded version, was bounded to the number of cores.

Multithreading is definitely a way to increase performance of long running, independent jobs. However, there is a major difference between jobs that are CPU bound (such a complex computations) and jobs that are IO bounds (file-system, web services, DB calls, whatnot). First, there is no reason to keep all those threads waiting for the IO call to complete, and second - the number of available threads is limited, so the improvement is bound to the number of cores.

The way to achieve a better improvement for the said scenario and similar others, is to use non-blocking calls that are using IO-completion ports instead of threads.

I’ve ran three versions of the code - serial, parallel, and Async IO based. The results are stunning. For 300 files, the serial one took ~3.5 minutes, the parallel to ~30 seconds, and the Async IO base took just under a second!

Notice the ServicePointManager.DefaultConnectionLimit = 1000; part, which tells the application how many concurrent outgoing connections are allowed. A modern windows host allow up to ~64k file descriptors (the stuff that amongst other things allow this behaviour) so a 1000 is not a problem.

I also like CountdownEvent very much. Easier than ManualResetEvent with a counter and Interlocked.Decrement calls.

Excerpt from the upcoming C# in depth Second Edition book - optional parameters and named arguments

  

see the announcement here: http://codebetter.com/2011/01/11/c-in-depth-optional-parameters-and-named-arguments-2/

 

Named arguments can easily make your code (on some occasions) more readable. One of c#4 features I miss when I work on a c#3 codebase

Official c# driver for MongoDB from 10gen

  

The announcement is on the users list - http://groups.google.com/group/mongodb-user/browse_thread/thread/62b071549a95dd4a?hl=en

 

Until now the two offerings were Norm and mongo-csharp, both are excellent OSS projects with lots of contributions and very nice velocity. My concern there was always that although there is definitely a place for more than one flavour, as usage patterns and even personal taste differ and pleasing everyone in a single product is impossible (see on rubyland for e.g., – there are MongoMapper, and Mongoid, and there are even some more, less-widespread ones). The major difference is that since the core of the ruby driver is maintained in a single location (and backed by paid-developers thx to 10gen), the things that are the same across (mainly BSON, client-server setup, connection management) are not duplicated, so we get a fully featured, very robust, tested by many core, and it gets out very fast.

On the c# side of things, the implementation of replica-sets in the client took some time to emerge after the official support on the server side was out.

 

So, it is an exciting announcement for the .NET community. I hope that the current drivers will know to adapt the drivers to use the official core.

fixing text files to DOS style line endings - CRLF

  

Today I ran into a project that had mixed line-ending styles between files in the project. There were even a few files that had different type of line endings within the same file (bulk of lines with UNIX style, and other bulks with DOS style)

 

I ended up running the following c# “script” to fix that, and set all files to UTF-8 while I was at it.

The trick is to simply load the file with File.ReadAllLines which is indifferent when it comes to the line-ending type, and then write that back using WriteAllLines which will use the currently set Environment.NewLine value (which is CRLF when on windows)

 

 

The code is listed here; you can simply download a zip, open it to the folder of your choice and dbl-click it.

the only prerequisite is .NET 4.0 (I wanted the recursive and lazy Directory.EnumerateFiles)

 

The is listed here. It is generated by a javascript snippet so if you cannot see this in your offline feed reader, just go to the gist page

 

JavaScript and .NET – meet jint

  

I’ve been looking for JavaScript scripting possibilities for .NET for quite some time. I always know I could hack an IKVM (java-to-csharp compiler) over Rhino (Java implementation of JavaScript), but it always felt a bit too complex.

I had my hopes on Microsoft to implement a JavaScript over the DLR but the news on the subject where vague at best, and with the latest moves on shutting down support of IronPython and IronRuby, I’d think that IronJS won’t really happen anytime soon. There is a project named IronJS over at github, but it is quite incomplete. (for e.g., the test suite include a single mostly-commented-out file).

 

Reading one more Rhino/IKVM article on CodeProject this week, I stumbled on a comment pointing to a new JS interpreter implementation for .NET.  yup – that’s right. Interpreter. Not a compiler, nor a VM. The project is at http://jint.codeplex.com/.

 

I Hg cloned the repo, ran MsBuild.exe on the Jint.sln file, and referenced output binaries (only two dll files - jint’s and antlr’s), and voila.

 

the following stupid code, showing executing JS code (see the regex syntax in script1), executing .NET code from JS script (the DateTime class), and passing a .NET object as parameter to the script:

 


class Person
{
    public string Name;
}
static void Main(string[] args)
{
    var script1 = @"return 'hello'.replace(/l{2}/gi, 'LL');";
    var script2 = @"var d = new System.DateTime(2010,3,1);
                    return d.Day;";
    var script3 = @"return 'hello ' + p.Name;";

    var jint = new Jint.JintEngine();

    var result1 = jint.Run(script1);
    Console.WriteLine(result1);

    var result2 = jint.Run(script2);
    Console.WriteLine(result2);

    var p = new Person { Name = "Ken" };
    jint.SetParameter("p", p);
    var result3 = jint.Run(script3);
    Console.WriteLine(result3);

}

 

The output is:

heLLo
1
hello Ken

 

 

so what the whole fuss is about?

 

think about a view engine that can execute in the Server for generating initial http response, and then executing the same templates on the client-side. Not only that, it should be possible to share templates between Java and .NET servers in a heterogeneous environment

 

I know that Spark view engine support both server and client side execution, but I remember hearing from the leaders of Spark that it was never a goal, and I also do not like the syntax of Spark anyway (brings back bad memories from nant)

 

It also has a few more appealing features. For one, it does not generate bytecode, so you can hot-swap scripts without leaking memory.

 

I’ll be playing with this some more should time allow.

ReaderWriterLockSlim vs lock

  

So you’ve got this boring old lock keyword, with its “only one at a time” semantics, and you think “hey, lets use the ReaderWriterLock, since its cooler, and it now has a Slim version so it MUST be great !”

 

That is wrong on many levels.

 

Lets start with exploring what the RWLS is about, in contrast to the lock keyword (which is a syntactic sugar for Monitor).

Both are used to synchronise access to a shared resource that might get read and written by different threads at the same time.

the general pattern is (pseudo-code, please do not Copy And Paste to your favourite IDE :) ):


variable aResource

lock aLock

 

// when reading from the shared resource

lock_for_read(aLock):

   foo = aResource.get_value

   do_something_with foo

 

// when writing to the shared resource

lock_for_write(aLock):

   aResource.set_value something

 

The Monitor construct only allow a single thread to access the synchronised block at a time, whether it is for reading or writing, so actually the isn’t a distinction between lock_for_read and lock_for_write, instead there is a single lock keyword.

 

The meaning is that if you have many threads coming in and trying to read from the shared resource, they would have to queue and enter the block one by one.

 

The ReaderWriterLock allow multiple threads to access a read block at the same time, so they will only need to wait once a thread is asking for a write lock. Then the writing thread will wait for all other threads within synchronised blocks to complete, then do its thing.

 

Sounds great, isn’t it?

 

Well, actually the benefit of a ReaderWriterLock will only be in place when these two conditions are in place:

why? because if the block executes very fast, then the waiting read threads will not need to actually queue up.

And if writes are not very sparse, an exclusive lock (because of the writes) will be taken many times, causing reading threads to queue anyway.

 

Adhering to the “no free gifts” rule, the usage of a ReaderWriterLock has more overhead than that of a Monitor, thus it would not be advisable to consider using the ReaderWriterLock unless you know for sure that the two aforementioned conditions will take place in the scenario.

 

And even then, you one should beware of a problem that might happen since there isn’t a syntactic sugar for the ReaderWriterLock. Since you have to release the lock yourself, the common usage pattern is:


ReaderWriterLockSlim locker = new ReaderWriterLockSlim();
...
// read block
locker.EnterReadLock();
try
{     //readAction
}
finally
{     locker.ExitReadLock();
}


// write block
locker.EnterWriteLock();
try
{     //write Action
}
finally
{     locker.ExitWriteLock();
}

 

Since I know that the usage is not 100% trivial, and that I might forget to exit the lock in a finally block (I’ve seen code examples around the interweb that forget to do so), I am usually looking up previous code of mine, and then copy-and-paste it.

Since like many other developers I tend to be lazy and sloppy when copy-pasting boring pieces of code around, I end up doing some mistakes such as entering a read lock, however exiting a write lock. I then get weird runtime exceptions that it takes a good few minutes to figure out. annoying.

This is without taking UpgradeableReadLock into account, which (imo) does not have a trivial API.  I will put a separate post explaining UpgradeableReadLock btw.

 

Summary:

 

Now since I found myself needing to use a ReaderWriterLock more than once lately, and since I did repeat the stupid copy-and-paste mistakes more than once, I created a little helper for that, included in my old-ish D9.Commons project, which is where I through reusable pieces of code at. Which reminds me that I need to move it to github some when soon.

Meanwhile it is at http://code.google.com/p/d-9/source/browse/trunk/src/D9.Commons/D9.Commons/Locks/Lock.cs, and it contains shortcut methods for executing code within Read, Write and UpgradeableRead blocks.

I’ll run a different post with a couple of usage snippets later.

HashSet.UnionWith documentation FAIL – trust your instinct

  

From the method’s doc:

Modifies the current HashSet<T> object to contain all elements that are present in both itself and in the specified collection.

 

image

 

Now I know my way around (at least the basics of) set theory, and I know what union means. nonetheless I read the doc of the method and for some reason I thought that I’d get the intersection.

 

For those unsure about what Union means (or what it actually does), the following code:

var set = new HashSet&lt;int&gt;(new[] {1, 2});
var other = new[] {2, 3};
set.UnionWith(other);
Console.WriteLine(Serialize(set));

 

So, I ended up bumping my head on the wall keyboard for a couple of minutes trying to understand why a perfectly good test fail with no reason, until I figured it out. It is true that I wasn’t showing a huge amount of smartness here, and it could be that my English skills are poor, but I believe replacing “and” with “or” will serve the method’s doc better.

 

If the BCL was open source I would have sent a patch with the doc fix …

AutoStubber to ease stub based unit tests

  

Tired of setting up stubs for your class under test?

Tired of compile errors when you add one more dependency to a class?

The AutoStubber to the rescue.

Given

interface IServiceA
{
	string GetThis(long param);
}
interface IServiceB
{
	Do DoThat(string s);
}

class MyService
{
	public MyService(IServiceA a, IServiceB b) { ... }
	...
}

...

you can write;

var service = new AutoStubber.Create();
// Arrange
var theString = &quot;whatever&quot;;
service.Stubs().Get.Stub(x=>x.GetThis(0).IgnoreArguments().Return(theString);

// Act
service.Execute();

// Assert
service.Stubs().Get.AssertWasCalled(x=>x.DoThat(theString);

 

The code for AutoStubber:

public class AutoStubber&lt;T&gt; where T : class
{
	static readonly Type TypeofT;
	static readonly ConstructorInfo Constructor;
	static readonly Type[] ParameterTypes;
	static readonly Dictionary&lt;object, AutoStubber<T&gt;> Instances = new Dictionary&lt;object, AutoStubber<T&gt;>();
	static AutoStubber()
	{
		TypeofT = typeof(T);
		Constructor = TypeofT.GetConstructors().OrderByDescending(ci => ci.GetParameters().Length).First();
		ParameterTypes = Constructor.GetParameters().Select(pi => pi.ParameterType).ToArray();
	}

	public static AutoStubber&lt;T&gt; GetStubberFor(T obj)
	{
		return Instances[obj];
	}

	bool _created;
	public T Create()
	{
		if (_created)
			throw new InvalidOperationException(&quot;Create can only be called once per AutoStubber&quot;);
		_created = true;
		return Instance;
	}

	readonly Dictionary&lt;Type, object&gt; _dependencies = new Dictionary&lt;Type, object&gt;();
	private T Instance { get; set; }
	public AutoStubber()
	{
		var parameters = new List&lt;object&gt;(ParameterTypes.Length);
		foreach (var parameterType in ParameterTypes)
		{
			var parameter = MockRepository.GenerateStub(parameterType);
			parameters.Add(parameter);
			_dependencies[parameterType] = parameter;
		}
		Instance = (T)Constructor.Invoke(parameters.ToArray());
		Instances[Instance] = this;
	}
	public TDependency Get&lt;TDependency&gt;()
	{
		return (TDependency)_dependencies[typeof(TDependency)];
	}
}
public static class AutoStubberExtensions
{
	public static AutoStubber&lt;T&gt; Stubs&lt;T&gt;(this T obj)
		where T : class
	{
		return AutoStubber&lt;T&gt;.GetStubberFor(obj);
	}
}

 

I know there is the AutoMockingContainer, and various other stuff out there, but this thing just was very natural to me, it uses a very simple API (do not need to keep reference to the Container), and took me less than an hour to knock off.

An enhancement I consider would be to allow setting pre-created values to some of the parameters. But meanwhile I did not happen to need it.

Interlocked.Increment vs. lock – surprise surprise !

  

 

Problem at hand: an ID generator.

 

Like many other things, developers can be categorized into three types : *

Now I am definitely not a concurrency guru like myteammates, however when I looked at a code for an ID generator that had

public int GetNextId() {
	lock(locker)
		return nextId++;
}

I immediately ran a git-checkout, changed that offending piece of code to

public int GetNextId() {
	return Interlocked.Increment(ref nextId) – 1;
}

And created a patch to send to the innocent owner of the code.

 

Smart heh? **

 

Then I thought that it won’t hurt to throw in a little proof for this amazing improvement.

Running 1000 calls to a GetNextId that was using a lock, took longer than calling the method using Interlocked !  Ah Ha – who’s the man?

 

Then I realised that a better test will be to run these 100 calls in parallel. That is after all the whole idea of a shared generator. Many threads might need to call it on the same time !

 

To my surprise, when asking for IDs in parallel, the interlocked construct was almost always slower, taking about 150% of the time the lock construct took on most runs (I tried this again and again, every time averaging 100 repeats).

 

Here’s a screenshot of the test run

interlocked vs lock

 

Code is here: https://gist.github.com/24b9012a49392c4e458b

 

After thinking about this a little, I think that I have an idea why this is happening, assuming my SpawnAndWait call is not entirely stupid (is it?)

 

So I call you my dear readers (most of which are way smarter than I am): what is your take on that? why did that happen? and would you have chosen lock or interlocked for an ID generator?

 

 

** probably not

Linq Cast extension method and InvalidCastException

  

For times when one wants the average of a collection of numbers, Linq’s Average() extension method is an easy win.

The problem is that it won’t work on a collection of byte elements.

The initial attempt would be:

var numbers = new byte[] {1, 2, 3, 4};
var avg = numbers.Cast&lt;int&gt;().Average();
Console.WriteLine(avg);

 

However this will fail with

Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
   at System.Linq.Enumerable.d__aa`1.MoveNext()
   at System.Linq.Enumerable.Average(IEnumerable`1 source)

 

The workaround is to cast using the Select operator, and manually cast to int:

var numbers = new byte[] {1, 2, 3, 4};
var avg = numbers.Select(b=>(int)b).Average();
Console.WriteLine(avg);

 

 

The author of the best explanation that will be posted as a comment to this post will get a huge prize (in other words – might get a mention in a follow up post …)

 

 

 

  This was a short reminder-post. I do have some more interesting things awaiting in the pipe, and I promise to re-attend my blog now that the pressure of the new baby and of setting up the IDCC conference is out of the way. Good things comes to those who wait blah blah blah.

System.DateTime.Date, or why a code review is definitely a good thing

  

So today a new dev has joined the team. Not too soon after he got his hands on one of our solutions I got an IM from him with the following snippet:

public static DateTime GetDateOnly(this DateTime dateTime)
{
   return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day);
}

My code. My blame.

It apparently skipped the DateTime.Date property of System.DateTime. After over 5 years in C# world.

Debug Driven Development

  

Imagine you have something weird going on in an application.

Something is not behaving they way it should be, yet no exception is being thrown.

 

Then drilling down you find this piece of magic:

try
{
    DoSomething();
}
catch (Exception exception)
{
    exception.ToString();
}

Beware of static session

  

The bug: Weird behaviours regarding session management

  The blame: (within session access wrapper static class):

private static IDictionary session;
...
if (session == null)&#160;&#160; session = new SessionAdapter(HttpContext.Current.Session);
...

so the first time the last line is called, the then-current-session is stored in a static variable, thus the first session is always referenced even for newer sessions.

 

The reason for the above code being present in the first place is that:

public static void SetSessionTo(IDictionary newSession)
{
    session = newSession;
}

So that tests that a stubbed ‘session’ could have been injected into the session-wrapper-static-class thingie.

Clearly, the implementation was wrong.

  The fix: now the code looks like this:

private static IDictionary stubbedSession;

static IDictionary Session
{
    get { return stubbedSession ?? MonoRailHttpHandler.CurrentContext.Session; }
}

And these were 60 seconds on careless coding.

 

Ken, the careless coder

Serving a file from a WCF service

  

Following my post on mini-web server with WCF, I’ve been asked about how to serve static files (images, stylesheets, scripts).

WCF services can return a Stream, so it’s just a matter of calling File.OpenRead to get a the stream


publicStreamGetFile(stringfile)
        {

            // We forbid access to directories outside of the site root 

if (file.Contains(".."))
                thrownewSecurityException();

            varext=Path.GetExtension(file).ToLower().TrimStart('.');

 

            // Just a helper that will 

            //set WebOperationContext.Current.OutgoingResponse.ContentType 



            SetContentType(ContentInfo.For(ext));

            varfilePath=Path.Combine(this.siteRoot, file);
            returnFile.OpenRead(GetActualFilePath(filePath));
        }

ContentInfo.For() is a helper for mapping an extension to a mimetype, with a two-stage lookup:

///&lt;summary&gt;
/// Represents info on a given file
///&lt;/summary&gt;
publicstaticclassContentInfo
    {
        staticreadonlyKeyValuePair&lt;MimeTypes, string&gt;[] contentInfoFor=new[]
        {
            newKeyValuePair&lt;MimeTypes, string&gt;(MimeTypes.Js, "text/javascript"),
            newKeyValuePair&lt;MimeTypes, string&gt;(MimeTypes.Css, "text/css"),
            newKeyValuePair&lt;MimeTypes, string&gt;(MimeTypes.Html, "text/html"),
            newKeyValuePair&lt;MimeTypes, string&gt;(MimeTypes.Plain, "text/plain"),
            newKeyValuePair&lt;MimeTypes, string&gt;(MimeTypes.Gif, "image/gif"),
            newKeyValuePair&lt;MimeTypes, string&gt;(MimeTypes.Jpeg, "image/jpeg"),
            newKeyValuePair&lt;MimeTypes, string&gt;(MimeTypes.Tiff, "image/tiff"),
        };

        ///&lt;summary&gt;
/// Gets the mime type for a given &lt;see cref="MimeTypes"/&gt;
///&lt;/summary&gt;
///&lt;param name="mimeType"&gt;The file's &lt;see cref="MimeTypes"/&gt;&lt;/param&gt;
///&lt;returns&gt;The file's mime type&lt;/returns&gt;
publicstaticstringFor(MimeTypesmimeType)
        {
            return (frompincontentInfoFor
wherep.Key==mimeType
selectp.Value)
                   .First();
        }

        ///&lt;summary&gt;
/// Gets the mime type for a given extension
///&lt;/summary&gt;
///&lt;param name="extension"&gt;The file's extension&lt;/param&gt;
///&lt;returns&gt;The file's mime type&lt;/returns&gt;
publicstaticstringFor(stringextension)
        {
            returnFor(MimeType.For(extension));
        }
    }

and

///&lt;summary&gt;
/// Helpers for &lt;see cref="MimeTypes"/&gt;///&lt;/summary&gt;
publicclassMimeType
    {
        staticreadonlyKeyValuePair&lt;string, MimeTypes&gt;[] mimeTypeForExtension=new[]
            {
                newKeyValuePair&lt;string, MimeTypes&gt;("js", MimeTypes.Js),
                newKeyValuePair&lt;string, MimeTypes&gt;("css", MimeTypes.Css),
                newKeyValuePair&lt;string, MimeTypes&gt;("htm", MimeTypes.Html),
                newKeyValuePair&lt;string, MimeTypes&gt;("html", MimeTypes.Html),
                newKeyValuePair&lt;string, MimeTypes&gt;("txt", MimeTypes.Plain),
                newKeyValuePair&lt;string, MimeTypes&gt;("gif", MimeTypes.Gif),
                newKeyValuePair&lt;string, MimeTypes&gt;("jpg", MimeTypes.Jpeg),
                newKeyValuePair&lt;string, MimeTypes&gt;("jpeg", MimeTypes.Jpeg),
                newKeyValuePair&lt;string, MimeTypes&gt;("tiff", MimeTypes.Tiff),
            };

        ///&lt;summary&gt;
/// Selects a &lt;see cref="MimeTypes"/&gt; for a given file extension 
///&lt;/summary&gt;
///&lt;param name="extension"&gt;The file's extension&lt;/param&gt;
///&lt;returns&gt;The file's mime type&lt;/returns&gt;
publicstaticMimeTypesFor(stringextension)
        {
            extension=extension.TrimStart('.');

            return (frompinmimeTypeForExtension
wherep.Key==extension
selectp.Value)
                .First();

        }
    }

When MimeTypes are:

publicenumMimeTypes
    {
        Js, Css, Html, Gif, Jpeg, Tiff, Plain
    }

Mini web server using WCF

  

I’ve written a simple application for a friend that monitors the fax machine in his office.

The machine saves incoming messages in the files server, and he needed a way to manipulate the files in various ways.

One of the things he wanted was the ability to present data and allow actions to run over the web. Also

As he’s thinking of deploying this on multiple different sites, and would like to be able to set this up easily without configuring web servers etc., and as there’s hardly any server-side logic to the UI anyway (the front is JSON consuming jQuery site), and there’s a windows service in there anyway for running some recurring tasks, I decided to set up the UI as a WCF service with WebHttpBinding, hosted within the Windows Service.

Here’s the code for the “Web Server”:

///<summary>
/// Serving HTTP for the UI
///</summary>

public class WebServer 
{
    ///<summary>
    /// Access to the current instance of <see cref="WebServer"/>
    ///</summary>
    public static WebServer Current { get; private set; }
    
    ///<summary>
    /// The current settings
    ///</summary>
    public ISettings Settings { get; private set; }
    
    private WebServiceHost host;
    private readonly ILogger logger;

    ///<summary>
    /// New WebServer
    ///</summary>
    ///<param name="logger"><see cref="ILogger"/></param>
    ///<param name="settings">Settings</param>
    public WebServer(ILogger logger, ISettings settings)
    {
        this.logger=logger;
        Settings=settings;
        Current=this;
    }

    ///<summary>
    /// Start a new server
    ///</summary>
    public void Start()
    {
        logger.Info("Initialising the web server");
        host = new WebServiceHost(typeof(FaxManagerService), newUri("http://localhost:"+Settings.WebServerPort+"/"));
        var bindings = new WebHttpBinding();

        host.AddServiceEndpoint(typeof(IFaxManagerService), bindings, "");
        host.Description.Behaviors.Add(new SessionAwareAttribute());

        var sdb=host.Description.Behaviors.Find<ServiceDebugBehavior>();
        sdb.HttpHelpPageEnabled = false;
            
        logger.Info("Starting the web server");
        host.Open();
        logger.Info("The web server was started successfully on port "+Settings.WebServerPort);
    }

    ///<summary>
    /// Restart the server (effectively creating a new service host)
    ///</summary>
    public void Restart()
    {
        Stop();
        Start();
    }

    ///<summary>
    /// Stop the server
    ///</summary>
    public void Stop()
    {
        host.Close();
        host = null;
    }
}

the “Web Application” is a WCF ServiceContract named IFaxManagerService.

I’ll post about it, and about interesting related stuff later on

Using generic classes and avoid locks

  

In D9.Commons, there’s a class responsible for mapping from enum values to their respective description, and vice versa - DescribedEnumHandler.cs

The initial API I had in mind was


var enumValue = Enums.From&lt;MyEnum&gt;("The description");

var enumDescription = Enums.ToDescription(MyEnum.Something);

The Enums class would hold an IDictionary to map from the given Enum type, to it’s DescribedEnumHandler

Then came the question: when should I initialise that map, and how should I allow access to it?

Solution 1: Synchronise access to the map.

Cons: every access to the Enums methods will require synchronisation code.

Solution 2: Allow only one point of initialisation, through a static Initialise(…) method, accepting enum types, or assemblies with enums. This method will be called when the application loads, and after all of the enums are initialised, all the following usages will be lock free.

Cons:

a. It’s ugly.

b. You end up creating way too many handlers, even if you won’t use most or even any of them.

c. It really is ugly. You don’t believe me? look here.

Solution 3: Instead of using Generic methods (From<T> and ToDescription<T>), I changed the Enums class to a generic Enum<T> class.

within the class, there’s a single static member, DescribedEnumHandler of T.

Every call to Enum<T> for a new T will instantiate the needed handler, Just In Time.

That’s because with generic types, every concrete type is a new type, so List<int> and List<long> are two separate types, without any inheritance relationship between them, so their static members are not shared.

That’s the class I ended up with: Enums.cs

Generic types vs. Generic methods - can you tell the difference?

  

classWrapper
{
    publicstaticintCounter{ get; privateset;}
    staticWrapper()
    {
        Counter=0;
    }
    publicTGet&lt;T&gt;()
    {
        ++Counter;
        returndefault(T);
    }
}

classWrapper&lt;T&gt;
{
    publicstaticintCounter{ get; privateset;}
    staticWrapper()
    {
        Counter=0;
    }
    publicTGet()
    {
        ++Counter;returndefault(T); 

    }

}   }

“The first uses generic methods while the second is a generic class” is true, but is not what I’m looking for here …

Single and looking

  

explanation (before the wife kills me): I have some free time in the coming months, so I’m looking for interesting consulting gigs.

So, if you’re in a company / dev team, and looking for some help with Castle (Windsor, MonoRail), NHibernate, or general information system design and architecture advices or training, setting up build and test environments, or any other of the things I rant about in this blog, then I’m your guy.

I also do web-client ninja work, dancing the crazy css/html/javascript tango (jQuery: yes, Ms-Ajax: no)

I currently live in Israel, but I’m fine with going abroad for short terms if you’re an off-shore client.

you can contact me at “ken@kenegozi.com”

Described Enums in NHibernate

  

First feature in D9.NHibernate: DescribedEnumStringType

That’s a generic IUserType for mapping enum columns using the descriptions of values instead of their names.

It depends on D9.Commons which contains the Described Enum helpers described in an early post

Usage:

given the following enum:

usingSystem.ComponentModel;

namespaceOpenUni.Domain.Modules
{
    publicenumModuleTypes
    {
        [Description("ר")]
        Standard,

        [Description("מ")]
        Advanced,

        [Description("מס")]
        AdvancedSeminar,

        [Description("תש")]
        Masters
    }
}

mapping a field of type ModuleTypes will look like that:

&lt;propertyname    = "ModuleType"column  = "ModuleType"type    = "D9.NHibernate.UserTypes.DescribedEnumStringType`1[[OpenUni.Domain.Modules.ModuleTypes, OpenUni.Domain]], 
              D9.NHibernate" /&gt;

or if you use Castle ActiveRecord attributes for mapping:

[Property(ColumnType = "D9.NHibernate.UserTypes.DescribedEnumStringType`1[[OpenUni.Domain.Modules.ModuleTypes, OpenUni.Domain]], D9.NHibernate")]
public virtual ModuleTypes ModuleType {get; set;}

Code is here:

http://code.google.com/p/d-9/source/browse/#svn/trunk

I’ll build and upload binaries once I get some time for that. meanwhile you should be able to just svn-co the code, then nant from the root. (assuming nant 0.86b2 and .net 3.5 on the machine)

Described Enums 2.0

  

As part of my university seminar, I found myself writing this little enum:

usingSystem.ComponentModel;

namespaceOpenUni.Domain.Modules
{
    publicenumModuleTypes
    {
        [Description("ר")]
        Standard,

        [Description("מ")]
        Advanced,

        [Description("מס")]
        AdvancedSeminar,

        [Description("תש")]
        Masters
    }
}

If you can’t read Hebrew then for the sake of this post, the following is applicable:

usingSystem.ComponentModel;

namespaceOpenUni.Domain.Modules
{
    publicenumModuleTypes
    {
        [Description("A standard module")]
        Standard,

        [Description("An advanced module")]
        Advanced,

        [Description("An advanced seminar")]
        AdvancedSeminar,

        [Description("Module in a Masters course")]
        Masters
    }
}

You want the description of a given value, or to parse a given description string (say from the DB) to get the value it represents.

Many code bases I’ve seen contains an EnumHelper class or a variation of one, which allow just the same. Many of these use un-cached reflection to achieve that. As in my scenario this mapping will happen many (I mean many) times, I thought about making it a bit more agile.

Here’s what I got:


usingSystem;
usingSystem.Collections;
usingSystem.Collections.Specialized;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Linq;
usingSystem.Reflection;

namespace NHibernate.Type

{
    ///&lt;summary&gt;
/// Allow access to enum values with 
///&lt;see cref="DescriptionAttribute"&gt;DescriptionAttribute&lt;/see&gt;
/// set on them
///&lt;/summary&gt;
publicstaticclassDescribedEnumHandlers
    {
        privatestaticreadonlyIDictionaryhandlers=newListDictionary();

        ///&lt;summary&gt;
/// Initialises enum types to be used with the &lt;see cref="DescribedEnumHandlers"&gt;&lt;/see&gt;
///&lt;/summary&gt;
///&lt;param name="assemblies"&gt;The assemblies to grab described enums from&lt;/param&gt;
publicstaticvoidInitialise(paramsAssembly[] assemblies)
        {
            Initialise((IEnumerable&lt;Assembly&gt;)assemblies);
        }

        ///&lt;summary&gt;
/// Initialises enum types to be used with the &lt;see cref="DescribedEnumHandlers"&gt;&lt;/see&gt;
///&lt;/summary&gt;
///&lt;param name="assemblies"&gt;The assemblies to grab described enums from&lt;/param&gt;
publicstaticvoidInitialise(IEnumerable&lt;Assembly&gt;assemblies)
        {
            vartitledEnums=fromassemblyinassemblies
selectassembly
intoa
fromtypeina.GetTypes()

                                  wheretype.IsEnum&amp;&amp;
                                        (fromfintype.GetFields()
                                         wheref.GetCustomAttributes(typeof (DescriptionAttribute), false).Length==1
selectf
                                        ).Count() >0
orderbytype.FullName
selecttype;

            foreach (vartypeintitledEnums)
            {
                handlers.Add(type, newDescribedEnumHandler(type));
            }
        }

        ///&lt;summary&gt;
/// Extract the description for a given enum value
///&lt;/summary&gt;
///&lt;param name="value"&gt;An enum value&lt;/param&gt;
///&lt;returns&gt;It's description, or it's name if there's no registered description for the given value&lt;/returns&gt;
publicstaticstringEnumToDescription(objectvalue)
        {
            varhandler=handlers[value.GetType()] asDescribedEnumHandler;
            
            returnhandler!=null?handler.GetDescriptionFrom((Enum)value) 
                : value.ToString();
        }

        ///&lt;summary&gt;
/// Gets the enum value for a given description or value
///&lt;/summary&gt;
///&lt;typeparam name="T"&gt;The enum type&lt;/typeparam&gt;
///&lt;param name="stringValue"&gt;The enum value or description&lt;/param&gt;
///&lt;returns&gt;An enum value matching the given string value, as description (using &lt;see cref="DescriptionAttribute"&gt;DescriptionAttribute&lt;/see&gt;) or as value&lt;/returns&gt;
publicstaticEnumToEnumValue&lt;T&gt;(thisstringstringValue)
            whereT :struct
        {
            vartype=typeof (T);
            varhandler=handlers[type] asDescribedEnumHandler;

            returnhandler!=null
?handler.GetValueFrom(stringValue)
                : (Enum)Enum.Parse(type, stringValue, false);
        }
        
        ///&lt;summary&gt;
/// Used to cache enum values descriptions mapper
///&lt;/summary&gt;
privateclassDescribedEnumHandler
        {
            privatereadonlyIDictionary&lt;Enum, string&gt;toDescription=newDictionary&lt;Enum, string&gt;();
            privatereadonlyIDictionary&lt;string, Enum&gt;fromDescription=newDictionary&lt;string, Enum&gt;();
            publicDescribedEnumHandler(Typetype)
            {
                varenumEntrys=fromfintype.GetFields()
                                 letattributes=f.GetCustomAttributes(typeof(DescriptionAttribute), false)
                                 whereattributes.Length==1
letattribute= (DescriptionAttribute)attributes[0]
                                 selectnew
                                 {
                                     Value= (Enum)Enum.Parse(type, f.Name),
                                     attribute.Description
                                 };

                foreach (varenumEntryinenumEntrys)
                {
                    toDescription[enumEntry.Value] =enumEntry.Description;
                    fromDescription[enumEntry.Description] =enumEntry.Value;
                }
            }

            publicstringGetDescriptionFrom(Enumvalue)
            {
                returntoDescription[value];
            }

            publicEnumGetValueFrom(stringtitle)
            {
                returnfromDescription[title];
            }

        }

    }
}

Usage:

DescribedEnumHandlers.Initialise(typeof(ModuleTypes).Assembly);

Console.WriteLine(DescribedEnumHandlers.EnumToDescription(ModuleTypes.Standard));
Console.WriteLine("ר".ToEnumValue&lt;ModuleTypes&gt;());

Next time I’ll show you how I made it play nicely with NHibernate

That's a better demo code

  

Lately I ranted a bit about the responsibility of community leaders, to not present totally crappy code, at least not without a disclaimer.

This is a better way of doing that. Another great post from Mike.

I might have also try-catch-ed the

(HttpWebRequest)WebRequest.Create(url)

bit, but anyway that’s good code for people to copy&paste into their project without leaving HttpWebResponses and other Streams in danger of hanging loose.

MSDN Killed my using directive

  

I’m now sitting in a certain lecture by a well known MS speaker.

The title is “ASP.NET Hidden Gems”, but that’s not the point.

During the presentation the dude is showing nice things like Custom Build Providers, Custom Expression Builders, Virtual Path Provider (that’s a nice one), Session State Partitioning (nice), and other stuff.

This is all great and cool and nice and blah blah blah.

However, now he’s just showed how he’s using a CustomBuildProvider to “make data access more efficient”, by setting a custom build provider for data-set xsd files, creating cleaner Data objects instead of TypedDataSets.

That’s a very nice thing.

However, his demo code, splashed over two 100” mega screens, included a use of SqlConnection and DataReaders, without using “using”.

heck, he didn’t even dispose the objects on “finally”.

I mean - WTF?

That’s the reason I hate DEMO codes. People in the crowd is looking at that, and then they go ahead and write the same code in their day job. And then I get called in to fix it.

Was it so difficult for the guy to write better code? heck, the “using” keyword would have eliminated at least 4 lines from the demo, so it would even be more presentable.

I simply don’t get it.

Key-level locked cache - real life implementation

  

Following my post on key-level locked cache, I got the following piece of code from my friend Moran Benisty, implementing the same idea over XmlDocuments which is being loaded over the Internet, and ASP.NET’s Cache.

This is a real life code. He’s using it on a very large-scale website in production.

As usual - use at your own risk, and be kind enough to share thoughts and improvement ideas here for his use.

public static class XmlService
{
    private static Dictionary _locks = new Dictionary();

    public static XmlDocument GetXml(string url)
    {
        return GetXml(url, new TimeSpan(1, 0, 0), false);
    }

    public static XmlDocument GetXml(string url, TimeSpan timeToHold, bool autoRefresh)
    {
        if (HttpRuntime.Cache[url] as string == "Failed")
            return null;

        XmlDocument xml = HttpRuntime.Cache[url] as XmlDocument;
        if (xml != null)
            return xml;

        if (!_locks.ContainsKey(url))
            lock (_locks)
                if (!_locks.ContainsKey(url))
                    _locks.Add(url, new object());

        if (HttpRuntime.Cache[url] == null)
            lock (_locks[url])
                if (HttpRuntime.Cache[url] == null)
                {
                    xml = LoadXml(url);
                    if (xml != null)
                        HttpRuntime.Cache.Insert(url, xml, null,
                            DateTime.Now.Add(timeToHold),
                            System.Web.Caching.Cache.NoSlidingExpiration,
                            System.Web.Caching.CacheItemPriority.NotRemovable,
                            delegate(string dataKey, object value, CacheItemRemovedReason reason)
                            {
                                if (autoRefresh)
                                    GetXml(url, timeToHold, autoRefresh);
                            }
                    );
                    else
                        HttpRuntime.Cache.Insert(url, "Failed", null, DateTime.Now.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration);
                }

        xml = HttpRuntime.Cache[url] as XmlDocument;
        return xml;
    }

    private static readonly ILog _errorlog = LogManager.GetLogger("ErrorLogger");
    private static XmlDocument LoadXml(string url)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Timeout = 3000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            XmlDocument xml = new XmlDocument();
            xml.Load(response.GetResponseStream());
            return xml;
        }
        catch (Exception ex)
        {
            _errorlog.Error(ex.Message, ex);
            return null;
        }
    }
}

I’d have switched XmlService with KeyLevelCacheService, XmlDocument with T, and LoadXml with Func<T>, then have a separate XmlService use KeyLevelCacheService internally.

Lockers dictionary

  

Situation:

Problem: A thread looking for an item in the cache to find that it’s not there, would issue the http request to fill the cache. A second thread might want to initiate another call if it needs the data before the first thread has updated the cache.

Solution 1: use locks on the cache object.

problem with that: you lock the whole cache, so other threads looking for a different type of data will be blocked, even though it’s okay for them to get data from the cache, and even to insert data with a different key into the cache.

Solution 2: Keep a key per requested entry. Now you only lock what needs locking.

You’d keep a dictionary of lockers ( new object() ), then the action of obtaining a locker will cause a full cache lock, however the lock duration will be short (the time it takes to retrieve an object from a Hashtable, or to new an object and put it in the Hashtable), and then the long out-of-process operation of loading the object will be with a lock on the specific key, while the rest of the Cache is accessible for reads and writes by other threads.

Note - this is notepad (or rather WindowsLiveWriter) code. You’d need to fix syntax errors, and inspect the usage. License is MIT - Use at your own risk, and don’t forget to attribute it to the writer


class KeyLevelSafeCache

{

   IDictionary lockers = new Hashtable();



   IDictionary cache = new Hashtable();



   object ObtainLockerFor(string key)

   {

      return thread-safely-get-an-object-from-lockers-hashtable()

   }   



   public T Get&lt;T&gt;(string key, Func&lt;T&gt; load())

   {

      var locker = ObtainLockerFor(key);

      //now retrieve the object from the cache using 'locker'

   }

}



STT - Extra comma in collection initialisers and enums

  

You all know what STL is (ok, not all of you, some have skipped C++ altogether and some have only created a few Carnivore/Herbivore classes for Uni).

But you don’t know what STT is.

Well I’ll tell you, just sit nicely and listen.

STT is “Silly Tip & Trick”.

This is one:

The Extra comma STT You probably already know of the collection initialiser syntax introduced into C# 3.0:

stt_comma 1

At times, you’d have a long list of items in the initialiser, and you find yourself doing copy&pastes to add lines, or removing lines from the list. There’s this little extra step you need to do, that is making sure that you have a comma between any two adjacent lines.

That makes the copy&paste a bit annoying.

stt_comma 2

However, it appear that csc.exe would accept an extra trailing comma at the end of the list, so this code is 100% valid:

stt_comma 3

Now it’s easier to text-manipulate the list.

It also works for Enum declarations:

stt_comma 4

So, even though having three cats in the house is busy enough, as far as c# is concerned I can easily add more of these. Not sure what the existing cats would think of that.

Just to make sure it actually works:

stt_comma 5

curiosities:

FTP Upload in .NET - You ain't need no libraries

  

Lately I’ve been asked about doing FTP related stuff in .NET .

There appear to be many “Ftp Clients” out there on CodeProject and other sites.

I really don’t get ‘em.

They are simple a leaky abstraction on top of straightforward BCL classes.

So what my solution is?

   1:  publicvoid Upload(string server, int port, string targetFolder, string fileName, string username, string password, bool isActive)   2:  {   3:  var url = string.Format(   4:  "ftp://{0}:{1}{2}/{3}", server, port, targetFolder, fileName)   5:  using (var ftp = (FtpWebRequest)WebRequest.Create(url))   6:      {   7:          ftp.Credentials = new NetworkCredential(username, password);   8:          ftp.KeepAlive = false;   9:          ftp.UseBinary = true;  10:          ftp.Method = WebRequestMethods.Ftp.UploadFile;  11:  if (isActive)  12:              ftp.UsePassive = false;  13:    14:  using (var writer = new BinaryWriter(ftp.GetRequestStream()))  15:              writer.Write(File.ReadAllBytes(fileName));  16:      }  17:  }

This basic notepad code covers most of the functionality in FtpWebRequest. You can easily set Binary/ASCII, Active/Passive, Credentials and whatnot.

Alternatively, in some cases you can just spawn a ftp.exe process with a simple ftp script. Anyway you can rid yourself from unneeded leaky abstractions.

FileBinderAttribute to ease FileUpload in MonoRail

  

Following Scott Hanselman’s post on FileUpload in ASP.NET MVC, I’ll add here a few bits on doing that in MonoRail.

First, as MonoRail is an extension on top of plain ol’ ASP.NET, just as ASP.NET MVC is, you can do the exact same thing - i.e iterate over Request.Files, and use a mocked Files collection for test or something.

But as the action parameters binder is very smart, and easily extensible, it’s even nicer to just bind the posted data to a HttpPostedFile, using a FileBinder:

   1:  [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]   2:  publicclass FileBinderAttribute: Attribute, **IParameterBinder**   3:  {   4:  publicint CalculateParamPoints(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)   5:      {   6:  var key = parameterInfo.Name;   7:  return context.Request.Files[key] != null ? 10 : 0;   8:      }   9:    10:  publicobject Bind(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)  11:      {  12:  var key = parameterInfo.Name;  13:  return context.Request.Files[key] as HttpPostedFile;  14:      }  15:  }

So a custom binder is an attribute, that implements IParameterBinder, a two methods interface:

so now you’re action can look like this:

   1:  publicvoid Save([FileBinder] HttpPostedFile myfile)   2:  {   3:  if (myFile != null)   4:      {   5:  // do stuff with the file   6:      }   7:  }

Cool? well actually what really is cool is that binding to HttpPostedFile is baked into MonoRail to begin with - so you don’t even need this FileBinderAttribute at all ! you can simply

   1:  publicvoid Save(HttpPostedFile myfile)   2:  {   3:  if (myFile != null)   4:      {   5:  // do stuff with the file   6:      }   7:  }

So why did I show you that?

Testablility.

Since HttpPostedFile is not easily mockable* (cuz it’s bloody sealed and not new-able), you should do what you always do when in need to bypass one of these un-testable hard-to-test* sealed classes: Adapter pattern. Introduce IHttpPostedFile, and supply your own HttpPostedFile encapsulating the built in one.

so:

   1:  [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]   2:  publicclass FileBinderAttribute: Attribute, **IParameterBinder**   3:  {   4:  publicint CalculateParamPoints(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)   5:      {   6:  var key = parameterInfo.Name;   7:  return context.Request.Files[key] != null ? 10 : 0;   8:      }   9:    10:  publicobject Bind(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)  11:      {  12:  var key = parameterInfo.Name;

  13:          var file = context.Request.Files[key] as HttpPostedFile;    14:  return file == null ? null : HttpPostedFileAdapter(file);  15:      }  16:  }

and

   1:  publicvoid Save([FileBinder] IHttpPostedFile myfile)   2:  {   3:  if (myFile != null)   4:      {   5:  // do stuff with the file   6:      }   7:  }

Can you spot the bug?

  

DISCLAIMER:

If you are a potential client of mine, or rather a current one, please stop reading NOW, as it’s one of these embarrassing “I am sometimes too stupid” posts.

Oh my.

That’s how my 3am code can look like:

   1:  var page = filter.Page.GetValueOrDefault(1);   2:  var pageSize = filter.PageSize.GetValueOrDefault(30);   3:  var firstResult = (page - 1) + pageSize;

It’s for NHibernate style paging (i.e. firstResult is for a 0 based index)

Spotted (thanks to DbAwareIntegrationTests) and fixed at 6pm

Simple String Hashing in .NET

  

I’ve been asked about it several times lately, so I’ll just put here an oldie that I’ve been using for a few years now untouched:

   1:  // MIT license   2:  // Copyright 2005-2008 Ken Egozi   3:  //    4:  // Permission is hereby granted, free of charge, to any person obtaining a copy   5:  // of this software and associated documentation files (the "Software"), to deal   6:  // in the Software without restriction, including without limitation the rights   7:  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell   8:  // copies of the Software, and to permit persons to whom the Software is   9:  // furnished to do so, subject to the following conditions:  10:  //   11:  // The above copyright notice and this permission notice shall be included in  12:  // all copies or substantial portions of the Software.  13:  //   14:  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR  15:  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  16:  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE  17:  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER  18:  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  19:  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN  20:  // THE SOFTWARE.  21:    22:  using System;  23:  using System.Collections.Generic;  24:  using System.Text;  25:  using System.Security.Cryptography;  26:  using System.Collections;  27:    28:  namespace KenEgozi.CryptographicServices  29:  {  30:  publicstaticclass Hashing  31:      {  32:  privatestatic Hashtable hashAlgorithms = Hashtable.Synchronized(new Hashtable());  33:    34:  /// &lt;summary&gt;  35:  /// Hashing a given string with SHA2.  36:  /// &lt;/summary&gt;  37:  /// &lt;param name="data"&gt;Data to hash&lt;/param&gt;  38:  /// &lt;returns&gt;Hashed data&lt;/returns&gt;  39:  publicstaticstring HashData(string data)  40:          {  41:  return HashData(data, HashType.SHA256);  42:          }  43:    44:  /// &lt;summary&gt;  45:  /// Hashing a given string with any of the supported hash algorithms.  46:  /// &lt;/summary&gt;  47:  /// &lt;param name="data"&gt;Data to hash&lt;/param&gt;  48:  /// &lt;param name="hashType"&gt;Hashing algorithm to use&lt;/param&gt;  49:  /// &lt;returns&gt;Hashed data&lt;/returns&gt;  50:  publicstaticstring HashData(string data, HashType hashType)  51:          {  52:              HashAlgorithm hash = GetHash(hashType);  53:  byte[] bytes = (new UnicodeEncoding()).GetBytes(data);  54:  byte[] hashed = hash.ComputeHash(bytes);  55:              StringBuilder sb = new StringBuilder(64);  56:  foreach (byte b in hashed)  57:                  sb.AppendFormat("{0:x2}", b);  58:  return sb.ToString();  59:          }  60:    61:  privatestatic HashAlgorithm GetHash(HashType hashType)  62:          {  63:  if (!hashAlgorithms.ContainsKey(hashType))  64:                  hashAlgorithms.Add(hashType, CreateaHashAlgorithm(hashType));  65:  return hashAlgorithms[hashType] as HashAlgorithm;  66:          }  67:    68:  privatestatic HashAlgorithm CreateaHashAlgorithm(HashType hashType)  69:          {  70:  switch (hashType)  71:              {  72:  case HashType.MD5:  73:  returnnew MD5CryptoServiceProvider();  74:  case HashType.SHA1:  75:  returnnew SHA1Managed();  76:  case HashType.SHA256:  77:  returnnew SHA256Managed();  78:  case HashType.SHA384:  79:  returnnew SHA384Managed();  80:  case HashType.SHA512:  81:  returnnew SHA512Managed();  82:  default:  83:  thrownew NotImplementedException();  84:              }  85:          }  86:      }  87:    88:  publicenum HashType  89:      {  90:          MD5,  91:          SHA1,  92:          SHA256,  93:          SHA384,  94:          SHA512  95:      }  96:  }

Not beautiful, however useful.

You can download this file from here (just remove the .txt - the server doesn’t serve .cs files directly)

btw, the colouring of the source was made with the help of http://www.manoli.net/csharpformat/, even though I had to do some manual tweaking to make it work with this blog. If colours of reserved words, comments etc. do not appear, then please refresh your browser’s cache to get the updated css

Naming Interfaces

  

An innocent question raised by Ayende has started an interesting debate on the comments.

In short (read it all there - don’t be lazy)

Which interface name is better?

a. IRecognizeFilesThatNeedToBeIgnored

b. IIgnoreFilesSpecification

with a single method: ShouldBeIgnored(string file);

Some were in favour of a, some in favour of b.

The interesting thing is that many has offered a third option:

c. IFileFilter

Let’s group these things:

Personally I couldn’t care less which one of the first type will be used. I slightly in favour of b., as I think funny names are good. The compiler cares nothing about names, but the human mind would remember the purpose well, and a newcomer would pick it up quickly.

The second group (IFileFilter) is not good. It might get filled with a lot of methods that do file filtering.and if it’s not, I think it should reflect the intention of the implementing class.Since multiple interfaces per class are allowed, it’s ok to have specialised ones.

AspView and C#3.0

  

MonoRail runs on .NET 2.0. AspView is no different, and is compiled for .NET 2.0, so people who cannot run 3.5 (shared hosting, other limitations) can still enjoy every shining new feature.

However, if you DO want to use c#3 stuff in view templates (like extension methods), then you can. Thanks to Felix Gartsman, the AspView compiler would try to load the c# compiler based on the codedom section of the application .config file.

So, if you’re using autorecompilation=true, the add this to your web.config:

&lt;system.codedom&gt; &lt;compilers&gt; &lt;compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4"&gt; &lt;provideroption value="v3.5" name="CompilerVersion" /&gt; &lt;provideroption value="false" name="WarnAsError" /&gt; &lt;/compiler&gt; &lt;/compilers&gt;
&lt;/system.codedom&gt;

If you want to precompile your views, then add the same to vcompile’s app.config.

AgentSmith - Resharper plugin

  

From the website:

Current version includes following features:

Smart paste.

The coolest thing is the ability to spell check identifiers. I’d love it.

It’s at http://www.agentsmithplugin.com/ and I found out about it on Castle’s dev list (thx Victor)

Generating XML - Do We Really Another API?

  

There appear to be yet another XML API.

So, when you want to generate:

&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;root&gt;
    &lt;result type="boolean"&gt;true&lt;/result&gt;
&lt;/root&gt;

instead of (using System.XML):

XmlDocument xd = new XmlDocument();
xd.AppendChild(xd.CreateXmlDeclaration("1.0", "utf-8", ""));

XmlNode root = xd.CreateElement("root");
xd.AppendChild(root);

XmlNode result = xd.CreateElement("result");
result.InnerText = "true";

XmlAttribute type = xd.CreateAttribute("type");
type.Value = "boolean";

result.Attributes.Append(type);
root.AppendChild(result);

one can (using the new API):

XmlOutput xo = new XmlOutput()
    .XmlDeclaration()
    .Node("root").Within()
        .Node("result").Attribute("type", "boolean").InnerText("true");

Exciting.

Or is it?

Why not just (using your template-engine of choice):


&lt;?xml version="1.0" encoding="utf-8"?&gt;

&lt;root&gt;

    &lt;result type="<%=view.Type%&gt;">&lt;%=view.Value%&gt;&lt;/result&gt;

&lt;/root&gt;

works great for the “complex” scenarios on Mark S. Rasmussen’s blog:


&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;root&gt;
    &lt;numbers&gt;

        &lt;% foreach (Number number in view.Numbers) { %&gt;
        &lt;number value="<%=number%&gt;">This is the number: &lt;%=number%&gt;&lt;/number&gt;


        &lt;% } %&gt;
    &lt;/numbers&gt;
&lt;/root&gt;

and:


&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;root&gt;
    &lt;user&gt;
        &lt;username&gt;&lt;%=view.User.Username%&gt;&lt;/username&gt;
        &lt;realname&gt;&lt;%=view.User.RealName%&gt;&lt;/realname&gt;
        &lt;description&gt;&lt;%#view.User.Username%&gt;&lt;/description&gt;

        &lt;articles&gt;

            &lt;% foreach (Article article in view.User.Articles) { %&gt;
            &lt;article id="<%=article.Id%&gt;">&lt;%#article.Title%&gt;&lt;/article&gt;

            &lt;% } %&gt;
        &lt;/articles&gt;
        &lt;hobbies&gt;
            &lt;% foreach (Hobby hobby in view.User.Hobbies) { %&gt; 

            &lt;hobby&gt;&lt;%#hobby.Name%&gt;&lt;/hobby&gt;

            &lt;% } %&gt; 

        &lt;/hobbies&gt;
    &lt;/user&gt;
&lt;/root&gt;

is Hobby and Article more complex? no probs. break it down to sub-views:


&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;root&gt;
    &lt;user&gt;
        &lt;username&gt;&lt;%=view.User.Username%&gt;&lt;/username&gt;
        &lt;realname&gt;&lt;%=view.User.RealName%&gt;&lt;/realname&gt;
        &lt;description&gt;&lt;%#view.User.Username%&gt;&lt;/description&gt;

        &lt;articles&gt;

            &lt;% foreach (Article article in view.User.Articles) { %&gt;

            &lt;subview:Article article="<%=article%&gt;">&lt;/subview:Article&gt;


            &lt;% } %&gt;
        &lt;/articles&gt;
        &lt;hobbies&gt;
            &lt;% foreach (Hobby hobby in view.User.Hobbies) { %&gt; 

            &lt;subview:Hobby hobby="<%=hobby%&gt;">&lt;/subview:Hobby&gt; 

            &lt;% } %&gt; 

        &lt;/hobbies&gt;
    &lt;/user&gt;
&lt;/root&gt;

Can you get more expressive that that?

Look how easy it is to visualize what we’re rendering, and how easy it is to change.

I consider all those XML API (including ATOM/RSS writers) as a leaky and unneeded abstractions, just like WebForms. Do you?

Equals != ==

  

Yep, I’ve made yet another noob mistake.

I needed to compare two enum values, on a method that was accepting objects.

public string Whatever(object currentOption, object selectedOption){ return currentOption == selectedOption ? "class='active' " : string.Empty;}

Didn’t work.

However,

public string Whatever(object currentOption, object selectedOption){ return currentOption.Equals(selectedOption) ? "class='active' " : string.Empty;}

Did work.

so, it appear that == isn’t polymorphic so it did the object.Equals method which apparently looks for reference equality, rather than the enum Equals.

And that has been yet another future-reference-post …

Cool vs Uncool in programming languages

  

Have just read Ayende’s post about C#/Java vs Boo/Ruby.

Tried to comment, but then I decided it’s worth a post.

I’d say that the difference is MAF - Management Acceptance Factor

Boo is also a way too cool/strange/creepy name for a distinguished suit to grasp.

It’s like when you’re a collage girl, and you want to introduce your new boyfriend to your mama. It doesn’t matter that he has a BSc and MBA plus 3 castles in the Swiss alps. If he’d first show up to the family on his way-too-cool motorcycle, then you’re going to be grounded.

When I approached my last manager about MonoRail, and told him that the views will be written in ‘Boo’, he got all scared. Then I wrote AspView, views to be written in c#, and he gave consent to go MonoRail.Even though, at least at that time, Brail was way more mature than AspView.The ‘cooler’ languages needs to be marketed to management.

Ruby works in Eclipse. I wonder who is going to start an OSS effort to create a decent Boo plugin for VS2008 (based on the VS2008 shell).

Make it demoable, make it look ‘official’, and MAF would go way higher.

ActiveRecord.Linq - naive but Working

  

I’ve spent some times lately with Linq To SQL and have played a bit with the Mapping namespace.

Why I do not like it very much is a matter for a different post. The matter at hand is that I want the power of Linq, and I want the power of NHibernate, and I want the easy road of ActiveRecord.

What do I mean by that? I’d like:

the needed prequisites:

So, Ayende has kick-started it, and with some help from Bobby Diaz, we have a prototype level NHibernate provider for Linq.

To make it work with ActiveRecord, all you need is to add:

using System;using Castle.ActiveRecord;using Castle.ActiveRecord.Framework;using NHibernate;namespace NHibernate.Linq{    public class ActiveRecordContext : NHibernateContext { public ActiveRecordContext() : base(null) { session = GetSession(); }  private ISession GetSession() { ISessionScope scope = SessionScope.Current; if (scope == null) throw new InvalidOperationException("You should be in a SessionScope()"); ISessionFactoryHolder holder = ActiveRecordMediator.GetSessionFactoryHolder(); return holder.CreateSession(typeof(ActiveRecordBase)); } }}

and now you can do stuff like:

using (new SessionScope()){ ActiveRecordContext context = new ActiveRecordContext(); var q =  from c in context.Session.Linq&lt;Category&gt;() select c;  foreach (Category c in q) Console.WriteLine(c.Name); }

Assuming Category has [ActiveRecord] mapping.

Typed View Properties in MonoRail and AspView

  

Following my last post on the DictionaryAdapter, I’ll demonstrate here how you can get typed access to your views’ properties.

What it requires from you:

  1. Declare an interface for each of your views. That is a Good Thing anyway, as designing to a contract is a good best practice, and it allows for easy testing.

  2. Have a base class for your controller that would define TypedFlash and TypedPropertyBag. Not mandatory, but very convenient.

  3. Use the newest build of AspView. Again - not mandatory, but helpful.

Now for the showtime.

First we would create a base class for our controllers, with a TypedPropertyBag and TypedFlash properties:

public abstract class Controller&lt;IView&gt; : SmartDispatcherControllerController    where IView : class{    IDictionaryAdapterFactory dictionaryAdapterFactory; IView typedPropertyBag; IView typedFlash; protected IView TypedPropertyBag { get         {             if (typedPropertyBag == null)         typedPropertyBag = dictionaryAdapterFactory.GetAdapter&lt;IView&gt;(PropertyBag);            return typedPropertyBag;         } }  protected IView TypedFlash { get         {             if (typedFlash == null)         typedFlash = dictionaryAdapterFactory.GetAdapter&lt;IView&gt;(Flash);            return typedFlash;         } }  protected override void Initialize() { base.Initialize();        IDictionaryAdapterFactory dictionaryAdapterFactory = new DictionaryAdapterFactory(); }}

tip:

You can look at a more complete version of that base-class, written by Lee Henson (who have made some improvements to the original DictionaryAdapter, and also have introduced me to Peroni Beer).The base controller also declares a type parameter for a Session DictionaryAdapter, hooks into the Castle.Tools.CodeGenerator, and uses IoC for DI.Talking about those issues is a separate subject, for other posts.

Now let’s create the view contract. A rather stupid example would be:

public interface IStupidView{ Guid Id { get; set; }    string Name { get; set; }}

controller:

public class StupidController : Controller&lt;IStupidView&gt;{    public void Index()    {    }    public void DoStuff(string name, string password)    {        if (password != "AspView Rocks")        {            TypedFlash.Name = name;            TypedFlash.Message = "Wrong Password";            RedirectToAction("Index");            return;        }        TypedPropertyBag.Id = Guid.NewGuid();        TypedPropertyBag.Name = name;    }}

view (Index.aspx):

&lt;%@ Page Language="C#" Inherits="Castle.MonoRail.Views.AspView.ViewAtDesignTime<IStupidView&gt;" %>&lt;%%&gt;&lt;p&gt;&lt;%=view.Message %&gt;&lt;/p&gt;&lt;form action="DoStuff.rails"&gt;Name: &lt;input type="text" name="name" value="<%= view.Name %&gt;" /> &lt;br /&gt;password: &lt;input type="password" name="password" /&gt; &lt;br /&gt;&lt;input type="submit" /&gt;&lt;/form&gt;

view (DoStuff.aspx):

&lt;%@ Page Language="C#" Inherits="Castle.MonoRail.Views.AspView.ViewAtDesignTime<IStupidView&gt;" %>&lt;%%&gt;The data was: &lt;br /&gt;Id: &lt;%= view.Id %&gt;, Name: &lt;%= view.Name %&gt;

Look at the intellisense (and at my ultra-cool black color scheme):

TypedView intellisense

Things to notice:

  1. Do not forget to reference the Assembly that has the view interface declaration. On the test site within aspview’s source repository the interface is declared in the Web project (AspViewTestSite), so the web.config has this:

view (Index.aspx):

&lt;aspview ... &gt;... &lt;reference assembly="AspViewTestSite.dll"/&gt;...&lt;/aspview&gt;
  1. you can use the DictionaryAdapter directly, on older versions of AspView (and on WebForms aspx/ascx files) by simply grabbing an adapter manually. sample:
...&lt;% IMyViewContract view = new Castle.Components.DictionaryAdapter.DictionaryAdapterFactory()       .GetAdapter<IMyViewContract&gt;(Properties); %>...blah blah &lt;%=view.UsefulProperty %&gt;...

Ok, cut the crap. where can I get it?

here (release, debug, source)

UPDATE:

The DictionaryAdapter was initially written by the guys from Eleutian as part of Castle.Tools.CodeGenerator.

Forget about Reflector-ing the BCL - the real deal is here

  

Another nice news from Scott Guthrie:

a small excerpt:

Today I’m excited to announce that we’ll be providing this with the .NET 3.5 and VS 2008 release later this year.

Dictionary of Actions instead of a Switch

  

I hate switch statements. They just looks bad.

So take a look ata nice example I’ve read at Luca Bolognese’s, for switching from a switch based code to a cleaner one.

The syntax in pre-c#3 would be less nice (delegate() instead of lambda, and parseFuncs.Add instead of the initializer) but it’s doable.

Heck, it reminds me of some old university-level Ansi-C code I’ve once wrote for a matrix-calculator program:

typedef struct { char * name; char * (*func)(char *); char * description;} cmd_class; 

// matrix functions.// pre: parameter string. post: answer is printed or stored in matrixchar * read_mat(char * parm_string);char * print_mat(char * parm_string);char * add_mat(char * parm_string);char * sub_mat(char * parm_string);char * mul_mat(char * parm_string);char * mul_scalar(char * parm_string);char * trans_mat(char * parm_string); 
cmd_class cmd[] = { {"read_mat", read_mat, "parameters: matrix,val1[,val2,...,val16]"},  {"print_mat", print_mat, "parameters: matrix"},  {"add_mat", add_mat, "parameters: matrix_A,matrix_B[,target_matrix]"},  {"sub_mat", sub_mat, "parameters: matrix_A,matrix_B[,target_matrix]"},  {"mul_mat", mul_mat, "parameters: matrix_A,matrix_B[,target_matrix]"},  {"mul_scalar", mul_scalar, "parameters: matrix,scalar[,target_matrix]"},  {"trans_mat", trans_mat, "parameters: matrix[,target_matrix]"},  {"stop", stop, "exit program"}, {"menu", print_menu, "print this menu"}, {"not_valid", NULL, "NULL"}};

It allowed me to avoid switch by looping over the cmd[] array in a helper method, thus able to do

command(commandName).func(params);

Not exactly a typical jet-fighter-realtime-c-code, but it gave me a better looking code, and a 100/100 grade.

Redirecting syndication link from dasBlog's one to the new one

  

TodayI was informed by Dror that although I managed to redirect all requests to html/aspx url’s on my blog (the ones that dagBlog was using) to the new pemalink format, I forgot to do the same for the old syndication link.

So that link was http://kenegozi.com/blog/SyndicationService.asmx/GetRssand now it’s http://kenegozi.com/Blog/Syndication/Atom.aspx

I could’ve used the monorai redirection module that is already in use on my blog, but I chose to do it differently, with a dedicated handler, just to show how easy it is do to such stuff, even without a full blown redirection engine.

So, I’ve added this:

publicclassSyndicationRedirectionHandler : IHttpHandler 
{
    #region IHttpHandler Members
    publicbool IsReusable
    {
        get { returntrue;}
    }

    publicvoid ProcessRequest(HttpContext context)
    {
        context.Response.StatusCode = 301;
        context.Response.Redirect("http://kenegozi.com/Blog/Syndication/Atom.aspx");
    }

    #endregion
}

and that line into web.config:

<addverb=”*“path=”SyndicationService.asmx”type=”KenEgozi.Com.Weblog.SyndicationRedirectionHandler, KenEgozi.Com.Weblog”/>

Voila.

Is XAML and WPF are really that cool?

  

I am considering WPF-ing a new component for one of are in-house projects. So I’ve done some reading, and to be sincere, I am not too excited.

Let’s refine the last statement. I am very excited with the technology. However, I find the examples out there very annoying.

It all seams to be “Hey it’s so cool !! I can do stuff IN THE MARKUP - woosh, god save XAML”.

So I came across this post.

It is just great!! it shows how I can easily use only 13 lines of XML to showa grind ONLY if the source is not null.

Sure a lot more expressive and easy than, say:

if (source != null) mySuperCoolGrid.DataBind();

Reflector 5 is out

  

The best tool ever is even better now, and you can find it here.

Thanks to Yosi for the reference.

AspView rev 38 is out

  

What we have:

  1. Default Helpers are now declared in the AspViewBase. It means that you can use <%=FormHelper.LabelFor(…) %> without the need to declare the helper at the begining of the view.

  2. the compiler was refactored to allow for better testing, and for implementation of further view languages. vurrently I’ve started with VB.NET but it is not working yet, since I have no time to make sure the VB syntax is correct. The tests of the compiler are missing due to some stupidity on my side, of not commiting the TestCase …

I’ve wanted to let svn access but I have some trouble with that. I’ve started a sourceforge project but I cannot upload the repo to the site. I did all they’ve asked on the site but the import process reporting failure no matter what I do. I guess that the best way will be if the Castle team would allow AspView into it’s codebase, maybe on the Contrib repo to begin with …

So meanwhile you can download the current bits from here.

Keep me posted,

Ken.

AspView - first release

  

So I’m releasing AspView.

You can download the source from here.

It was written against the Castle 1.1 from the trunk, build no. 152.

Please note that in order to run the TestCases you’d have to make sure that the latest Castle.MonoRail.TestSupport is in the GAC.

The documentation is poor since I have a little time now. I am working on a website for my employer (that utilizes AspView and AR) and until the first beta release I won’t have time to do anything but major bugfixes. This project isn’t open sourced so I won’t be able to share it’s sources, however since this will be a public site, it would serve as a Proof Of Concept to the MonoRail and AspView.

The views MUST have the following structure: a. Page header - Must be present for intellisense to work:

   1:  &lt;%@ Page Language="C#" Inherits="Castle.MonoRail.Views.AspView.ViewAtDesignTime"%&gt;

b. Directives - Not mandatory:

   1:  &lt;%@ Import Namespace="System.Text"%&gt;   2:  &lt;%@ Import Namespace="System.Drawing"%&gt;

c. Properties decleration - Currently it’s mandatory. If you have no properties you mast have an empty block:

   1:  &lt;%   2:  string[] strings;   3:      DateTime today;   4:  int index;   5:  %&gt;

or just

   1:  &lt;%   2:  %&gt;

d. View body

In a layout view you place the inner view using the ViewContents property, like this:

   1:  blah   2:  blah   3:  &lt;%=ViewContents%&gt;   4:  blah   5:  blah

AspView - Yet another MonoRail ViewEngine

  

.hlt { background-color:yellow;}
So what is AspView?

It is a Visual Studio 2005 friendly ViewEngine implementation.

The scripting is done using VisualStudio languages (c# and VB.NET). The views are precompiled, (or can be compiled on-demand, but anyway not interpreted).

The project was inspired by the Brail ViewEngine, but since it doesn’t use Boo it is more Management-Friendly, since they need not worry about getting out of the “safe” microsoft world.

I tend to like Boo as a language very much, and I like Brail a lot, too (since it allows for less code in the view thanks to the Boo magic) but I lack the tight Visual Studio integration (opening .boo files in #Develop messes up my desktop), and the intellisense is quite important, at least for the developers I worl with.

So I will post in the next few days about it, and I’ll make it available to be downloaded (source and binary) as soon as I’ll test it a little more. I hope to have a public svn repository soon.

A little demo view:

   1:  &lt;%@ Page Language="C#" Inherits="Castle.MonoRail.Views.AspView.ViewAtDesignTime"%&gt;   2:  &lt;%   3:  string[] strings;   4:  %&gt;   5:     6:     7:  hello from index&lt;br /&gt;   8:  This are the strings:&lt;br /&gt;   9:  &lt;%foreach (string s in strings) { %&gt;  10:  &lt;%=s %&gt;&lt;br /&gt;  11:  &lt;%  } %&gt;  12:    13:  &lt;br /&gt;  14:  End of normal view  15:  &lt;br /&gt;  16:  &lt;% OutputSubView("Home/SubViewSample"); %&gt;

Duck Type in .NET

  

There is a great article on CodeProject, by Guenter Prossliner.

A simple class in presented there, that makes Duck Typing possible for Generics enabledCLS languages (VB.NET 8 and C#2.0 for instance).

I’ll present it here in short form:

let’s say we have two classes:

   1:  class Foo1   2:  {   3:  publicstring Bar() { }   4:  }   5:  class Foo2   6:  {   7:  publicstring Bar() { }   8:  }

Now you have a method that can work with instances of eiether one, and invoke Bar on it:

   1:  void SimpleMethodOnFoo1(Foo1 foo)   2:  {   3:      foo.Bar();   4:  }   5:  void SimpleMethodOnFoo2(Foo2 foo)   6:  {   7:      foo.Bar();   8:  }

A Generic Execute Callback for ActiveRecord - Execute<T>

  

I am working with AR for a few month now, ignorantly ignoring the Castle Project’s wiki.

Stupid I am. I could have learned a lot and save a bunch of wandering around the net and the intellisense to learn obvious stuff.

Thanks to hammett who pointed me there.

Anyway - now I read it from <html> to </html>, and I saw the part about running HQL using the Execute Callback

There are examples, each one with two flavors: “not using generics”, and “using generics”. Well, the one about the Execute Callback is misleading. It should have been “not using anonymous method” and “using anonymous methods”, since the second one does not use generics.

So I thought - let’s make the API simpler.

We would have like to allow the user execute her hql like that:

   1:  publicstatic Post[] GetPostsByAuthorName(string authorName)
   2:  {
   3:  return (Post[])Execute(typeof(Post), "from Post p where p.Author = ?", authorName);
   4:  }

Or even better, by using generics (this time for real):

   1:  publicstatic Post[] GetPostsByAuthorName(string authorName)
   2:  {
   3:  return Execute&lt;Post&gt;("from Post p where p.Author = ?", authorName);
   4:  }

Here is the magic:

   1:  publicstatic T[] Execute&lt;T&gt;(string hql, paramsobject[] parameters)
   2:  {
   3:      IList untypedResults = (IList)Execute(delegate(ISession session, object data)
   4:      {
   5:  object[] queryParams = (object[])data;
   6:          IQuery query = session.CreateQuery(hql);
   7:  for (int position = 0; position &lt; queryParams.Length; ++position)
   8:              query.SetParameter(position, queryParams[position]);
   9:  return query.List();
  10:      }, parameters);
  11:      T[] results = new T[untypedResults.Count];
  12:      untypedResults.CopyTo(results, 0);
  13:  return results;
  14:  }

I’ll add an overload that will accept named parameters. I am not sure about the right way to do that, though.

My options are:

   1:  Execute<T&gt;(string hql, 
   2:  string[] paramNames, 
   3:      Type[] paramTypes, 
   4:  object[] parameters)

Or:

   1:  Execute&lt;T&gt;(string hql, IParameter[] parameters)

where IParameter definition is something like:

   1:  publicinterface IParameter&lt;T&gt;
   2:  where T: Type
   3:  {
   4:  publicstring Name { get; set;}
   5:  public T Value { get; set;}
   6:  }

Maybe both?

And maybe I haven’t read the wiki thoroughly enough and there are already implementations for all that?

Inheritence in Castle's ActiveRecord

  

The reference I’ve used whilelearning to use Castl’e ActiveRecord implementation is the Blog/Post demos that can be found on Castle’s site.

Let’s look at the Type Hierarchy example, that can be found here.

It shows an implementation of a class diagram that look a little bit like this:Class Diagram

Let’s look at the code : [ActiveRecord(“entity”), JoinedBase]publicclassEntity : ActiveRecordBase{privateint _id;[PrimaryKey]publicint Id{get { return id; }set { id = value; }}}[ActiveRecord(“entitycompany”)]publicclassCompanyEntity : Entity{privateint comp_id;[JoinedKey(“comp_id”)]publicint CompId{get { return comp_id; }set { comp_id = value; }}}[ActiveRecord(“entityperson”)]publicclassPersonEntity : Entity{privateint person_id;[JoinedKey(“person_id”)]publicint PersonId{get { return person_id; }set { person_id = value; }}} But look what happens. since the Id property on entity is public and inherited to the subclasses, you get something like this:Should I use .Id or .PersonId?

So there is a duplicate field here !!!. and it’s not only a getter-setter thingie. It also have different private members.

My solution for this is to virtualize the base Id, and protectedize (hehe) the _id member, like this:

[ActiveRecord(“entity”), JoinedBase]publicclassEntity : ActiveRecordBase{protectedint _id;[PrimaryKey]publicvirtualint Id{get { return id; }set { id = value; }}}[ActiveRecord(“entitycompany”)]publicclassCompanyEntity : Entity{[JoinedKey(“comp_id”)]publicoverrideint Id{get { return _id; }set { _id = value; }}}[ActiveRecord(“entityperson”)]publicclassPersonEntity : Entity{[JoinedKey(“person_id”)]publicoverrideint Id{get { return _id; }set { _id = value; }}} Now it makes more sence:I should use .Id

And before you hit me with a big stick - I do know of ActiveRecordBase<T> . :) the above code is for demonstration purposes only, not to be Copy&Pasted to your Brand-New-Best-Erp-Ever-Made-And-Will-Make-You-Rich

System.Net.Mail.MailMessage.AlternateView - strange documentation

  

Check this out.

I’ve wanted to send emails, and have messages with both plain text and html views. A quick look at MSDN have braught this up, and it looked good. Waydago MSFT - good work.

However, a strange exception occured in runtime, and after a little check it was obvious that the constructor used in MSDN’s doc is just NOT THERE.

This guy also had the same problem, and someone there pointer out the solution. There is a static method to create an instance of a AlternateView from a string that represents a message’s body. It’s called CreateAlternateViewFromStringand It’s nice to have it.

Mistakes in docs are exceptable, however, the guy braught it up last January, and MSFT didn’t fix the doc until now.

Strange it is.

Ways to run a method in a new Thread

  

I’m going to explore a few ways to spawn new threads in c# 2.0.Let’s say that we want to do a time consuming process, and that we do not need that the main program will wait for it to end.For the sake of the examples here, I’ll assume that the long run process is sending an e-mail to “you”, from “me” and the message’s body is “the body of the message”. the email will be processed by a thread-safe(1) static method, called SendMail(string, string, string) that resides in the Utilities class. How convenient.(1) A thread-safe method is an enchanted, voodoo-enabled method that behaves well under multithreading (2) environment.(2) Multithreading is a cool name for the ability to knit long sleeved shirts(3)(3) Disregard the last three comments. Really, you should.The non-multithreading code looked like this:{…Utilities.SendMail(“from”, “to”, “body”);…}In the good old .NET 1.1 way, Thread wasn’t really able to run a method with arguments, so you should have built a wrapper for that. Something like:class Program{publicstaticvoid Main(){SendMailHelper sendMail =new SendMailHelper(“from”, “to”, “body”);}}class SendMailHelper{public SendMailHelper(string from, string to, string body){_from = from;_to = to;_body = body;Thread t =new Thread(Run);t.Start();}publicvoid Run(){Utilities.SendMail(_from, _to, _body);}}.NET 2.0 offers an overload for Thread’s constructor: Thread(ParametrizedThreadStart), that should help with that.ParametrizedThreadStart is a delegate that accepts an object as it’s argument. So the naive thing to do is to wrap the method in a method that accepts an object, and call the target method from within, unpacking the object during the process:class Program{publicstaticvoid Main(){Thread t =new Thread(RunSendMail);object[] parametersArray =newobject[] {“from”, “to”, “body” };t.Start(parametersArray);}void RunSendMail(object parameters){object[] parametersArray = (object[])parameters;Utilities.SendMail((string)parametersArray[0], (string)parametersArray[1], (string)parametersArray[2]);}}

Ugly.Luckily, .NET 2.0 comes with anonymous delegates, that simplifies things a lot:class Program{publicstaticvoid Main(){Thread t =new Thread(delegate() {Utilities.SendMail(“from”, “to”, “body”);});t.Start();}}But what if you want to be notified when the method completes? Well, you could try this:class Program{publicstaticvoid Main(){Thread t =new Thread(delegate() {SendMail(“from”, “to”, “body”, SendMailEnded);});t.Start();}publicdelegatevoid Callback();publicstaticvoid SendMailEnded(){Console.WriteLine(“Do That ended”);}publicstaticvoid SendMail(string from, string to, string body, Callback callback){Utilities.SendMail(from, to, body);if (callback !=null)callback();}}but, of course, now the code is less clean than before, because we have to declare the delegate Callback.

In the next few days I’ll introduce a helper class (well, I think it helps) that encapsulate the things you need to do to spawn a new thread, pass parameters to it, and be notified on it’s lifecycle.sources, etc. will be here soon, too

C# 2.0 Nulleable Types and GetType()

  

I’m developing some Two-Way Databound ASP.NET Server Controls lately, and I use some reflection in order to do the actual binding and unbinding.

During my work, I found out something strange.

Let’s consider the next code segment:

bool? myNullableBool =true;Type t = myNullableBool.GetType();

You’d think that t == typeof(bool?),

but actually, t == typeof(bool)!!!

So it seams that the Nullable<> types in c# 2.0 aren’t “real”, in the sense that instances of those types, actually are of the corresponded “regular” type, but has some kind of an overload on the = operator, that allow null as a input value.

It’s not the behavior that I’ve expected, and so it caused my a lot of headaches during the development of my binding/unbinding methods.

I guess it is documented on MSDN, but I got to excited about the nullable types feature, that I’ve started using it without fully understanding it.

So my lesson for today is: study well, and stay out of hell.

OR-ing type constraints on generic declerations in C#

  

Consider the next scenario:

You want to have a generic class, to handle different types of primitive data, but also strings.

So you’d like to have something like this:

publicclass Manager&lt;T&gt;where T: struct OR string{...}

or maybe you’d like to handle objects and strings:

where T: (ISomeInterface, new()) OR struct

or even specify some specific available types:

where T: long OR int

or two possible base classes:

where T: MyGreatUserControlBase OR MyGreatWebControlBase 

et cetera.

I’d like to hear comments about that (and suggestions to the OR sign - ,   , ; or whatever). If the feedback will be positive, I might suggests it to MS guys as a ladybug or such, and we might see it as part of C# 3.0, or maybe 4.0?

WinFX May CTPs are out

  

I’m downloading the whole package, letting Roee play with the WPF and Oren with WWF, leaving the WCF stuff to myself.I hope to have some insights on the subject, soon.The Linq preview is already installed, and I’m working on some minor project as part of my Bachelor’s degree seminar, dealing with the impendency mismatch, between the software OO world and the database E-R world, using DLinq to demonstrate this kind of O/R mapping solution.


Follow @kenegozi