Stephen Sulzberger’s Blog

May 26, 2008

Use C# ?? null coalescing operator for parsing request query string parameters

Filed under: .net,asp.net,C#,Web development — Stephen @ 7:16 pm

I’m a big fan of succinct code, especially when it comes to satisfying requirements that are ultimately trivial but redundant. That being said, I think the following is the best way to parse query string parameters:

    string sParam = "t"; 
    string sResult = string.Empty; 

    sResult = (Request.QueryString[sParam] ?? "").Trim();

    if (sResult != "")
    {
      // Do something
    }

If the request string param is null, the string returns “”. If the request string param has a value, we snag it and Trim() to ensure that we get what we want and nothing else (this is important, especially since users can toy with the param values and send values with unexpected extra spaces). The idea here is to encapsulate as many “checks” into a simple, quick parse to ensure that you don’t have to back track and validate anything (insofar as handling null or empty data). Notice, also, that I use the Trim() method outside of the “coalescing” routine – this is because if the Request.QueryString[] call returned null, Trim() would throw an object reference exception.

Some other methods you might use for accomplishing the same thing:

Example 1

      string sParam = "t";
      string sResult = string.Empty;
      
      if ((Request.QueryString[sParam] != null) && (Request.QueryString[sParam].Trim() != ""))
      {
        sResult = Request.QueryString[sParam].Trim();
      }

      if (sResult != "")
      {
        // Do something
      }

Example 2

      string sParam = "t";
      string sResult = string.Empty;      
      
      sResult = (null != Request.QueryString[sParam]) ? Request.QueryString[sParam].Trim() : "";

      if (sResult != "")
      {
        // Do something
      }

Example #1 and #2 will each give the same end result and functionality as the null coalescing approach sketched above, but at any rate they contain a lot of redundancy. The null coalescer is the easiest approach of the proffered bunch, I think. 

For more information on the C# null coalescing operator and some other interesting uses (e.g. using it with LINQ), check out: http://weblogs.asp.net/scottgu/archive/2007/09/20/the-new-c-null-coalescing-operator-and-using-it-with-linq.aspx

April 2, 2008

asp.net: Handle comments in xml files

Filed under: asp.net,C#,Web development,xml — Stephen @ 7:29 pm

A small point, but asp.net’s XmlDocument doesn’t seamlessly handle xml comments when iterating through sub elements of an XmlNodeList. It’d be nice if XmlDocument didn’t read comments in the first place (I’d venture to say that xml comments aren’t meant to be read by compiled code), but I suppose it might be useful on some occasions to have the Load() method return everything in an xml doc. 

Not a big deal, but remember to handle comments explicitly any time an editable data file is consumed using the XmlDocument object.

For example, if expecting an xml document such as:

<?xml version="1.0" encoding="utf-8" ?>
<items>
  <item>
    <itemValue>value1</itemValue>
    <!--<itemValue>value2</itemValue>-->
    <itemValue>value3</itemValue>
  </item>
  <item>
    <!--<itemValue>value1</itemValue>-->
    <itemValue>value2</itemValue>
    <itemValue>value3</itemValue>
  </item>
</items>

The following approach (or similar) would need to be used in order to prevent the commented areas from being processed as bona fide elements:

    XmlDocument xmlDoc = new XmlDocument(); 
    xmlDoc.Load(HttpContext.Current.Server.MapPath(@"~\App_Data\file.xml"));

    XmlNodeList nodeRoot = xmlDoc.GetElementsByTagName("item");

    for (int i = 0; i < nodeRoot.Count; i++)
    {
      XmlNodeList objNodes = nodeRoot[i].ChildNodes;

      foreach (XmlNode node in objNodes)
      {
        if (node.NodeType == XmlNodeType.Comment)
          continue;

        // Do something.
      }      
    }

In this case, “objNodes” actually contains 3 elements for each item – 2 elements with NodeType Element and 1 element with NodeType Comment. If this is not handled properly in the iterations, it is possible for the code (or general routine) to fail supposing that an element is commented out with the intention for it to not be processed.

For more information: http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.value.aspx

February 29, 2008

Capture color code from screen

Filed under: Web development — Stephen @ 8:22 pm

http://instant-eyedropper.com/
“Instant Eyedropper is a free software tool for webmasters that will identify and automatically paste to the clipboard the HTML color code of any pixel on the screen with just a single mouse click.”

http://colorcop.net/
“Color Cop is a multi-purpose color picker for web designers and programmers.”

February 9, 2008

Firefox add-ons – development tools (best of)

Filed under: Extensions,Firefox,Web development — Stephen @ 2:30 pm

Some Firefox add-ons I’ve found indispensable for web development and everyday use:

Cookie Manager Button – Creates an icon on the navigation toolbar for quick access the Cookie Manager.
Add-on page: https://addons.mozilla.org/en-US/firefox/addon/3402

QuickJava – Allows quick enable and disable of Java and Javascript from statusbar.
Site: http://quickjavaplugin.blogspot.com/
Add-on page: https://addons.mozilla.org/en-US/firefox/addon/1237

Firebug – Edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.
Site: http://www.getfirebug.com/
Add-on page: https://addons.mozilla.org/en-US/firefox/addon/1843

Flashblock – Enables/disables flash for web sites that you designate.
Site: https://addons.mozilla.org/en-US/firefox/addon/433
Add-on page: http://flashblock.mozdev.org/

WebMail Notifier
Site: http://webmailnotifier.mozdev.org/
Add-on page: https://addons.mozilla.org/en-US/firefox/addon/4490

Tabs Open Relative
Site: http://jomel.me.uk/software/firefox/tabsopenrelative/
Add-on page: https://addons.mozilla.org/en-US/firefox/addon/1956

User Agent Switcher – Adds a menu and a toolbar button to switch the user agent of the browser. (Useful for testing browser-specific sites.)
Site: http://chrispederick.com/work/user-agent-switcher/
Add-on page: https://addons.mozilla.org/en-US/firefox/addon/59

CSSViewer – A simple CSS property viewer.
Site: http://www.nicolashuon.info/?page=work&type=projects&id=cssviewer
Add-on page: https://addons.mozilla.org/en-US/firefox/addon/2104

Firecookie – An extension for Firebug that makes possible to view and manage cookies in your browser.
Site: http://www.softwareishard.com/blog/firecookie/
Add-on page: https://addons.mozilla.org/en-US/firefox/addon/6683

CacheViewer – GUI Front-end for “about:cache”.
Add-on page: https://addons.mozilla.org/en-US/firefox/addon/2489 

IE Tab – View web page displayed in IE but within Firefox tab.
Site: http://ietab.mozdev.org/
Add-on page: https://addons.mozilla.org/en-US/firefox/addon/1419

February 8, 2008

asp.net: vs_targetSchema meta tag (and others) no longer required

Filed under: asp.net,Web development — Stephen @ 3:52 pm

Recently I was migrating legacy asp.net pages (v1.1) to 2.0 and noticed the following code snippet in every header:

  <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1" />
  <meta name="CODE_LANGUAGE" content="C#" />
  <meta name="vs_defaultClientScript" content="JavaScript" />
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />

Apparently the tags had been used in the past for design-time html support/validation. They’re no longer required if using Visual Studio 2005 or higher.

Some more good info at: http://www.velocityreviews.com/forums/t97952-can-i-remove-this-meta-tag.html

January 12, 2008

Why SWFObject is better than AC_RunActiveContent.js for flash embedding

Filed under: Flash,Web development — Stephen @ 1:41 pm

Some advantages of using SWFObject over Macromedia’s AC_RunActiveContent.js approach (that most places don’t talk about):

  1. SWFObject degrades gracefully. If flash isn’t detected, the “flashcontent” div element never gets replaced with the flash object script. This being the case, you can use xhtml compliant code that’s far cleaner and more robust than anything Macromedia supports out of the box. Interestingly, Macromedia doesn’t even support alternative content when their implementation is called using the jscript. They allow a <noscript> content area, but in that case you’re limited to only having a replacement <img> instead of full-blown replacement content.  
  2. SWFObject entails terser code. When using SFWObject, you’re only placing/calling your flash script once instead of multiple times. Notice, for example, that Macromedia requires the flash object to essentially be placed twice, thereby duplicating your work outright. Needless to say, SFWObject’s code implementation is far more elegant and much easier to maintain.
  3. SWFObject contains an efficient and robust framework that has extensive functionality built right in. As it stands, Macromedia’s implementation has no (or at least an extremely cryptic) method for doing things like, for example, passing flash argument variables. In fact, a quick glance at Macromedia’s AC_RunActiveContent.js file shows that their rendering mechanism is proprietary to the point of absurdity. Case in point, notice Macromedia’s AC_FL_RunContent() function for generating the <embed> object – if that’s not ad hoc, I don’t know what is. Dirty, cumbersome, and the perfect example of unnecessary overhead that bars anything from being readily transparent or extensible.  
  4. And, of course, all of the regular advantages.

Some caveats:

  1. SWFObject doesn’t work if/when javascript is disabled. I personally consider this a small point, but it’s still a valid shortcoming. Of course, it seems to me that browsers that are running without javascript enabled are likely to be running without flash enabled, either; this is hardly the sort of crowd that most web applications (relying on flash, nonetheless) have to cater to. Incidentally, Macromedia’s approach doesn’t suffer this setback given their use of <noscript>. 

EXAMPLE

Anyone familiar with Macromedia’s suggested method for deploying a flash component will find the following typical:

   <script src="app/flash/default3/AC_RunActiveContent.js" type="text/javascript"></script> 

   <script type="text/javascript"> 

     if (AC_FL_RunContent == 0) { 
       alert("This page requires AC_RunActiveContent.js."); 
     } else { 
       AC_FL_RunContent( 
              'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0', 
              'width', '770', 
              'height', '190', 
              'src', 'data/flash/flashObject', 
              'quality', 'high', 
              'pluginspage', 'http://www.macromedia.com/go/getflashplayer', 
              'align', 'middle', 
              'play', 'true', 
              'loop', 'true', 
              'scale', 'showall', 
              'wmode', 'window', 
              'devicefont', 'false', 
              'id', 'flashObject', 
              'bgcolor', '#ffffff', 
              'name', 'flashObject', 
              'menu', 'true', 
              'allowFullScreen', 'false', 
              'allowScriptAccess','sameDomain', 
              'movie', 'data/flash/flashObject', 
              'salign', '', 
              'base', 'data/flash/' 
              ); //end AC code 
          } 

    </script> 

    <noscript> 
       <object id="_objflashObject" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" 
          codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" 
          width="770" height="190" align="middle" type="application/x-shockwave-flash"> 
           <param name="allowScriptAccess" value="sameDomain" /> 
           <param name="allowFullScreen" value="false" /> 
           <param name="movie" value="data/flash/flashObject.swf" /> 
           <param name="quality" value="high" /> 
           <param name="bgcolor" value="#ffffff" /> 
           <param name="base" value="data/flash/" /> 
           <img src="images/flashReplacement.gif" alt="banner" /> 
       </object> 
    </noscript> 

Using SWFObject, one can replace the above using about 1/4 the code:

   <script type="text/javascript" src="data/scripts/swfobject-1.5.js"></script> 

   <div id="flashcontent"> 
     <img src="images/flashReplacement.gif" alt="banner" /> 
   </div> 

   <script type="text/javascript"> 
     var so = new SWFObject("data/flash/flashObject.swf", "flashBanner1", "770", "190", "9", "#fff"); 
     so.addParam("allowScriptAccess", "sameDomain"); 
     so.addParam("base", "data/flash/"); 
     so.write("flashcontent"); 
   </script>

Blog at WordPress.com.