ASP.NET MVC HtmlHelper methods and CSS class

ASP.NET MVC 4 Comments

If you in ASP.NET MVC use a Html helper method to render out e.g. an input box:

<% = Html.TextBox("name")  %>

Sometimes you might need to add an CSS class attribute to your input box (this should be a fairly standard thing). For this there exist overload methods that takes a “htmlAttributes” parameter of type object. Now my experience with this is somewhat similar to Ayende Rahien experience – although I have not begun banging my head against the wall out of frustration. This is not a rant, I love ASP.NET MVC, I just had an experience with something simple that was hard to figure out because of some of the design decisions – not that they are bad, they can just be confusing – especially with the lack of documentation at the current stage (yes, I know it is just a beta). So if you try this:

<% = Html.TextBox("name", null, new{ class = "required"})  %>

You will (of course) get a compiler error, since “class” is a keyword and cannot be used like this. So how do you specify the class? Well, like this:

<% = Html.TextBox("name", null, new{ @class = "required"})  %>

Just for future reference :)

ADO.NET Entitity Framework vs. LINQ to SQL

.NET General 1 Comment

I have never been a huge fan of all the ADO.NET stuff – one exception: the DataReader. Everything else seems to me just to be bloated functionality around what I really need. How ADO.NET handles connections and commands are in my opinion overly "complex" – not that they are complex in any way, they could just be done way simpler. Whenever I have been writing code that access a database, I tend to rely on my trusted companion: the Enterprise Library. It provides such a nice and clean abstraction to the unneeded (IMHO) overhead posed by Connection, Command and Parameter handling.

Compare:

Database db = DatabaseFactory.CreateDatabase("my connectionstring");
using (IDataReader reader = db.ExecuteReader("my stored procedure", "my parameter 1", myParameter2, etc))
{
    // do my thang
}

To:

using (SqlConnection conn = new SqlConnection("my connectionstring"))
{
    conn.Open();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "my stored procedure";
    cmd.CommandType = CommandType.StoredProcedure;

    SqlParameter param = cmd.CreateParameter();
    param.ParameterName = "@param1";
    param.DbType = DbType.String;
    param.Value = "my parameter 1";
    cmd.Parameters.Add(param);

    param = cmd.CreateParameter();
    param.ParameterName = "@param2";
    param.DbType = DbType.Int32;
    param.Value = myParameter2;
    cmd.Parameters.Add(param);

    param = cmd.CreateParameter();
    param.ParameterName = "@param3";
    param.DbType = DbType.Int32;
    param.Value = etc;
    cmd.Parameters.Add(param);

    using (IDataReader reader = cmd.ExecuteReader())
    {
        // do your thang
    }
}

And don’t get me started on the DataSet

Now, MS has implied that LINQ to SQL will be deprecated and focus will be moved to the ADO.NET Entity Framework and LINQ to Entities. This has already stirred up the .NET community: David Hayden, Ian Cooper, Ayende Rahien to name a few.

I have never really considered using LINQ to SQL in big applications, mainly because I think LINQ to SQL imposes some constraints on my applications – one simple thing like the “low coupling” principle is not something that comes out of the box, it has to be tweaked and twisted to even give just a hint of low coupling. However I see LINQ to SQL as a very, very nice low-level method to create a basic SQL based data foundation.

For example, I am privately playing around with a blog engine based on ASP.NET MVC and LINQ, both XML and SQL. In this case LINQ to SQL is near-perfect for my needs. It provides sufficient abstraction from the database without imposing too much overhead, by providing flexibility in all future scenarios if the database suddenly need to be converted to an Oracle DB or refactored/de-normalized due to poor performance or whatever. It allows me to write SQL like-statements that (to a large extent) is verified at compile time. Sure I could do the same in LINQ to Entities, but it feels like firing up a super-tanker for something that really just need to be according to the KISS principle. LINQ to SQL is to a large extent very much KISS’ish, and fits perfectly in to the use I required for my playground project here.

I like to throw in this favorite quote of mine:

"Perfection is not when there’s nothing to add, but when there’s nothing to take away."
- Antoine de Saint-Exupéry

Or Occam’s Razor for that matter:

“All other things being equal, the simplest solution is the best”

Another thing about LINQ to Entities (and this is just based on a my brief experience with the ADO.NET Entity Framework), the designers within Visual Studio are not very good pretty bad very bad.

When creating a new “ADO.NET Entity Data Model” it does allow a reverse engineering possibility for an existing database. The model you end of with is simply a 1:1 mapping between entities and tables, i.e. the Active Record pattern. This is fine, but LINQ to SQL does the same – again “supertanker”. The Entity Framework is designed to be an abstraction of your database not “just” an Active Record pattern, i.e. your data model does not need to reflect your database schema in a 1:1 mapping. This is pretty neat, and can be useful, especially on larger projects where you are not creating the database schema yourself, or you are working on top of an existing SQL database. BUT if I create a very simple SQL database for a very specific scenario, I don’t really need this.

Another thing that is very bad in the designers is that once your model has been reverse engineered and you want to begin modifying/abstracting it, things get very, very tedious. The tools in the designer are not helping very much, i.e. apart from initial reverse engineering the database, utilizing the schema meta data to create properties etc. is not possible. The model is (granted) fairly intuitive, but the task of adding properties that map to columns, etc. is just overly “complex” (again complex in as it could be done way simpler).

The key feature of the Entity Framework to work on-top of any database has also on my first shot failed. Maybe it is poor database design, I’m not really a DBA so I’ll let others be the judge of that. But I have a scenario where I have a n:n relation between two tables – Person and Group. But instead of having the foreign keys in my cross reference table being the primary key hereof, I have an explicit primary key:

image

When creating the ADO.NET Entity Data Model in Visual Studio (by reverse engineering).

image

That is of course fair enough, so I remove the PersonGroup entity and create a many-many association between Person and Group with the following setup:

image

I get this error:

Error 3025: Problem in Mapping Fragment starting at line 115: Must specify mapping for all key properties (PersonGroup.Id) of table PersonGroup.

You also have to map ALL columns in the database to properties in the entity model, maybe I don’t what that! What if my entity model is really built on top of an already running database, and my job is to create a another user interface for e.g. a mobile device which requires just a subset of the database schema. I don’t want to map the entire shebang, for one because it is very tedious and second because the rest of the schema might contain sensitive information that should not be exposed on the mobile device (or whatever reason).

What is it with that homemade Entity-SQL stuff, that really smells too much like reinventing the wheel – we already have SQL (a standard) which on top of that has T-SQL and then we have LINQ in our managed code – this is really enough query languages for one application! Do we really need yet another proprietary query language (although it has a lot of similarity with SQL – but so does T-SQL and LINQ)? I don’t think so!

Not to mention that for demoing LINQ to SQL is just perfect – however I don’t (sadly) think that could justify MS investments in the LINQ to SQL framework alone.

This is just my gut feeling, maybe it has no substance when it comes to reality! But one thing I know is: I like LINQ to SQL for what it is, but equally much for what it isn’t.

Please prove me wrong!

Cool upcoming .NET stuff from Microsoft

.NET General, ASP.NET 1 Comment

Silverlight 2.0

Version 2.0 of the ubercool Silverlight, Microsoft’ pendant to Adobe Flash, is drawing nigh. Currently available as beta 2, release in june ‘08. Silverlight 2.0 allows embedded code client-side, by some magic, that does not even require having the .NET framework installed on the client.

ASP.NET MVC Framework

Quoting the ASP.NET MVC page:

ASP.NET MVC enables you to build Model View Controller (MVC) applications by using the ASP.NET framework. ASP.NET MVC is an alternative, not a replacement, for ASP.NET Web Forms that offers the following benefits:

  • Clear separation of concerns
  • Testability – support for Test-Driven Development
  • Fine-grained control over HTML and JavaScript
  • Intuitive URLs

References: Official page, Scott Guthrie MVC Preview 5 Release post

Zermatt

Quoting Zermatt home page:

Zermatt is a framework for implementing claims-based identity in your applications. By using it, you’ll more easily reap the benefits of the claims-based identity model described in this paper.

References: Official page, Vittorio Bertocci blog, Keith Brown blog

Velocity

Quoting Velocity Blog

(…) a distributed caching product to provide the .NET application platform support for developing highly performant, scalable, and highly available applications.

References: Velocity blog

Oslo

Quoting the official Oslo page:

”Oslo” is the codename for Microsoft’s forthcoming modeling platform. Modeling is used across a wide range of domains and allows more people to participate in application design and allows developers to write applications at a much higher level of abstraction. “Oslo” consists of:

  • A tool that helps people define and interact with models in a rich and visual manner
  • A language that helps people create and use textual domain-specific languages and data models
  • A relational repository that makes models available to both tools and platform components

References: Official page, Douglas Purdy – "What is Oslo?", Don Box blog, Various MS SOA articles (incl. non Oslo stuff)

Must have tools for .NET developers

.NET General, Reference Sheet No Comments

Like so many others have done before me I would like to present my take on a compiled list of favorite tools for developing using .NET.

Here goes:

Reflector

The most useful tool ever to reverse engineer assemblies – yes, it is a gray-zone regarding IP, but nonetheless very, very use full. Kudos to Lutz Roeder for this ultimate tool, and thank you very much for your effort in this. Lutz announced some days ago that he would end his work on Reflector. Red Gate (known for their useful tool SQL Compare – as mentioned later on ;) ) has taken over and "(…) will continue to maintain a free version for the benefit of the community". Do they implicitly say that there will be a commercial version!? I hope not – that would for sure have some effect on the Reflector community.

Red Gate SQL Compare

I really, really hate to include a commercial product in my toolbox, but being there are no free alternatives to a much required tool, I will include the best one I know of (or rather the only one I have used, but it is extremely useful and good so why bother with the others!?). Please drop a comment if you know of free and/or good/better alternatives. Price tag on the basic SQL Compare is $395.

LINQPad

Query Analyzer for LINQ. Very nice tool to help build, execute and debug queries, wether it be LINQ for SQL, LINQ for Objects or LINQ for XML.

StyleCop

StyleCop is a Visual Studio plug-in that performs code analysis directly on source code with the intent on enforcing a common coding standard for layout, readability, documentation and maintainability. SDK documentation for creating custom rules is available. StyleCop was originally created by one devoted (and might I add brilliant) Microsoft employee (Jason Allor) in his spare time. The tool has been used internally in Microsoft for years, but was first made available to the general public earlier this year. Follow Jason’s/the StyleCop blog here.

FxCop

FxCop is a tool to analyze managed assemblies for possible security issues and possible design and performance improvements that can be implemented.

VisualSVN

Sorry, but yet another commercial product. If you are using the most excellent version control system Subversion (if not then consider it!), there is a most excellent plug-in for Visual Studio. Comes with a free server version as well, which simplifies setup of Subversion on a Windows box. A free alternative – however I did not find it nearly as good as Visual SVN – is AnkhSVN. Neither unfortunately though are MSSCCI (Microsoft Source Code Control Interface) which means that they do not plug-in to the native source control module in Visual Studio. Price tag for Visual SVN is $49. For more information about Subversion you can read the SVN Book online.

For ASP.NET Developers

Must haves:

Firefox with Firebug and Web Developer Toolbar

Firefox speaks for itself, and so should Firebug, but a brief introduction: Firebug allows you to inspect and modify HTML, CSS and DOM. Debugging JavaScript and explicitly capture JavaScript XmlHttpRequest calls for debugging AJAX. The Web Developer Toolbar provides some additional functionality to what Firebug adds, but to some extent is a complimentary plugin.

Internet Explorer with Developer Toolbar

It is inevitable that as a web developer you need to assure cross-browser compatibility. Therefor a similar tool exists for Internet Explorer 6 and 7, however it not nearly as cool, so for general debugging, etc. Firebug is the choice, but for IE specific, the Internet Explorer Developer Toolbar does come handy.

Fiddler

Another tool that can help in debugging web applications/services is Fiddler. Fiddler acts as a HTTP proxy, logging all HTTP traffic from the local computer to other computers. This however means that out-of-the-box HTTP debugging when using Cassini (i.e. the development web "server" in Visual Studio) is not possible. It has to be tweaked.

For WPF / Silverlight Developers

Kaxaml

Kaxaml is a lightweight XAML editor with the split design / output view similar to the Visual Studio IDE. Kaxaml is a complimentary tool to Expression Blend, however Blend provides much more functionality, hence "lightweight".

Mole

Mole is a reverse engineering tool, similar to Reflector. However Mole disassembles the XAML of a WPF/Silverlight application and provides a tree view of the XAML structure. Nice for "how did they do that", but again gray zone concerning IP.

"Dark Horses"

Since I have not had any real experience with these I will put them on a "dark horse" list, just for reference, since they might prove themselves valuable given the time/opportunity to use them.

Framework Design Studio

Quoting the FDS site:

Framework Design Studio is a set of tools for reusable library designers. The package contains a GUI tool for viewing, reviewing, and comparing versions of managed APIs. It also contains a command line tool for generating API diff reports. Simple user guide explaining the basics of the tool is included in the setup.

Temporary Stream

.NET General, Code No Comments

Scenario: you need to store a large block of data, e.g. as the result of an XSL transformation on an XML document. Using a MemoryStream would simply kill your server/application since it would use too much memory. Using a FileStream can be a but tedious since it would require write permissions on a specific folder…

Wait, doesn’t this sound just like a temporary file, i.e. storing a file in the TEMP path.

Yes, it does – and a simple solution is actually just to use a FileStream with a twist:

public class TempFileStream : FileStream
{

    public TempFileStream()
        : base(Path.GetTempFileName(), FileMode.OpenOrCreate, FileAccess.ReadWrite)
    {
    }

    public override void Close()
    {
        base.Close();
        if (File.Exists(Name))
        {
            File.Delete(Name);
        }
    }

}

Here we simply create a new temporary file with R/W access. In the Close method of the FileStream we simply delete the file. Nice and simple and your temporary file only "lives" during your "using" statement…

FormsAuthentication.HashPasswordForStoringInConfigFile() continued…

.NET General 1 Comment

In "response" to my own previous post: two little extension methods that does exactly what "we" need:

public static string GetHashValue(this MD5 hash, string value)
{
    return GetHashValue(hash, Encoding.UTF8.GetBytes(value));
}

public static string GetHashValue(this MD5 hash, byte[] value)
{
    byte[] data = hash.ComputeHash(value);
    string md5 = "";
    for (int i = 0; i < data.Length; i++)
    {
        md5 += data[i].ToString("x2").ToLowerInvariant();
    }
    return md5;
}

Usage:

MD5 md5 = MD5.Create();
Console.WriteLine(md5.GetHashValue("test"));

Using ASP.NET Development Server in Firefox

Uncategorized No Comments

Scott Mitchell wrote a post about performance using Cassini (the "integrated" Development Server in ASP.NET) when running sites under Firefox. Having myself been living with this issue for a long time, but just blamed my dev setup, this news is sweet music in my ears.

Just did the "network.dns.ipv4OnlyDomains" fix (i.e. about:config -> set network.dns.ipv4OnlyDomains to "localhost") and everything seems like I just received the latest state-of-the-art dev machine (well almost :) ).

Therefor if you have not done it already, what are you waiting for go right ahead! Just type about:config in your location bar.

Using Type.IsAssignableFrom() to check inheritance

.NET General, Reference Sheet No Comments

Having been in the situation needing to check if a given instance of an object either implements an interface or a class in the form of a given Type object (i.e. "if A is B" wont do) I decided to write a little "note to self" post which others might find useful.

This is basically just a "wrapper" around Scott Hanselman’s post from a long time ago Does a Type Implement an Interface?

For a "class type" you can use the Type.IsSubclassOf() method and for an interface you can use something in the line of:

if (typeof(MyClass).GetInterface("MyNamespace.IMyInterface") != null)
{
    // MyClass implements IMyInterface
}

However the string literal looks bad also neither solution provides a simple check for "is this type implementing/a subclass of this interface/class".

The gist of Scott’s post is that using Type.IsAssignableFrom() can solve your problem concerning interfaces, but the same logic applies for classes. So:

if (typeof(IMyInterface).IsAssignableFrom(typeof(MyClass)))
{
    // MyClass implements IMyInterface
}

if (typeof(MyClass).IsAssignableFrom(typeof(MySubClass)))
{
    // MySubClass is a subclass of MyClass
}

if (typeof(IMyExtendedInterface).IsAssignableFrom(typeof(IMyInterface)))
{
    // IMyExtendedInterface extends IMyInterface
}

Actually this is exactly what the MSDN page for Type.IsAssignableFrom() states:

true if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c

First in "layman" terms it means:

TypeA a;
TypeB b;
if (typeof(TypeA).IsAssignableFrom(typeof(TypeB)))
{
    a = b; // this will work
}

But what does the underlined text then mean in the context of this check? The samples on this on the MSDN page are totally nonsense (e.g. text states "List<int> assignable from List<Type>" but in fact List<int> and int[] are compared).

The point in that statement is that A<T> is assignable from A<S> if T is assignable from S.

So it is a little more inclusive (which is no surprise) than just checking inheritance, but as long as the "master" class/interface is known explicitly (which is most often the case, since a scenario for this is checking if a type specified in config is in the correct inheritance tree) the check will be safe.

Abuse of FormsAuthentication.HashPasswordForStoringInConfigFile() method?

.NET General, ASP.NET 3 Comments

I can’t help but get a annoyingly creepy feeling whenever I see people using FormsAuthentication.HashPasswordForStoringInConfigFile() to generate a hash cipher for a given value (for example here). On the other hand I can’t really decide wether I think it is the method which has a bad name/should be "located" somewhere else or it is the "abuse" of it as it is today.

If we look at the actual implementation of HashPasswordForStoringInConfigFile using Reflector:

public static string HashPasswordForStoringInConfigFile(string password, string passwordFormat)
{
    HashAlgorithm algorithm;
    if (password == null)
    {
        throw new ArgumentNullException("password");
    }
    if (passwordFormat == null)
    {
        throw new ArgumentNullException("passwordFormat");
    }
    if (StringUtil.EqualsIgnoreCase(passwordFormat, "sha1"))
    {
        algorithm = SHA1.Create();
    }
    else
    {
        if (!StringUtil.EqualsIgnoreCase(passwordFormat, "md5"))
        {
            throw new ArgumentException(SR.GetString("InvalidArgumentValue", new object[] { "passwordFormat" }));
        }
        algorithm = MD5.Create();
    }
    return MachineKeySection.ByteArrayToHexString(algorithm.ComputeHash(Encoding.UTF8.GetBytes(password)), 0);
}

The net result of this of course is that you do get the MD5/SHA1 hash of the password or value.

However the method name is HashPasswordForStoringInConfigFile, i.e. the name suggests it is for hashing passwords and further more it is a method of a class called FormsAuthentication… see a pattern!? The name does not suggest it is a generic MD5 method (although the implementation shows it is that).

IMHO using HashPasswordForStoringInConfigFile as a generic MD5 calculation method does nothing but make code less readable and hence harder to maintain. The very, very least a developer can do is to comment the code, but we all know when that’ll happen…

Look at the alternative:

public static string GetMD5(string value)
{
    MD5 algorithm = MD5.Create();
    byte[] data = algorithm.ComputeHash(Encoding.UTF8.GetBytes(value));
    string md5 = "";
    for (int i = 0; i < data.Length; i++)
    {
        md5 += data[i].ToString("x2").ToLowerInvariant();
    }
    return md5;
}

The ONLY problem with not doing this stuff yourself is the conversion from a string and back to a string…

Yes, this might be a little slower due to the string stuff, but you can always "inherit" ;) the MachineKeySection.ByteArrayToHexString method.

The point is that using FormsAuthentication.HashPasswordForStoringInConfigFile to calculate all MD5/SHA-1 hash values just because the implementation happens to support this seems wrong. Writing this I think I actually blame Microsoft the most for not providing this method somewhere else and named more appropriately.

That was just a little rant…

Finding unique values from a list of objects

.NET General No Comments

I have several times had to get a unique list of values from a set of objects, for example the simplest way to populate a filter dropdown with possible names of the people in a list of persons. A simple/nifty little routine that does that:

Based on an list (IEnumerable<S>) loop through them all, using a delegate get the value/property (of type T) from the object (of class S) and return all uniques hereof (using basic object equality – Equals)

public delegate T ValueDelegate<T, S>(S obj);

public static IEnumerable<T> FindUniques<T, S>(IEnumerable<S> list, ValueDelegate<T, S> valueDelegate)
{
    List<T> result = new List<T>();
    foreach (S item in list)
    {
        T value = valueDelegate(item);
        if (!result.Contains(value))
        {
            result.Add(value);
            yield return value;
        }
    }
}

Icons by N.Design Studio. Designed By Ben Swift. Powered by WordPress, Search Optimization and Free WordPress Themes
Entries RSS Comments RSS Log in