Monday, December 10, 2012

Setting a "Content-Disposition" HTTP Header in Web API Controller Method

When developing an ASP.NET Web API controller method that allows to download a file it is considered a good practice to set a "Content-Disposition" header to guide a browser of a name of a file being downloaded.

There are two different ways to approach this simple task. First is to add a new HTTP header to the HTTP response using string values for the header's name and value. The second is to try and use the .NET framework's infrastructure methods that presumably should make this task easier.

The first method seems to be very simple but potentially dangerous: one would need to hard-code string values and be totally responsible for the values to be properly formatted according to the W3C standards.

The second method is to try and delegate handling of the specifics of the HTTP protocol to the .NET framework by using corresponding presumably built-in methods. This seems more appropriate and even easier to achieve. However due to poor documentation of the Web API extensions that is easier said than done. without further ado this is how it's done:

Only one string value here should hard-coded with a guideline available in the official documentation so it's not that bad.

If you find this information possible share it with your fellow colleagues so it may save their valuable time.

Tuesday, February 21, 2012

Fixing 'Bootmgr is missing' problem on Windows 7

The reason for this post is that it took me three hours on the weekend to fix this problem and based on the amount of search results the Google returns for that keywords I figured there are a lot of people facing such a problem. So my goal is to provide with a simple explanation and easy fix to save one's time and may be even prevent this problem from happening.

Let's start first from understanding what exactly is the problem. Secondly we see how to fix it and lastly we discuss the scenarios that could cause such a problem.

The problem

When one tries to boot up a computer with Windows 7 OS on it and instead sees a black screen with a message "Bootmgr is missing - Press CTRL+ALT+DEL to restart". (I guess it's obvious that restarting will not fix the problem)

There is an important condition for the fix described in this article: the computer was booting before but after some changes this error occurred. If this is not the case than the solution might not be applicable but from another hand it would not hurt to read further.

So what exactly is the problem? The answer is easy: it's right in the message. Windows is looking for a file with a name "bootmgr" and cannot find it. This is a hidden file of a size about 320Kb that should reside in the root of a boot partition on a hard drive where the Windows OS is installed. We will discuss the reasons why it's missing later but now since we know what the problem is how can it be fixed?

The fix

Copy the bootmgr file from the source to the root of the boot Windows partition on hard drive. An XCOPY command can be used with an /h switch that allows copying hidden and system files. For example:
X:/>xcopy bootmgr C:\ /h

Where to find the bootmgr file?

This is an important question. The answer depends on a particular computer's configuration but based on the problem statistics let's just mention the most probable locations to search for the file (don't forget it's hidden):
  • Root of another hard drive with Windows 7 on it
  • Root of another partition on the same hard drive with Windows 7 on it
  • Windows 7 installation DVD
Once you figure the location of the bootmgr file simply copy it over to a boot partition and restart the computer: it should be able to boot in windows successfully this time and you are done.

The possible causes of the problem

In my case and based on the Internet search results that seems to be a very popular cause I have installed a second hard drive in the computer and then installed Windows 7 on a new hard drive. The key here is that Windows installer did not copy the bootmgr file on a new hard drive because it already existed on an old hard drive. The same problem would have happened if Windows was installed on a new partition on the same hard drive where another Windows installation present. These two reasons cover over 80% of the problem occurrences with some variations around different versions of Windows that existed at the moment of a new Windows installation and dual-boot related problem with the same outcome.

Another set of reasons relate to hardware problems with hard drives and not covered in this post for an obvious reason that the only solution for that is to replace a hard drive and reinstall Windows.

Prevention

Apparently the only proper way of installing Windows is first to hide a hard drive or a partition with another Windows installation and once a new Windows is installed make it visible again. Unfortunately to the best of my knowledge that is not mentioned in the installation instruction.

Advanced technical details

For those who would like to dig a bit deeper I suggest to boot into a Windows Recovery environment (F8 for Windows boot advanced options), open a command line prompt and use a bcdedit utility to explore the BCD (boot configuration database) content to see where Windows looks for the bootmgr file.

Conclusion

Once the cause of the problem is understood the fix is easy however the search for the cause has been significantly slowed down by an amount of misinformation that Google search returned.

Saturday, November 5, 2011

Using Anonymous Types Outside of Local Context with Dynamic Keyword

Anonymous types that have been introduced in C# with .NET 3.5 is a convenient and powerful feature and can be used to simplify and speed up development without sacrificing code quality or violating coding standards. Perhaps one most widely known application is to use anonymous types in a context of LINQ expressions since that is mentioned on MSDN in most of the anonymous types related examples. Such strong association between anonymous types and LINQ though being true creates a wrong impression of that LINQ is the only application for anonymous types an perhaps discourages many developers from discovering many other ways of utilizing anonymous types. For example, I could mention returning anonymous type object from a JSON enabled ASP.NET Web, WCF or MVC service method which is extremely beneficial due to anonymous types being very lightweight and readily JSON serializable. However that is a topic for another article.

When considering their applicability anonymous types frequently declined to be used due to their local scope visibility that is usually considered an unbreakable obstacle. What that means is an anonymous type object can only be used inside a code scope where it was defined with the largest scope being a method scope. In other words an anonymous type object cannot be used as a strongly typed object outside of its scope of visibility since its type does not exist in an outer scope from the compiler point of view. For example, if an anonymous object returned from a method it can only be seen and used as a base C# object type which makes it totally useless from a conventional point of view since its properties and their values are not accessible. Compiler will throw an error on any attempt to cast an anonymous type object to any other type. Based on the above the obvious conclusion would be to not continue down this road and consider the topic closed. That is however not true.

With another powerful feature introduced in C# by .NET 4 called dynamic types anonymous types are given even more reasons to be used since they now can be used outside of their scope of visibility. Sounds fantastic? Let me show you how it's done.

Let's consider a usual scenario when there is a long list of complex objects that is used as a data source and we need to select several objects from that list and display some of their properties. Old school approach would be to define a POCO type that consists of properties to display, iterate through the original list and build a new list of POCO objects populated from the data source properties and then bind that list of POCO objects to a visual control that displays the output. Nothing is wrong with that except that a new POCO type must be defined even if it's not going to be reused anywhere else. That requires additional coding and future maintenance if the content that should be displayed changes. With anonymous types we can avoid creating a POCO type by using an anonymous type instead and providing a list of anonymous objects as a data source for the visual control. That will work just fine as long as no additional data processing is required against the list of the anonymous objects. Often however it is required to perform some additional processing against a newly build data source which is now a list or anonymous objects and this is where the problem occurs: it is not possible to access properties of an anonymous object outside of a method where this object was created. Is it true though?

A dynamic keyword allows to overcome this problem as it instructs compiler to not perform a compile time type check and leave that to the run-time environment. As such we can write a C# code that operates with an anonymous object as it was a strongly typed object. See the code example below:

I assume comments are not required for the example as it speaks for itself. Just try and use this cool technique in your next project and see how much time and headache you'll save.

Just to reiterate: anonymous types is a powerful feature that helps create cleaner and better code however it has some limitations. Using a dynamic keyword allows to overcome limitations of the anonymous types.

Tuesday, July 12, 2011

Using jQuery to Consume ASP.NET MVC JSON Services

Introduction

Since the inception of ASP.NET Web Services have been an important part of any professional web developer's tool set. Starting .NET 3.5 Web Services became even more useful as it became possible to call Web Services asynchronously from a browser using JavaScript and ASP.NET AJAX.

However for the last two years the alternative ASP.NET MVC framework has been drawing more and more attention from the development community due to its good implementation of the MVC design pattern and adherence to web standards and bleeding edge web technologies.

For many experienced ASP.NET developers accustomed to Web Services especially accompanied with ASP.NET AJAX framework a natural question occurs: how to implement similar approach with ASP.NET MVC framework and its natural JavaScript companion jQuery?

ASP.NET MVC JSON Services

First of all there is no concept of Web Services in ASP.NET MVC however it is very easy to implement its functional analog. Any Controller Action method that returns data rather than an HTML formatted page can be considered an analog of a Web Method and used correspondingly. From this point of view a set of Controller Action methods that return properly formatted JSON response I will call MVC JSON Services. Below is a simple example:

The code above when properly implemented should return a JSON representation of the data object and that is an illustration of how easy it is to implement an MVC JSON Service method.

Security

By default a JSON Service method will throw an exception when called by an HTTP GET request. This behavior is in accordance with the behavior of a regular ASP.NET Web Service method that also would not accept a GET request. This is also considered a best practice to call a JSON Service method only by HTTP POST request. In order to implement that an [HttpPost] attribute should be applied to a JSON Service method. If you would like to learn more about security considerations read this post.

Another consideration is authentication/authorization. Similarly to any other Controller Action method an [Authorize] attribute applied to the JSON Service method controls that the method can only be called by an authenticated user with proper authorization (if required).

Now the corrected JSON Service method will look like this:

How to use jQuery to call an MVC JSON Service method

One of the most popular application for JSON Services is to call them from JavaScript asynchronously and then use returned data to update the HTML content. With regular ASP.NET and ASP.NET AJAX such an exercise would be easy to accomplish as all the necessary JavaScript code is automatically generated and referenced on the page. That convenience however comes with a price of bigger payload and longer loading time as many additional scripts must be referenced on a page.

In ASP.NET MVC natural JavaScript environment is jQuery library that has everything we need in order to accomplish our task. See the code example below:

We use a jQuery.ajax method to make an asynchronous POST request to our JSON Service method. Notice contentType and dataType properties that are responsible for identifying that we are requesting and expecting back JSON-formatted data. The url property defines the URL of our JSON Service method constructed based on standard ASP.NET MVC Routing rules. The value of the success parameter is a callback function name that will be called when the request completes successfully.

Input parameters

Rarely the Service methods are called without parameters. In case of one or two simple parameters we can rely on ASP.NET MVC Routing automatic parameters mapping feature that will automatically extract a parameter from the URL and then pass it to a Service method. Look at the example.

Let's assume we would like to call a JSON Service method with a single parameter "id" that is used to acquire our data object on the server side. First we'll have a corresponding routing rule defined in the global.asax.cs file:

Next we'll have a JSON Service method with a parameter:

When we call our JSON Service method using a URL like "JsonServices/MyJsonMethod/123456" the method will receive a string value "123456" as an id parameter automatically.

That was simple. Now what if we need to pass a complex object as a parameter and we cannot use URL? In this case we just pass a JSON literal as a string representing our complex parameter using a data property in the jQuery.ajax method:

Now we need to modify our JSON Service method in order to receive the parameter correctly.

We need to define a MyObject class as the following:

Notice that the class is marked with a [Serializable] attribute and names of the public properties match exactly the ones we used in a JSON parameter string in the jQuery.ajax function call. This is just enough for the ASP.NET MVC framework to do all the work behind the scene and provide our JSON Service method with the correct parameter value. It's easy to see a similarity between this asynchronous AJAX call and a regular form POST request with the only difference that a parameter on the client side is provided as a JSON literal string.

Consuming returned data

Our final goal is to receive a JSON-formatted piece of data that we'll be able to consume by JavaScript and we hope to minimize our efforts by fully exploiting abilities of the ASP.NET MVC framework and jQuery library. So far we've managed to make a request to a server-side JSON Service method and the next step is to consume the returned data. We have provided the onSuccess JavaScript function as a callback to the jQuery.ajax method and we should use it for all the data processing we want.

When the AJAX request completes the onSuccess function is called and receives a parameter data that is our expected result. data is already a regular JavaScript object that has been deserialized from a JSON string and we can use as intended. It fully corresponds to a server-side data object that we have returned from a JSON Service method. Notice that as opposed to a regular Web Service call with ASP.NET AJAX the returned object is not wrapped in a "d" property so there is no need for additional processing.

A word about DateTime

If a returned object contains a property of a DateTime type the MVC framework returns it in a specific form that requires some preliminary processing on the client side before can be consumed. A simple function below converts a value returned by the MVC framework into a standard JavaScript Date object:

Please read this post and do some Internet search to better understand the mechanics of DateTime value format transformation when returned in a JSON-formatted message.

Conclusion

In this article we have learned how to implement a JSON Services using ASP.NET MVC framework and how to call JSON Services methods asynchronously from JavaScript using jQuery library.