Checking Consistency of Database Column Data Types

July 19, 2015

Working on a database project, I noticed that column data types where not specified consistently.

For example, one table might have a column “Name” specified as nvarchar(50), and another one as nvarchar(100). Or a column “Description” specified nvarchar(500) in one table, and nvarchar(max) in others.

To find the inconsistencies, I wrote a script which finds inconsistently typed table columns, and then writes out the column specifications:

with cte as (
  select, tname, c.max_length, count(*) C
  from sys.columns c
  inner join sys.objects o on o.object_id = c.object_id
  inner join sys.types t on c.user_type_id = t.user_type_id
  where o.type = 'U'
  and not in ('sysdiagrams', 'dtproperties')
  group by,, c.max_length

The first CTE retrieves all unique combinations of column names and type specifications

, cols as (
  select name from cte
  group by name
  having count(*) > 1

The second CTE, which operates on the result of the first CTE, filters out the column names with different type specifications

select,, tname,
    when = 'nvarchar' and c.max_length = -1 then null
    when = 'nvarchar' then c.max_length / 2
    when = 'varchar' then c.max_length 
    else null
  end max_length
from sys.columns c
inner join cols on =
inner join sys.objects o on o.object_id = c.object_id
inner join sys.types t on c.user_type_id = t.user_type_id
where o.type = 'U'
and not in ('sysdiagrams', 'dtproperties')
order by,

And finally, we select all table names and column specifications along with their effective data type length.

Note that we need to explicitly exclude the built-in tables “sysdiagrams” and “dtproperties”.

Compile-Safe Links in ASP.Net MVC

June 11, 2015

One of the drawbacks of the Html.ActionLink() method is that it accepts controller and action as strings. As a consequence, there no compile-time check is performed to ensure that the referenced action is actually implemented. This also applies to Html.BeginForm(), Url.Action() and similar methods.

Recently I found an alternative extension method on SO which accepts the controller class and a controller method as parameters, rather than their names as strings:

public static MvcHtmlString ActionLink<TController>(
    this HtmlHelper htmlHelper,
    Expression<Action<TController>> expression, 
    string linkText, 
    object routeValues, 
    object htmlAttributes) where TController : Controller
    var urlHelper = 
        new UrlHelper(htmlHelper.ViewContext.RequestContext, 

    var attributes = AnonymousObjectToKeyValue(htmlAttributes);

    var link = new TagBuilder("a");

    string actionName = ExpressionHelper.GetExpressionText(expression);
    string controllerName = 
        typeof(TController).Name.Replace("Controller", "");

        urlHelper.Action(actionName, controllerName, routeValues));
    link.MergeAttributes(attributes, true);

    return new MvcHtmlString(link.ToString());

private static Dictionary<string, object> AnonymousObjectToKeyValue(
    object anonymousObject)
    var dictionary = new Dictionary<string, object>();
    if (anonymousObject == null) return dictionary;
    foreach (PropertyDescriptor propertyDescriptor in 
    return dictionary;

Personally, I prefer the single-action controller approach, as sketched here, or here, for example, where each action is implemented by a separate controller class. The meaning of the ActionLink() parameters changes such that the controllerName parameter is really a sub-namespace, and actionName is the controller class name.

Then we can simply extract the last part of the namespace and the class name of the controller class name, and pass everything else to MVC’s Html.ActionLink():

public static MvcHtmlString ActionLink<C>(this HtmlHelper htmlHelper, 
    string linkText, 
    object routeValues = null, 
    object htmlAttributes = null) where C: BaseController
    if (string.IsNullOrEmpty(linkText))
        return new MvcHtmlString("");

    var rgs = typeof(C).FullName.Split('.');
    return htmlHelper.ActionLink(linkText, 
        rgs[rgs.Length - 1].Replace("Controller", ""), 
        rgs[rgs.Length - 2], 
        routeValues, htmlAttributes);


No Language Bar in Windows 7 Home Premium

April 2, 2015

If you add keyboard layouts in Windows 7 Pro, the Language Bar shows up in the Taskbar, after you enabled it in the language bar settings dialog.

However, I found that Home Premium does not automatically the language bar, even if all the required checkboxes are checked.

The first hint I found that partly fixed the situation was to manually start (Start|Run) the program ctfmon.exe.

Annoyingly, the tiny buttons in the language bar allow you to accidentally close it, and there is no straight-forward way to bring it back.

Changing the settings to disable the symbols

Language Bar settings

Language Bar settings

and adding ctfmon.exe to system start as sketched here finally solved the problem:

  • start regedit
  • navigate to
  • add string key named “ctfmon”
  • set its value to “C:\Windows\system32\ctfmon.exe”


Compiled Spam

March 12, 2015

We encountered the unprocessed spam template nearly 2 years ago.

And now there’s the compiled processed spam comment, which seems to include every spam comment ever posted in just 1 comment. Hooray!

I’m excited to uncover this great site. I want to to thank you
for your time due to this wonderful read!! I definitely appreciated every little bit of it and i also have you saved as a favorite to look at
new stuff in your site.

May I simply say what a comfort to find somebody that genuinely
knows what they’re discussing on the web.
You certainly know how to bring a problem to light and make it important.
More and more people really need to check this out and understand this side of the story.
I was surprised that you’re not more popular since
you most certainly possess the gift.

Excellent post. I absolutely appreciate this site.
Continue the good work!

It’s hard to find knowledgeable people on this topic, however, you seem like you know what you’re talking
about! Thanks

You should take part in a contest for one of the best sites on the internet.
I will highly recommend this blog!

An intriguing discussion is worth comment. There’s no doubt that that you should write more
about this issue, it might not be a taboo matter but generally people do
not discuss these subjects. To the next! Cheers!!

Hello there! I just want to offer you a huge thumbs up for your excellent
information you’ve got here on this post. I will be coming back to your web site for more soon.

After I initially left a comment I seem to have
clicked on the -Notify me when new comments are added- checkbox and now
whenever a comment is added I get four emails with the exact same
comment. Is there an easy method you are able
to remove me from that service? Cheers!

Next time I read a blog, Hopefully it does not disappoint me as much as
this one. After all, Yes, it was my choice to read, nonetheless I genuinely thought you’d have
something helpful to say. All I hear is a bunch of moaning about something you could fix if you weren’t too busy seeking

Spot on with this write-up, I absolutely believe this
website needs a lot more attention. I’ll probably be back again to see more, thanks for the

You’re so awesome! I do not think I’ve read through
something like that before. So good to discover somebody with some
unique thoughts on this subject. Seriously.. thanks for starting this up.
This website is one thing that is needed on the internet, someone with a little originality!

I love reading through an article that can make men and women think.

Also, many thanks for permitting me to comment!

This is the perfect blog for everyone who wishes to
understand this topic. You realize so much its almost tough to argue with you (not that I actually would want to…HaHa).

You certainly put a new spin on a subject that’s been discussed for ages.
Wonderful stuff, just great!

Aw, this was an exceptionally good post. Taking a few minutes and actual effort to create a great article… but what can I say… I put things off a whole
lot and never seem to get nearly anything done.

I’m impressed, I must say. Seldom do I encounter a blog
that’s both educative and entertaining, and without a
doubt, you’ve hit the nail on the head. The problem is something that too few folks are
speaking intelligently about. Now i’m very happy I came across this in my
search for something regarding this.

Oh my goodness! Amazing article dude! Thanks, However I am experiencing issues with your RSS.

I don’t understand why I cannot join it. Is there anyone else
having similar RSS problems? Anyone that knows the answer can you
kindly respond? Thanx!!

An outstanding share! I’ve just forwarded this onto a friend who was conducting
a little research on this. And he actually ordered me lunch
simply because I discovered it for him… lol. So let me reword this….

Thank YOU for the meal!! But yeah, thanx for spending time to talk about this matter here on your website.

After looking into a handful of the articles on your web site,
I honestly like your technique of blogging. I saved
as a favorite it to my bookmark website list and will be checking back in the
near future. Take a look at my web site too and tell me what you think.

This site truly has all of the info I wanted concerning this subject and didn’t know who to ask.

There’s certainly a lot to know about this subject.

I really like all of the points you made.

You have made some good points there. I looked on the web for additional information about the issue and found most people
will go along with your views on this website.

Nice post. I learn something totally new and challenging on blogs I stumbleupon on a daily basis.
It will always be helpful to read through articles from other writers and practice something from other websites.

I blog often and I genuinely appreciate your content. This article has really peaked my interest.
I’m going to book mark your blog and keep checking for new details about once a week.
I opted in for your Feed as well.

Pretty! This has been an incredibly wonderful post.
Thanks for supplying these details.

Greetings! Very useful advice in this particular post!

It’s the little changes which will make the biggest changes.
Many thanks for sharing!

Howdy! This blog post could not be written any better!

Looking through this article reminds me of my previous roommate!
He always kept talking about this. I will send this information to him.

Fairly certain he will have a great read. Thanks for sharing!

Howdy, I think your site could be having web
browser compatibility issues. Whenever I look at your web site in Safari,
it looks fine however, when opening in Internet Explorer, it has some overlapping issues.
I merely wanted to give you a quick heads up! Apart from that, wonderful website!

Having read this I thought it was really informative.
I appreciate you taking the time and effort to put this content together.
I once again find myself personally spending a significant amount of time both reading and commenting.

But so what, it was still worth it!

Hi there! I could have sworn I’ve visited this site before but after browsing through many of the posts I realized it’s new to me.
Anyhow, I’m definitely happy I stumbled upon it and I’ll be bookmarking it and checking
back regularly!

I want to to thank you for this very good read!! I certainly
loved every little bit of it. I’ve got you book-marked to look at
new stuff you post…

Hi, I do believe this is an excellent site. I stumbledupon it ;) I am going to return yet again since i have book-marked it.
Money and freedom is the greatest way to change, may you be rich and continue to help others.

Your style is unique compared to other people I’ve read stuff from.
Many thanks for posting when you’ve got the opportunity,
Guess I will just book mark this web site.

I used to be able to find good advice from your blog posts.

Very good post! We will be linking to this great post on our website.

Keep up the good writing.

That is a very good tip particularly to those fresh to the blogosphere.
Simple but very accurate info… Many thanks for sharing
this one. A must read article!

I could not refrain from commenting. Perfectly written!

bookmarked!!, I really like your website!

Very good article. I am experiencing a few of these issues as well..

Way cool! Some very valid points! I appreciate you writing this write-up plus
the rest of the website is very good.

Great web site you have got here.. It’s hard to find
good quality writing like yours these days. I really appreciate people
like you! Take care!!

This is a topic that’s near to my heart…
Cheers! Exactly where are your contact details though?

I truly love your website.. Pleasant colors & theme.
Did you create this site yourself? Please reply back as I’m
attempting to create my own personal site and want to know where you
got this from or just what the theme is named.

Appreciate it!

I really like it when people get together and share thoughts.
Great website, stick with it!

Very good info. Lucky me I recently found your blog by chance (stumbleupon).
I’ve book-marked it for later!

This blog was… how do you say it? Relevant!!
Finally I’ve found something that helped me. Appreciate it!

Everything is very open with a clear clarification of the
challenges. It was really informative. Your site is
very useful. Many thanks for sharing!

I would like to thank you for the efforts you’ve put in penning this blog.
I am hoping to see the same high-grade content from you in the
future as well. In fact, your creative writing abilities has
motivated me to get my own, personal site now

Avoiding repetitive code using Actions and Funcs

March 12, 2015

Some coding guidelines require that functions follow a pre-defined scheme, such as

  • log function begin
  • execute function
  • log function end
  • exception handler
  • log exception

to name just the simplest structure.

Since repetitive code is prone to errors, it’s a good idea to encapsulate these steps in a method which in turn calls the “execute function” step.

An example from an MVC project:

public ActionResult Method() {
  logger.Info("begin method");

  try {
    var user = CurrentUser();
    var data = DoSomething(user);
    logger.Info("end method");
    return View("View", data);
  catch (Exception ex) {
    logger.Error("method exception", ex);

We can now extract most of the code into a common method

protected ActionResult Execute(string actionName, 
  Func<User, ActionResult> action) {
  logger.Info("begin " + actionName);

  try {
    var user = CurrentUser();
    var result = action(user);
    logger.Info("end " + actionName);
    return result;
  catch (Exception ex) {
    logger.Error(actionName, ex);

so that the original method can be reduced to

public ActionResult Method() {
  return Execute("method", (user) =>
    var data = DoSomething(user);
    return View("View", data);

Deploying ASP.Net MVC 5 on Windows Server 2008

December 5, 2014

Developing an MVC application in Visual Studio 2013 (Update 3), I needed to install a demo on a Windows 2008 server.

Since Server 2008 ships with .Net 3, we first need to install .Net 4.5.1, either from the Visual Studio download page, or from MSDN.

After the required reboot and setting up a web application in IIS, browsing to the new site resulted in HTTP errors 403 (refers to directory browsing) and 404 (when navigating to a specific controller action).

Luckily, this issue could be solved by re-adding <modules> to the <system.webServer> section (found on SO):

    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" 
        preCondition="" />

After editing the web.config, the web application could be accessed, but all CSS and JavaScript requests, which are served using Bundling and Minification, would result in a 404.

Again, another module wanted to be included

      <remove name="BundleModule" />
      <add name="BundleModule" type="System.Web.Optimization.BundleModule" />

Finally, the web application looked as expected, so I logged in, and

No owin.Environment item was found in the context.

The internets are full of helpful tips to add

<add key=”owin:AppStartup” value=”[Namespace].Startup, [AssemblyName]” />

but that did not change anything. What really solved that last problem was to add the attribute

<modules runAllManagedModulesForAllRequests="true" />

in web.config.

In the end, the web.config section looks like this

    <modules  runAllManagedModulesForAllRequests="true">
      <remove name="FormsAuthentication" />
      <remove name="UrlRoutingModule-4.0" />
      <add name="UrlRoutingModule-4.0"
          preCondition="" />
      <remove name="BundleModule" />
      <add name="BundleModule" 
          type="System.Web.Optimization.BundleModule" />

Remove Unused References with Visual Studio 2013

December 3, 2014

My favorite reference removal tool, Reference Assistant, only target Visual Studio 10 (2010) and 11 (2012), according to the description.

To install it in VS 2013, you need to follow the tips given on the Q&A tab of the assistant’s page on the Visual Studio Gallery:

So, the manifest file in this extension has a typo, which is why it wont install in VS2013. Change the vsix file to .zip, unzip it, edit the manifest file for the installationtargets from “[11.0,12.0)” to “[11.0,12.0]” and save it. Select all the files and zip it up. Rename the zip file to .vsix again and install.

If you follow those instructions literally,

  • rename the .vsix to .zip
  • unzip the .zip
  • edit the extension.vsixmanifest file
  • replace every instance of
InstallationTarget Version="[11.0,12.0)"


InstallationTarget Version="[11.0,12.0]"
  • save the file
  • zip all files
  • rename the .zip to .vsix

then the modified vsix can be installed in VS2013.

When I first tried it (by not following exactly), I simply dragged the .vsixmanifest file out of the .zip, edited it, and then moved it back into the .zip using Windows Explorer, I actually received the error message reported in the Q&A:

The file is not a valid VSIX package.
---> System.IO.FileFormatException: File contains corrupted data.

Good to have the tool in the latest version of VS as well ;)


Get every new post delivered to your Inbox.

Join 78 other followers