Wednesday, December 17, 2008

throwing exceptions should not be done ad-hoc

what would you expect from this code?


System.Drawing.Image.FromFile("file.mp3")


Notice that i deliberately pass a non-image file to this function. Do you expect you will get InvalidImageFormatException? I would expect that, but as Microsoft documentation says it will return OutOfMemoryException.

Since when out of memory has something to do with image format? That's a rhetoric question of course, since .Net2 is many years on the production already :)

Monday, December 15, 2008

Reading XmlNode.AppendChild Method documentation

While reading XmlNode.AppendChild documentation i found myself thinking of this:

If I have the following code, what would be its result?

XmlNode parentNode = new XmlNode(...);
XmlNode childNode = new XmlNode(...);

parentNode.AppendChild(childNode);
parentNode.AppendChild(childNode);

Console.WriteLine(parentNode.Childs.Count)


By reading the code i would tell that we would get two children. But by reading the documentation you can find that it will be one. Take a careful look at the following sentence in official Microsoft documentation.


If the newChild is already in the tree, it is removed from its original position and added to its target position.



How the in the world I can understand from the method name "AppendChild" that it not only appends, but removes and then appends?

So yes, naming your functions correctly is very important for clean code.

Wednesday, December 10, 2008

Asynchroniaus data fetching with NHibernate

yes, that, AFAIK, does not work out of the box. Up to know the following thoughts come to my mind:

How does ISessionFactoryHolder react to multiple threads? Does it generate one session factory holder or one for each thread?

Looking at ThreadScopeInfo.cs:26 we see this code

[ThreadStatic] static Stack stack;

This clearly tells that we have a new stack of of session scopes for each thread.

Googling around i've came to this post. It suggested to just register your own thread-safe implementation of IThreadScopeInfo.

While I think that is OK and might solve the problem, but why reinvent, whenc Castle.ActiveRecord already provides the following implementations of IThreadScopeInfo:

  • AbstractThreadScopeInfo - this is used as an abstract implementation, not useful

  • HybridWebThreadScopeInfo - the docs say: This is used for scenarios where most of the you need per request scope, but you also does some work outside a request (in a thread pool thread, for instnace).

  • ThreadScopeAccessor - This is just an accessor, and does not provide single scope for all threads

  • ThreadScopeInfo - this is the default implementation, which has static instances per-thread

  • WebThreadScopeInfo - this implements a Session Per Request pattern pattern, So not useful



So, no helpful implementation, so will do the same as suggested here. But, really, i hate copy-paste things, that's pure evil

Tuesday, November 25, 2008

Isolator for Sharepoint : Unit testing for sharepoint made easier

In one of the blogs I'm reading found that there's a new product for unit testing SharePoint without running Sharepoint instance. Well, that is nice.


And here's the adverticement:


Typemock are offering their new product for unit testing SharePoint called Isolator For SharePoint, for a special introduction price. it is the only tool that allows you to unit test SharePoint without a SharePoint server. To learn more click here.

The first 50 bloggers who blog this text in their blog and tell us about it, will get a Full Isolator license, Free. for rules and info click here.

Thursday, June 19, 2008

Eagerly load two or more collections

I'll be verbose on it:

this link has exactly what i needed for.

As a proof of concept I wrote this unit test to check that collections are loaded eagerly. Domain model is a client has a collection of prders. An Order has a collection of bills


Client client = null;
using (new NHibernateSession())
{
ISession session = NHibernateSession.GetISession(typeof(Client));

client = session.CreateCriteria(typeof(Client))
.SetFetchMode("Orders", FetchMode.Join)
.UniqueResult();

session.CreateCriteria(typeof(Client))
.CreateCriteria("Orders")
.SetFetchMode("Bills", FetchMode.Join)
.List();
}

// Assert that orders and order.Bills are eagerly laoded
foreach (RisingStar.BLL.Model.Order order in client.Orders)
{
order.Bills.Count.ToString()
}

Wednesday, May 7, 2008

Dynamic assembly generation

Interestingly enough, if you build a dynamic assembly, you can not call GetExportedTypes on it, because the method is not implemented. Very funny, ha ha.


Microsoft has confirmed it is a bug


I encountered this bug while trying to compile boo code with boo compiler


[Test, ExpectedExceptionAttribute(typeof(NotSupportedException))]
public void GetExportedTypes_NotSuportedInDynamicAssembly()
{
string assemblyText = @"
class Foo:
x as int
";
BooAssemblyCompiler compiler = new BooAssemblyCompiler("test", assemblyText);
Type[] types = compiler.CompilerContext.GeneratedAssembly.GetExportedTypes();
}



BooAssemblyCompiler is just a helper class, which inside just does these steps

// creates a boo compiler
m_compiler = new BooCompiler();

// adds a CompileToMemory step to the compiler pipeline
m_compiler.Parameters.Pipeline = new Boo.Lang.Compiler.Pipelines.CompileToMemory();

// defines that an output should be a library
m_compiler.Parameters.OutputType = CompilerOutputType.Library;

// finally, compiles boo text
StringInput input = new StringInput(assemblyName, booText);
m_compiler.Parameters.Input.Add(input);
m_compilerContext = m_compiler.Run();

Thursday, April 10, 2008

How to to effective error handling using Exceptions

I've never actually grasped enough how to work with Exceptions. It was a mystery for me when to throw them and when to catch them. Lately, i have done some improvisation with the code, and I got some new ideas.



As far as I know there are two main approaches to error handling.


  1. One is c/c++ style, where error codes are returned with return codes and optionally passing aditional info in other parameters

  2. Second approach is to throw and catch Exceptions





To begin working with exceptions effectively one must first decide which way to go. Exceptions and error codes can not go together, as this will make the code spaghetti like, and people will get confused. Important thing is to remember is that code is for people, not for machines




My preference is to go Exceptions way, for these reasons:


  1. Exceptions allow you indicate an error in any place, and error handling can occur in any other place

  2. Using error codes forces every function to also return an error code, which is very intrusive. Error handling should not force you to change your existing or new code in any way.

  3. Exceptions can be catched on a very high granularity (having that there is a proper exception hierarchy). One can catch internal errors in service layer, and UI related exceptions in UI layer

  4. Exceptions can be used to carry a very brief error message, and, what is even more important, information how to solve the problem

  5. Exceptions can even be catched, stuffed with more detailed exception text (for example context-specific information) and rethrown again