Category: c#

Strongly Typed EventRaiser with Rhino.Mocks

I’ve been playing in my limited spare time with Rhino.Mocks, trying to come up with a way to simplify interactions with events, and creating strongly typed IEventRaiser (or something similar). Here’s what I’ve come up with so far:

Strongly typed Rhino.Mocks Event invocation 

It’s not an easy task, but I have few ideas. If you have any ideas or suggestions post them in the comments. I’ll submit it to Ayende, so if he likes it you may actually see this stuff in some future version of Rhino.Mocks.

Technorati Tags:

More on inline initialization (answer)

Well, due to overwhelming feedback for the previous post, here’s the answer: 0.

Now the most interesting part: why?

When you use inline initialization, compiler generates a static constructor for you, and does all the initialization there. It looks like, it’s not smart enough to pick this kind of dependencies, and simply initializes fields in the order they’ve been declared in the class’ body. That’s why, by the time Field is initialized, _height has value 3, but _width is still 0. If you wanted to overcome this, you’d have to use const instead of readonly (that’s an option only for primitives and strings), or move dependant properties to some other class (for example private class). Or if slight performance decrease during creation of your class’ instances is not going to be a problem, use explicit static constructor.

Using Extension Methods to make code more readable.

Let’s look at an example:

  diagramThis is somewhat simplified diagram of classes that are part of object model I created for a certain XML format (it doesn’t reflect physical structure of XML file, rather it’s a conceptual, higher level model).

Document can contain few types of elements. To achieve this, it has a method Add, that takes a ValueElement (which is an abstract class).

The problem here, is that it is not obvious what is a ValueElement. You have to know what you can put into Add method, which means, you have to know what ValueElement’s children are. Their names however reflect their other properties, not the fact that they are value elements, which makes it even harder to guess.  You’d have to poke around in the source code to find out.

diagram_document  Why not create Add overload for each value element then? – one might ask, This way IntelliSence would hint us on what are available value elements, would it not?

diagram_code1 Well, it would but it would fix one thing and break few others.

It ties, Document to ValueElement’s hierarchy. This way, every time a new ValueElement’ descendant is added, we would have to change document as well, to add yet another overload to Add.

Why not leave general overload as a catch-all, and add overloads for those descendants we know about?

Well, this is not a good option either. At this point Document doesn’t really care about specific ValueElement. All it needs to know is that it receives a ValueElement. Telling it more, would be telling it too much. Also adding handful of new overloads would bloat the class, and introduce big-class smell.

diagram_extension This is actually one place, where I think Extension Methods would prove useful. I would introduce an extension class, that would keep all specific overloads, calling the only Document’s Add under the cover. This way, Document does not gain any more knowledge about value elements, than it needs to, and users get IntelliSence hints about what they can actually Add to Document.diagram_code2

It could be made even a little bit more verbose, by creating specific methods for each value element, instead of Add’ overloads

public static void AddText(this Document document, Text text)

{ document.Add(text); }

 

public static void AddTranslationUnit(this Document document, TranslationUnit unit)

{ document.Add(unit); }

 

public static void AddUnknownTag(this Document document, UnknownTag tag)

{ document.Add(tag); }

If I was to make a design pattern out of this, I would call it Godfather, partially because I think it’s a cool namesmile_teeth, and partially because DocumentAddExtension (our Godfather class in this example) knowledge about ValueElement’s descendants (its godchildren) and it provides this knowledge to the user, but hides it from the class it’s tied to (Document). Also important thing is, that it’s not part of ValueElement’s inheritance hierarchy (that’s why it’s called Godfather, instead of, ‘Uncle Fred’ or something like thissmile_wink).

C# tricks: Array initialization in C# 3.0

I found pretty slick new feature in C# 3.0 that I haven’t seen anyone mentioning before.

In C# 2.0 to initialize List<T> inline you had to use arrays, like

List<string> keys = new List<string>(new string[]{"key1"});

As you probably already know, in C# 3.0 you can initialize collections in in similar way like you did with arrays in C# 2.0:

List<string> keys = new List<string>(){"key1"};

This has been said many times in many places. What I missed however, was that syntax for initializing arrays changed as well. Now you can simply write:

string[] keys = new[]{"key1"};

Did you know that?

Technorati Tags: ,

C# tricks: set and return in one line

I found nice trick. Instead of writing:

private string SetNewName()

{

    string newName = GetName();

    _name = newName;

    return newName;

}

you can write

private string SetNewName()

{

    return _name = GetName();

}

And it works exactly the same. Slick.

Technorati Tags:

Testing callbacks with Rhino.Mocks

I’m currently writing tests for a piece of code that has lot of events flying here and back. Something like:

public class Caller

{

    public event EventHandler<CancelEventArgs> MyEvent;

 

    public void Call()

    {

        if (MyEvent != null)

            MyEvent(null, new CancelEventArgs(false));

    }

}

If I not only want to test if the event was fired but also examine it’s arguments I end up writing quite a lot of code to do simple thing.

First I have to define IEventSubscriber interface (contrary to IEventRaiser).

public interface IEventSubscriber<TEventArgs> where TEventArgs : EventArgs

{

    void Method(object sender, TEventArgs e);

}

Next I have to initialize it in my SetUp method

 

[SetUp]

public void SetUpTests()

{

    _mocks = new MockRepository();

    _subscriber = _mocks.CreateMock<IEventSubscriber<CancelEventArgs>>();

}

This is however quite dumb plumbing code, and I have to write it once (or once per TestFixture, in case of initialization). The worst part are the tests alone:

[Test]

public void When_Call_called_Caller_should_raise_MyEvent_with_cancel_set_to_false()

{

    using (_mocks.Record())

    {

        Expect.Call(delegate { _subscriber.Method(null, null); }).IgnoreArguments().Do(

            new EventHandler<CancelEventArgs>(

                delegate(object o, CancelEventArgs e) { Assert.IsFalse(e.Cancel); }));

    }

   using (_mocks.Playback())

   {

       Caller caller = new Caller();

       caller.MyEvent += _subscriber.Method;

       caller.Call();

   }

}

My concern is that lines 6-8 are just one big blob of code, and you have to read it carefully, to find out what it actually does. Another thing is inability to use anonymous delegates where type Delegate is expected, which results in more verbose, less readable code.

After writing few tests like this I decided to do something with this ugly piece of code, and thanks to the magic of generics I came up with a helper method:

private void ExpectCallback<TEventArgs>(IEventSubscriber<TEventArgs> subscriber, EventHandler<TEventArgs> handler)

    where TEventArgs : EventArgs

{

    Expect.Call(delegate { subscriber.Method(null, null); }).IgnoreArguments().Do(handler);

}

With it I can shorten my tests to look much nicer:

[Test]

public void Test_Callback_in_C_Sharp_20()

{

    using(_mocks.Record())

    {

        ExpectCallback(_subscriber,

                       delegate(object o, CancelEventArgs e) { Assert.IsFalse(e.Cancel); });

    }

    using(_mocks.Playback())

   {

       Caller caller = new Caller();

       caller.MyEvent += _subscriber.Method;

       caller.Call();

   }

}

and with lambdas, even to:

[Test]

public void Test_Callback_in_C_Sharp_30()

{

    using (_mocks.Record())

    {

        ExpectCallback(_subscriber, (o, e) => Assert.IsFalse(e.Cancel));

    }

    using (_mocks.Playback())

    {

       Caller caller = new Caller();

       caller.MyEvent += _subscriber.Method;

       caller.Call();

   }

}

It not only improves readability of my code, but thanks to generic constraints I get more compile-time type checking. Now I can get back to testing:)

Technorati Tags: , ,

Hello World: the ‘new’ keyword

Everyone knows what the new keyword is for in C# – you use it to call constructor of an object, right? What can be simpler? Actually, that’s true, but not the whole truth. That’s the most common way to use it. However, new is one of contextual keywords, which means, it can have different meaning, depending on the context where it’s being used.

The new keyword can be used in three scenarios:

  • the one presented above, everyone immediately thinks of – creating objects.
  • as modifier, to hide members of a base class.
  • as generic constraint.

Creating objects is pretty straightforward, and there’s no magic there:

string[] stringArray = new string[] { "kot", "knur", "pies" };  //creating array

List<string> stringList = new List<string>(stringArray);        //creating class

DateTime dateTime = new DateTime(2000, 1, 1);                   //creating struct

Action myDelegate = new Action(delegate { });                   //creating delegate

var myAnonymousType = new { A = 1, Name = "My name" };          //creating anonymous type

The only thing that may look unfamiliar, is new C# 3.0 anonymous types initializing. It works in similar way to anonymous delegates. Here I created a nameless class, that two fields: A (of type int) and Name (of type string). This is the most basic stuff.

Not everyone however, knows about two other usages of that keyword. Let’s consider very simple example:

class Program

{

    static void Main(string[] args)

    {

        InheritedClass inherited = new InheritedClass();

        inherited.Write();

        UseBaseWrite(inherited);

    }

 

    public static void UseBaseWrite(BaseClass item)

    { item.Write(); }

}

 

public class BaseClass

{

    public void Write()

    { Console.WriteLine("Hello. I'm a BaseClass' Write!"); }

}

 

public class InheritedClass : BaseClass

{

    public new void Write()

    { Console.WriteLine("Hello. I'm a InheritedClass' Write!"); }

}

We have two classes, BaseClass, and InheritedClass that inherits from BaseClass. They both have non-virtual method Write, that writes a string to the console, and inherited class has a new keywords as its modifier (the code would actually work the same without that keyword, we would however receive compile time warning). We then create InheritedClass’ instance, and pass it to UseBaseWrite, method, that calls its Write method.

So what would be the outcome of that program?

Hello. I’m a InheritedClass’ Write!

Hello. I’m a BaseClass’ Write!

 

If you bet on that answer you can give yourself a reward. Now the question for those of you who guessed differently is – why? Notice that Write in BaseClass is not virtual, and as such we’re not overriding it in InheritedClass. We just create brand new method, that has no connection whatsoever to BaseClass’ Write, except the fact that it has the same name. This way,(as InheritedClass inherits from BaseClass) we have in it two unrelated methods with the same name. And here comes the tricky part: Which one of those two methods will be called, depends on the type of reference you’re holding to your object. If you reference it as InheritedClass (as we did in 6th line), we call Write implemented in InheritedClass. When we however reference the same object as BaseClass (as we did in 10th line) BaseClass’s implementation gets called. That’s why new is not inheritance modifier, but it let’s you have method in inherited class with the same name as base class, you don’t get however polymorphic  behavior. In this context it’s usability is really limited.

More interesting usage is new as generic constraint:

static void Main(string[] args)

{

    GenericClass<DateTime> d = new GenericClass<DateTime>();//ok

    DateTime dateTime = d.GetNewItem();

    GenericClass<string> s = new GenericClass<string>();//compile error

}

 

public class GenericClass<T> where T : new()

{

    public T GetNewItem()

    {

        return new T();

    }

}

When you specify new() on constraints list for your generic type, you demand, that generic type T has to have public parameterles constructor.

In the example above, it’s ok to pass DateTime as generic parameter, as it meets the constraint. String however does not have default constructor, that’s why this code would fail to compile.

It let’s you then call new T() anywhere in your code. It can be very useful sometimes. One more thing to keep in mind, is that when you specify more than one generic constraint, new() must be the last one of them.

//compilation error

public class GenericClass<T> where T :  new(), IEnumerable

{ public T GetNewItem() { return new T(); } }

 

//now ok

public class GenericClass<T> where T : IEnumerable, new()

{ public T GetNewItem() { return new T(); } }

And that’s basically all. I hope it was informative and I didn’t miss anything. Happy coding.

Technorati Tags: , , ,

Framework Tips V: Extension Methods and nulls

You can call extension methods on null elements. It’s obvious when you think about it: its a normal static method where you specify its first parameter with this.

using System;

 

namespace ExtensionMethods2

{

    class Program

    {

        static void Main(string[] args)

        {

            string isNull = null;

            Console.WriteLine(isNull.IsNullOrEmpty());

            string isNotNull = "string";

            Console.WriteLine(isNotNull.IsNullOrEmpty());

        }

    }

 

    public static class StringExtensions

    {

        public static bool IsNullOrEmpty(this string s)

        {

            return s == null || s == "";

        }

    }

}

Notice that if it was normal instance method (i.e. defined in the System.String class) I would have to check if my string instance is not null, before calling it, or I would receive runtime NullReferenceException. Now I can move that check to the method, where it belongs, and make my code cleaner. Pretty slick 😉

Framework Tips IV: Check if character exists for given Encoding (CodePage)

In a project I’m currently working on, I needed to check if particular character is a part of given CodePage. Problem with .NET’s Encoding class, is that although it maintains a table mapping Unicode characters to codes in particular CodePage, it keeps it as private field. Moreover it does its best to replace characters it does not contain, with some fallback character.

One might use this fact, and compare character received this way from Encoding’ instance, with original character, assuming, that if they are different, this character is not a part of that CodePage, but this is not an elegant solution. And involves lot of overhead, by first converting char to byte[] and next the other way around.

Another solution is to use an overload of Encoding’s static GetEncoding method, like this:

Encoding.GetEncoding(1252, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);

this way, when user tries to convert a character that is not a part of given Encoding’s CharSet, fallback encoder throws an exception. So one might use try/catch and be happy with it, but this too is an awful solution, and also limiting, as you have to create Encoding instance yourself, so you’re helpless in cases when you receive arbitrary encoding.

After little bit of poking around I came up with yet another solution, that seems to be better, faster and more elegant than those two. I however didn’t test it thoroughly so it may have flaws as well (or may not even work at all in some cases). First, let the code speak:

using System;

using System.Text;

 

namespace ConsoleApplication3

{

    public class Program

    {

        static void Main(string[] args)

        {

            char s = '\x015f';  //exists in 1250 but not in 1252

            char a = 'a';       //exists in both

            char t = '\x00fe';  //exists in 1252 but not in 1250

            Encoding ce = Encoding.GetEncoding(1250);

            Encoding we = Encoding.GetEncoding(1252);

            Print(ce, we, s);

            Print(ce, we, a);

            Print(ce, we, t);

            Console.ReadKey();

        }

 

        private static void Print(Encoding ce, Encoding we, char c)

       {

            Console.WriteLine("{0}: {3}: {1,-6} {4}: {2,-6}",

                c, ce.Contains(c), we.Contains(c), ce.WebName, we.WebName);

        }

    }

 

    public static class EncodingExtensions

    {

        public static bool Contains(this Encoding encoding, char character)

        {

            Encoding enc = encoding;

            if (!(enc.EncoderFallback is EncoderFallbackCheckExists) && enc.IsReadOnly)

            {

                //you might want to cache these, in order to avoid having to

                //clone given encoding every time.

                enc = (Encoding)encoding.Clone();

                enc.EncoderFallback = new EncoderFallbackCheckExists();

            }

            int result = enc.GetByteCount(new char[] { character }, 0, 1);

            return result > 0;

 

        }

    }

    

    internal class EncoderFallbackCheckExists:EncoderFallback

    {

        public override int MaxCharCount { get { return 1; } }

 

        public override EncoderFallbackBuffer CreateFallbackBuffer()

        { return new FallbackBufferCheckExists(); }

    }

 

    internal class FallbackBufferCheckExists:EncoderFallbackBuffer

    {

        public override int Remaining { get { return 0; } }

 

        public override bool Fallback(char charUnknown, int index)

        { return false; }

 

        public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)

        { return false; }

 

        public override char GetNextChar() { return '\0'; }

 

        public override bool MovePrevious() { return false; }

    }

}

I created two classes: one inheriting from EncodierFallback, and one inheriting from EncoderFallbackBuffer. Basically my idea was, that I will provide Encoding instance with fake fallback encoder, that should not try to provide any fallback character. That way Encoding will silently (and fast) fail and its GetBytes and GetByteCount methods will return respectively empty array and 0y.

Only problem I had was to inject actual EncoderFallbackCheckExist instance info Encoding’s EncoderFallback property. Although this property has setter, when IsReadOnly is true, trying to set it, will raise an exception. Encoding however implements ICloneable, and cloning it, does not preserve its readonly state. So after its cloned, you can safely assign its EncoderFallback.

I also created simple EncodingExtensions class, with single extension method, to wrap the whole logic, and attach it to Encoding class, so that you can write:

Encoding encoding = Encoding.GetEncoding(1256);

bool b = encoding.Contains('ź');

Looks good to me, and as far as I’ve checked – works. However if you have better idea how to accomplish this, please leave a comment.

Technorati Tags: , , ,

Framework Tips II: How to get default ANSI Encoding for given culture

It’s sometimes useful to know what is the default ANSI CodePage, for some given culture. It’s quite easy to achieve, thanks to System.Globalization namespace.

CultureInfo cultureInfo = CultureInfo.GetCultureInfo(1252);

Encoding encoding = Encoding.GetEncoding(cultureInfo.TextInfo.ANSICodePage);

However this code will not always work correctly. The problem is, not every culture has default ANSI CodePage, and therefore, for them you’d have to have plan B, like using UTF-8.

CultureInfo cultureInfo = CultureInfo.CurrentUICulture;

int codePage = cultureInfo.TextInfo.ANSICodePage;

Encoding encoding = codePage.Equals(0)?

                        Encoding.UTF8:

                        Encoding.GetEncoding(codePage);

To see, all such cultures, you can use following code:

var cultures = from c in CultureInfo.GetCultures(CultureTypes.AllCultures)

                         where c.TextInfo.ANSICodePage.Equals(0)

                         select c;

foreach (CultureInfo info in cultures)

    Console.WriteLine("{0,-10}{1}", info.Name, info.EnglishName);