My DateTime serialization practices

on September 4th, 2013 at 5:32am 0 responses

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:

  1. If the input datetime is of UTC kind, it will render the letter Z
  2. If the input datetime is of Unspecified kind, it will render … nothing
  3. If the input datetime is of Local kind, it will render + (or –) the offset

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

on March 15th, 2011 at 10:50pm 2 responses

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

on January 11th, 2011 at 7:00am 0 responses

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

on October 16th, 2010 at 9:33am , , 0 responses

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

on September 16th, 2010 at 10:11am , 0 responses

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

on September 9th, 2010 at 3:36pm , 0 responses

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

on August 15th, 2010 at 2:13pm , 0 responses

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:

  1. There is a low write contention – i.e. most of the times when a thread asks for a lock, it is for a read access only
  2. The synchronised read block is not very quick anyway

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:

  1. The good old simple lock construct is always more readable and maintainable, than ReaderWriterLock. Sometimes most of the times it even performs better.
  2. When the two conditions are met (low write contention, non-trivial read block), it is wise to consider a ReaderWriterLock
  3. When using ReaderWriterLock, one should beware (more than the usual) from blind copy-and-paste operations.

 

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

on June 6th, 2010 at 7:48pm 2 responses

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<int>(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

on January 17th, 2010 at 7:39pm , , 2 responses

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 = "whatever";
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:

* Mind you – it’s not the prettiest, but it gets the job done

public class AutoStubber<T> where T : class
{
	static readonly Type TypeofT;
	static readonly ConstructorInfo Constructor;
	static readonly Type[] ParameterTypes;
	static readonly Dictionary<object, AutoStubber<T>> Instances = new Dictionary<object, AutoStubber<T>>();
	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<T> GetStubberFor(T obj)
	{
		return Instances[obj];
	}

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

	readonly Dictionary<Type, object> _dependencies = new Dictionary<Type, object>();
	private T Instance { get; set; }
	public AutoStubber()
	{
		var parameters = new List<object>(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<TDependency>()
	{
		return (TDependency)_dependencies[typeof(TDependency)];
	}
}
public static class AutoStubberExtensions
{
	public static AutoStubber<T> Stubs<T>(this T obj)
		where T : class
	{
		return AutoStubber<T>.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 !

on January 1st, 2010 at 8:11pm 10 responses

 

Problem at hand: an ID generator.

 

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

  1. Does not know anything about concurrency issues. Might try to put lock(this) on a couple of code blocks, and hope it will help.
  2. Will throw lock(locker) statements where ever needed. Probably even use a ReaderWriteLock, or the Slim-er brother of his
  3. Will use lock-free constructs.

Now I am definitely not a concurrency guru like my teammates, 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?

 

 

* apparently there’s at least one more type – smartass, and I’m there

** probably not

Linq Cast extension method and InvalidCastException

on October 1st, 2009 at 4:36pm 5 responses

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

on May 3rd, 2009 at 11:39am 1 responses

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

on March 8th, 2009 at 7:58am , 8 responses

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

on January 12th, 2009 at 3:10pm , , 0 responses

The bug:

Weird behaviours regarding session management

 

The blame:

(within session access wrapper static class):

private static IDictionary session;
...
if (session == null)   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

on October 30th, 2008 at 9:17am 0 responses

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

 

 

 

 

public Stream GetFile(string file) {

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

if (file.Contains("..")) throw new SecurityException(); var ext = Path.GetExtension(file).ToLower().TrimStart('.');

// Just a helper that will

// set WebOperationContext.Current.OutgoingResponse.ContentType

SetContentType(ContentInfo.For(ext)); var filePath = Path.Combine(this.siteRoot, file); return File.OpenRead(GetActualFilePath(filePath)); }

 

 

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

    /// <summary>
    /// Represents info on a given file
    /// </summary>
    public static class ContentInfo
    {
        static readonly KeyValuePair<MimeTypes, string>[] contentInfoFor = new[]
        {
            new KeyValuePair<MimeTypes, string>(MimeTypes.Js, "text/javascript"),
            new KeyValuePair<MimeTypes, string>(MimeTypes.Css, "text/css"),
            new KeyValuePair<MimeTypes, string>(MimeTypes.Html, "text/html"),
            new KeyValuePair<MimeTypes, string>(MimeTypes.Plain, "text/plain"),
            new KeyValuePair<MimeTypes, string>(MimeTypes.Gif, "image/gif"),
            new KeyValuePair<MimeTypes, string>(MimeTypes.Jpeg, "image/jpeg"),
            new KeyValuePair<MimeTypes, string>(MimeTypes.Tiff, "image/tiff"),
        };

        /// <summary>
        /// Gets the mime type for a given <see cref="MimeTypes"/>
        /// </summary>
        /// <param name="mimeType">The file's <see cref="MimeTypes"/></param>
        /// <returns>The file's mime type</returns>
        public static string For(MimeTypes mimeType)
        {
            return (from p in contentInfoFor
                    where p.Key == mimeType
                    select p.Value)
                   .First();
        }

        /// <summary>
        /// Gets the mime type for a given extension
        /// </summary>
        /// <param name="extension">The file's extension</param>
        /// <returns>The file's mime type</returns>
        public static string For(string extension)
        {
            return For(MimeType.For(extension));
        }
    }

 

and

    /// <summary>
    /// Helpers for <see cref="MimeTypes"/> 
    /// </summary>
    public class MimeType
    {
        static readonly KeyValuePair<string, MimeTypes>[] mimeTypeForExtension = new[]
            {
                new KeyValuePair<string, MimeTypes>("js", MimeTypes.Js),
                new KeyValuePair<string, MimeTypes>("css", MimeTypes.Css),
                new KeyValuePair<string, MimeTypes>("htm", MimeTypes.Html),
                new KeyValuePair<string, MimeTypes>("html", MimeTypes.Html),
                new KeyValuePair<string, MimeTypes>("txt", MimeTypes.Plain),
                new KeyValuePair<string, MimeTypes>("gif", MimeTypes.Gif),
                new KeyValuePair<string, MimeTypes>("jpg", MimeTypes.Jpeg),
                new KeyValuePair<string, MimeTypes>("jpeg", MimeTypes.Jpeg),
                new KeyValuePair<string, MimeTypes>("tiff", MimeTypes.Tiff),
            };

        /// <summary>
        /// Selects a <see cref="MimeTypes"/> for a given file extension 
        /// </summary>
        /// <param name="extension">The file's extension</param>
        /// <returns>The file's mime type</returns>
        public static MimeTypes For(string extension)
        {
            extension = extension.TrimStart('.');

            return (from p in mimeTypeForExtension
                    where p.Key == extension
                    select p.Value)
                .First();

        }
    }

 

 

When MimeTypes are:

    public enum MimeTypes
    {
        Js, Css, Html, Gif, Jpeg, Tiff, Plain
    }

Mini web server using WCF

on October 23rd, 2008 at 2:18pm 1 responses

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), new Uri("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 IFaxManaderService.

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

Using generic classes and avoid locks

on October 17th, 2008 at 7:14pm , 0 responses

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<MyEnum>("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?

on October 16th, 2008 at 9:39pm 8 responses

 

class Wrapper { public static int Counter{ get; private set;} static Wrapper() { Counter = 0; } public T Get<T>() { ++Counter; return default(T); } } class Wrapper<T> { public static int Counter{ get; private set;} static Wrapper() { Counter = 0; } public T Get() { ++Counter; return default(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

on October 12th, 2008 at 9:33pm , , 3 responses

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:

using System.ComponentModel;

namespace OpenUni.Domain.Modules
{
    public enum ModuleTypes
    {
        [Description("ר")]
        Standard,

        [Description("מ")]
        Advanced,

        [Description("מס")]
        AdvancedSeminar,

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

 

mapping a field of type ModuleTypes will look like that:

<property
    name    = "ModuleType"
    column  = "ModuleType"
    type    = "D9.NHibernate.UserTypes.DescribedEnumStringType`1[[OpenUni.Domain.Modules.ModuleTypes, OpenUni.Domain]], 
              D9.NHibernate" />

 

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

on October 10th, 2008 at 1:48am 2 responses

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

 

using System.ComponentModel;

namespace OpenUni.Domain.Modules
{
    public enum ModuleTypes
    {
        [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:

 

using System.ComponentModel;

namespace OpenUni.Domain.Modules
{
    public enum ModuleTypes
    {
        [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:

 

using System; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; namespace NHibernate.Type

{ /// <summary> /// Allow access to enum values with /// <see cref="DescriptionAttribute">DescriptionAttribute</see> /// set on them /// </summary> public static class DescribedEnumHandlers { private static readonly IDictionary handlers = new ListDictionary(); /// <summary> /// Initialises enum types to be used with the <see cref="DescribedEnumHandlers"></see> /// </summary> /// <param name="assemblies">The assemblies to grab described enums from</param> public static void Initialise(params Assembly[] assemblies) { Initialise((IEnumerable<Assembly>)assemblies); } /// <summary> /// Initialises enum types to be used with the <see cref="DescribedEnumHandlers"></see> /// </summary> /// <param name="assemblies">The assemblies to grab described enums from</param> public static void Initialise(IEnumerable<Assembly> assemblies) { var titledEnums = from assembly in assemblies select assembly into a from type in a.GetTypes() where type.IsEnum && (from f in type.GetFields() where f.GetCustomAttributes(typeof (DescriptionAttribute), false).Length == 1 select f ).Count() > 0 orderby type.FullName select type; foreach (var type in titledEnums) { handlers.Add(type, new DescribedEnumHandler(type)); } } /// <summary> /// Extract the description for a given enum value /// </summary> /// <param name="value">An enum value</param> /// <returns>It's description, or it's name if there's no registered description for the given value</returns> public static string EnumToDescription(object value) { var handler = handlers[value.GetType()] as DescribedEnumHandler; return handler != null ? handler.GetDescriptionFrom((Enum)value) : value.ToString(); } /// <summary> /// Gets the enum value for a given description or value /// </summary> /// <typeparam name="T">The enum type</typeparam> /// <param name="stringValue">The enum value or description</param> /// <returns>An enum value matching the given string value, as description (using <see cref="DescriptionAttribute">DescriptionAttribute</see>) or as value</returns> public static Enum ToEnumValue<T>(this string stringValue) where T :struct { var type = typeof (T); var handler = handlers[type] as DescribedEnumHandler; return handler != null ? handler.GetValueFrom(stringValue) : (Enum)Enum.Parse(type, stringValue, false); } /// <summary> /// Used to cache enum values descriptions mapper /// </summary> private class DescribedEnumHandler { private readonly IDictionary<Enum, string> toDescription = new Dictionary<Enum, string>(); private readonly IDictionary<string, Enum> fromDescription = new Dictionary<string, Enum>(); public DescribedEnumHandler(Type type) { var enumEntrys = from f in type.GetFields() let attributes = f.GetCustomAttributes(typeof(DescriptionAttribute), false) where attributes.Length == 1 let attribute = (DescriptionAttribute)attributes[0] select new { Value = (Enum)Enum.Parse(type, f.Name), attribute.Description }; foreach (var enumEntry in enumEntrys) { toDescription[enumEntry.Value] = enumEntry.Description; fromDescription[enumEntry.Description] = enumEntry.Value; } } public string GetDescriptionFrom(Enum value) { return toDescription[value]; } public Enum GetValueFrom(string title) { return fromDescription[title]; } } } }

 

Usage:

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

Console.WriteLine(DescribedEnumHandlers.EnumToDescription(ModuleTypes.Standard));
Console.WriteLine("ר".ToEnumValue<ModuleTypes>());

 

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

 

 

* code is licensed as BSD if you wish to use it

That's a better demo code

on October 5th, 2008 at 8:18am 2 responses

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

on September 23rd, 2008 at 7:30am , 7 responses

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

on August 24th, 2008 at 6:35am , 0 responses

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

on August 23rd, 2008 at 4:00pm , 2 responses

Situation:

  • Your application aggregates data from external sources (say XML data returned via Http)
  • You want to cache such data locally, say up to an hour
  • You have some processing mechanism going over the cached data, using multiple threads

 

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<T>(string key, Func<T> load())

{

var locker = ObtainLockerFor(key);

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

}

}

 

STT - Extra comma in collection initialisers and enums

on July 31st, 2008 at 7:59am 7 responses

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:

  1. Envy code R rock.
  2. I use red background for my elevated CMD window
  3. For the Visual Studio only dudes: csc.exe is the c# compiler bundled as part of the .NET runtime install.
  4. yes, I sometimes use edit.exe
  5. Envy code R rock.

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

on June 28th, 2008 at 3:06pm 11 responses

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:  public void 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

on June 28th, 2008 at 12:18pm , , , 2 responses

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: public class FileBinderAttribute: Attribute, IParameterBinder
3: {
4: public int 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: public object 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:

  1. CalculateParamPoints() - is for helping the framework correctly guess the best candidate of the action overloads. If the file exists in the request then it makes an action with a HttpPostedFile parameter with the name of the file upload name, a better candidate than an overload with a String parameter with the same name.
  2. Bind() - well, kinda' self explanatory.

 

so now you're action can look like this:

   1:  public void 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:  public void 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: public class FileBinderAttribute: Attribute, IParameterBinder
3: {
4: public int 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: public object 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:  public void Save([FileBinder] IHttpPostedFile myfile)
2: {
3: if (myFile != null)
4: {
5: // do stuff with the file
6: }
7: }

 

 

 

 

 

 

* Yes Roy, I know you can throw some TypeMock magic at it

Can you spot the bug?

on June 26th, 2008 at 3:40pm 3 responses

 

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

on June 22nd, 2008 at 1:34pm , 0 responses

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: public static class Hashing
31: {
32: private static Hashtable hashAlgorithms = Hashtable.Synchronized(new Hashtable());
33:
34: /// <summary>
35: /// Hashing a given string with SHA2.
36: /// </summary>
37: /// <param name="data">Data to hash</param>
38: /// <returns>Hashed data</returns>
39: public static string HashData(string data)
40: {
41: return HashData(data, HashType.SHA256);
42: }
43:
44: /// <summary>
45: /// Hashing a given string with any of the supported hash algorithms.
46: /// </summary>
47: /// <param name="data">Data to hash</param>
48: /// <param name="hashType">Hashing algorithm to use</param>
49: /// <returns>Hashed data</returns>
50: public static string 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: private static 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: private static HashAlgorithm CreateaHashAlgorithm(HashType hashType)
69: {
70: switch (hashType)
71: {
72: case HashType.MD5:
73: return new MD5CryptoServiceProvider();
74: case HashType.SHA1:
75: return new SHA1Managed();
76: case HashType.SHA256:
77: return new SHA256Managed();
78: case HashType.SHA384:
79: return new SHA384Managed();
80: case HashType.SHA512:
81: return new SHA512Managed();
82: default:
83: throw new NotImplementedException();
84: }
85: }
86: }
87:  
88: public enum 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

on June 17th, 2008 at 6:16am , 4 responses

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:

  1. Options a. and b. => Narrow and very specific interfaces. You can guess exactly what a class implementing them can do.
  2. Option c. => a general-purpose interface. You'd know that a class that implement this type of interface is doing stuff with files, but it's kinda vague. Can it filter a file out of a list of files? can it filter the content of a file? can it do other kinds of filtering on some kinds of files?

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

on April 29th, 2008 at 2:06pm , 2 responses

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:

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

 

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

AgentSmith - Resharper plugin

on March 9th, 2008 at 7:00pm , , 1 responses

From the website:

Current version includes following features:

  • Naming convention validation.

  • XML comment validation.

  • XML comment, string literals, identifiers and resources (.resx files) spell checking

  • 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?

on February 27th, 2008 at 10:26am , , 10 responses

There appear to be yet another XML API.

So, when you want to generate:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <result type="boolean">true</result>
</root>

 

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

<?xml version="1.0" encoding="utf-8"?>

<root>

<result type="<%=view.Type%>"><%=view.Value%></result>

</root>

 

works great for the "complex" scenarios on Mark S. Rasmussen's blog:

<?xml version="1.0" encoding="utf-8"?> <root> <numbers>

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

<% } %> </numbers> </root>

 

and:

<?xml version="1.0" encoding="utf-8"?> <root> <user> <username><%=view.User.Username%></username> <realname><%=view.User.RealName%></realname> <description><%#view.User.Username%></description>

<articles>

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

<% } %> </articles> <hobbies> <% foreach (Hobby hobby in view.User.Hobbies) { %>

<hobby><%#hobby.Name%></hobby>

<% } %>

</hobbies> </user> </root>

 

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

<?xml version="1.0" encoding="utf-8"?> <root> <user> <username><%=view.User.Username%></username> <realname><%=view.User.RealName%></realname> <description><%#view.User.Username%></description>

<articles>

<% foreach (Article article in view.User.Articles) { %>

<subview:Article article="<%=article%>"></subview:Article>

<% } %> </articles> <hobbies> <% foreach (Hobby hobby in view.User.Hobbies) { %>

<subview:Hobby hobby="<%=hobby%>"></subview:Hobby>

<% } %>

</hobbies> </user> </root>

 

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 != ==

on February 4th, 2008 at 3:08pm 6 responses

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

on December 4th, 2007 at 6:30am , 4 responses

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

  • Java and C# has the Big Names behind them, so managers are comfortable. Ruby and Boo does not, hence ...
  • Java is v6, c# is v3, while Ruby and Boo are v0.x - another Management Scary.

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

on November 18th, 2007 at 9:07am , , , , 10 responses

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:

  1. query language == Linq
  2. persistence engine == NHibernate
  3. Mapping == ActiveRecord attributes

the needed prequisites:

  1. Linq (framework => framework.Version >= 3.5)
  2. NHibernate.Linq (source => source.getFrom(Rhino-Tools) )
  3. Linq for ActiveRecord - Keep on Reading

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<Category>()
            select c; 
    foreach (Category c in q)
        Console.WriteLine(c.Name);
}

Assuming Category has [ActiveRecord] mapping.

Typed View Properties in MonoRail and AspView

on October 17th, 2007 at 9:33am , , , , 3 responses

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<IView> : SmartDispatcherControllerController
where IView : class
{
IDictionaryAdapterFactory dictionaryAdapterFactory;
    IView typedPropertyBag;
    IView typedFlash;
    protected IView TypedPropertyBag
    {
        get
{
if (typedPropertyBag == null)
        typedPropertyBag = dictionaryAdapterFactory.GetAdapter<IView>(PropertyBag);
return typedPropertyBag;
}
    }
    protected IView TypedFlash
    {
        get
{
if (typedFlash == null)
        typedFlash = dictionaryAdapterFactory.GetAdapter<IView>(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<IStupidView>
{
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):

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



password: <input type="password" name="password" /> <br />
<input type="submit" />
</form>

 

view (DoStuff.aspx):

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

 

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

<aspview ... >
...

    <reference assembly="AspViewTestSite.dll"/>
...
</aspview>

 

2. you can use the DictionaryAdapter directly, on older versions of AspView (and on WebForms aspx/ascx files) by simply grabbing an adapter manually.  sample:

...
<% IMyViewContract view = new Castle.Components.DictionaryAdapter.DictionaryAdapterFactory()
.GetAdapter<IMyViewContract>(Properties); %>
...
blah blah <%=view.UsefulProperty %>
...

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

on October 3rd, 2007 at 7:04pm , , , , 0 responses

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

on September 1st, 2007 at 10:18am 0 responses

I hate switch statements. They just looks bad.

So take a look at a 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 matrix
char * 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

on June 28th, 2007 at 9:25pm , , , 0 responses

Today I 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/GetRss and 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:

public class SyndicationRedirectionHandler : IHttpHandler 
{
    #region IHttpHandler Members
    public bool IsReusable
    {
        get { return true;}
    }

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

    #endregion
}

and that line into web.config:

<add verb="*" path="SyndicationService.asmx" type="KenEgozi.Com.Weblog.SyndicationRedirectionHandler, KenEgozi.Com.Weblog"/>

Voila.

Is XAML and WPF are really that cool?

on April 15th, 2007 at 7:45pm , 2 responses

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 show a 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

on February 22nd, 2007 at 10:37am , 0 responses

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

on November 27th, 2006 at 7:37am , , , , , , 2 responses

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

on November 16th, 2006 at 11:05am , , , , , , 6 responses

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:  <%@ Page Language="C#" Inherits="Castle.MonoRail.Views.AspView.ViewAtDesignTime" %>

    b. Directives - Not mandatory:

   1:  <%@ Import Namespace="System.Text" %>
2: <%@ Import Namespace="System.Drawing" %>

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

   1:  <%
2: string[] strings;
3: DateTime today;
4: int index;
5: %>

or just

   1:  <%
2: %>

    d. View body

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

   1:  blah
2: blah
3: <%=ViewContents%>
4: blah
5: blah

AspView - Yet another MonoRail ViewEngine

on November 14th, 2006 at 2:42pm , , , , , , 3 responses

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

Duck Type in .NET

on November 1st, 2006 at 9:48am , , 3 responses

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

A simple class in presented there, that makes Duck Typing possible for Generics enabled CLS 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: public string Bar() { }
4: }
5: class Foo2
6: {
7: public string 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&lt;T&gt;

on October 10th, 2006 at 8:31am , , 3 responses

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:  public static 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:  public static Post[] GetPostsByAuthorName(string authorName)
   2:  {
   3:      return Execute<Post>("from Post p where p.Author = ?", authorName);
   4:  }

Here is the magic:

   1:  public static T[] Execute<T>(string hql, params object[] 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 < 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>(string hql, 
   2:      string[] paramNames, 
   3:      Type[] paramTypes, 
   4:      object[] parameters)

Or:

   1:  Execute<T>(string hql, IParameter[] parameters)

where IParameter definition is something like:

   1:  public interface IParameter<T>
   2:      where T: Type
   3:  {
   4:      public string 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

on September 7th, 2006 at 7:39am , , 10 responses

The reference I've used while learning 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]
public class Entity : ActiveRecordBase
{
   private int _id;
   [
PrimaryKey]
   public int Id
   {
      
get { return id; }
      set { id = value; }
   }
}

[
ActiveRecord("entitycompany")]
public class CompanyEntity : Entity
{
   private int comp_id;
   [
JoinedKey("comp_id")]
   public int CompId
   {
      get { return comp_id; }
      set { comp_id = value; }
   }
}

[
ActiveRecord("entityperson")]
public class PersonEntity : Entity
{
   private int person_id;
   [
JoinedKey("person_id")]
   public int 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]
public class Entity : ActiveRecordBase
{
   protected int _id;
   [
PrimaryKey]
   public virtual int Id
   {
      get { return id; }
      set { id = value; }
   }
}
[
ActiveRecord("entitycompany")]
public class CompanyEntity : Entity
{
   [
JoinedKey("comp_id")]
   public override int Id
   {
      get { return _id; }
      set { _id = value; }
   }
}
[
ActiveRecord("entityperson")]
public class PersonEntity : Entity
{
   [
JoinedKey("person_id")]
   public override int 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

on August 20th, 2006 at 12:56pm , 0 responses

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 CreateAlternateViewFromString and 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

on August 10th, 2006 at 6:03pm 3 responses

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
{
   public static void 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();
   }
   public void 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
{
   public static void Main()
   {
      Thread t = new Thread(RunSendMail);
      object[] parametersArray = new object[] {"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
{
   public static void 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
{
   public static void Main()
   {
      Thread t = new Thread(delegate() { 
         SendMail("from", "to", "body", SendMailEnded);
         });
      t.Start();
   }
   public delegate void Callback();
   public static void SendMailEnded()
   {
      Console.WriteLine("Do That ended");
   }
   public static void 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()

on June 7th, 2006 at 3:01pm 2 responses

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#

on May 28th, 2006 at 9:09am 1 responses

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:

public class Manager<T>
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

on May 27th, 2006 at 8:38am 0 responses

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

Statistics

Posts count:
447
Comments:
950