Google analytics script

Latest jQuery CDN with code tiggling.

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, 27 August 2014

Simplifying method parameter checking

Next version of C# that will be coming with Visual Studio (supposedly version 2014) will have a new operator called the null-propagating operator (?.) allowing us to write null conditional statement expressions. This will help us simplify our code tremendously by collapsing several lines of conditional blocks to a single statement. Combining it with null-coalescing operator makes it even more powerful as seen in this example: string username = GetUser()?.name ?? "anonymous"; Object will be null checked before trying to access its members so we'll avoid the infamous null reference exception. It will therefore automatically continue to null coalescing part of the statement. You can read more about it on this link.

Parameter null value checking code is something we frequently write at the beginning of method body to avoid null reference runtime exceptions. You know these if statements right at the beginning of your methods:

   1:  public string DoSomething(Model data)
   2:  {
   3:      if (data == null)
   4:      {
   5:          throw new ArgumentNullException("data");
   6:      }
   7:      
   8:      // actual processing
   9:  }

Even static code analysis tools complain if you don't do these checks and to be honest this is a very good practice to avoid many future bugs in your code. The problem isn't this code per se, but rather that we're writing these seemingly same lines over and over again. Many developers tried simplifying this process using different techniques but the one I'm going to show here is a bit different.

Wednesday, 23 April 2014

Mapping SQL stored procedures to C# class methods with matching strong type parameters using T4 template

Blog post provides T4 template that generated strong typed C# code which maps to SQL stored procedures. It doesn't actually call those SPs, but rather prepares SQL queries to call stored procedures with various parameters. These provided T4 template queries are NPoco/PetaPoco compatible, so if you use a different DAL lib (maybe even simple .net Sql client), you'll have to adjust methods to generate and return different results (with .net Sql client it will likely be SqlCommand instance).

NPoco/PetaPoco DAL libraries use strings to provide database optimised queries and these are prone to typing errors which we aren't able to catch during compile time but rather during runtime, when effects can be much more devastating. That's why it would be great if we could somehow avoid these magic string values and just used C# code with string types and not make a mistake. We can't really avoid magic strings when writing direct TSQL but if we write stored procedures, we can do something about it.

We could self-write those C# calls that use stored procedures internally but that would just mean we moved typing errors to those methods, so this is not really a solution. Enter code generation with T4 Visual Studio templates. A t4 template will help us automate the process of writing C# methods while also making sure we get compile time errors when we change particular stored procedure's signature (sp name, parameter count or their types). So let's do just that.

Friday, 18 October 2013

Parametrized code testing and code exploration

Few days ago I had the pleasure of presenting parametrized unit testing among other things to a group of developers as part of my consulting side of work. I'm sure everyone got something useful out of those few hours we spent together.

So I thought of writing an introduction blog post to parametrized unit tests using NUnit library. But to give it some edge let me do this along with code exploration that makes our tests (and consequently our production code) better. I'll be using Code Digger Visual Studio 2012 extension. Hopefully you'll learn something new as well.

Tuesday, 25 October 2011

Application model entity localisation in Asp.net MVC

If you are an Asp.net MVC developer and live in non English speaking country, then you've faced the challenge of application localisation. Although frameworks these days support localisation it's usually not a straightforward process. Especially when it comes to web applications. There's always a dilemma how to implement localisation and how to choose request locale. Should it follow browser language settings or user preference? Either way there's an underlying base foundation that can be used to implement each.

This post is not about localisation in general but rather just about application model classes and their property names localisation when presented in Asp.net MVC views by means of Html.LabelFor() extension methods. There already is a class DisplayNameAttribute but it lacks capabilities we need.

This blog post is related to .net framework 3.5 and older because there's a new attribute provided by the .net framework 4 and newer. It's called DisplayAttribute which has even more capabilities than those implemented below.

Friday, 5 August 2011

BLToolkit MapResultSet builder

or How I refactored my seemingly identical methods with generic type parameters

As I've written in the past I'm using BLToolkit lightweight ORM on one of my projects. But some parts of it seem very silly actually and I can't really see why did they decide to do certain parts the way that they did. One of them being the configuration for multiple result sets. You know those where you write TSQL query that returns more than one result. BLToolkit has this nice DbManager mapping method called ExecuteResultSet() that takes an array of MapResultSet objects. And these you have to prepare yourself first so mapper will actually populate your object lists. Their example looks like this (just the relevant code):

   1:  List<Parent> parents = new List<Parent>();
   2:  MapResultSet[] sets = new MapResultSet[3];
   3:   
   4:  sets[0] = new MapResultSet(typeof(Parent), parents);
   5:  sets[1] = new MapResultSet(typeof(Child));
   6:  sets[2] = new MapResultSet(typeof(Grandchild));
   7:  // and so on and so forth for each result set
   8:   
   9:  using (DbManager db = new DbManager())
  10:  {
  11:      db
  12:          .SetCommand(TestQuery)
  13:          .ExecuteResultSet(sets);
  14:  }

As you can see you have to create an array of MapResultSet objects of the correct size (using a magic value - and you know I don't like them) and then set an instance to each (again using magic values). Seems tedious? I thought so as well. Hence I've done it differently.

Thursday, 17 March 2011

Removing route values from links/URLs in Asp.net MVC

I didn't really know how to properly title this post to make it easily searchable by those who bump into routing-related issue. Words like arbitrary, ambient, unwanted, unneeded, extra, unrelated etc route values popped into my mind, but I decided to title it as it is now.

One of the main pillars of Asp.net MVC is routing. Many applications can just use default route definition to cover all their scenarios but some applications require it to be a bit more complex. Look at this example:

   1:  routes.MapRoute(
   2:      "CustomerSpecific",
   3:      "Customers/{customerId}/{controller}/{action}/{id}"
   4:      new { controller = "Customers", action = "Index", id = UrlParameter.Optional },
   5:      new { customerId = @"\d+" }
   6:  );
   7:   
   8:  routes.MapRoute(
   9:      "Default",
  10:      "{controller}/{action}/{id}",
  11:      new { controller = "Home", action = "Index", id = UrlParameter.Optional }
  12:  );
Seems fine? Well it does and it works, but you will have problems when you'll be anywhere in http://www.domain.com/Customers/n/... and would like to also generate links to parts of your application that are covered by default route definition (second route). Let me show you why.

Monday, 28 February 2011

Improving Asp.net MVC maintainability and RESTful conformance

I've used Asp.net MVC for a few years now but this issue I've stumbled upon just a few days ago seems something everydayish and I wonder how come I've never bumped into it. It has to do with Asp.net MVC routing and action method selection. First of all think of default route definition that looks like this:

   1:  // default application route
   2:  routes.MapRoute(
   3:      "Default",
   4:      "{controller}/{action}/{id}",
   5:      new { controller = "Home", action = "Index", id = UrlParameter.Optional }
   6:  );
Mind that id route value is optional? Yes optional. So it should be perfectly feasible to have two action methods: one with the id parameter and one without it: public ActionResult Index() { ... } and public ActionResult Index(int id) { ... } But you've probably guessed it? This doesn't work out of the box. You'll get a runtime error stating that there are two matching action methods for the current request. A bit strange? I thought so as well. So let's try and accomplish just that!

Sunday, 23 January 2011

How to correctly use IHttpModule to handle Application_OnStart event

In one of my previous blog posts (Writing a custom IHttpModule that handles Application_OnStart event) I've been talking about using IHttpModule to also handle application start event which is a non-documented feature. Sure it works, but you may see some strange behaviour of duplicated (or even multiplicated) functionality being executed. You probably won't see this with your applications in development, because your local IIS isn't really heavy duty workhorse, but in production environment you may see this strange behaviour. Investigating it is even a bit more complicated because of the running application serving live traffic. Let me help you. So I will point you in the right direction and more importantly show you a solution that makes things work reliably even on a heavy load IIS.

Wednesday, 12 January 2011

Custom Asp.net MVC route class with catch-all segment anywhere in the URL

Asp.net MVC routing does a fine job with routes that have a finite number of segments. We define them with route URL pattern string. The default provided by the Asp.net MVC project template being {controller}/{action}/{id}. Most web applications can do everything using only this single route definition and many developers don't even think beyond this standard. But sometimes this single route just isn't enough or it's just not acceptable.

A real world example

Think of a web site you're building that has hierarchically organised categories. Like Amazon. We have books, music, electronics, etc. And every top category has sub categories. And so on and so forth. Using default route definition we would access a particular (sub)category simply by: www.domain.com/categories/index/647 That's fine, but it's definitely not human friendly. If we'd change our route URL definition to {controller}/{action}/{id}/{name} this would already be much friendlier: www.domain.com/categories/index/647/web-development That's something similar (not the same, because we're still using action names here) to what Stackoverflow does with it's questions.

But now think of this super human readable web address: www.domain.com/books/computer-internet/web-development/latest This one would display latest web development books. As we can see it defines categories in hierarchical order similar to breadcrumbs. All in human readable format. Doing this kind of routing isn't supported out of the box (because we have an action at the end), but I think we could do better. Let's try and create a route that supports this.

Saturday, 8 January 2011

Generate enum from a database lookup table using T4

This is something rather common. You're building an application that uses database storage in the background. If your database isn't completely trivial and you're not fatally in love with magic values/numbers, then you probably also use lookup tables to gain referential integrity when it comes to certain types, codes and similar data. But to follow the DRY software development principle we want to use these values defined in database on upper layers as well without manually writing any additional code. Because as mentioned magic values are evil regardless of where they're used.

Tuesday, 14 December 2010

Custom action method selector attributes in Asp.net MVC

Some of the least customized but very useful extension points in Asp.net MVC are action method selector attributes. We use them all the time without actually knowing, but we may write our own as well and make seemingly complex things trivial.

A real world example

Take for instance Twitter website. When you first visit their site, you are presented with the anonymous visitor home page that provides search capabilities, trends etc.

But when you're logged in you see a completely different page. Web address is still the same, but content is completely different. You see your home twitter page where you can send tweets and read your stream.

Using custom action method selector attributes, you can easily differentiate between such requests without using multifaceted controller actions.

Friday, 19 November 2010

Handling validation errors on Ajax calls in Asp.net MVC

If you're developing rich web clients using Asp.net MVC on the back-end, you've probably come across this functionality that can be described with these conditions:

  1. client side data (may be a form),
  2. ajax posting of this data (form),
  3. controller action has strong type parameters,
  4. controller action processes data and returns anything but a full view (since it was an Ajax call)
Familiar? Then you've come across this problem: »What should be done when validation fails?«
Seems fairly straight forward, right? Well not so fast my fellow developer friend...

Wednesday, 3 November 2010

T4 template to generate BLToolkit compliant stored procedure calls

Developing data aware applications used to be quite a pain before various helper libraries emerged. At first we used Enterprise Library from Microsoft that made things much simpler and standardized. In all the years of development it became very complex or even too complex for usual everyday projects. Anyway. Lately we started using more popular OR/M tools and libraries that go even further and provide a really transparent abstraction layer between our logic and the actual data store (whichever it may be).

Choosing DAL layer technologies isn't always straight forward. You have to choose wisely and think of the scenarios you'll use in your application. The same thing happened to me this last time when I was at the same decision point. Yet again.

I've used Entity Framework on two past projects (using EF Extensions along with it to make it simpler to integrate custom occasional stored procedures). Contrary to popular belief I was quite pleased with it even though we had to resort to not so seldom hacks to make it snappy. Usually provided by stored procedure calls and result materialization. Nonetheless it worked as expected. We still didn't have to write any entity classes, connection lifetime was auto-managed in entity context as well. Entity Framework FTW so to speak. On the downside I should as well mention that speed is not its strength. You use SQL Profiler quite often to analyse those all but easy to grasp spaghetti T-SQL queries. But things have greatly improved after EF4 was released. Visual Studio integration was of course one of its best strengths that gives you the all familiar drag and click UI without writing XML files. Even though it wasn't fully working in version 1.

Custom complex stored procedures aren't OR/M friendly

But this time I knew this application will be much heavier on the database side with much more complex processes and larger amounts of data. All these will most probably be better processed by stored procedures in the database itself. So I ruled out Entity Framework completely because I would be writing lots of custom materializers and such. But what should one choose instead? Most of these days OR/M libraries don't support custom stored procedures quite well, so I had to rule out LINQ to SQL, NHibernate, Subsonic and similar as well. I'd use Fluent NHibernate anyway since I prefer syntax checked code over XML configuration.

BLToolkit library to the rescue

So I resorted to semi-biased ORMBattle.NET website that lists most popular OR/M libraries along with their measured benchmarks. My main requirements for my DAL layer library were:

  • support for all kinds of custom stored procedures and
  • automatic result materialization and of course
  • it had to be free
After a while (and some checking) I've decided to give BLToolkit a try since it seems it provides exactly what I require. I agree it's not an actual OR/M library, but that makes it even faster. I was thinking of writing a few of my own generic calls that would do just what I need, but I had to to follow the DRY principle. Ok, BLToolkit it is then.

The good thing is that BLToolkit is fast and provides data materialization. But the bad thing is that you may end up with lots of magic strings. This is where T4 comes into play. I wanted to avoid writing stored procedures' names and parameters using plain strings, because that's very prone to human errors. Not to mention tedious work and updates when something gets changed on the DB side.

Database side

To make things more generic and structured I had to stick to certain syntax rules on the database side. I didn't want to end up with a single class that has as many methods as there are stored procedures in the database. Certain stored procedures are related to certain common tables, that are usually reflected in some middle layer entity class. For instance if we have a table Person we will have several stored procedures that will manipulate data around this table and related ones as well. But basically these stored procedures will be somehow related to the Person database table. We usually name stored procedures that way. At least most of the time:

  • Person_GetAll
  • Person_SaveRelatedData
  • etc.
So I shall make this a rule. Part before underscore is related to class name, part afterwards will provide method name. Perfect.

The usual stored procedure call in BLToolkit

If you haven't used BLToolkit before, let me get you up to speed and show you some code, that makes it easy to understand how to execute a parametrised stored procedure call.

   1:  using (var db = new DbManager())
   2:  {
   3:      return db
   4:          .SetSpCommand(
   5:              "Person_SaveWithRelations",
   6:              db.Parameter("@Name", name),
   7:              db.Parameter("@Email", email),
   8:              db.Parameter("@Birth", birth),
   9:              db.Parameter("@ExternalID", exId))
  10:          .ExecuteObject<Person>();
  11:  }
This represents some code within data repository. Stored procedure populates certain tables (most notably Person table) and then executes a SELECT statement as well to return the newly created record (with relations if necessary).

As you may see, this is a very easy and comfortable way of calling stored procedures (can easily call regular queries as well) and having results materialized along the way. But. The problem lies right there in front of our eyes. Magic strings.

What if we make a typo?
What if we slightly rename a stored procedure?
What if we add a few others?
What if we rename a parameter or its type?
But the main one is what if we're part of a larger team where each developer's writing a separate part of application and not everyone is tedious or/and communicative?

The answer to all these questions is use automation. So let's automate generation of our stored procedure calls with strong typed parameters. The most obvious way of doing this is by using Text Transformation Template Toolkit or in short T4 because it's very well integrated into Visual Studio and works really well. If we use extensions like Tangible T4 editor we get nice code highlighting and intellisense support along the way as well.

Stored procedure call after using T4 template

What we'd like to achieve in the end is to get previous code to be called this way:

   1:  using (var db = new DataManager())
   2:  {
   3:      return db
   4:          .Person
   5:          .SaveWithRelations(
   6:              name,
   7:              email,
   8:              birth,
   9:              exId
  10:          )
  11:          .ExecuteObject<Person>();
  12:  }
So we can see there're no magic strings any more and we get code intellisense as well, so we don't have to check store procedure names or check parameter names either. The best part is that when anyone else changes parameters or renames a stored procedure we get compile time errors. Code generation FTW!

Gimme gimme gimme code

You can download T4 template from Google code site. There's a comment header at the top of the template where you'll find all instructions how to use the template. For now all stored procedures are treated the same. These will probably be next extensions to this template:

  • Support for output parameters
  • Handling multi result set stored procedures - there will have to be some naming convention to distinguish these and template will either have to provide some sort of support or skip generation
  • etc.

I'm attaching template comment head here so you can provide some input whether it's readable (just add a comment to this post):

   1:  /* BLToolkit stored procedure calls T4 generator          */
   2:  /* ------------------------------------------------------ */
   3:  /* 1. Fill in variables below this comment head           */
   4:  /* 2. Stored procedures must use this notation:           */
   5:  /*    ie. "Person_SaveWithRelations"                      */
   6:  /*    which will generate:                                */
   7:  /*    - a class PersonClass                               */
   8:  /*    - a property DataManager.Person of type PersonClass */
   9:  /*    - an instance method Person.SaveWithRelations()     */
  10:  /*    - method will have strong typed parameters          */
  11:  /* 3. Save template and use code                          */
  12:   
  13:  // set your preferred DbManager inherited class name (ie. class DataManager: DbManager { ... })
  14:  string className = "DataManager";
  15:  // provide namespace of your class
  16:  string useNamespace = "ApplicationName.Data.General";
  17:  // provide DB connection name (from .config file) that will be used by your DB manager
  18:  string dbConnectionName = "DefaultDatabaseConnection";
  19:   
  20:  // provide DB connection string that will be used by this generator
  21:  string connection = "Data Source=.;Initial Catalog=somedb;User ID=someuser;Password=somepassword";
  22:   
  23:  /* That's it. Save this file now. */

Provide some feedback

If you have any additional ideas how to enhance or change this template I'm willing to consider your ideas. You can easily provide code snippets that would make it even better. Anyway. I hope you'll use it and that you'll like it.

Thursday, 9 September 2010

Asp.net MVC model binding to List<T>

Asp.net MVC is really a great platform to build performant and very controllable web applications. But sometimes some functionality is scarcely documented if at all. Internet proves (thank you Google) to be an invaluable wealth of information in this regard since other developers are usually solving similar problems. But sometimes you either don't find usable information or you want to test things for yourself as well and learn something new as you go along.

Something similar happened to me on my previous project. I had to dynamically generate a list of objects in the browser and then reliably POST them back to web server so that data would be reliably model bound and validated as well. I wanted to avoid manual validation at all costs because it would unnecessarily overcomplicate server code.

Wednesday, 18 August 2010

Writing a custom IHttpModule that handles Application_OnStart event

If you've been developing Asp.net web applications you've probably come across the IHttpModule interface, that makes it possible to write reusable request-level event handlers. The same thing can of course be done by writing event handlers inside the Global.asax codebehind, but then you wouldn't be able to reuse the same code unless you do a copy/paste.

But Global.asax codebehind has one particular advantage over your custom modules: it can also attach to application-level events like application start event for instance. As per documentation, this is not possible with a custom module. Or so I thought...