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.

Sunday, May 1, 2011

Fix for Bing Maps not working in Firefox 4+

UPDATE
Apparently that problem exists for Firefox 5 also and perhaps will apply for the future versions too. So the solution below should be considered a best practice for using Bing Maps 6.x with Firefox 4+.

Recently I've upgraded from Firefox 3.6 to Firefox 4 and while doing regression testing I've notice that apparently Bing Maps has some issues in Firefox 4. In particular I saw a JavaScript error that said "p_elSource.attachEvent is not a function":


The problem at this point looks like this:
  1. the error happens in Bing's JavaScript itself; and
  2. it only happens in Firefox 4 browser. Other browsers like IE 8 & 9, Chrome, Safari, Opera and Firefox 3.6 don't produce that problem.
Since the page where I saw an error belonged to a web application I've been working on I had to fix the problem. Initial search on the Internet did not bring up anything useful except that a few other people also stepped on this problem. I tried Bing Maps interactive SDK and it worked all right. That told me the Bing Maps script itself does work but it clearly depends on some other condition that does not necessarily happen on other pages like mine.

What's that condition? I looked at the difference between Firefox browser and the other browsers. When in Firefox Bing Maps dynamically loads another JavaScript file atlascompat.js. Apparently that file is required since it contains a definition for the attachEvent function that caused an error and must be loaded first before the main Bing Maps script. So that's the condition I've been looking for! Now the picture got clearer:
  1. the error happens in Bing's JavaScript itself; and
  2. it only happens in Firefox 4 browser. Other browsers like IE 8 & 9, Chrome, Safari, Opera and Firefox 3.6 don't produce that problem;
  3. it happens when the atlascompat.js is not present on a page at the moment when the main Bing Maps script is being loaded.
Now why the error is happening on my page and not on the Bing Maps SDK page? Apparently the conditions #3 is not satisfied since my page contains a whole bunch of other scripts and the atlascompat.js did not load before the main Bing Maps script due to internal differences that have been introduced in Firefox 4. Now I have a complete picture of the problem and can come up with a solution for it.

The solution is simple: since the Bing Maps itself cannot load the atlascompat.js reliably I need to help it and just add a reference to the atlascompat.js script on my page before a reference to the main Bing Maps script. This can be easily accomplished with a few line of code like below:



Notice that the browser version is more or equal 4 to cover the future versions of Firefox too (for version 5 this solution is confirmed). In my case I've added the code above into a GetScriptReferences method of an IScriptControl that was responsible for rendering the Bing Maps on a page.

Friday, February 11, 2011

.NET Reflector is becoming a paid-for product

As you may already have learned the famous .NET Reflector created by Lutz Roeder almost a decade ago that was always free to use is becoming a paid-for product thanks to Red Gate Software. The decision is confirming the worst suspicions many had when first heard about Lutz's agreement with the Red Gate and has already created a massive controversy in development communities.

For those who do not remember the .NET Reflector was born in the beginning of 2000s and has quickly become one of the must-have tool for every serious professional .NET developer. A large users community has quickly formed around the tool and many great add-ons have been written by inspired developers. Reflector has influenced great many developers' careers and earned community recognition. Scott Hanselman included the program in his "Ultimate Developer Tool List".

The Reflector's success was growing for over half a decade when out of a sudden the original author of .NET Reflector announced about his decision to stop developing the product and give it over to Red Gate Software in August 2008. One part of the agreement was that
...Red Gate will continue to provide the free community version... [of .NET Reflector]
confirmed by James Moore of Red Gate Software but many had skepticism about that part of the agreement from the very beginning.

During the period of Red Gate's ownership there were not many real improvements to the Reflector except for the annoying built-in "time-bomb" feature forcing one to upgrade to the newer version of the product even though the installed version worked perfectly. Some time ago a paid-for "Pro" version was announced with an obvious reason to raise some money for the owner but based on the Red Gate's plea was not successful among developers. One of the suggested explanations for that is that paid-for functionality was not really of any interest (more creativity, please, Red Gate) for professionals and beside there were already free add-ons doing similar things.

So now Red Gate wants to charge $35 for "a perpetual license, with no time bomb or forced updates" for the version 7 that will come out in early March and promises some new features in V7.

Red Gate claims that they need money to "keep .NET Reflector up-to-date and relevant" and cannot do that "without revenue coming in". That may be true for the Red Gate Software but there is a proven recipe for that: how about make the product open source, put it on Code Plex or any other similar location and let the community take care of its relevancy? To make it even more interesting let's make it a challenge: you, Red Gate, charge for your new shiny V7 but give away the previous version to the open source community and let's see which version survives in a few years. I personally have no doubts on the results.

There is a discussion going on about the Reflector's future on Red Gate's user forum. However if you are a professional developer that uses and loves Lutz Roeder's Reflector I encourage you to share your opinion and vote for the Reflector's future right here in my blog on the right side or answer polls on LinkedIn here and here. Please share the poll with your friends and colleagues.


UPDATE

Interesting list of open-source alternatives to Reflector on Stack Overflow: http://stackoverflow.com/questions/2425973/open-source-alternatives-to-reflector

To my taste the closest to .NET Reflector user experience is provided by the ILSpy. I am going to try and compare it with the Reflector.


Another UPDATE of May 1, 2011
Apparently free Reflector's lifespan is going to end on May 30, 2011. Today I've started my free copy and saw this alert:



UPDATE of May 31, 2011
Free version of Reflector is finally dead. Now those who does not want to switch to a paid version has to consider alternatives. A couple of new alternatives include:

JustDecompile

Telerik has recently released a beta version of their new JustDecompile, designed to enable easy .NET assembly browsing and decompiling. While Telerik is not know for free software, this product is featured as being free. According to Telerik, "Unlike Open Source alternatives, Telerik JustDecompile benefits from a dedicated development team, which is focused on continuously improving the product in line with your feedback. Telerik is recognized as one of the leading providers of .NET development tools and JustDecompile will benefit from our years of experience in the field."

dotPeek

JetBrains, an author of an extremely popular ReSharper Visual Studio add-in, has recently released a beta version of the dotPeek which is another new and free .NET decompiler with search features from JetBrains. dotPeek has gone public for the first time on Wednesday, May 11, as JetBrains opened an Early Access Program (EAP) that implied regular publishing of pre-release builds. According to JetBrains they are going to keep the product free.


Final Thought

JetBrain's dotPeek has become my tool of choice for the time being. It's functional, free and being updated frequently. For those who also uses JetBrain's ReSharper starting version 6 the dotPeek functionality is built-in and available through the Navigate/To Decompiled Source menu.