Switching between ASP.NET application services providers at runtime.

by Scosby Wednesday, April 15, 2009

I had to spend a little time thinking about this one tonight, so here it is for you to digest!

Let's say you have a web app that utilizes the ASP.NET Role provider and Membership provider. Specifically, we'll focus on the SQL providers (SqlRoleProvider and SqlMembershipProvider). It is easy enough to wire these providers up in your web.config and get things running quickly (yay for agility *cough*). Visit either link for the SQL provider classes mentioned above for a sample web.config from MSDN if you're still wondering.

Consider the following: what if I want to set up "test" or "staging" environment providers in the web.config and have the web app use the "test" provider instead of the default (production) provider during testing? In my case, I wanted to use different databases, but this could easily happen to you should you wish to use a completely different provider depending on a condition (for instance, a query string parameter might indicate you should use an Active Directory or Oracle provider, ect).

At first, I thought I could simply change the application's provider at runtime but it became obvious to me, eventually ;), that it wasn't going to work. Instead, I created a static ProviderManager class which returns a cached instance of a Role or Membership provider. It was a pity to say goodbye to the Roles and Membership classes, but alas, I now delegate them to my ProviderManager class' method when I want to work with either provider. This ProviderManager class makes it possible for me to cache the desired provider from the web.config based on any criteria of my choosing. In my case, I simply choose to use the DEBUG constant with compiler directives to return my "test" or "staging" providers (only when debugging, obviously). You certainly could make it more complicated and work with any number of conditions, such as multiple connection strings and/or providers. Enjoy!

public static class ProviderManager
{
     private static MembershipProvider membershipProvider;

       .....

     public static MembershipProvider GetMembershipProvider()
     {
          if (ProviderManager.membershipProvider == null)
          {
               //Get the default provider
               MembershipProvider provider = Membership.Providers["ScosbyMembershipProvider"];
#if DEBUG
          provider = Membership.Providers["TestMembershipProvider"];
#endif
               ProviderManager.membershipProvider = provider;
          } 
               return ProviderManager.membershipProvider;
     }

      ..... 

}

Thus, instead of writing code such as: Roles.CreateRole("WidgetTechs");

We write code to use the new ProviderManager class: ProviderManager.GetRoleProvider().CreateRole("WidgetTechs");

Tags: ,

Technology | Programming

Low Bandwidth MSDN Library

by Scosby Thursday, March 19, 2009

Beth Massi's blog discusses a great way to get a "Low Bandwidth" version of MSDN. Thanks, Beth.

http://blogs.msdn.com/bethmassi/archive/2009/03/16/the-low-bandwidth-version-of-the-msdn-library.aspx

Tags: ,

Technology | Programming

Silverlight 3 Beta 1 released

by Scosby Wednesday, March 18, 2009

Today is the first day of Microsoft MIX 2009. One of the best developments of the day is the release of Silverlight 3 beta 1. Here are the details. Beta documentation is available here. Many, many, many new goodies in this new version. Here are a couple of my favorites:

  • New features for data validation which automatically catch incorrect input and warn the user with built-in validation controls.
  • Desktop shortcuts and start menu support. Silverlight applications can be stored on any PC or Mac computer’s desktop with links in the start menu and applications folder, and so are available with one-click access.
  • Themed application support. Developers can now theme applications by applying styles to their Silverlight 3 applications and changing them at runtime. Additionally, developers can cascade styles by basing them on each other.
  • True HD playback in full-screen. Leveraging graphics processor unit (GPU) hardware acceleration, Silverlight experiences can now be delivered in true full-screen HD (720p+).

I am loving the data validation and can't wait to mock up some examples this weekend. Also, the themed application support lets us change styles at runtime (thank God), this was(is) a HUGE kick in the teeth for Silverlight 2 applications.

Important to note: after installing the Silverlight 3 Beta dev tools you will be unable to build Silverlight 2 applications. Visual Studio 2008 SP1 does not support multiple targets for Silverlight applications yet. So, as always, don't blow up your production environment!

Tags: ,

Technology | Programming

Mouse double click in Silverlight 2

by Scosby Wednesday, March 4, 2009

Mike Snow posted an excellent code snippet on how to implement your own Double Click functionality on his blog:

http://silverlight.net/blogs/msnow/archive/2009/01/15/silverlight-tip-of-the-day-82-how-to-implement-double-click.aspx

You could take his example and extend it by creating a new event in your own class, something like "Double Click" Wink

Tags: , ,

Technology | Programming

But Wait!! I want to respond to the space bar in my Silverlight 2 ListBox!

by Scosby Wednesday, March 4, 2009

Assume you are registered for the KeyDown event on a ListBox control that contains a collection of CheckBoxes. You want to make your users' lives easier by letting them hit the space bar to toggle the CheckBox.IsChecked property you're in for a surprise!

If you're looking for an explanation of why you can't handle the Key.Space enumeration. According to Microsoft, "ButtonBase implements OnKeyDown in such a way that the SPACE key invokes a button click, but also sets Handled, which prevents SPACE from being reported as a KeyDown event that could be handled by a button instance". Obviously, ButtonBase has nothing to do with a ListBox, but we can see that depending upon the implementation of the OnKeyDown event, a class might not allow a specific event bubble up if the Handled property is set to true. This appears to be the case with the ListBox class as well. Since I cannot think of a reason for a ListBox (NOT an item) to not respond to the space bar, I don't mind changing this behavior.

So how do you get a ListBox to respond to the space bar? Well, young grasshopper, you must follow the Silverlight 2 way of creating your own class to function the way the base classes should. Create a class derived from ListBox and override OnKeyDown. In your derived class implementation, do NOT call the base class implementation all the time. Instead, set handled to false if the space key was pressed, for all other keys you should call the base class implementation. This allows the arrow keys to continue to function as you would expect.

protected override void OnKeyDown(KeyEventArgs e)
{
     switch (e.Key)
     {
           case Key.Space:
                 e.Handled = false;
                 break;

           default:
                 base.OnKeyDown(e);
                 break;
     }
}

Tags: , ,

Technology | Programming

Localized hours of the day

by Scosby Thursday, February 19, 2009

This code snippet is great for generating culturally correct (formatted) strings representing all 24 hours of the day. It returns a List of Strings localized to the current culture (for en-US this is 12:00 AM, 1:00 AM, 2:00 AM, ect)

private List<String> GetFormattedLocalHours()
{
     List<String> times = new List<String>(23);
     for (Int32 i = 0; i < 24; i++)
     {
           System.Globalization.
DateTimeFormatInfo dtfi = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
           DateTime temp = new DateTime(2008, 1, 1, i, 0, 0, DateTimeKind.Local);
           times.Add(temp.ToString(dtfi.ShortTimePattern));
     }
     return times;
}

The key point worth noting here is the use of the CultureInfo class' CurrentCuture.DateTimeFormat property. This property returns a DateTimeFormatInfo object that we can use to get the format string appropriate for the CurrentCulture's local from the DateTimeFormatInfo.ShortTimePattern property. Pass this property's value to a DateTime.ToString() instance as the format pattern and you'll get a localized (format) string. Amazing!

What this means is that for any "localized" application,  there is NO excuse for putting AM or PM in front of the numbers 1-12. It takes you very little code to generate culturally correct times of the day for any culture supported by the .NET Framework. Many cultures around the world strictly use a 24-hour clock and thus use "14:00" to represent "2:00 PM". So don't be lazy and, more importantly, culturally insensitive by forcing users in other cultures to read DateTime values in a format other than what they are expecting.

Tags: ,

Technology | Programming

To comment or not to comment...

by Scosby Thursday, February 12, 2009

After recently being told, "you comment your code too much", I was shocked. I quickly explained my intent was to facilitate documentation of the code, and not for consumability, should we ever desire to produce such luxuries. This seemed to barely be an acceptable response, so I took to the internets.

In my humble opinion, if you're such an elitist programmer that you don't need comments to read code, then you're perfectly capable of taking your own advice and can ignore them in the source file as if they didn't exist -after all, this is what managed compliers do anyways. Apparently, I am not one of the chosen few who are able to compile and excute code statements in their brain. However, I have been "that junior developer" who has had to maintain code from a cowboy who considered himself an elitist that wrote perfect, self-documenting code...he most certainly did not write anything close to this kind of coding pattern, and I wanted to pull my hair out after going through 10,000 lines of undocumented code that mostly didn't work. So please, do us "lesser" developers a favor and save us from having to jump all over your custom APIs and frameworks to see what the implementations are doing by putting some comments in there. I promise, you'll spend less time ignoring comments in code than answering questions from the "juniors"...that is if you work with people confidient enough (or ballsy?) to ask you questions, b.c. you're a code troll anyways.

Utimately, I admit that not everything needs commenting because one probably doesn't publish the entire source in documentation anyways. But I tend to be verbose and GhostDoc (free, btw) makes it sooooo easy to comment in Visual Studio that I have a hard time not doing so Laughing

I found Dan Dyer's blog post to be representative of what I agreed with on the internet. Thanks, Dan.

 

Tags: ,

Technology | Programming

Good article for Silverlight 2: A UserControl base class for Visual State Manager

by Scosby Monday, February 9, 2009

The Expression Blend and Design team have posted a base class for building your own UserControl and utilizing the Visual State Manager on their blog. This makes it easy for you to define states for your control and transition between them when appropriate.

Read their article here.

Tags: , ,

Technology | Programming

Silverlight 2 and cross-browser compatibility when using HtmlTextWriter

by Scosby Tuesday, February 3, 2009

If you are using a custom ASP.NET web control to render your Silverlight 2 Object tag with the HtmlTextWriter, you need to make sure to render the Object tag's param elements as self-closing. Otherwise, you will discover that IE 6, 7, and 8 will ignore the invalid XHTML 1.0 Transitional "</param>" element and load the Object tag (meaning your Silverlight app) correctly but Google Chrome and Mozilla Firefox will not.

Instead, you should render your param elements as self-closing by using the HtmlTextWriter's WriteBeginTag method and the SelfClosingTagEnd constant. According to MSDN's WriteBeginTag documentation, "the WriteBeginTag method does not write the closing angle bracket (>) of the markup element's opening tag. This allows the writing of markup attributes to the opening tag of the element." This means you can close it yourself with the SelfClosingTagEnd constant, which they do not demonstrate but is easily to accomplish and removes the need to call WriteEndTag in their example.

This behavior can be verified easily. If you remove the self-closing tag from a Visual Studio Silverlight Web's *.html test page and add the explictly closed element, the behavior will manifest itself.

PS - Chrome and Firefox will also not load the Object tag if you provide a param element with an empty value. For example: <param name="onerror" value="" />

Tags: , , , ,

Technology | Programming

Using Windows Server 2008 as your workstation OS

by Scosby Wednesday, January 7, 2009

Here is a great post from VIJAYSHINVA KARNURE for using Server 2008 as your primary workstation OS instead of Vista. Just remember, x64 2k8 requires signed hardware drivers so make sure your vendors provide these.

http://blogs.msdn.com/vijaysk/archive/2008/02/11/using-windows-server-2008-as-a-super-desktop-os.aspx

Tags: ,

General | Technology