Drafts

I have many posts that are actually 'drafts', this is ideas that could be useful, but I have not time to complete them. This page is all about such posts.

Kiev ALT.NET: Some geek details

Our logo, Kyiv 4AM, 35 mm camera

  1. Our logo is actually Kyiv 4AM, 35 mm camera.
  2. Sources of all our stuff is hosted on github.
  3. Blog is hosted on tumblr. Main problem is tumblr does not support Live Writer.
  4. Main site is hosted… well this is bit modified parking page. Hope someday we will have normal hosting. And hope it will be Mono based.
  5. Our event registration should be easy. You just have to drop e-mail message to support@kievalt.net or write something to twitter.
  6. We do not have Google Groups mail list, LinkedIn Group yet. Ping me if you need one.
  7. Inception is probably best movie I seen this year.
  8. Inspired by SPB ALT.NET

Hope to see you this Friday :).


Array aware model binder for ASP.NET MVC

What do expect from this ASP.NET MVC action method, especially from argument ids:

public ActionResult Print(Guid[] ids){		
    this.View(ids);
}

I expect array of identifiers. Do you expect that ids can be null then? But it can! For some reasons default model binder desides to send null instead of empty array! For me this behaviour was quite surpriseing.

Solution

Solution is simple. Custom model binder should resolve all problems. Unfortunatelly not this time. Custom model binders are registerd per type. So the only solution I found to the time is inherit DefaultModelBinder and override object BindModel(...) for all arryas and fallback to base for everything else. Something like this:

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
	var model = bindingContext.Model;
	var modelType = bindingContext.ModelType;
	if ((model == null) && modelType.IsArray)
	{			
		// ... materialize array from request ...
		return justCreatedArray;
	} 
	else
	{
		return base.BindModel(controllerContext, bindingContext);	
	}
}

Most of the code has been taken from ASP.NET MVC sources and therefore should work exactly the same.

Full copy of the class is here.

Enjoy!


ASP.NET does not cache CSS on the client

Yes this is true. To fix, modify web.config.


Live without mocks

How to mock IQueriable

REXML could not parse this XML/HTML: 
<T>? How to mock LINQ to SQL? How to mock Entity Framework Context? How to mock WCF Service? How to mock this thing? And eventually how to mock that thing?


http://chaliy.name/blog/2009/12/data_sql_modeling_looks_great

Entity Framework Model genereated via M, does not support “M” functions.


ASP.NET MVC Web Services - Exception Handling (Part #2)

Last time I described how to remove requirment ActionResult from the controller actions by automatically wrapping results of the action into the JsonResult.


.NET 4.0: The new way to implement lazy singleton

Among other new stuff in upcoming .NET 4.0, I found LazyInitislizer. The idea is simple. Method accepts reference to the object, and in case it null, creates new one. So now your lazy singletons could look like the following:

public class Stuff
{
    private static Stuff _instanceStorage;
    public static Stuff Instance
    {
        get
        {
            LazyInitializer.EnsureInitialized(ref _instanceStorage);
            return _instanceStorage;
        }
    }
}

This code will use default constructor in case instanceStorage is null. Of course, EnsureInitialized has overrides that allow custom create.

What about .NET 3.5?

This stuff (with small changes) also awailable for .NET 3.5. They are part of the Parallel Extensions for .NET 3.5. The same example will look like the following:

Code example goes here...

Enjoy!


Our Data Access testing approaches

To continue Data Access theme not a worth to mention how we teasting all this stuff. So let start from Domain Model.

Domain Model Mappings


LINQ to Entities less known queries

Form time to time I am facing cases that has well know solution in SQL, but less intuitive in LINQ. Following is such “cases” and solutions for them.

How to check if query return at least something

In SQL you just write EXISTS clause and you have result. Analog in LINQ word is Any. So.

var r = from c in ds.Customers
	  select c;

var result = r.Any();

Result is bit overcomlicated:

SELECT 
	CASE 
		WHEN ( EXISTS (SELECT 1 AS [C1] FROM [SalesLT].[Customer] AS [Extent1] )) 
		THEN cast(1 as bit) 
		WHEN ( NOT EXISTS (SELECT 1 AS [C1] FROM [SalesLT].[Customer] AS [Extent2])) 
		THEN cast(0 as bit) 	
	END AS [C1]
FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]

As for me better reuslts will be with the following:

WHEN ( EXISTS (SELECT 1 AS [C1] FROM [SalesLT].[Customer] AS [Extent1] )) 
THEN cast(1 as bit) 	
ELSE cast(0 as bit) 

But we have leave?


Stuff to know when starting with ADO.NET Data Services (Part 2)

The server encountered an error processing the request. The exception message is ‘Unable to load the specified metadata resource.’. See server logs for more details.

http://stackoverflow.com/questions/689355/metadataexception-unable-to-load-the-specified-metadata-resource

On data context type ‘XXXX’, there is a top IQueryable property ‘XXXX’ whose element type is not an entity type. Make sure that the IQueryable property is of entity type or specify the IgnoreProperties attribute on the data context type to ignore this property.

This message means ADO.NET Data Services cannot find primmary key. There are at least two solutions

  1. Decorate entity with DataServiceKeyAttribute
  2. or name it as “ID” or “XxxxID” (yes, Xxxx is name of your enity)

NHibernate.Linq tricks

Select by date part of the DateTime

expr.Where(i => i.OrderDate >= date && i.OrderDate < date.AddDays(1));

ASP.NET MVC DateTime Serialization format

As expected ASP.NET MVC uses CultureInfo.CurrentCulture for simple values.

http://msdn.microsoft.com/en-us/library/1k1skd40.aspx

return DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), DateTimeStyles.None);


Inventing the wheel. Custom primitive types

What I hate in .NET is strings. Even not strings, rather nullable behavior of them. I do not know why MSFT decided to make them nullable, but IMHO this was really stupid. My code is overloaded with stupid contracts to ensure that input string is not null!

Solution is obvious. I needed to implement my own string. It’s easy. Most of the time I spent to name new class. This is how StringValue was born! Implementation is trivial, link to code here.

After few weeks of using StringValue. I realized that there is special kind of strings. Identifier strings. Often they are case-incentive. This is how IdentifierString class was born.

Next step was easy. Many of my domain properties like description, content are semantically long texts. This is how Text was born. Btw, semantic is not the only benefit. You can see “features”, but most interesting is automatic mapping to the database fields tbd.

Well, for now that’s all. At least for strings :). I also have bunch for numerics and dates.

Of course. Money. Just semantical decimal.

Amount. Simple non-negative Money.

Some notes:

  1. Semantic types are yet another metadata. For example you can use this metadata for automaping to database.
  2. Code to check if age of the person is more than zero is stupid. Just use appropriate type. Do not worry, if there are no “appropriate” type. This not worse code to create one. Readability of your code will benefit largely.
  3. tbd

Public API Guidelines

http://stackoverflow.com/questions/1168161/1168257#1168257


The Pragmatic Way. Persistence identity field in domain entries

There are dozens of best-practices, patterns, recomendations… Sometimes I catch myself on spending time to overcome code smells. Did you?

Recent example is persistence ignorance and question if domain entities should have persistence identifier. On the first side, you should prohibit identitiy fields and rather use domain identy fields. On other side well know benefits of the unique identification. What to choose?

Of course, “it depends”. First is to be pragmatic. For example, if you developing domain model, most probably it’s easy to follow common practise and do not use identities. But do not be fooled, this is just principle. I you need identifier to be serialized on a wire or you need identity for some other purposes like referencing outside of the application, just open it.

At this point, many people ask me:

  • But! This means that everybody can use identity field. There is nothing that enforces this practice.

Well, yes this is true. Everybody can. But why they? Do you have peers that try to break architecture? Just make your team aware of this rule. Small email message.


DDD. Domain Messages - Theory

Common issue with DDD is situations when business operation envolves more than one root aggregate.

For example, you are modeling file system. You need to model user quota, so when user creates new file, system should ensure that there are some space. To do this we create entity Quota that will keep AllowedSpace and CurrentUsage. For physical file, we use File entity, no surprises here. When user creates new File we check if Quota


Poor Man's Dependency Injection Pattern, the pragmatic way.

Well, you probably know that Poor Man’s Dependency Injection(PM DI for short) is big no-no? No? Then please read Jimmy Bogard here and here, read TBD and TBD. When done - return back. And I will try to show other side of the coin.

So for now we know for sure that Poor Man’s Dependency Injection is something terrible, unacceptable and unprofessional. This statments has some background. I will TBD

Main reason for DI movement is to replace direct dependencies with indirrect. So instead of depending on implementation, you depend on the contract and then only in runtime on the implementation. This is good stuff, since you can change implementation for example for puposes of tesiting or something else.

Pure DI leverage on the third-party to make sure that all dependencies are available.