.Net framework versions and dll hell

With .net version numbers increasing and increasing I recently encountered something which reminded me of dllhell. Which the .net framework promised to end. The nice part is that it already shows up at build time. Not at run time, leading to disappointed customers. Framework versions can be mixed in one solution. Up to the moment one assembly references another assembly built against a higher version. At this moment the VS build process starts to lose track.

The catch is that it’s not always clear you’re mixing framework versions in a solution. Adding a new project will default against the newest framework version. Which is not constant over a solution’s life time. The result can be quite strange. I managed to get away with a circular reference which was not seen because one project was using a version of the other built against an older framework version. And was thus considered a different assembly. Up to the moment I checked the framework version of all projects.

The only good way to solve this descend into hell would be having all projects in the solution on one version. In a big solution with a lot of projects this can be quite tedious. I would love to be able to set the version on the solution level. Or else to have a nice ‘refactoring’ tool to the work for me. R# are you listening ?

 

Posted in Uncategorized | 7 Comments

@model and beyond

In my previous post I had been fiddling with the html helper used in Razor views. Since then our custom html-extensions have been doing great things for our project. To mention some:

  1. Standardizing the look and feel. It is far more consistent and maintainable to set attributes (including a css class) and event handlers in one centralized place.
  2. Simplify the script. Often a part of the logic the script will follow is already known server side. Instead of writing everything out in javascript rendering the intended statements leads to a leaner client. There is an example in my previous post on building post-data.
  3. Decoupling the libraries used. At the moment we are using the Telerik MVC suite. In my previous post I described how our html helpers build standardized Telerik components for our views. In the not to far future we want to switch to the Telerik Kendo suite. Having wrapped up the library dependency in our Html helper will make this switch a lot easier to implement.

What has evolved is the way we work with the model. In MVC the implementation of the controller and the view is clear. When it comes to the implementation of the model there are almost as many different styles of implementation as there are programmers. In general the model can bring any data to the view you can imagine. Not only the source of the data varies, from plain sql to a C# property, also the use of the model’s data varies. It can be a customers name from the database. Or it can be the string representation of some html attribute needed for a fancy picker. Here data and presentation start to get mixed up. Our extensions needed information for the Html-Id. The original Html helper had a custom constructor to get that specific data from the model into the helper. Which required to create our own htmlhelper when starting the view and use that one instead of the standard @html. As seen in the eposHtml in the previous story. It would be cleaner if our extension methods could be satisfied with the default html helper. It would also be cleaner to keep a better separation between ‘real’ data and presentation.

The model is available in every HtmlHelper extension method.

public static PostDataBuilder<TModel> PostData<TModel>(this HtmlHelper<TModel> htmlHelper)

{

    return new PostDataBuilder<TModel>(Id(htmlHelper.ViewData.Model));

}

 

It’s a property of the ViewData.

In our case we needed something to give the control an unique Id. The Id method builds that Id. Previously we passed the Id-base in the constructor, which lead to the custom helper. A far more elegant solution is using a very basic IOC-DI pattern. As implemented By the Id method

private static string Id(object model)

{

    var complex = model as IProvideCompositeId;

    if (complex != null)

        return complex.CompositeId;

    var simple = model as IProvideId;

    return simple == null ? “” :  simple.Id < 0  ? String.Format(“N{0}”, Math.Abs(simple.Id)) : simple.Id.ToString();

}

 

The method queries the model first for the IProvideCompositeId interface, in case the model does not implement that it is queried for the IprovideId interface. Resulting in a string which can be safely used in an HtmlId. (A negative number would lead to a ‘–’ in the string, which is not accepted in an Html Id).

These interfaces are very straightforward

public interface IProvideCompositeId

{

    string CompositeId { get; }

}

 

public interface IProvideId

{

    int Id { get; }

}

 

In case the model is going to be used in a view requiring unique Id’s the model has to implement one of these interfaces.

public class FactuurDefinitie : IProvideCompositeId

{

    public readonly int IdTraject;

    public readonly int UZOVI;

    public readonly bool Verzekerd;

 

    public FactuurDefinitie(int idTraject, int uzovi, bool verzekerd)

    {

        // The usual stuff

    }

 

    public string CompositeId

    {

        get { return String.Format(“{0}{1}{2}”, IdTraject, UZOVI, Verzekerd); }

    }

}

 

Working this way:

  • We can use our custom html extensions in the default html helper
  • Specific data from the model is available inside our extensions
  • The model and the view do not get entangled

The code is no big deal. I know. But the model is something whose horizons are still not in sight.

Posted in Uncategorized | 1 Comment

@Html and beyond

I like the way MVC builds the content of my web-apps. I write plain HTML, and the @Html helper object will build all Html controls needed for in and output of the dynamic data. The nice thing is that the HtmlHelper object is strongly typed, all properties of the view’s model are available as lambda expressions.

<tr>

    <td>

        @Html.LabelFor(m => m.AanmeldingsKlacht)

    </td>

    <td>

        @Html.TextBoxFor(m => m.AanmeldingsKlacht)

    </td>

</tr>

 

Nice clean code.

Things are getting harder when you need more than the standards the HtmlHelper class gives you.

Extending the HtmlHelper

The way to extend the HtmlHelper is by using extension methods. An extension method extends an existing class without inheriting from it like in “classical” oop. Which extension methods are added to an object is ruled by the namespaces used in the code using the extended class.

The methods of the HtmlHelper class should return strings typed as MvcHtmlStrings. A standard string would be Html encoded by the view engine. An MvcHtmlString is literealy rendered into the view. The way to go is to extend the HtmlHelper class with methods which will build plain Html.

As an example of this is Purple, a very simple extension method which does demonstrate the principles and possibilities.

public static MvcHtmlString Purple<TModel, TProperty>(

this HtmlHelper<TModel> htmlHelper,

Expression<Func<TModel, TProperty>> expression)

{

    return new MvcHtmlString(

string.Format(“<span style=’background-color: blueviolet’>{0}</span>”,

                htmlHelper.EditorFor(expression)));

}

 

Note the following points

  • The return type is MvcHtmlString, as discussed above
  • The method is generic. <TModel> is the type of the model of the view where the method is used. <TProperty> is the type of the model’s property.
  • The method is static. The method’s class also has to be static
  • The first parameter this HtmHelper<TModel> hooks the the method into the HtmlHelper object
  • The second parameter expression describes the lambda of the property
  • The htmlHelper object itself, with its rich collection  of methods and properties is available. Here it builds an EditorFor the expression.
  • The result is embedded in a plain Html span with a  “nice”  background

Now when the view uses the class containing this method I can do this:

<tr>

    <td>

        @Html.LabelFor(m => m.HulpvraagInitiatief)

    </td>

    <td>

        @Html.Purple(m => m.HulpvraagInitiatief)

    </td>

</tr>

 

And now the textbox, or whatever other control is built, has a nice purple background. Of course this is not be the way to achieve that effect. But I do hope it clarifies the way the htmlhelper works.

A custom HtmlHelper

We now have a way to extend the HtmlHelper with new methods. These methods can have custom parameters. But what if I needed a custom HtmlHelper with some extra properties which are needed in many instances of many methods ? As a casus I will explore fiddling with the Html Id’s of the controls built.

In the default behavior all EditorFor controls built get an id which is equal to the name of the property. Which is great, when posting back the form TryUpdateModel will bind all posted values to an instance of the model. All of this goes horribly wrong when several instances of a view are rendered on one and the same page. Not just contents gets jumbled up, scripts will go haywire as well.

It is possible to give each control an unique Id by setting it’s HtmlAttributes. Some, like the Telerik suite, even have a method to assign a name. Assigning these Id’s is a hassle and he controller receiving the postdata will also have a lot of work to do to extract all posted values.

Here’s the plan:

  • Build an extended HtmlHelper which takes an Id to uniquify names
  • Give this class EditorFor methods which build controls with an unique name
  • Let the class create the postdata

The class will be generic, typed to the Model

public class MyHtmlbuilder<TModel>

{

    private readonly int _id;

    private readonly HtmlHelper<TModel> _htmlHelper;

 

    public MyHtmlbuilder(int id, HtmlHelper<TModel> htmlHelper)

    {

        _id = id;

        _htmlHelper = htmlHelper;

    }

}

 

In the constructor it receives the Id needed for unique names and the original HtmlHelper object.

To hook into the existing helper and model the builder is again created from an extension method.

 

public static MyHtmlbuilder<TModel> MyHtml<TModel>(this HtmlHelper<TModel> htmlHelper, int id)

{

    return new MyHtmlbuilder<TModel>(id, htmlHelper);

}

 

Having my helper in place I can give it methods to build Html. To create the unique names I need yet another extension method. This one is on the lambda expression to find the property name using reflection.

 

private static string NameBuilder<TModel, TProperty>(this Expression<Func<TModel, TProperty>> expression, int id)

{

    var me = expression.Body as MemberExpression;

    if (me == null)

    {

        throw new ArgumentException(“You must pass a lambda of the form: ‘(object) => object.Property’”);

    }

    return string.Format(“{0}{1}”, me.Member.Name, id);

}

 

The Html building methods are quite simple. Building a dropdownlist for a property:

 

public MvcHtmlString DropDownListFor<TProperty>(Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectListItems)

{

    var id = expression.NameBuilder(_id);

    return _htmlHelper.DropDownListFor(expression,

selectListItems,

new { id }) ;

}

The namebuilder method builds an unique name. The original htmlhelper does the real work. Using my name in the Html-attributes.

 

I can also build third party controls here. Here’s a Telerik datepicker:

 

public MvcHtmlString DatePickerFor(Expression<Func<TModel, DateTime>> expression)

{

    return

        new MvcHtmlString(_htmlHelper.Telerik()

                    .DatePickerFor(expression)

                    .OpenOnFocus(true)

                    .Name(expression.NameBuilder(_id)).ToHtmlString());

}

 

Note that Telerik has it’s own method for setting the name. It’s controls are extremely picky over unique names.

I leave it up to you to add the builder methods you need. Working with this kind of code is somewhat puzzling in the beginning, all the this’s and generics take some time to sink in. But when working with it it soon falls into place. It made me even more delighted over the powers of the C# language.

The helper can do more than building just Html. It’s also great for building script. Posting the form-data as they are will lead to all the funny names leaking back to the controller. It would be great to have the original simple names. To control this you have to post from script.

    $.post(‘/EersteLijnsTraject/Bewaren/?idTraject=@Model.Id’,

        {

            MyPostValue : $(‘#MyPostValue@(Model.Id)‘).val()

   }

        

 

Here a form variable named MyPostValue is posted with its value coming from a control named MyPostValueX. This works but is ugly code which is hard to write and maintain.

Here my custom helper comes to the rescue. It uses a class to build the postdata. The class takes the id in its constructor and uses a stringbuilder to build the script. The Add method adds a model member to the post. Using the pattern described above based on a lambda on the generic TModel type of the data.

public class PostDataBuilder<TModel>

{

    private readonly StringBuilder _sb = new StringBuilder();

    private readonly int _id;

 

    public PostDataBuilder(int id)

    {

        _id = id;

    }

 

    // Add form field to postdata

    public PostDataBuilder<TModel> Add<TProperty>(Expression<Func<TModel, TProperty>> expression)

    {

        var propName = expression.NameBuilder();

        // JQuery  i.e. : BeginDatum : $(‘#BeginDatum1′).val()

        _sb.Append(string.Format(“{0} : $(‘#{0}{1}’).val()”, propName, _id));

        // comma separated

        _sb.Append(‘,’);

        return this;

    }

    // Generate

    public HtmlString Render()

    {

        /*  Resulting in

            BeginDatum : $(‘#BeginDatum1′).val(),

            EindDatum : $(‘#EindDatum1′).val(),               

            DBC : $(‘#DBC1′).val()                

 

            */

        return new HtmlString(_sb.ToString(0, _sb.Length – 1));

    }

}

 

The Render methods builds the desired script snippet.

$.post(‘/EersteLijnsTraject/Bewaren/?idTraject=@Model.Id’,

    {

 

        @(myHtml.PostData().Add(m => m.DatumAanmelding)

                                    .Add(m => m.HulpvraagInitiatief)

                                    .Add(m => m.Aanmelding)

                                    .Add(m => m.AanmeldingsKlacht)

                                    .Add(m => m.DiagnoseSet)

                                    .Add(m => m.Werkzaamheden)

                                    .Add(m => m.Tests)

                                    .Add(m => m.BehandelMethodiek)

                                    .Add(m => m.MedicatieGebruik)

                                    .Render())

        },

        // return function

        function(data) {

 

 

This code is a lot better to read and maintain. Thanks to the lambdas. As an extra bonus posting this way does not require an html-form.

Wrapping up and winding down

Building a custom HtmlHelper is, when you understand how, no big job. Give these snippets of my experiments it should be no big problem to create your own.

It takes these steps to use your own custom helper in a view

  • Make sure the code is included the uses
  • Create a helper in the head of the page
  • Use its methods

Here’s a slightly stripped version of one of our pages using EposHtml, our custom HtmlHelper 

@model ELPTrajectModel

@using Epos4.Website.EposZilos.Helpers

@using Epos4.Website.EposZilos.Models

 

@{

    var eposHtml = Html.EposHtml(Model.Id);

}

 

<script type=”text/javascript”>

function Bewaar@(Model.Id)() {

    $.post(‘/EersteLijnsTraject/Bewaren/?idTraject=@Model.Id,

        {

 

            @(eposHtml.PostData().Add(m => m.DatumAanmelding)

                                     .Add(m => m.HulpvraagInitiatief)

                                     .Add(m => m.Aanmelding)

                                     .Add(m => m.AanmeldingsKlacht)

                                     .Add(m => m.DiagnoseSet)

                                     .Add(m => m.Werkzaamheden)

                                     .Add(m => m.Tests)

                                     .Add(m => m.BehandelMethodiek)

                                     .Add(m => m.MedicatieGebruik)

                                     .Render())

            },

            // return function

            function(data) {

                var grid = $(‘#EersteLijnsTrajecten’).data(‘tGrid’);

                grid.pageTo(grid.currentPage);

            });

    }

</script>

 

 

<table>

    <tr>

        <td>

            @Html.LabelFor(m => m.DatumAanmelding)

        </td>

        <td>

            @eposHtml.DatePickerFor(m => m.DatumAanmelding)

        </td>

    </tr>

…………………………….

    <tr>

        <td>

        </td>

        <td>

            <button type=”button” onclick=”Bewaar@(Model.Id)()”>

                Bewaar</button>

        </td>

    </tr>

</table>

 

You don’t want to see the pages before the custom Helper Glimlach  The way the name of the save method is “uniquified” might give a clue. Anyway, I hope to have inspired you to explore the HtmlHelper as well.

Posted in Uncategorized | 2 Comments

2013

Almost 2013 and my blog still ain’t dead yet. The turning of the year I looks like a good moment for another ride on one of my favorite hobby-horses: looking into the future through the eyes of the past. In my youth pretending to be a cowboy turned into another Texan adventure: exploring space. The images in this post are from a 1959 Golden Press book on the future of space exploration. In 1963 a translation hit the Dutch market which appeared just in time to be swallowed by me.

HNY1

These days there’s nothing futuristic about it, both technologically and social just antique.

It got even better when describing a ‘rocket freight liner’

HNY2

Notice the (mail) bags on the left. The only thing missing is a “Wells Fargo Stage Coach” emblem.

I could go on and on. The lesson I learned once again is that foreseeing the future is not just hard, it’s next to impossible. It still is today. Who would seven years ago could have predicted the current state of (FI) JavaScript or Microsoft ? So next year we can just keep exploring and imagining. And most of all, stay critical on prediction.

And in case you make it into space, don’t forget your soda and sandwich:

HNY3

Happy new year.

Posted in Uncategorized | 1 Comment

A crash course into Mac recovery for Windows users and other dummies

A while ago I posted on taming a Mac to do Visual Studio development, including the settings to completely satisfy Resharper. We’ve been a happy couple since.  Until recently, when I lost my Macbook’s disk drive. It took me some time to find out what was wrong. OS X has no blue screens, it just shows a beachball (spinning pizza’s), due to the smoothness of the OS it took time to pinpoint the problem to the physical disk itself.

It is a legend that OSX is simple, diving into the internal workings you will meet a complete Unix system with all the endless list of mysterious parameters. It is also a legend 3d party tools have nothing to offer not included in the OS. Onyx is free, quite nice and integrates Unix documentation. Nevertheless nothing helped to fix the problem. The day my Mac would no longer boot I had to try to salvage some last pieces of work and planned to replace the disk.  Which was, in the end, quite easy but my experience with Windows machines was, in the beginning, not the best place to start.

The first try was to boot from the original install disks. Doing that the Mac beeped loudly and refused to do anything else. As it turned out you cannot boot a Mac with a disk containing another version of the OS than the machine’s latest version. OS-X 10.7 and 10.8 come as internet downloads. The upgrade made the install discs useless.

When choosing where to boot from (hold the option key when switching on) several options turn up :

  • Boot from the mac’s volume
  • Boot from CD
  • Boot from the recovery disc
  • Boot from the internet

The recovery disc is a second volume on the hard disc. In case that volume is also unreadable booting from (Apple’s servers) on the internet looks quite interesting. I have not tried that myself as my recovery disc was still readable.

The recovery disk offers the opportunity to reinstall the OS from the internet. It communicates with the Appstore and your Mac’s ID, no need to buy a new license. Unlike Windows there is no option to reinstall without preserving anything on the disk. I still needed a way to salvage my data.

The good thing is that you can install OS X on any volume attached at boot time. I plugged in an external USB drive and installed OSX there. Which resulted in a perfect working Mac with the original broken internal hard disk mounted as an extra volume. It was readable although it took a lot of patience to wait for the results. After copying my lost data (a complete VMware Fusion virtual hard disc) it was time to replace the disk drive itself.

A modern macbook looks pretty closed but replacing the internal hard drive is easy provided you have the right screwdrivers. As a new drive I took an SSD.  Best thing ever happened to the Mac. Especially a disc intensive app like VMware Fusion shines with that.

Reinstalling apps on a Mac is a no brainer. As there is no registry or anything like that it is a matter of copy and paste. An app like Monotouch needs some attention due to its many dependencies on other software. It cannot be installed more than two times. The good thing is that it did not consider the new disc as a fresh installation. The Mac is identified by something independent of disc or OSX installation. Soon everything was up and running without any trouble.

In the end I wish I had known all of this before. Or had an open mind on things possible instead of one narrowed by the way things work with Windows.

Posted in Uncategorized | 3 Comments