Dynamic TDD

This post is about Dynamics in C#, TDD and how we can mix all of this in a fun and fluent way ;-)

I presented that at the last ALT.NET Fr meetup and I want to share it more widely now after the very good first impressions given by the community.

For a long time now, I thought about how dynamic can help writing tests. Since my friend  Thomas Pierrain started the NFluent library, I tried to keep in mind introducing dynamic in it’s library because I think it could help.

I then came with some ideas in a form of a small POC that I want to share with you. Instead of a long discourse, I preferred to record the following small videos because the most interesting part of the concept is how things changes constantly in a very small feedback loop. And thanks to Remco Mulder and it’s continuous testing tool NCrunch, it’s even better and quicker ;-)

Introduction : problems, concepts


Dynamic TDD intro

Demo 1 : 2 step dynamic implementation


Dynamic TDD Demo 1

Demo 2: Function mocking facilities


Dynamic TDD Demo 2

As I said, this is now mostly ideas, concepts, tests but I think it’s important to go deeper in that direction because getting a better feedback loop is very important and we also have to test things like that to discover new usages.

Any ideas, comments are welcome, you can post comments here, ping me on twitter (@rhwy) or send me a mail to rui at rui dot fr.

happy coding!

Posted in Articles, Projects Tagged with: , , ,

NFluent Extensions

About

NFluent has been designed since the beginning to be easy to use and to provide a great user experience. That means that we want the API to be as Fluent as possible. And important part of the NFluent value is to allow a smooth writing of all the checks. That’s why we provided an important set of checks for all the base types.

But, in order to make it enjoyable for everyone we also provide a set of extensions that allows you to create extensions for your own types. we hope to provide with NFluent the core DSL for your tests and enhance the quality you can put in their writing.

Default Checks

Just to refresh you with the concepts of the NFluent Checks, let’s see some of the bases.

In order to provide a DSL for your tests, the Checks are based on the type of the SUT (System Under Test). Then, depending on the type you test, you’ll have a full fluent experience while writing with only the methods allowed on that type.

For example if you are testing an Integer:

var age = 21; 
Check.That(age).IsPositive(); 
Check.That(age).IsGreaterThan(18); 

Or Dates:

var einstein = new Date(1879,3,14); 
var anelka = new Date(1979,3,14); 
Check.That(einstein).IsBefore(anelka); 
Check.That(einstein).IsInSameMonthAs(anelka); 
//This one doesn't exist but it could;-) 
//Check.That(einstein).StopDoingStupidComparisonsJustBecauseOfMatchingDates(anelka) 

Or even better with lists :

var user = new User(); 
Check.That(user.Roles).ContainsExactly("guest","anonymous"); 

NFluent Extension

The default fluent checks provided in the core NFluent library are enough to replace you habitual Asserts. But Sometimes when you work with a real Domain (not anemic) and you want to provide a nice experience for the users of your library it is very valuable to create your own NFluent Checks!

This fit very well with recurrent tests you need to do.

All the secret of the NFluent extensions is on the ICheck<T> returned by the Check.That<T>(T sut) (among other things).

The idea is to provide an extension method on the ICheck<T> interface for the T type you want to check. That’s it! Don’t forget that it is this check type you have to extend and not the T type itself.

In fact, there is another secret to be able to extend you checks…In order to not pollute the intellisense experience, the value of the type you are checking is not provided on the ICheck<T> interface. That’s why it needs to be casted to a proper compatible type:

ICheck<mytype> mycheck = thecheck; 
var runnableCheck = mycheck as IRunnableCheck<mytype>; 
mytype myvalue = runnableCheck.Value; 
//test my Value.

This is now mostly internals and this cast is here only for information. Since v0.11 we have a nice helper to do that and this is how you must use it now:

void MyExtention(this ICheck<mytype> check) {

var runnableCheck = 
       ExtensibilityHelper<mytype>.ExtractRunnableCheck(check);

mytype myvalue = runnableCheck.Value; 

//test my Value and throw with a nice message if it is not what you expect
}

Once here you can use the Value and check what you need.

One other important point the Chaining part. If your extension is only a simple test, you may return nothing and just throw if you don’t have what you expect. On the other side, if you are building more complex things, it should be better to allow your Checks to be chainable. If you want to provide to the users of your extension an happy fluent syntax, you may want to be able to chain it with an other operator. In this case, you have to encapsulate your code inside a dedicated execute method in the runner. Then instead of the previous exemple, you may use:

ICheckLink<ICheck<mytype>>  MyExtention(this ICheck<mytype> check) {
 var runnableCheck = ExtensibilityHelper<mytype>.ExtractRunnableCheck(check);
 return runnableCheck.ExecuteCheck(
                () =>
                {
                    //do some test and throw if you're not happy
                },
                //add here a negated exception message for the NOT chaining);
}

Extend it now!

For example, imagine that you have in your application Users with Roles. For most of the business tests you need to do you’ll need to check that the user have a certain role.

Our User class for future usage:

public class User { 
   public int Id {get;set;} 
   public string Name {get;set;} 
   public IEnumerable<string> Roles {get;set;} 
   public User(int id, string name,IEnumerable<string> roles = null) { 
      Id = id; Name=name; 
      Roles = roles ?? new List<string>(); 
} } 

As you have many tests that include checking the roles existence of a user it is convenient to create a specific Check in order to factorize some code and to be more domain specific.

You just have to create a static class with your extension method on ICheck<User> like this:

public static class CheckUserExtensions 
{ 
   public static void HasRole(this ICheck<User> user, string role)
   {
      var runnableCheck = ExtensibilityHelper<User>.ExtractRunnableCheck(user);
      User value = runnableCheck.Value; 
      Check.That(value).IsNotEqualTo(null); 
      Check.That(value.Roles).IsNotEqualTo(null); 
      Check.That(value.Roles).Contains(role); 
   } 

Then, everywhere you need it instead of doing a lot of testings, you have a real domain word that makes sense:

[Test] 
public void should_do_something_with_users() 
{ 
   var user = new User(1,"rui",new []{"admin","editor"}); 
   Check.That(user).HasRole("test"); 
} 

Some conclusion

We saw some of the basics of NFluent and also how to create our own checks for our models.

NFluent by it’s nature, provides a really nice way to produce tests that make sense, that are easy to write (with dedicated intellisense for each type) and easy to read (it’s near plain english). Don’t forget that your tests should also be your documentation and providing fluently sentences near plain english instead of questionable asserts will enhance that.

If you are providing a library to other developers, it can also be very valuable to provide them a testing library with dedicated Checks for your models. It will enhance the understanding of the domain but also help them to write their own tests with the fluent interfaces you provided.

Happy Checking!

Posted in Articles, Technical Posts Tagged with: , ,

DUX – Developer User Experience

Sometimes, I wonder why things are not simple and expressive.

One thing that I try to advocate for many years is something that I should call DUX – Development User Experience. It means what it should mean : the user experience while you are doing your development.

We know that good software is hard to achieve and that most of the times people care only about what is visible. Crafting all the parts of the code in the right way is also important. The final end user experience is not the only part…

When you build frameworks or lower level components, even if their target is to be used by developers for higher level software, never forget that you still users! Your users are the developers working with your libraries.

Why do I complain? Because DUX is also an important part of the things you should care when you are building libraries. Framework developers usually though about:

  • Try to provide the functions needed for the framework with a defined priority order (maybe defined by marketing guys…)
  • Try to provide as much functions as possible because a richer framework is better than a framework providing a small set of things.
  • Use some unit tests for internal use because most people do.
  • Try to care about performance because a framework should do
  • Try to fit as much as possible in the current ecosystem
  • …certainly a lot of other things

I don’t know if all these things are the main reason I prefer to use open source libraries but in most cases these ones provide a slightly different results when they are realized with a decentralized unordered team:

  • Functions are provided because people really needs them
  • Delivery and functionalities are not subsidiaries of the market
  • You can control functionalities with the unit tests provided and also see how it works (most of the times this is much more efficient than a regular documentation…)

Another good point with open source is that the good and the bad are automatically currated by the community. If your framework doesn’t deserve enough needs, if it is not enough clear about it’s usage and so on, it will die. Simple and efficient.

Frameworks have to be simple and fun to use. The .Net world has a lot of legacy stuff and history that tends to be complicated by essence because it takes its roots in entreprise. Alternatively languages like Ruby have things simple and expressive mostly because it is a developer to developer platform with pragmatism in mind.

Take a simple exemple. Suppose, you are building a shell application. You want to print messages and draw some lines to present things clearly, like this:

 

--------------------------------------------------------------
-- My App (c) 2013
--------------------------------------------------------------

In C# to build lines like this, you should write all the line in a string and print it like that:

Console.WriteLine("--------------------------------------------------------------");

Or with an iteration if you want to get more reusability :

public string Repeat(string pattern, int timesToRepeat)
	{
		string[] resultArray = new string[timesToRepeat];
		string result = pattern;
		for (int i = 1; i < timesToRepeat; i++)
		{
			result = result+pattern;
		}
		return result;
	}
...
Console.WriteLine(Repeat("-",80));

Instead of that, in the ruby world, you just do that:

puts "-" * 80

Which literally means : “put in standard output the string ‘-‘ repeated 80 times. Which one sounds better for you?

Attention: please note that I am a .Net developer, we are just trying to talk about DUX, I am far than saying that Ruby is better than C#, yeap?

Btw, C# is a very high level platform and you have a lot of better things but that’s not the problem here. And In fact you should get more fluent things with a simple extension method like that:

public static string Repeat(this string pattern, int timesToRepeat)
	{
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < timesToRepeat; i++)
		{
			sb.Append(pattern);
		}
		return sb.ToString();
	}
...
Console.WriteLine("-".Repeat(80));

If you want a shortest way to achieve that you should also try:

String.Join("",Enumerable.Repeat("-",80))

 

Never forget that software is complicated by essence, so, don’t help this complication, try to make things clean even if your audience are developers!

Posted in Articles Tagged with: , , ,

.Net Web dev Mac – Nuget, Monodevelop and Nancy

Basic Support

In the Beginning

Managing binaries, dependencies and packages is such an important point that it is unbelievable  that it takes 10 years to get something like Nuget on .Net from Microsoft…

If you are running Mono for .Net web development on your Mac, it is not better regarding this point…

It was painful with MonoDevelop was the lack of support for Nuget.

We can do things by hand since v2 of Nuget (and before 1.7 btw) because you can use nuget.exe from mono command line but as it wasn’t integrated in solutions and projects it only helps you get binaries.

But let’s see how to setup Nuget on mono.

Install & configure Nuget

First download the las exe:

curl -O -L  http://nuget.org/nuget.exe

As Nuget is a .Net binary, you need to launch it via mono. If your installation is ok – and it should with the installer -, you are able to launch mono from every path in your shell. Note also that you need to specify the framework 4 runtime compatibility to make it work properly. So start the nugget exe, just execute this line:

mono --runtime=v4.0 Nuget.exe [then follow your nuget args]

In order to make this work from every, I should advise you to create an executable shell script that handle that.

In the folder you downloaded Nuget, copy it to /usr/local/bin:

cp Nuget.exe /usr/local/bin

Create a new file for your command, just name it nuget to get the same semantics:

touch nuget

Edit your file and just copy/paste this code:

#!/bin/sh
# add a simple 'nuget' command to Mac OS X shell under Mono
PATH=/usr/local/bin:$PATH
mono --runtime=v4.0 /usr/local/bin/NuGet.exe $*

Then give the correct execution rights to your file:

sudo chmod +x nuget

Then open a new console and try nuget (with a nuget help for exemple). The good point is that you can now use Nuget from everywhere!

You should also have a default config path working with NuGet, if you don’t have one created automatically, create a new fresh one

Local config should be stored at:

~/.config/NuGet/Nuget.config

Once you have this, you can play with nuget, with your own repositories too, but you still closed in the command shell.

If you work with MonoDevelop, you have to create your package folder, your packages config file and then reference your binaries manually. It’s not an ideal configuration but that’s better than nohting ;-)

Nuget support on Monodevelop

Install

This morning my eyes flashed after a tweet of David Fowler:

David Fowler tweet about nuget monodevelop support

nuget monodevelop support

Ok, let’s see what is it about?

This is about an Addin written by Matt Ward. You can find the sources on his github 

 

You can build it and install it by your own, but Matt did the things well and provided a Monodevelop addin channel with this:

http://mrward.github.com/monodevelop-nuget-addin-repository/3.0.5/main.mrep

Click on Monodevelop, then Add-in manager. Select Gallery and manage repositories:

monodevelop addin repositories

monodevelop addin repositories

Then click [Add] and paste the url:

Add repository definition url

Add repository definition url

Once you have it, you should get a new addin available:

new addin

new addin

Select it and install.

Let’s try a web project with Nancy!

First, create a new empty ASP.NET web project:

New empty asp.net project

New empty asp.net project

Before playing with Nuget, Add a web.config file because it is not provided by default with this project template:

add web.config

add web.config on monodevelop

Then you should try to run it but obviously you’ll get nothing.

Now, right click on references:

References with Nuget

References with Nuget

So cool! We have now Nuget resources just here! Select Manage Nuget Packages.

You’ll have a box just as the one you use to use under Visual Studio (if you are in click-click mode instead of the Package manager console which is a Powershell host of course…):

Nuget box

Nuget box

Just start with typing ‘Nancy.host’, select ‘Nancy.Hosting.Aspnet’ then Add. You can see in the messages, that it handles correctly the download of Nancy.dll too.

Then add a new class to your project with your HomeModule with a simple test route:

using System;
using Nancy;

namespace Demo
{
	public class HomeModule : NancyModule
	{
		public HomeModule ()
		{
			Get ["/(.*)"] = _ => "Yes it works!";
		}
	}
}

That’s supposed to be enough for now. Build and run. Guess what? it doesn’t work.

Why? Remember that nuget installation features under Visual Studio are full of Powershell and transforming files are part of it. So, remember that when you install something with Monodevelop Nuget you don’t have the transforms like web.config updates!

UPDATE: Thanks to author Matt Ward that points an explication for that in the comments: “PowerShell is not actually needed for the web.config transform to be applied. It is not currently working in the MonoDevelop NuGet addin due to a bug. The addin is not detecting the project is a web project and ignoring the transform. Transforms for app.config files are currently working.”

Then open your web.config file and update  it  to setup Nancy handler:

<?xml version="1.0"?>
<!--
Web.config file for Demo.
The settings that can be used in this file are documented at
http://www.mono-project.com/Config_system.web and

http://msdn2.microsoft.com/en-us/library/b5ysx397.aspx

-->
<configuration>
<system.web>
<compilation defaultLanguage="C#" debug="true" targetFramework="4.0">
<assemblies>
</assemblies>
</compilation>
<customErrors mode="RemoteOnly">
</customErrors>
<authentication mode="None">
</authentication>
<authorization>
<allow users="*" />
</authorization>
<httpHandlers>
<add verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*"/>
</httpHandlers>
<trace enabled="false" localOnly="true" pageOutput="false" requestLimit="10" traceMode="SortByTime" />
<sessionState mode="InProc" cookieless="false" timeout="20" />
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
<pages>
</pages>
</system.web>
<system.webServer> <modules runAllManagedModulesForAllRequests="true"/> <validation validateIntegratedModeConfiguration="false"/> <handlers> <add name="Nancy" verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*"/> </handlers> </system.webServer>
</configuration>

Re-run it and now it works!

How easy to do .Net web!

Just to finish with that and show you how cool it is, relaunch Nuget manager and Add also Nancy.ViewEngines.Razor, jQuery and Twitter bootstrap.

Create Folders Views/Home and add a new html file called “Index.cshtml”

If you’re like me and never remember the right syntax for bootstrapping things, keep a visible bookmark to Twitter bootstrap page and take this one as exemple:

http://twitter.github.com/bootstrap/examples/marketing-narrow.html

Copy paste the source on your file as exemple, then update it to fit your config, paths and update the main block (just extracts with updated things ):

...
<title>Nuget on MonoDevelop</title>
...
<link href="/Content/bootstrap.css" rel="stylesheet">
...
<link href="/Content/bootstrap-responsive.css" rel="stylesheet">
...
<div class="jumbotron">
<h1>Nuget on MonoDevelop!</h1>
<p class="lead">
Get started with .Net Web dev on Mac with Monodevelop, Nuget, Nancy and Bootstrap!
</p>
<p>Generated at @Model.Generated by @Model.Author
<a class="btn btn-large btn-success" href="#">It's alive</a>
</div>

Then update your home module to return the Razor view and with a small model class to test passing things to the view

public class HomeModule : NancyModule
	{
		public HomeModule ()
		{
		Get ["/(.*)"] = _ =>
                   View ["Index", new HomeInfo (
                          DateTime.Now, "Rui Carvalho")];
		}
	}

	public class HomeInfo
	{
		public DateTime Generated { get; private set; }
		public string Author { get; private set; }

		public HomeInfo (DateTime generated, string author)
		{
			Generated = generated;
			Author = author;
		}
	}

Run it and enjoy more happy dappy path of web development with Nancy, Nuget and Mono on your Mac

Nancy with twitter bootstrap

Nancy with twitter bootstrap

cheers!

 

Posted in Articles Tagged with: , , , ,

WebNet12 Conference – Feedback, slides, photos

Last week-end, I was part of the Web.Net conference in Milano. It was the first Edition of the event and I really feel it was a success!

Big thanks to Simone Chiaretta(@simonech) and Ugo Lattanzi(@imperugo) for starting all this, for the big organisation work and to be such kind people ;-)

I really hope to help them next time and hope that we can manage to create the event in Paris next year.

For this edition, I did a presentation about “Simplicity”, why it matters and how to achieve it with tiny frameworks and tools.

You can find the slides just below.

I’ll publish the sources for all my samples as soon as I’ll organise them better and clean a little bit. You’ll find them here:

https://github.com/rhwy/SimplicityWeb.Net

***

After the conference, this means sunday, I finally took some time to enjoy the city. There is a lot of things to see in Milano, but you can find most of them in the old city center. In that way, I went for a walk from the hotel to these hotests point for about 4 hours.

You can find below some pics, really nice time ;-)

Another thing that was nice in the trip was the transportation. Nowadays, we use to take plane as a default solution, but sometimes train should be a really nice alternative! It was direct, starting from Paris, nearest station from house, then a very nice and comfortable trip of 7 hours while you can work, have lunch, then you arrive in the near center of Milano. That was really a good choice for me, and also a real joy of crossing the Alps by train.

Again, it was very nice to see all this people, a special mention for nice discussions with Chris Massey (@camassey), Robert Mühsig (@robert0muehsig), Kris (@Kvdm) and so much more!

Hope to see Milan again next year and hope to see you all for the 2013 Paris Edition ;-)

cheers!

Posted in News Tagged with: , , , , ,

SOLID – A small refactory sequence on ConfArt

I am working on a small library to help working with some dynamic stuff, but the target is mainly to use dynamics to simplify configuration and exchange data when types are not needed. This started as a demo project, but as I used some differents classes and techniques in different projects I tought it should be interesting to share all that in a full functional library and, at least it should be interesting help to learn a few things.

By the way, this is not the target of this first post about it, it’s only about refactoring. As this starts in a demo mode, most of the code was not really well constructed, even if it is almost well tested and most parts were done in TDD mode.

Let’s analyse a method I have:

private  void InitializeSetter()
{
    var expBoxy = _setterExpression.Body;

    if (expBoxy.NodeType == ExpressionType.Convert)
    {
        var convertExp = (UnaryExpression)expBoxy;
        var operand = (MemberExpression)convertExp.Operand;

        if (operand.Member is PropertyInfo)
        {
            PropertyInfo pi = typeof(T).GetProperty(operand.Member.Name);
            _setter = pi.GetValueSetter<T>();
        }

    }
    else if (expBoxy.NodeType == ExpressionType.MemberAccess)
    {
        var operand = (MemberExpression)expBoxy;

        if (operand.Member is PropertyInfo)
        {
            PropertyInfo pi = typeof(T).GetProperty(operand.Member.Name);
            _setter = pi.GetValueSetter<T>();
        }

    }
    else
    {
        throw new InvalidOperationException("Expression is not valid to set a property, should be something like x=>x.Name");
    }
}

This is not too long, but when I get back reviewing the code, it is almost complicated. And why it is complicated because this ends up with too much responsabilities and this does not use the full power of open close principles…

To complete this method, this is also the properties of this class and the constructor:

private Action<T, object> _setter;
private readonly Expression<Func<T, object>> _setterExpression;
private readonly ConfigurationMappingsBase<T> _source;

public Action<string, Action<T, object>> UpdateSource { private get; set; }

public PropertySetterExpression(ConfigurationMappingsBase<T> source, Expression<Func<T, object>> setterExpression)
{
    _source = source;
    _setterExpression = setterExpression;
    InitializeSetter();
}

Ok, Let’s analyse the code now.

I get all my properties from the constructor, that’s the good design point, but just in the constructor It begins to fail. It relays too much on ‘Void’ methods to set magicaly stuff and that matters!

As, the goal of InitializeSetter is to initialize the member _setter with some content of the member _setterExpression Let’s do it in another way:

public PropertySetterExpression(ConfigurationMappingsBase<T> source, Expression<Func<T, object>> setterExpression)
{
    _source = source;
    _setterExpression = setterExpression;
    _setter = InitializeSetter(_setterExpression);
}

private Action<T, object> InitializeSetter(Expression<Func<T, object>> expression)
{
    var expBoxy = _setterExpression.Body;
    return null; //temp hack
}

Ok, it compiles again and I have no more magical void method stuff, and I should test now this method (But I don’t want to, as I consider it as an internal mechanism and I made it private, but that’s another debate ;-)

But, what do I in the method? I get the Body – which is of type Expression and I work with it. Shouldn’t it be better to pass it directly and avoid a new var?

public PropertySetterExpression(ConfigurationMappingsBase<T> source, Expression<Func<T, object>> setterExpression)
{
    _source = source;
    _setterExpression = setterExpression;
    _setter = InitializeSetter(_setterExpression.Body);
}

private Action<T, object> InitializeSetter(Expression expression)
{
    if (expression.NodeType == ExpressionType.Convert)
    {
        var convertExp = (UnaryExpression)expression;
    }
    else if (expression.NodeType == ExpressionType.MemberAccess)
    {
        var operand = (MemberExpression)expression;
    }
    else
    {
        throw new InvalidOperationException("Expression");
    }
}

Now, What did I do with this expression? I rely on my procedural methods deeply printed in my reptilian cortex to make an if-then-else construct to do some work based on the type information of the expression and then cast it to the right type…That’s not too much object oriented no? And more, it violates the OCP…

Let’s rewrite it in an object way:

public PropertySetterExpression(ConfigurationMappingsBase<T> source, Expression<Func<T, object>> setterExpression)
{
    _source = source;
    _setterExpression = setterExpression;
    _setter = InitializeSetter(_setterExpression.Body);
}

private Action<T, object> InitializeSetter(UnaryExpression expression)
{
    var operand = (MemberExpression)expression.Operand;

    if (operand.Member is PropertyInfo)
    {
        var pi = typeof(T).GetProperty(operand.Member.Name);
        return pi.GetValueSetter<T>();
    }
    return null;
}

private Action<T, object> InitializeSetter(MemberExpression expression)
{
    if (expression.Member is PropertyInfo)
    {
        PropertyInfo pi = typeof(T).GetProperty(expression.Member.Name);
        _setter = pi.GetValueSetter<T>();
    }
    return null;
}

private Action<T, object> InitializeSetter(Expression expression)
{
    throw new InvalidOperationException("Expression");
}

Well, much better. But, I focuses me much more on what the code do right now, this can be simplified again:

The code of the unary expression, gets the member and do the same code that the member expression one, and as I had to return a value, I had to set to null, this means that my original code should failed If I don’t fall in the right path (or at least my _setter value should be null). Let’s do a last refactor:

public PropertySetterExpression(ConfigurationMappingsBase<T> source, Expression<Func<T, object>> setterExpression)
{
    _source = source;
    _setterExpression = setterExpression;
    _setter = InitializeSetter(_setterExpression.Body);
}

private Action<T, object> InitializeSetter(UnaryExpression expression)
{
    return InitializeSetter(expression.Operand);
}

private Action<T, object> InitializeSetter(MemberExpression expression)
{
    if (expression.Member is PropertyInfo)
    {
        var pi = typeof(T).GetProperty(expression.Member.Name);
        return pi.GetValueSetter<T>();
    }
    return InitializeSetter(expression);
}

private Action<T, object> InitializeSetter(Expression expression)
{
    throw new InvalidOperationException("Expression");
}

I am now quite happy with that, and that’s all for the theorical part ;-).

But wait…My tests fail now!

Why do they fail? Because of two things:

  • Expressions don’t rely on an interface but on public abstract class Expression : this means that our _setterExpression.Body will always fall on the last generic method.
  • and because the type PropertyExpression which I need implicitely here is defined as internal class PropertyExpression : MemberExpression

I don’t want to criticize the design of the Linq Expressions namespace, because I can imagine this design has it’s own very good reasons to be like that. But in my simple condition of developper and user of their framework I don’t agree with the way I have to work with it.

That’s why in this real life scenario, I finally end up with this code in order to make tests pass:

public PropertySetterExpression(ConfigurationMappingsBase<T> source, Expression<Func<T, object>> setterExpression)
{
    _source = source;
    _setterExpression = setterExpression;
    _setter = InitializeSetter(_setterExpression.Body);
}

private Action<T, object> InitializeSetter(UnaryExpression expression)
{
    return InitializeSetter(expression.Operand as MemberExpression);
}

private Action<T, object> InitializeSetter(MemberExpression expression)
{
    if (expression.Member is PropertyInfo)
    {
        var pi = typeof(T).GetProperty(expression.Member.Name);
        return pi.GetValueSetter<T>();
    }
    throw new InvalidOperationException("Expression");
}

private Action<T, object> InitializeSetter(Expression expression)
{
    if (expression.NodeType == ExpressionType.Convert)
        return InitializeSetter((UnaryExpression) expression);
    if (expression.NodeType == ExpressionType.MemberAccess)
        return InitializeSetter((MemberExpression) expression);
    throw new InvalidOperationException("Expression");
}

Still better than my very first iteration but not as good as I want.

Any thoughts?

Posted in Articles Tagged with: , , ,

About Asp.Net Web Stack

A few days ago, Microsoft released its ASP.NET Web Stack (of Love as called by Hanselman) to OSS.

Good news? Bad news?

I don’t know… I am still not convinced by the capacity of Microsoft to produce with a real OSS community a really pen source project. This time, and it’s quite new for them, they claims to accept pull requests from community.

I am not sure that it will make a big difference with the past, but I may be wrong (and I hope so!)

Just before continuing, I am not here to say that all this asp.net web stack and oss stories are a mess! I am still a big fan of the stack and I am only writing about some thoughts and experiments.

So, I git clone!

Obviously we can spend hours discussing philosophy about Microsoft misconception on open source, but to begin, the better way is to try it.

I don’t know if it is on purpose to be on the “OSS Move”, but CodePlex support since a few time Git. It’s another good news!

Oh wait…Perhaps we missed something?

  1. If you’re true open source now, why not choosing a neutral platform –like GitHub – instead of a Microsoft source showcase without any soul like Codeplex?
  2. Codeplex supporting git is good, but,  after svn or mercurial some years ago because it was the trend of the moment, doesn’t it undermines the solutions based on TFS a little bit? Or finally they are now convinced that TFS is not good for distributed open source project? Must probably, it is to let the platform die silently and empower in the future a platform based on the Tfs Cloud solution – which can be most intelligent solution.

 

So I can clone without installing the 300Mo iso of TFS explorer and that’s nice Clignement d'œil

git clone https://git01.codeplex.com/aspnetwebstack.git

 

That’s pretty quick (due to git compression, yeah!) and I can navigate the sources now.

Build It

I don’t know if everyone is more serious than me but one thing I always do after getting some sources, is to type “build” in the shell and see what happened, don’t you? It’s just to see if it can work immediately on a simple way. Let’s call it a “Download and Run” pattern.

I was a little bit disappointed with all screaming in red…And I forgot to say that, like most people, I explicitly forgot to read the recommendations and “README” you should read after downloading something.

So that’s it. It’s not clear on the project home page, but if you go to Documentation, you have most of the solutions to your problems:

  1. Download SkipStrongNames, and unzip it. From an elevated command prompt, run “skipstrongnames -e" to allow you to run unit tests against the delay-signed binaries.
  2. Don’t try to open directly the Runtime.sln  and “enable nuget restore” before launching a first build command. I will run a mess when you try to launch build.cmd later…

 

Additional Tip: You may need to manually add a specific Microsoft nuget development feed for some packages not yet officially distributed: In Visual Studio, open Tools/Library Package Manager/Settings Then in Packages Sources add new with this url:

http://www.myget.org/F/f05dce941ae4485090b04586209c8b08/

 

So, after applying SkipStrongNames (did I already mention that I hate StrongNames?), just restore your nuget packages:

./build.cmd RestorePackages

 

Then try to build it (without restore).

I said hope, because depending on your current configuration and state it may work or not:

  • Having .Net 4.5 and/or aspnet mvc4 beta installed may cause troubles
  • Having some data components may cause troubles (Maybe Sql 2012 is one…)

 

I finally get it working after removing .Net 4.5/mvc4 and removing the Microsoft.Web.Http.Data.Test project…

But, after uninstalling these components, msbuild 4 disappear too and mvc3 template projects just not work anymore.

 

A few words more

It’s is interesting to have the real sources of all the web stack but use it with caution.

It’s usually hard to compose with some beta versions from Microsoft that are not compatible with other tools but it’s also the case with these sources.

It’s far to be an independent project, and I can understand why it’s not, but it’s quite difficult to exploit and contribute to sources with these inter-dependencies.

I just hope that it will open some minds and bring real innovation. In the other hand, I hope it will help people usually using basically Microsoft products to have a new point of view on new ways of working.

Posted in Articles Tagged with: ,

Entity Framework Code First Helpers–Efmaps

I am always astonished with the way Microsoft and some people communicate around some good products they produce…

Code first, is for me the first evolution of Entity Framework that is really usable and nice to use. There is still some lacks and pain points, but globally it’s far better than before. You can now have clean code and simple configuration. Don’t look too much at non-standard scenarios, but on the other side you can do a majority of things simply. This combined with a really cool linq engine, you have a great and efficient tool that fits most usages.

But finally, there isn’t not so much buzz around all of this, isn’t it? Most people blog about new features during the ctps and not so much after. There is good posts about how to handle relations or start working with it.

Mainly two things bothered me:

  • the lack of good explanations on how to resolve current limitations (can’t define default values for the sql side for exemple)
  • the mappings are ALWAYS expressed inside the ‘OnModelCreating’ of the user DbContext. Do you really like 100+ lines tricky configuration and untestable methods?

That was the starting point of this project. This is an humble project to only help some tricky usage issues of the current version of Entity framework code first, it doesn’t change in any way how it works.

 

This is a small vision based on my experience, you should read the following introduction as a sample usage and how should be the way we use EF code first ;).

You will find the sources of the project on my github here:

https://github.com/rhwy/efmap

Nuget pack with this library will be available soon.

 

Let’s present the project

EF map provides easy additional helpers to work with Entity Framework Code First and make it more valuable. It allows you to be focused on configuration and mapping in a clean way.

Functionalities:

  • Helps defining clean mappings with a single class mapping per entity and auto load them
  • Helps defining database initialization with additional sql commands
  • Helps defining database initialization through default model data
  • Helps defining an identity column
  • Add validation helpers (for data anotations)
  • more to come …

it helps you keeping focused with your data

Sample usage

 

Build your domain

Let’s define a simple idea suggestion system, this how our domain looks like:

public class Idea
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Detail { get; set; }
    public DateTime Published { get; set; }
    public string Author { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
    public virtual Vote Votes { get; set; }

    public Idea()
    {
        Comments = new HashSet<Comment>();
        Votes = new Vote();
        Published = DateTime.Now;
    }
}

public class Comment
{
    public int Id { get; set; }
    public string Content { get; set; }
    public DateTime Published { get; set; }
    public string Author { get; set; }

    public Comment()
    {
        Published = DateTime.Now;
    }
}

public class Vote
{
    public int VoteUp { get; set; }
    public int VoteDown { get; set; }
}
 

Define your persistance

You have defined your domain in clean way until here, let’s define now from your infrastructure perspective how you persist it with Entity Framework code first:

public class IdeaMap : EntityTypeConfiguration<Idea>
{
    public IdeaMap()
        : base()
    {
        this.WithRequiredGeneratedIdentity(p => p.Id);
        Property(p => p.Title)
            .IsRequired()
            .HasMaxLength(100);
        Property(p=>p.Votes.VoteUp)
            .HasColumnType("int")
            .HasColumnName("VoteUp");
        Property(p => p.Votes.VoteDown)
            .HasColumnType("int")
            .HasColumnName("VoteDown");
        ToTable("Ideas");
    }
}

public class CommentMap : EntityTypeConfiguration<Comment>
{
    public CommentMap() : base()
    {
        this.WithRequiredGeneratedIdentity(p => p.Id);
    }
} 
 

Add some default data

There is usually two ways to complete the database initialisation process started by entity framework code first engine. These options are complementary:

You can add some sql in order to add some specific commands that can not currently be generated automaticaly by Entity Framework engine during the initialization process : we call these DbInitializers. For exemple, let’s define that we want to ensure at database level that the title of our ideas is unique to avoid exact duplicates

public class IdeaDbInitializer : DbInitializer
{
    public IdeaDbInitializer()
    {
        //add constraint to avoid exact duplicate ideas
        this.AddCommand(
            "IF NOT ISNULL(OBJECT_ID('Ideas','U'),0)=0 ALTER TABLE Ideas ADD CONSTRAINT UN_Ideass_Title UNIQUE(Title)"
        );
    }
}
 
  • You can add some entity objects during the database initialisation to be used as default or starting values by your application just like any other data : we call these EntityInitializers For exemple, let’s add a default idea with a comment to show users after the installation of our system an usage exemple:

    public class IdeaEntityInitializer : EntityInitializer<IdeaContext>
    {
        public IdeaEntityInitializer()
        {
            this.AddCommand(
                "add presentation idea",
                (context) =>
                {
                    Idea idea = new Idea();
                    idea.Title = "what about creating an ideas site?";
                    idea.Author = "admin";
                    idea.Comments.Add(new Comment { Author = "admin", Content = "vote and add your comments about the idea" });
                    idea.Votes.VoteUp++;
    
                    context.Ideas.Add(idea);
                });
        }
    }
  •  
 
 
 
 
 

Finish defining your context

You just have to define now your context with your DbSets. The interesting option now is the auto load. Define your sets available to your context, then, when defining autoload, it will search for each set of your context for a mapping. That’s a cleaner way than handling everything in the “onModelcreating” method don’t you think?

public class IdeaContext : DbContext
    {
        public DbSet<Comment> Comments { get; set; }
        public DbSet<Idea> Ideas { get; set; }

        public IdeaContext()
            : base("IdeasDb")
        {}

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            this.AutoLoadForThisContext(modelBuilder);
            base.OnModelCreating(modelBuilder);
        }
    } 

create your app

You have now all your need, here is now how you link and use this in your application layer. Let’s configure it, initialize it, and get print default values in a sample console app:

static void Main(string[] args)
        {
            //define the data class to use to initialize database through entity
        EntityMapHelper.SetEntityInitializer<IdeaContext>(new IdeaEntityInitializer());

        //define the data class to use to add custom sql commands at 
        EntityMapHelper.SetDbInitializer<IdeaContext>(new IdeaDbInitializer());

        //define the pattern structure to initialize database
        EntityMapHelper.Initialize<IdeaContext>().With<DropCreateAlways<IdeaContext>>();

        //that's all, you can now use it and directly get the default data as in the exemple
        using (IdeaContext context = new IdeaContext())
        {
            Console.WriteLine("default ideas : ");
            context.Ideas.ToList().ForEach(
                    idea => Console.WriteLine("- {0} ({1} comments)", idea.Title, idea.Comments.Count)
                );
            Console.WriteLine("Press enter so print sql initialization script");
            Console.ReadLine();
            Console.Clear();

            string sql = context.GetSqlCreationScript();
            Console.WriteLine(sql);

            Console.WriteLine("Press enter so print generated Edmx script");
            Console.ReadLine();
            Console.Clear();

            string edmx = context.GetGeneratedEdmx();
            Console.WriteLine(edmx);
        }

 

Foreword

This is not supposed to be revolutionary, but these should help you working better with your EF code first projects by removing some plumbing practices and kept more focused on your business. This is aim to evolve with time, so share your thoughts and contribute with your additions.

Hope it helps ;-)

Posted in Projects Tagged with: , , ,

What’s up 2012?

Hi there, we are still in January and it is still time to wish you an Happy new Year!

With all the mess around, what should we want for this new year? Still here in 2013 should be a good start just in order to say “cool, I survive to my 25th apocalyptic end or the world event…”.

2011, real life

Before looking forward, let’s have a word about what append in 2011.

People think what they want, but I think that 2011 was a great year. I suppose that worldwide changes felt differently depending on your country, but globally, revolutions are key word this past year. It’s great. It’s a sign. Even in countries where we thought liberty never come again, it came, where dictatorship is the only leading way, we are building democracies and so on…

The main dictatorship that should be hard to remove is the global finance market. Maybe 2012 will see the first wide attempts of introducing a Tobin tax? But it should also get some country bankruptcy which may be catastrophic…

2011, tech life

I was very happy with this tech year. Nothing revolutionary. But a lot of small improvements that changes life or enhance it.

I tried to promote Html5 family in a .Net world since 2 years ago and I was mainly flowed by everyone. Most Web designers still thought that Flash was the only way and most .Net web developers thought that Silverlight would beat Flash in RIA world domination…It seems, that I was right and both are today in an hard path.

People should pay attention to the mass effect. Even if excellent solutions exists in some domain, and you are convinced that this technology is far better than any others, follow with attention the trends. The reference technology will always be the one used by most people! Do you thought that php is much better than any other web technology? Far away! It is certainly one of the most ugly I ever saw, but there it starts its career because it’s “easy” to start and there was lots of web hosts providing web hosting for free with php. Then, people developed useful software on it and that’s the glue! Again, do you think that as a senior .Net developer I am happy to blog with WordPress instead of a .Net blog engine? Obviously not, but it’s far the best blogging tool I used!

For RIA, it’s the same, today flash or silverlight are better than Html5 on most points if you want to develop a tricky complex designed app for the web (ie : a game). But who really cares today? Even partially supported, Html5 responds yet today to the needs of 95% of the needs where flash/silverlight were used before (Ads, cool designed interfaces…). If don’t understand that when Apple digg a tomb for flash, you probably missed something ;-)…

 

Another cool thing was Node.js. You have to understand what is behind it, it’s not “only” a buzz machinery…

If you pay some attention to what people want in 2012 for web apps, we are far way from what people want 2 years ago. Web 2.0, ajax, ok cool, these notions are heavily integrated now. People want today responsive designs, people want real time, simplicity. That’s simple, people want simple apps doing things quickly in a natural way…

And again, like php story, node.js is easy to start, even for the designer not developer. Node.js was the first large audience tool to allow easy build of real time applications! Cross this with the rebirth of javascript these last years and you have a simple and integrated platform to develop really cool apps! And more, Node.js is naturally driven by Single responsibility pattern applied to frameworks. In Node, most frameworks do one thing in a simple way. Then you compose. Quickly. You don’t have to pay for an expensive learning ticket, you don’t have to load huge libraries while really using a small part. Take care of these principles and take care of  effervescence of a community, you will learn a lot of it.

 

On the other side, I was disappointed by Windows 8.

It looks great, it smells great. But it should be only a façade…

I am disappointed with the mix of Windows forms and Metro apps in the same environment. Relatively to user experience, every time you try to propose 2 completely different approaches to complain to most people, you fail.

But I am most disappointed with their Html5 “sounds only like a buzzword” approach natively on the desktop. Have you see the code of a html5/javascript Metro project? it’s scary, I don’t know what’s the advantage coding like this in javascript. Other platform web developers will never develop applications using these native Windows javascript framework! And for .Net developpers, why confusing them with code like this? So, for whom are these javascript Metro projects? Isn’t it only to say we also do Html5, and do it better because it’s native on the desktop? Don’t you remember the fail of the Active Desktop?

This is a great sign to understand why big companies, older in the market, have great difficulties to follow the trends without deeply taking in account the needs.

 

2012, what’s next?

I hope to have an even better year!

I will continue to improve myself daily in the technologies I believe in. I still keep my focus on .Net web architecture, performance and user experience on ASP.NET MVC. I promise to use more and more parts of Html5. I hope to really have time to start the projects around micro data with my company.

I will continue to follow Sql Server activities and Sql Server 2012 will give some really good improvements. But on the other side, I work more and more with NoSql data persistence. It is the key of a modern architecture. I hope people will massively understand that not all the data have the same lifecycle, the same needs, and that for each one, there is a preferred data repository.

But, the point on which I will work harder is to improve my software craftsmanship abilities, to improve the way I work everyday, to exchange more with people and to learn and share more with people. I will try also to share more code and discuss less…

And the what’s the best? We’ll build a new .Net conference in Paris and I hope that everyone will enjoy it just like I am exited in preparing it! Soon, we’ll make some announces.

 

 

So, enjoy this Year!

Posted in News Tagged with: , , , ,

Hi there!

We are happy to start this new community blog, so as usual:

Hello world

 

This is our first hello world to .Net community through this platform but for most of us, we write since a long time. We want to merge and share some of our thoughts, principles and projects  in this common place.

But that’s not all, before starting we want to give you the concepts that drives our writings. So, let’s introduce the several Why’s of this site.

  • We are mainly .Net developpers and we love C#, the framwork and most of their architecture and way to work.
  • But we are not attached to one company and their way of thinking
  • We are true open source believers and we think that OSS projects on the .Net platform are great for everyone, inclusively Microsoft
  • We love good practices and we are strongly attached to adding value to software
  • Our business is still young, and we think that there will be a lot of evolutions, so, keeping minds opened is so important as our knowledge
  • Factories, processes and automatisation are great but we give more value to craftsmanship.

Read, share, comment!

Posted in News Tagged with: