:::: MENU ::::

Monday, September 29, 2008

I was looking through some code the other day and ran across something that looked remotely familiar.  It was the null coalescing (??) operator.  I had read about this operator, but never used it.  It was introduced with the .NET 2.0 Framework.

The null coalescing operator basically checks to see if a value is null and if so returns an alternate value.  Below is a simple example.

C# Code Listing

using System;
 
namespace CoalesceTst
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "GabrielGray";
            string userName2 = null;
 
            string name = userName ?? "<no name>";
            string name2 = userName2 ?? "<no name>";
 
            Console.WriteLine(name);
            Console.WriteLine(name2);
        }
    }
}

 

Friday, September 26, 2008

The jQuery Javascript library has gotten a significant amount of attention from Microsoft developers this year in large part to its nice fit with the new ASP.NET MVC framework.  I myself was totally new to jQuery and I started using it with MVC because I wanted to see what the big deal was.  Sure enough, I became a true believer like many others.  And I found myself suddenly having "JavaScript envy" because I couldn't do all the cool jQuery stuff in traditional ASP.NET (i.e., non-MVC) web applications.

The good news is that it turns out, it really is a simple thing to do to incorporate jQuery into a traditional ASP.NET web app!  Let's take an example.  I recently had a client with a requirement that when the user first come to a screen they wanted all the text boxes to be disabled (basically a read-only view).  They then wanted to user to click an "Edit" button and all the text boxes suddenly become enabled.

So often the default mind-set of a traditional ASP.NET developer is to write some server-side C# code to do something like this:

   1:  private void ToggleControls(bool enabled)
   2:  {
   3:      TextBox1.Enabled = enabled;
   4:      TextBox2.Enabled = enabled;
   5:      TextBox3.Enabled = enabled;
   6:      TextBox4.Enabled = enabled;
   7:  }

But there are a couple of problems with this approach.  First off, if I have 30 text boxes on this screen, that is some pretty ugly code to write. Sure, I could loop through the page's Control collection and programmatically set all the TextBoxes appropriately but what if I have drop downs or checkboxes?  Other than writing some IF statements, there no true elegant way to do this.  Secondly, you have to question why you're going to make a round trip to the server to do this sort of thing.

So let's say we approach this by using the Microsoft AJAX JavaScript library. We can make our implementation better by eliminating the round-trip to the web server by keeping everything in JavaScript like this:

   1:   var controlsEnabled = true;
   2:   
   3:   function pageLoad() {
   4:       $addHandler($get("btnToggle"), "click", toggleControls);
   5:   }
   6:   
   7:   function toggleControls(eventElement) {
   8:       controlsEnabled = !controlsEnabled;
   9:       $get("TextBox1").disabled = controlsEnabled;
  10:       $get("TextBox2").disabled = controlsEnabled;
  11:       $get("TextBox3").disabled = controlsEnabled;
  12:       $get("TextBox4").disabled = controlsEnabled;
  13:   }

Although this is better because we've eliminated the extra trip to the server, we're still stuck with the same problem that if we have 30 text boxes (and dropdowns, etc.) we have potential to have to write some ugly (or at least repetitive and boring JavaScript).

Now with jQuery this all becomes much more elegant.  One of the most powerful features of jQuery is that it allows you to easily select elements based on all kinds of different complex criteria by using jQuery Selectors. If you follow the link for the jQuery Selectors, you'll see that the possibilities are endless in terms of selecting elements by a combination of id, attribute matches, etc., etc.

The primary problem is that BOTH jQuery and the Microsoft Javascript library using the $ symbol as the global variable alias to the library. Fortunately, jQuery provides a simple mechanism to easily rectify this with the jQuery.noConflict() function. Now that we can use the full power the jQuery Selectors, we can essentially implement what was 30 lines of Javascript code with the Microsoft library to simple 3-lines of jQuery code:

   1:  var $j = jQuery.noConflict();
   2:  var disabled = true;
   3:   
   4:  $j(function() {
   5:      $j('#btnToggle').click(function() {
   6:          var disabledValue = (disabled ? "disabled" : "");
   7:          $j(":text").attr("disabled", disabledValue);
   8:          disabled = !disabled;
   9:       });
  10:   });

We alias the $ to be $j for jQuery instead. Now we can leverage jQuery any way we please and it can peacefully co-exist with the Microsoft JavaScript library.

More

When it comes to proper usage of CSS and HTML layout, I have to admit I’ve been somewhat slow to get up to speed. Although I’ve been fully aware of what ‘you’re supposed to be doing’ it’s been quite a different story from  what I’ve actually been doing. Part of it is that a lot of the apps I work on are based on older code that didn’t pay close attention to CSS based layout and so it’s often hard to retrofit those apps. But slowly and gradually I’ve been drifting more to the ‘recommended’ approach to page layout with CSS isolation to style sheets and as little to no inline styling of any kind and of course have come to realize that this is a much better way to work.

I suspect there are more of you out there who are in the same boat especially if you’re using ASP.NET and Web forms. Web forms with its high level of abstraction doesn’t make it very easy to use pure CSS style layout. Controls have display properties that are just too easy to set on the controls themselves rather than setting them externally in styles and there’s no doubt doing it the right takes some diligence and is more work in the immediacy of creating pages. But there’s also no doubt that proper CSS layout makes it easier to maintain pages later and change the look of them as well as making it easier to reference content via script code.

There are also the ASP.NET CSS Control Adapters but they are a pretty intrusive change and I’ve actually had lots of issues just getting them installed on several machines.However, with a little bit of diligence even some of the badly rendering ASP.NET controls (especially the GridView) can be managed reasonably well with pure CSS layouts.

Those damn browser differences

One thing that I’ve been struggling with for a long time is browser differences even when using the strict XHTML schemas for layout. The XHTML doctypes are the first step for doing consistent layout as they force at least a reasonable baseline on all browsers (particularly IE) and force them to use certain rendering rules. But even with XHTML there are still major differences between different browsers and how they set their default settings for various CSS tags.

More

Wednesday, September 24, 2008

This is my first shot at creating add-ons for Firefox. This add-on can decode and show viewstate contents of an *.aspx page. Once you intall this add-on, it shows up a 'Show Viewstate' item in context menu of Firefox. When this menuitem is clicked, a popup comes up showing the viewstate details.

There are a couple of things I want to make clear here:

  • This add-on does NOT decrypt viewstate. It means it does not work on encrypted viewstate.
  • This add-on does NOT perform deserialization of viewstate. It was just designed to give a sneak-peek of whats in the viewstate. This information could be useful to developers and testers of web applications.

The contents of ViewState are serialized using 'LOSFormatter' which performs ASCII serialization and encodes the output using Base64 encoding. This add-on merely performs a Base64 decoding and shows the content of viewstate.

 

More

Friday, September 19, 2008

In Asp.Net apps, we are used to storing data in the current context.  Objects that are specific to the currently executing Request, like a User object retrieved a database, or another object that you want to make globally available without requiring multiple database trips, can benefit from this.

But what about this situation in non-web applications?  Or what about situations like an assembly that needs to have this contextual caching logic coded into it, but needs to be used from both web and non-web applications?

Below is an example of a static property that stores a User object, which is retrieved from a database, in the current HttpContext.  If it is already available in Context, it simply returns it.

image

 

What will happen if this property is accessed from a non-Asp.Net application, such as a windows service?  HttpContext.Current will return null, and we will get an exception.

We could simply store a static field in this class and access that if HttpContext.Current is null. But if that application has more than one thread, such as a Windows Service that is hosting a WCF Service, the static field will be shared across all threads.

Right?

Right - Unless we add the [System.Threading.ThreadStaticAttribute] to it!

Below is the updated property that will work in both kinds of applications:

 

image

There you go - a property access to contextual variable that caches for the length of the current thread, and isolated to the current thread.

Awesome!

More

Monday, September 15, 2008

For a better user experience you would your users to see please wait message while browser render the page completely. Here is the one solution to the same problem. Let's create a master page called Site.master and a web content form as demo.aspx.

   1:  Loading Demo

 

Demo.aspx is the web content form which fetches data from a database.

   1:  <!-- Code to fetch data from a database -->

To show loading message add following code to the code behind of master file Site.master.cs

   1:   
   2:  protected override void OnLoad(EventArgs e) 
   3:  { 
   4:  if (!IsPostBack) 
   5:  { 
   6:  Response.Buffer = false;
   7:  Response.Write("
   8:  <div style="top: 2px; left: 2px; width: 83px; height: 19px; text-align: right; background-color: orange">
   9:  Please wait...
  10:  </div>
  11:  "); 
  12:  Response.Flush(); 
  13:  } 
  14:  base.OnLoad(e); 
  15:  } 
  16:  protected override void Render(HtmlTextWriter writer) 
  17:  { 
  18:  if (!IsPostBack) 
  19:  { 
  20:  Response.Clear(); 
  21:  Response.ClearContent();
  22:  } 
  23:  base.Render(writer); 
  24:  } 

in the Site.master.aspx file add following javascript at the end of the file.

   1:   
   2:  try{
   3:  var divLoadingMessage = document.getElementById("divLoadingMsg");
   4:  if (divLoadingMessage != null && typeof(divLoadingMessage) != 'undefined') 
   5:  { 
   6:  divLoadingMessage.style.display="none"; 
   7:  divLoadingMessage.parentNode.removeChild(divLoadingMessage); 
   8:  } 
   9:  }
  10:  catch(e){} 

That's it now all your pages using Site.master will be showing Please wait.. message when the page starts loading. Of course instead of putting a message you can put a nice web2.0 loading image in between divLoadingMsg tags.

So how does this works? The onLoad event of master page will be called before any of the content web form's Onload event. as soon as master page loads div tag becomes visible. After the page has loaded completely the script written at the end of the master page hides the div tag. so simple isnt't it.Hope this helps!

More

Tuesday, September 9, 2008

Earlier this year I posted a port of the CSS minifier from YUI Compressor, Yahoo's java-based library that reduces CSS and JavaScript resources with a measurable advantage over other similar tools. I made plans to port the JavaScript compressor as well, which is known for its ability to rename inner function variables, but could not find the time, as the task would involve porting the entire JavaScript parser used to decompile the JavaScript and perform the refactoring.

Thanks to Justin Adler, the entire YUI Compressor is now available as an open source, native C# project! Justin has leveraged the ECMAScript.NET project to bridge the parser gap, and bring YUI's JavaScript compression to .NET. He has also tossed in full MSBUILD support for those who prefer static over dynamic script compression. If you're looking for the best resource minification in your next project, check out Justin's YUI Compressor for .NET on CodePlex.