Category Archives: C#

ASP.NET ModelState – keys are changed behind your back

Summary

Today I came across a strange behaviour within the ModelState property of the APIController .

In summary I discovered that the keys used by the developer get changed by ASP.Net … but only sometimes !

Background

To paraphrase the doco the ModelState dictionary is used to “represent the state of an attempt to bind a posted form to an action method, which includes validation information”.

One straightforward place this is seen is where an API request has provided a value which can’t be used to populate the relevant property of the underlying model. The resultant error is reflected in the contents of the ModelState property.

As well as this type of ‘automatic’ population of ModelState it’s possible use the AddModelError method to add your own errors to the dictionary like this :

ModelState.AddModelError("inputSample.StartDate", "Some sort of validation error");

Weirdness (or should I say ‘WeIrdNeSs’ ?)

The behaviour I saw today concerns the way the key used as the first argument to AddModelError gets manipulated in what I consider to be a rather confusing manner.

In the example above the underlying model had a property of ‘StartDate’ and so everything worked as you might have expected.

If however you use a key which is unrelated to any property of the model, eg ‘Foo’, you can still add the item to ModelState and it will exist in the underlying dictionary under the key used, like this :

ModelState.AddModelError("inputSample.Foo", "Some sort of validation error");

Where things get strange, at least in my view, is if you use a string which happens to match a property name if both your proposed key and the a Model property match when both are lower cased. For instance ‘HairColour’ might be a Model property name and a key might be used of ‘HaIrCoLoUr’ .

In that situation something in the ASP.NET plumbing decides that you didn’t really mean to use a key of ‘HaIrCoLoUr’ and instead meant to use ‘HairColour’.

I don’t like this behaviour because I really don’t like ‘magic’ going on in the background – others may feel differently.

Sandcastle XML Reference

Sandcastle XML Reference

Handy reference to Sandcastle XML

Summary

Hard working Michael Sorens has produced a wall chart documenting the XML used with the Sandcastle Document Generator.

Reference to Sandcastle’s XML Documentation Comments

In a previous post about Sandcastle I mentioned a useful guide to the Sandcastle Documentation Generator written by Micheal Sorens.

I’ve just come across an accompanying wall chart.

Sandcastle XML Reference Sample

Sandcastle XML Reference Sample

The wall chart provides a quick reference to the XML used by a programmer in source code comments to allow Sandcastle to automatically generate documentation.

The wall chart is a good resource for anyone using Sandcastle and is available for download as a PDF here.

EDIT: The link to the wallchart went bad after this post was published. I’ve now amended the link to point to a version of the wallchart which works as at April 2012.

Sandcastle – the whole story !

Sandcastle – the whole story !

Documenting a document generator !

Summary

Sandcastle Document Generator is a great tool for producing project documentation but getting it to work can be … challenging ! Here’s some resources to help.

How does this thing work ?

If you’ve used Sandcastle and XML Documentation to automatically produce your .NET project documentation you’ll know:

  • the resulting output is great
  • getting the output can be challenging !

I came across an article by Michael Sorens which very comprehensively documents the process you need to go through.

Taming Sandcastle: A .NET Programmer’s Guide to Documenting Your Code is (as the intro says) “the easy guide to the process that Microsoft never managed, and introduces several applications that help” – it’s so much better than the process I went through when I was first using Sandcastle – I highly recommend it.

XML Documentation ? – How’s that ?

Now backtracking a little. For those who are not fully on the XML Documentation train here are some other good resources:

  • GhostDoc – Great Visual Studio Extension for ‘automagically’ producing XML Documentation of classes; methods; and properties – it’s very good indeed and … it’s free !
  • Within Michaels main article there’s a nice section introducing the benefits of using XML Documentation
  • Having read the intro mentioned above the nice people at Dynicity have produced a very comprehensive referenceto XML Documentation Comments of all the options available.

What’s wrong with this ?

What’s wrong with this ?

From a long list of things I’m amazed I didn’t see more quickly.

Summary

Do you sometimes find you go looking for a difficult problem when what you have is a simple problem ?

Todays Learning Point

Todays learning point is : if something weird is happening look at the simple things first.

 private bool _blnShowContractTabs;
 public bool blnShowContractTabs
 {
 get { return _blnShowContractTabs; }
 set { _blnShowContractTabs = value; }
 }

 private bool _blnShowAddEditLinks;
 public bool blnShowAddEditLinks
 {
 get { return _blnShowAddEditLinks; }
 set { _blnShowContractTabs = value; }
 }

I spent a little while today looking for a “big problem” which turned out to be a carelessly typed property set statement (… carelessly typed by me … I should add).

Zen ?

I was listening to the This Developers Life podcast the other day and Michael Moore spoke about problem solving and times when your problem isn’t really a problem at all (he expressed it much better than I could). I thought about Michael when I found this one !

Hex to Decimal Conversion in .NET

Hex to Decimal in C#

Two alternate ways of converting a hex string to decimal

Summary

The other day I needed to write some code to convert an integer expressed in hexadecimal to decimal. I was surprised to find that the way to do it wasn’t the way I expected.

The value I was processing had come from a different environment and had a ‘0x’ prefix to define its base – it was also a string. I just assumed i could feed this to int.Parse and I’d get the answer I was after.

In fact it seems that you either have to get rid of the ‘0x’ prefix or find some other way of doing it. I write a little program to illustrate the choices.

AllowHexSpecifier Weirdness

One thing to notice here which is really quite strange is that the int.Parse option takes an enumerated type argument System.Globalization.NumberStyles.AllowHexSpecifier when in fact it doesn’t allow a Hex specifier ! I’m sure there’s some sense to that but I don’t see it myself !

Example Code

using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

namespace HexParsing
{
    class Program
    {
        static void Main()
        {
            string strTestHex ;
            int iTestHex;
            string sOut;
            string s1 = "{0} converted to base 10 using int.Parse is {1}";
            string s2 = "{0} converted to base 10 using Convert.ToInt32 is {1}";

            //Without a prefix - using int.Parse
            strTestHex = "7FC3DAE0";
            iTestHex = int.Parse(   strTestHex,
                                    System.Globalization.NumberStyles.AllowHexSpecifier,
                                    CultureInfo.CurrentCulture);
            sOut = String.Format(CultureInfo.CurrentCulture, s1, strTestHex, iTestHex);
            Console.WriteLine(sOut);

            //With a prefix - using Convert.ToInt32
            strTestHex = "0x7FC3DAE0";
            iTestHex = Convert.ToInt32(strTestHex,16);
            sOut = String.Format(CultureInfo.CurrentCulture, s2, strTestHex, iTestHex);
            Console.WriteLine(sOut);

            Console.WriteLine("Press ENTER to close window");
            Console.ReadLine();

        }
    }
}