CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Brendan Tompkins [MVP]

Blog First. Ask Questions Later.

January 2004 - Posts

  • Homeland Security Threat Level Service Anyone?

    I've been tasked with creating a control to display the current Homeland Security Threat Level on our site's home page.  Of course, I don't want to change anything when our threat level changes, so I went in search of a Web Service that gives me this information.  I couldn't find a SOAP service, but I did find this URL provided by the Department of Homleand Security, which gives an XML string containing the current threat level.

    I created this following enumeration that represents the current condition, so that I can use this information from within our .NET framework.

    public enum DHSAdvisoryLevel
    {
        SEVERE,
        HIGH,
        ELEVATED,
        GUARDED,
        LOW,
        UNKNOWN
    }

    And this static method to parse the DHSA's XML and return my enum.

    public static DHSAdvisoryLevel GetHomelandSecurityThreatLevel()
    {
          DHSAdvisoryLevel currentLevel = DHSAdvisoryLevel.UNKNOWN;
          try
          {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load("http://www.dhs.gov/dhspublic/getAdvisoryCondition");
                System.Xml.XmlNodeList el = doc.GetElementsByTagName("THREAT_ADVISORY");
                string threatLevel = el[0].Attributes["CONDITION"].Value;
                currentLevel = (DHSAdvisoryLevel) Enum.Parse(typeof(DHSAdvisoryLevel), 
                threatLevel, true);
          }
          catch 
          { 
                // Do something here, if needed 
          }
          return currentLevel;
    }

    Now, what would be really cool is for someone to host a Web Service that returns this enum... Any takers?

    -Brendan

  • Moblie Image Device-Specific Filtering

    So, I'm working on this mobile site.  I've created a title image that looks great on a color phone. I went to show it to my boss, who has an older phone without color, and it looks like crap.  I knew that you could do device-specific filtering with MMIT, so I tried it out and it worked great and was easy...  I converted the image to a 1BPP GIF, and a WBMP (wireless bitmap format) using this online application here, and added the following code to my mobile web form:

    <mobile:Image id=Image1 ImageUrl="images/mobiletitle.gif" AlternateText="VIT Mobile" runat="server">
    <DEVICESPECIFIC>
      <CHOICE ImageUrl="images/mobiletitle.gif" Filter="supportsColor"></CHOICE>
      <CHOICE ImageUrl="images/mobiletitlebw.gif" Filter="prefersGIF"></CHOICE>
      <CHOICE ImageUrl="images/mobiletitle.wbmp" Filter="prefersWBMP"></CHOICE>
    </DEVICESPECIFIC>
    </mobile:Image>

    Now, I can see the image on a variety of devices:

    -Brendan

  • Who do you think you are, anyway?

    Sometimes simply knowing who you are can help a great deal.  I just figured out some tricky Active Directory permission issues by tracing out the current WindowsIdentity, like so:

      string strCurrentID = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
      System.Diagnostics.Trace.WriteLine("Current Impersonated Identity: " + strCurrentID );

    Anyhow, I kept getting Unknown error (0x80005000).  Problem was, the current user didn't have the proper permissions to our AD store. From an ASP.NET application, this user is: NT AUTHORITY\NETWORK SERVICE.   I changed this to a more trusted account, by changing the anonymous user and password in the “Authentication Methods“ tab in the Directory Security tab of the site properties but I then remembered that I also had to adding the following to my web.config file.

      <identity impersonate="true"/>

    Problem solved.

    -Brendan

     

  • Cool Article - Generate Security Images with .NET

    Cool article at code project shows how to create CAPTCHA "completely automated public Turing test to tell computers and humans apart." images from .NET .  Just to check, I submitted the image it generated to MyFonts.Com's What The Font? program (which is awesome by the way), it couldn't pick out the numbers.  I guess it works!

    -Brendan

  • RSS Feed Reader for the .NET Compact Framework or MMIT

    Haiko Hebig posts a nice list of RSS Fee Readers here.  I tried out NewsGator for Outlook, but I'm not overly impressed, and I surely won't be shelling out $30 bucks for it.   I'm thinking of creating a dinky reader with the Microsoft Mobile Internet Toolkit, so that I can read RSS on my mobile phone.  Before I do, I was wondering if anyone has heard of something like this out there...

    -Brendan

  • Use GDI+ to Save Crystal-Clear GIF Images with .NET

    In an effort to make our gate camera images visible on a ridiculously small cellphone screen,  I spent the past couple of days learning about the process of image Quantization.   GDI+ will allow you to take a full-color 32 bpp image and save it as a .gif file!  This turns out to be quite simple, and you can even re-size the image before saving it, by using the CreateThumnailImage method.

    System.Drawing.Bitmap b = new System.Drawing.Bitmap(“c:\\original_image.gif“);
    System.Drawing.Image thmbnail = b.GetThumbnailImage(100,75,
    null,new IntPtr());
    thmbnail.Save(“c:\\thumnail.gif“, System.Drawing.Imaging.ImageFormat.Gif);

    “Cool!“ You're thinking to yourself, but don't think too soon.  You may be less-than-impressed by the dithery, grainy image produced by this technique.  Here's the output of this method with one of our gate camera images: 

    So, what accounts for the grainy image?  It has to do with color quantization, sometimes called “palettization” or simply, the process of slapping a 256 color palette onto a full-color image, thereby reducing the total colors (and file-size).  The image is grainy because GDI+ by default uses the windows 256-color palette, and doesn't take into account the colors in the actual image.  When I found this out I went in search of a better color quantization technique for saving .GIF images... 

    Personally I've found that almost all GIF images should be saved with an adaptive palette. These days, forget about the Web Palette, unless you're doing icons or big areas of solid color.  Most everyone will be running in at least 16K colors, and if by some small chance they're still running 256 colors, the browser will dither an adaptive image to a reasonable version anyhow.  An adaptive palette contains the 256 most frequently used colors in the image. Well, um sort of anyway. (As an aside, I tried to write my own “popularity palette” algorithm which used the most frequently used colors to build the palette, but my images looked worse than before!)  A good quantization algorithm also takes into account spacing between colors and stores colors that are, say blue and very-nearly-blue as one color, freeing up more space for colors that the eye sees as separate.  One such adaptive palette algorithm is called the “Octree“ algorithm.

    I found two articles from Microsoft that helped out a great deal, KB 319061  and Optimizing Color Quantization for ASP.NET Images by Morgan Skinner at MS.  Morgan's article had some great code samples, and really useful base class which will allow you to plug in your own algorithm to quantize images. I ended up pulling bits and pieces of code from the two articles to create a library of objects used for creating Octree and Grayscale palettes.  Using the OctreeQuantizer object was easy, as you can see in this code snippet:

    System.Drawing.Bitmap b = new System.Drawing.Bitmap(“c:\\original_image.gif“);
    System.Drawing.Image thmbnail = b.GetThumbnailImage(100,75,
    null,new IntPtr());
    OctreeQuantizer quantizer =
    new OctreeQuantizer ( 255 , 8 ) ;
    using ( Bitmap quantized = quantizer.Quantize ( thmbnail ) )
    {
         quantized.Save(“c:\\thumnail.gif“, System.Drawing.Imaging.ImageFormat.Gif);
    }

    OctreeQuantizer grayquantizer = new GrayscaleQuantizer ( ) ;
    using ( Bitmap quantized = grayquantizer.Quantize ( thmbnail ) )
    {
         quantized.Save(“c:\\thumnail.gif“, System.Drawing.Imaging.ImageFormat.Gif);
    }

    This code produced the following beautiful (In this case, beauty truly is in the eye of the guy who just spent three days trying to get it to work!) thumbnails, one with an adaptive palette, and one in grayscale. 

    If you've got a cellphone with web capabilities, go to http://mobile.vit.org/ and see the image in all its 100 X 75 pixel glory.

    UPDATE: 

    See this post here for the latest version of this library

     

    -Brendan

     

  • In search of a good book on Algorithms

    As far as I can tell, there are no released books on algorithms for C#.  I'm looking for a good general (best in C or Java?) , comprehensive book on Data Structures and Algorithms, and was wondering if anyone out there could make a reccomendation...

    Thanks in advance!

    Brendan

  • SharePoint™ RSS Feed Reader Web Part

    Stared working with SharePointPortal again yesterday and I installed Tim Heuer's RSS Feed Reader Web Part.  It's a pretty simple implementation, but it's free, and the installation worked great. 

    -Brendan

  • Simplified State Management with StateClassBase

    OBSOLETE CONTENT
    The author of this post has determined that this content is obsolete. Use at your own risk! Blog posts are a point-in-time snapshot of the blogger's thinking and should not be assumed to represent this blogger's current opinions. This post was left up for historical purposes.

    State management in web applications can be tricky.  ASP.NET and the .NET framework offers some help in this regard, with controls that can maintain their own state.  Often, however, you may find yourself storing things in Session or ViewState to maintain other stateful properties of your applications.  You've really got two options for doing this 1) Store objects individually in view state, or 2) Create a state class object that exposes your state objects as typed public properties.  There's really no question here as to which is the better option.  With #1 you have to manage hash keys, and box and unbox your objects.  You also have no way of simply re-setting state, or restoring state from persistent storage, such as a database.  Mark DiGiovanni has blogged about the advantages of maintaining state in one place.

    So, how do you go about this?  I've developed a method of doing this that I'm pretty happy with.  It involves the use of a base State class (StateClassBase) that is meant to be sub-classed when you wish to maintain state.  This class will handle storing state in Session or ViewState, depending on your implementation.  Here's the class. (I've removed comments for simplicity)

    [Serializable()]
    public class StateClassBase
    {
          
    private string _stateKey;

           public StateClassBase(string stateKey)
           {
               _stateKey = stateKey; 
           }

           public virtual object StateRestore(System.Web.UI.StateBag ViewState) {
             
    if(ViewState[_stateKey] != null) return ViewState[_stateKey];
              
    else return null;
           }

            public virtual object StateRestore(System.Web.SessionState.HttpSessionState ViewState) {
              
    if(ViewState[_stateKey] != null) return ViewState[_stateKey];
              
    else return null;
            }

             public virtual void StateStore(System.Web.UI.StateBag ViewState) {
                 ViewState[_stateKey] =
    this;
             }

            
    public virtual void StateStore(System.Web.SessionState.HttpSessionState ViewState) {
                 ViewState[_stateKey] =
    this;
             }

             public virtual void StateRemove(System.Web.UI.StateBag ViewState) {
                ViewState[_stateKey] =
    null;
             }
            
              
    public virtual void StateRemove(System.Web.SessionState.HttpSessionState ViewState) {
                
    ViewState[_stateKey] = null;
             
    }
    }

    Pretty simple, huh?  I've found that it's best for each control that needs to store state to store its own state using a derived state class object.  This way, I can reset state for one part of the application without affecting another.  If I need the state to persist only for the lifetime of the page, I pass the current StateBag object (ViewState) to the StateClassBase methods.  If I need more persistent state, or if I'm storing a lot of data, I pass a HttpSessionState object (Session). 

    The following design pattern seems to work best for my purposes.  The example is for maintaining page index and sort expressions for a DataGrid.

    1. Create a derived StateClass object

      public class DataGridPageState : VIT.Common.Classes.StateClassBase
      {
         private int m_intCurrentPageIndex = 0;
         private string m_strCurrentSortExpression;

         public DataGridPlusPageState(string uniqueID) : base(uniqueID + "DATA_GRID_PAGE_STATE"){}

         public int CurrentPageIndex
         {
            get {return m_intCurrentPageIndex; }
           
      set {m_intCurrentPageIndex = value; }
         }

         public string SortExpression
         {
         
      get {return m_strCurrentSortExpression; }
         
      set {m_strCurrentSortExpression = value; }
         }

      }

    2. Create a private class-level member instance of this object

      private DataGridPageState m_pageState;

    3. In the page or control's OnInit() method, restore this member instance from your state store

      this.m_pageState = (DataGridPageState) new DataGridPageState(this.UniqueID).StateRestore(this.Session);
      if(this.m_pageState == null) this.m_pageState = new DataGridPageState(this.UniqueID);

    4. Call the StateStore method after setting any property on the object.   This example is from the event handler for the DataGrid's PageChanged method.

      this.m_pageState.CurrentPageIndex = e.NewPageIndex;
      this.m_pageState.StateStore(this.Session);
    5. When you need access to your state, simply use your member variable, which should always contain the current state, like so:

      this.DataGridPlus1.PageSize = m_pageState.PageSize;

    That's it!  You now have your state in a nice package with typed versions of your state objects to work with.  You can use this pattern from any control that has access to the System.Web namespace. 

    -Brendan

  • .NET replacement projects

    SD Times had a recent story about replacements for the .NET runtime... They metion “Mono“ for Linux, and DotGnu.   Here's a quote.

    Among the motivations for the project posted on www.dotgnu.org is “a desire to prevent Microsoft from achieving monopolistic control of ‘webservices,’

    Um... monopolistic control of webservices?   I know what they're saying, but this seems a little Oxymoronic to me.  Anyhow, I,  for one, think it would be cool to be able to run my .NET app on a Linux box, or on a different runtime. 

    -Brendan

  • WebMethods Executes .NET Assemblies

    From SD Times:

    “Integration tools vendor WebMethods Inc. is set to release on Jan. 30 an update to its flagship Integration Platform that it claims is able to execute .NET assemblies directly, simplifying the reuse of program code in integration projects for developers using Visual Studio .NET. “

    Could prove interesting for service oriented architectures....

    -Brendan

  • XP Remote Desktop Bug - Fix

    Microsoft's Remote Desktop technology is Rocket Science.  I have no idea how it works, but I've come to depend on it.  Gone are those trips down to the server room to stand in the cold while installing an application.  Gone are the days of bringing home the project on CD and having everything installed at home.  I just VPN and connect to my machine at work.  Over my Cox connection, it's like I'm sitting at my desk.

    So when it doesn't work, it sucks.  There's a bug in the client that causes everything to be REALLY SLOW on a second connection.  Well, MS has a fix for this that will be released with XP SP2.  But for now, a simple restart of your remote computer will do it. Problem is, it's not obvious how to restart your computer when connected remotely.  You don't get the shutdown options.  So, if this happens to you, open a command promt, and type the following:

    tsshutdn /reboot

    -Brendan

     

  • Web.config Parsing Error - Fix

    Every once in a while when I build and debug a Web application with VS.NET, I get the following error when the web.config is being parsed...  I've found out that  this has to do with Index Server building an index for the .config file (or something like that) and if I turn indexing off on my dev machine, the error goes away.  Since this was an obscure fix, I thought I'd share it!

    -Brendan

    Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

    Parser Error Message: [some message]

    Source Error:

    Line 329: type="Microsoft.VJSharp.VJSharpCodeProvider, VJSharpCodeProvider, Version=7.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /></compilers> Line 330: <assemblies> Line 331:<!-- Line 332:BEGIN section inserted by Device Update 2 installer. Line 333:-->
  • Best Regular Expression Tool

    I've tried a bunch of different tools for developing Regular Expressions, such as Rad Software's Regular Expression Designer, and Roy's The Regulator (which has the coolest icon), but I keep coming back to Eric Gunnerson's Regular Expression Workbench.  The thing I like the most is Eric's “Add Item” menu bar which has sinppets of regex code.  The other two may be great tools, but I can never seem to remember regex syntax, so the built in reference is cool. 

    UPDATE: Roy has pointed out that The Regulator does in fact have a snippets library, and it's even customizable...  That being the case, I'll be using it for sure...

    UPDATE: 3/9/04 Rad Software has added a regex library feature.

    Anyone care to weigh in?  Any other favorites?

    -Brendan

  • Sticky Draggable Divs

    OBSOLETE CONTENT
    The author of this post has determined that this content is obsolete. Use at your own risk! Blog posts are a point-in-time snapshot of the blogger's thinking and should not be assumed to represent this blogger's current opinions. This post was left up for historical purposes.

    If you do Web Application development, you've no doubt struggled with the task of creating Modal forms.  You have different options for doing this, each with their own advantages and pitfalls.  Hosting your form in a new browser instance (window.open()) is really a kludge, and many users have popup blocking software which will break this approach. Using true Modal dialogs (window.showModalDialog()) doesn't work well from within ASP.NET.   Using draggable DIV elements solves some of these issues, but has its own set of problems.  Dragging DIV elements involves using DHTML and JavaScript and the script that you have to write to enable this can be tricky.  Toss browsers other than IE into the mix, and you've got even more problems.

    Taking all this into account, I've come up with an approach that works pretty well from within ASP.NET applications.  Sticky Draggable Divs! (SDDs) ;)  They involve using DHTML Behaviors, and .htc files. If you're not familiar with this technology, see http://msdn.microsoft.com/library/default.asp?url=/workshop/components/htc/reference/htcref.asp

    So, check out my example of SDDs.  I've included the source files in a .zip file here.

    Creating SDD's is easy! Just follow these steps: 

    1. Create an ABSOLUTELY positionable DIV element
    2. Reference the DragParent.htc file
    3. Include the DragParent namespace in the page's HTML element.  
    4. Wrap an element within <DragParent:DragParentDiv> tags

    Any element included within the <DragParent:DragParentDiv> tags will become the anchor to enable dragging of that element's parent DIV control.  Within the .htc file, events are attached to the element to support the dragging.  When the dragging is complete, a cookie is set so that the element will be positioned properly for postbacks. This is also done automatically for you by the .htc file.

    For this to work well, and for the windows to be Draggable, your users have to be using Internet Explorer 5 or above.  I can count on most of my users to be using IE.  Mozilla users won't be able to drag the window, but this is okay since they can still see the content.  The best part is that these nerds won't get JavaScript errors, because Mozilla won't parse the HTC script. 

    -Brendan

More Posts Next page »