Posts Tagged ‘asp dotnet’

Taking stock of my thoughts on ASP .NET and the alternatives

If you’re an ASP .NET developer (Webforms or MVC) and haven’t picked up on the recent undercurrent of negative sentiment towards the Microsoft development platform then I’m not sure where you’ve been. In any case, welcome back. To fill you in, there have been a number of developers who have raised various concerns about the efficiency of an ASP .NET web developer, and how as a group, they compare to those developing with other languages (such as Ruby) and frameworks (such as Rails). I thought I would add my thoughts to the conversation.

I want to be as objective as possible about my thoughts so as to add value to the discussion, but I guess I need to confess that my development experience is heavily weighted to the .NET platform. Over the years I’ve developed web, mobile and desktop applications using various languages, platforms and frameworks. That said, by far, I am most proficient in C#.

Firstly, I think it is important to note that it is somewhat difficult to accurately compare development contexts. It’s easy to confuse platforms, frameworks and languages. I once overlooked a developer typing this into Google:

Say what?

Huh?

What makes Ruby on Rails so popular? Can we attribute its success to the language (Ruby) or the framework (Rails) or both? Some people may say that what makes developing using Rails so awesome is Ruby itself. Others may say it’s the framework, in which case the same developers could be as efficient on other similar frameworks such as CakePHP. If I had to venture a guess, I think that most experienced developers would go with option 3. It’s the entire ecosystem that makes Ruby and Rails so popular, as much as it’s the .NET ecosystem that makes ASP .NET a popular option as well. This makes it difficult to compare aspects of each.

I have never had the opportunity to develop an application using Ruby on Rails but I think I have enough experience on various other web platforms to raise the following point. No single language or framework defines a developer, especially a web developer. Right now, most of the applications I develop are web applications and this means I need to be fairly proficient at a number of languages, not just C# ( HTML/XHTML, CSS, JavaScript and SQL to name a few). When it comes to assessing efficiency of developing on a platform, we need to address all of these aspects. Sure, Rails addresses the SQL aspect (Active Record) right off the bat, but how does a Rails developer approach HTML, CSS and JavaScript development? As web developers, we spend a lot time in our server side language of choice, developing code to dynamically output HTML. That said, a lot of time is also spent on the client side as well – designing, developing and debugging JavaScript. How does the Rails environment stack up in this department? We make use of Spark as our view engine on MVC projects, and I guess Rails developers use something as slick (or better?). I’m not saying Visual Studio offers a better story for developers, I’m just interested to hear more about the Rails context. From a server side perspective, what is the debugging experience like in Rails? I’ve used Eclipse and a few other popular IDE’s and I’m yet to find one that matches Visual Studio’s debugging capabilities. Within a minute, a developer can write some code, set a breakpoint and have the breakpoint hit within seconds. No drama. The real point I am trying to make is that there is far more to just the server side language, or the framework that impacts on the efficiency of a developer in the web context. There are a lot of other factors which include the IDE, view engine and development web server.

I mentioned earlier that I haven’t ever had the opportunity to develop a Ruby on Rails application. That said, I have started learning Ruby and have recently developed an application that routinely synchronises our Basecamp data with a local SQL Server database. I specifically wanted to learn Ruby out of the Rails context first. I was delighted that within a relatively short amount of time I had some functional code. It bodes well for my continued personal investment in Ruby. I took a crack at developing my Ruby application using NetBeans on Windows. While I enjoyed developing the code (and learning more about chunky bacon), I really didn’t enjoy the environment. Debugging was a pain in the ass and I resorted to debugging by logging. I hate this approach. I’m not sure if my experience is unique, and would really appreciate feedback from seasoned Ruby/Rails developers on this.

One of the topics that constantly repeats itself in these types of conversations is that .NET developers are stuck. They aren’t good at venturing out of their comfort zone and learning about new languages on other platforms. While this is a gross generalisation, I fear that the recent converts to Ruby from C# are right (for the most part). I think familiarity plays a key role in this and the problem does not only apply to developers using .NET. In the book The Pragmatic Programmer, Hunt and Thomas recommend that a developer should strive to learn a new language every year. I must say that when I read this, I was astounded. Every year? Thats crazy! Then I realised that not only is it possible, but they are right. You see, developing on a single platform using the same language and framework, year in and year out has some advantages, but in general, your solutions to problems tend to take the general form of your environment. My recent foray into Ruby has proved this. Your mind becomes boxed into approaching problems in a single way where there may be another number of better solutions that expose themselves wonderfully when you are forced into a different pattern of programming. All in all, I would say that even though I haven’t been using Ruby for long, I’m a better C# developer for it. Note, that I am not suggesting that Ruby itself was the reason, you could replace Ruby with Python in the paragraph above and I believe the same would hold true.

When it comes to comparing .NET (and Microsoft solutions generally) to alternative free and open source solutions, cost and licensing are often cited as reasons to migrate away from the Microsoft platform. This seems to be an important part of the discussion. The argument that always seems to be tossed around is that as a startup, you don’t want to have sink your limited cash into technologies when the alternatives are free. I think this argument is flawed for a few reasons. If you have no experience using the alternative language, framework and platform then the comparison between cost only makes sense if your time is free. Lets face it, in the startup world, your time is not free. Whether being first to market is important or the fact that you only have a small window of opportunity where you can sustain yourself in the back of your garage, you will want to focus on getting your application deployed as soon as possible. Having to sit and learn something new and foreign when you should be focusing on building your app seems to be a weird approach to me, especially considering the factors described above. Even if you could get up to speed with the new language/framework/platform relatively quickly, once you have your application up and running for the world to see and use, you will have no experience dealing with runtime operational issues that usually crop up as people start using your app. Even when you have experience on certain platform, dealing with edge case operational issues can be tricky. In an ideal world, time wouldn’t be a factor. You could perform a systematic analysis on all languages, frameworks and platforms and assess the pros and cons of each. Unfortunately, I doubt anyone has the luxury of doing this.

So given that it makes sense to build your app using technologies familiar to you, what are you in for? Microsoft haters will most certainly start quoting licensing costs for SQL Server Enterprise Edition, Windows Server Enterprise Edition and how the costs will sink you in a month (or less). Again, I think one needs to look at licensing objectively. I just deployed an environment with 4 servers.

  • 1 x load balancer running Nginx on Ubuntu
  • 2 x web servers running Windows Server 2008 Web Edition
  • 1 x database server running Windows Server 2008 Web Edition and SQL Server 2008 Web Edition

Hosting environment

In terms of costing for bandwidth, hardware, offsite backup etc., the licensing costs associated with the Microsoft operating systems and servers accounted for just 6% of the monthly cost. I would hardly call that prohibitive. Sure, if I had to use the Enterprise (or even Standard edition) versions of the software, the costs increase quite dramatically. That said, I don’t see why a web startup would require these versions. In any event, if you want to compare apples with apples, then one should consider that the enterprise version of MySQL is not free. At this point, NoSQL fans will probably be butting their heads against a wall muttering that neither SQL Server or MySQL are good options. That’s fine. Use what works. The likes of MongoDB, CouchDB and RavenDB are available on the Windows platform (the latter developed in C# exclusively for the platform).

What about Visual Studio? Isn’t it quite expensive? Well, unfortunately, yes it is. That said, I think the one thing people don’t mention when discussing the cost of Visual Studio is what you are actually paying for. Have a look here. The Professional Edition with MSDN Essntials ($799) unlocks the following software for you:

  • Visual Studio 2010 Professional
  • Windows 7 *
  • Windows Server 2008 *
  • SQL Server 2008 *

* Per-user license allows unlimited installations and use for designing, developing, testing, and demonstrating applications.

So for essentially $800, you should be sorted for all the development software you will need to develop, test and demonstrate your application. It’s not free, but the deal isn’t too bad either.

This post is getting a bit long so I’m going to end here by saying this. While I’m a proficient C# developer, there is no reason why I should not dedicate time to learning about alternative languages, frameworks and platforms. It’s only going to make me a better developer, whether I stick to the Microsoft platform or not.

Custom tooltips and Microsoft’s chart control

I have been meaning to blog about this topic for a while now because I am interested to find out if anyone else has picked up performance issues when using the Microsoft Chart Controls and the “MapAreaAttributes” property to create custom tooltips.

Before going into the mechanics of creating a custom tooltip as suggested by the documentation provided with the charting framework, I thought I would simply outline how you would create an instance of the default styled tooltip:

1 series.Points.DataBind(data,“X”,“Y”,“Tooltip=MyTooltipProperty”);

 

The code above illustrates the databinding capabilities of the charting control. The data array is made up of a list of objects that are of type Point which is a simple class I created:

    1     public class Point

    2     {

    3         public double X {get;set;}

    4         public double Y { get; set; }

    5 

    6         public string MyTooltipProperty { get; set; }

    7 

    8         public Point()

    9         {

   10             this.MyTooltipProperty = “Hello!”;

   11         }

   12     }

 

From the above it is obvious that each data point’s tooltip will look like something like this:

Normal tooltip

 

 

 

 

 

 

 

The tooltip is simply rendered using the relevant browser’s default implementation for elements.

Custom Tooltips:

You may be aware of the charting framework’s capability for creating rich HTML tooltips using the MapAreaAttributes property. As illustrated in an example provided with the framework you could create an HTML tooltip using code similar to that shown below:

series.Points[j].MapAreaAttributes = “onmouseover=\”DisplayToolTip(‘<strong>Hello From an HTML tooltip</strong>’);\” onmouseout=\”HideTooltip();\””

 

The DisplayTooltip method referenced is a JavaScript method which essentially displays an absolutely positioned element which tracks your mouse position. The method is fired as you hover over the data point area (which is defined by an image area map). The parameter passed to the method is injected into the element as HTML. As you mouse out of the area (the relevant data point) the Hidetooltip method fires and hides the element displaying the custom tooltip. Using this methodology your tooltip could look something like this:

 HTML tooltip

 

 

 

 

 

This looks promising because it illustrates the capability to extend our tooltips to include images, links etc. however, there is a caveat. I picked up an issue when you have a chart with a large number of data points, or a number of charts on a single page that utilise this feature. I started noticing that page loads took longer than usual. I put together a test page that rendered 40 instances of the same chart as shown above using the default tooltip. With tracing turned on the page took roughly 270ms to render:

 Default performance

 

 

 

 

 

 

 

 

 

By implementing one extra line of code to implement my rich HTML tooltip using the MapAreaAttributes property as outlined earlier, the page took almost 5 seconds to render!

 Poor performance

 

 

 

 

 

 

 

 

 

It turns out anyone who dares to use the MapAreaAttributes property is severely penalised! Clearly we can’t put a page into production that takes 5 seconds just to render our charts, so we either need to revert to our dull looking tooltips or look for other ways to achieve rich HTML tooltip functionality.

Now, we know that setting the tooltip property doesn’t seem to have any performance impact but that it doesn’t result in a pretty looking tooltip either, but what if we could use the tooltip property to store the HTML tooltip markup. I know what your thinking:

Ugly tooltip

 

 

 

 

 

Yuck. That will certainly have your users scratching their heads. So, what next? So far we know that using the example as provided by the charting documentation has an adverse affect on rendering times so that’s not ideal. Default tooltip styles work without performance issues but don’t allow us to render rich tooltips. Injecting HTML into the default tooltip property means our users need to slap on their XHTML goggles.

Well, there is an option available which I will outline here.  Essentially, it relies on the ability to interpret the default tooltip property and project it into a custom tooltip that we control. If we look at the HTML rendered by the chart control, you will notice an associated image map that looks something like this:

Image map

 

 

 

 

 

 

 

 

 

As you can see, our HTML tooltip detail is sitting inside the title property, encoded of course. If we leave the mark-up untouched and hover over any element on the chart, the default tooltip is rendered with unparsed HTML. Thankfully, we can access this image map using JavaScript to rebuild the image map with mouseover/out events to render our custom tooltip. While this is exactly what setting the MapAreaAttributes property is supposed to do, modifying the rendered HTML to do the same thing bypasses the performance issue noted. I have provided the JavaScript method below which rebuilds the image map. All that is required, from a server side scripting point of view, is the registration of a start-up script to process any chart you wish to load with custom tooltips.

    1 RebuildImageMap: function(id) {

    2     // Fetch the image and grab the imagemap ID

    3     var map = $(“#” + id).attr(“usemap”);

    4 

    5     // If the map ID is null, then perhaps there

    6     // were no datapoints. Don’t bother

    7     // processing an empty set

    8     if (map == null)

    9         return;

   10 

   11     // Fetch the map element using jQuery and

   12     // return the raw HTML element

   13     var areaMap = $(map)[0];

   14     if (areaMap == null) {

   15         return;

   16     }

   17 

   18     // Create an empty array to store our new elements

   19     var elementArray = [];

   20 

   21     // Iterate over existing map elements and create a new

   22     // set with our mouseover/out events

   23     for (var i = 0; i < areaMap.areas.length; i++) {

   24         var oldAreaElement = areaMap.areas[i];

   25         var element = document.createElement(“AREA”);

   26         element.shape = oldAreaElement.shape;

   27         element.coords = oldAreaElement.coords;

   28        

   29         element.tooltip = oldAreaElement.title;

   30         element.onmouseover =

   31             function() { DisplayTooltip(this.tooltip); };

   32         element.onmouseout =

   33             function() { HideTooltip(); };

   34         element.href = oldAreaElement.href;

   35         elementArray[elementArray.length] = element;

   36     }

   37     // Get rid of the old map elements

   38     areaMap.innerHTML = ;

   39 

   40     // Add our new elements back in

   41     for (var i = 0; i < elementArray.length; i++) {

   42         areaMap.appendChild(elementArray[i]);

   43     }

   44 

   45 }

 

The code above utilises jQuery which is useful, but not required to get the job done. If you are going to use another framework, just note that the map attribute (which contains the map’s ID) is prefixed with a #. You may want to get rid of that. The code above is a modified
snippet of an existing class. The DisplayTooltip method simply takes the tooltip HTML and loads it into a custom hidden element on the page. It then displays the element and tracks the mouse position so the element moves as the user’s cursor does. The HideTooltip method simply hides the tooltip and resets the HTML content. Using this technique, our HTML tooltip is rendered correctly without using the MapAreaAttributes  property.

 HTML tooltip

 

 

 

 

 

 

So far I have tested this method of rendering custom tooltips in Firefox, IE 7/8 and Chrome. Its a pity that this was required in the first place. I am really not sure why setting the MapAreaAttributes  property has such a huge impact on rendering times. If anyone could shed light on the matter, please feel free to post the detail! For now, the implementation above will suffice. Since the image map processing is performed on the client side, there is no effect on the server side processing time.

Hope this helps someone out there.

AJAX Control Toolkit Update

A new version of the AJAX Control Toolkit has been released and is now available. You can download it from here.

There are three new controls:


  1. HTMLEditor – essentially a WYSIWYG editor (similar to FCKEditor). Demo.
  2. ComboBox – combines the functionality of a TextBox and DropDownList control. Demo.
  3. ColorPicker – a control which generates a color swatch (in a popup) for users to pick a color from. Demo.

Find out more about the new release here.

Validation with confirmations in ASP .NET

In his book Designing The Obvious, Robert Hoekman makes a few good points regarding inline validation techniques. Validation is often neglected when building a web application and little or no time is spent improving validation to give the end-user a better experience when using online forms. Validation should not get in the way of people using your site or web application, it should be seamless. The most effective way to manage validation is to catch errors before they happen. This would seem obvious but many of us out there are guilty are not paying attention to validation. Supplying hints of expected content format or simply confirming to a user that he/she has entered the correct data goes a long way to ensuring that a user feels comfortable using your web application.

I am quickly going to show you how to implement a confirmation ‘tick’ using the built in ASP .NET validators in Visual Studio 2005. Assuming that you are using these validators and you expect your clients / users to be using a javascript enabled browser, you can use some simple javascript to implement confirmation ticks every time a user successfuly completes a field.

Validation Example

Using one of the fundamental principals of Ruby on Rails, ‘Convention over Configuration’ we need to set the ID of the tick image to the name of the Textbox + ‘_ValidatorOk’. So if our textbox ID is called ‘Field_Duration’ then our tick image ID is ‘Field_Duration_ValidatorOk’. We also need to set the display style attribute of the image to ‘none’ (style=’display:none’) by default so that the tick is hidden until valid data is entered.

We need to fire off some javascript when the onblur event of our textbox is fired. This javascript will fire the ASP .NET Validators which will let us know if the data is valid or not. If the data is valid we can display the tick. To do this, simply add an onblur event to the Textbox.

Example: <asp:Textbox id=”Field_Duration” runat=”server” Text=”” onblur=”FireCustomValidation(this);” />

Then include the javascript function ‘FireCustomValidation’ which will look something like this:

function FireCustomValidation(fldobj)
{
    if (typeof(Page_ClientValidate) == 'function') {
        var passed = true;
        for (i = 0; i < Page_Validators.length; i++) {
            if (Page_Validators[i].controltovalidate == fldobj.id) {
                ValidatorValidate(Page_Validators[i]);
                if (!Page_Validators[i].isvalid)
                    passed = false;
            }
        } 
        if (passed)
            document.getElementById(fldobj.id + 'ValidatorOk').style.display = '';
        else
            document.getElementById(fldobj.id + 'ValidatorOk').style.display = 'none'; 
   }
}

Now, when the user completes and leaves a field, the function above will execute. The function uses the Client API for the ASP .NET validators (see here). If Client Side Validation is not supported then the function does nothing. Otherwise it iterates through each validator on the page looking for ones that match the field just completed. When found, their respective validation functions are fired. The ‘isvalid’ attribute is then checked, if any of the validators return false then the tick is hidden, if all pass then the tick is shown. You could write some extra code to stop errors occuring if the ‘tick’ object does not exist.

You could include this script in a javascript file that is included in your master page. Using this technique, users feel more confident as they complete your webform. There is a lot more you could do with this code, such as highlight the entire table row when an error occurs.

Hope you found this useful.