I consistently refrain from using this platform for anything other than sharing professional experiences and insights. I feel that this is a sensible approach to writing — covering topics outside of your field of expertise is almost always a foolhardy move (although I’d imagine most things published online fall under this category).

But, to break from my usual routine, I felt that it was very interesting in how the language in the recent May 26th, 2011 bill (S. 990) which extended the PATRIOT Act ended up the way that it is. My intention isn’t to proclaim that this is some never-before-seen legal maneuver, but I found it interesting all the same. I did some looking into the history of the bill, and here’s what I came up with.

Note that I do not cover the full history of the bill here. There were some minor amendments and actions I’m not going to go over, as I felt they were inconsequential in the end.

The Initial Bill

First off, you can find the entry for this bill at the Library of Congress website here:

Library of Congress Entry for S. 990

From the link above, we can see that the Latest Title of the bill is:

Small Business Additional Temporary Extension Act of 2011

To be honest, I am not too familiar with what the Small Business Act is or what programs it provided. The original legislation appears to have been passed during the year of 1958. On the surface, it would seem like an “agreeable” sort of legislation, assuming it worked as intended.

Here is the text of the S. 990 extension bill when it was first introduced:

Initial Revision of S. 990

The most important thing to read here is:

(a) [The Small Business Act]…is amended by striking ‘May 31, 2011′ each place it appears and inserting ‘May 31, 2012′.

We can see that this legislation is meant to replace all dates of “May 31, 2011″ with “May 31, 2012″ in the Small Business Act, which would result in an extension of all the programs provided under the Small Business Act.

So far, the bill looks like a genuine “small business” bill. Here’s where the interesting part comes in.

The Final Revision

After a few other amendments related to the original Small Business Act were introduced and debated, Senator Reid authored an amendment that managed to pass the Senate which effectively tacked on extensions to the PATRIOT Act to this bill.

The text of the bill with this amendment can be seen here:

Revision Adding PATRIOT Act Extensions S. 990

The part I found most interesting was this phrase, near the top:

In lieu of the matter proposed to be inserted, insert the following:

If I understand that phrase correctly, it basically means everything originally in the bill will be removed and replaced with whatever follows (which, in this case, would be the PATRIOT Act extensions).

You may be asking yourself: “So, the Small Business Additional Temporary Extension Act of 2011 no longer has anything to do with small business?”

As we can see in the final version of the bill, that seems to be the case:

Final Revision S. 990

Quick Thoughts

I found it rather amusing that the final text starts off with:

An Act

To provide for an additional temporary extension of programs under the Small Business Act and the Small Business Investment Act of 1958, and for other purposes.

But then goes on to mention nothing related to small business at all!

All of this would seem to mean then that the Small Business Act was, in fact, not extended. I’m not intimate with the finer details of the Act, and it is not known to me or whether or not it was even effective. Despite this, I’m left wondering why they didn’t renew the Small Business Act.

The legal maneuver I just described could very well be a technique frequently applied in the legislative process, however the PATRIOT Act is a powerful and consequential piece of legislation. Therefore, this specific legal maneuver should be regarded as a powerful and consequential action. And, like any other powerful and consequential action, it bares examining.

 

I recently supplied an answer to a question I stumbled across on stackoverflow.com. Because the information may be useful to someone, I’ve decided to share my response here as well.

The question the user had is how he could detect the locale Outlook was running in.

The answer I provided can be found below.

There are a number of ways you can go about doing this. Although the exact process depends on the Exchange server version, a MAPI client (Outlook in this case) will set the  PR_LOCALE_ID property in the user’s information store to the ID of the locale (LCID) in which the MAPI client (Outlook) is running during logon. That may or may not work for you.

I do not know exactly how the value used for the LCID is determined by Outlook, so this may not be useful in environments that have a complicated Office language configuration.

Also, the way in how the PR_LOCALE_ID property is set varies greatly depending on your Exchange version. I believe that in Exchange 2007+ it will only set the LCID during profile creation and initial logon, and won’t touch it again, even if the user’s locale changes. Creating a new profile is the only way for it to update.

I have not written anything that provides the functionality described above, so your mileage may vary with that technique.

You do have another option available to you if you have access to the registry, however. If you have Outlook 2007 installed, you should have a registry key named “InstalledUI” located at (assuming 32-bit machine):

HKLM\SOFTWARE\Microsoft\Office\12.0\Common\LanguageResources\InstalledUI If you look in that key, you should see values that have an LCID for the name. You can conclude that any LCID appearing here is supported by the system. The values for each LCID (REG_SZ) indicate the status of the language. So, for example, I’ll have a value named “1033″ set to “On” if English is active for me.

Hopefully, one of these techniques will prove useful for you.will prove useful for you.

My response does leave some questions open however. Any comments or thoughts on this subject would be appreciated.

 

There are a number of ways suggested on various forums for checking whether or not Outlook is installed, and which version if it is. You may have some code that needs to act differently based on whether Outlook 2007 or 2010 is installed.

Many of the ways suggested are hacks at best, and certainly not resilient. I’m not automatically convinced that the most commonly suggested methods would yield consistent results across all localizations and organizations. This article discusses how to check whether Outlook 2007 or 2010 using a more foolproof method.

A less hackish way of determining which version is installed is to make use of the MSI API. This would add some overhead in comparison to simply reading a registry key, of course; however, whenever I’m faced with a situation where I need to make decisions based on a product’s installation state, I tend to gravitate towards using the API for the system that oversees those sorts of things.

If you make use of the MSI API, the most sensible thing to look for would probably be the Outlook core component (OUTLOOK.EXE) itself. This component is not localized, so the component GUID will be the same across every language Office comes in.

Because you won’t know the Product Code easily, you can simply check the component’s installation state by using MsiLocateComponent. The only thing you’ll need in order to use this function is the actual component you’re looking for.

Here’s some component codes I’ve compiled for Outlook’s core component:

Outlook 2007{0638C49D-BB8B-4CD1-B191-055E8F325736}

Outlook 2010 32-bit{CFF13DD8-6EF2-49EB-B265-E3BFC6501C1D}

Outlook 2010 64-bit{ECCC8A38-7855-46CA-88FB-3BAA7CD95E56}

 

If your application’s data model layer uses an ORM, such as the Entity Framework, to read and write data to and from a database, you may find yourself in situations whereby the solution cannot be provided through the normal offerings of the particular ORM.

An example of this with the Entity Framework would be a situation requiring you to create a new VIEW without dropping the rest of the database. You cannot do something like this using the standard capabilities exposed by the Entity Framework.

Fortunately, the framework does allow for the execution of arbitrary SQL commands. Read on for more information.

There are a number of methods that will allow you to execute arbitrary SQL statements.

Some examples of functions provided to allow for arbitrary statement execution are ExecuteStoreCommand and ExecuteStoreQuery. You can use ExecuteStoreQuery when you are expecting a result set to be returned, and ExecuteStoreCommand otherwise.

Executing these methods requires a live data context. The code sample showing the usage of these methods is going to refer to some static properties in a class named “SqlQueries”. I’m going to show you some snippets from this static holder class so you know what queries we’re executing:

    public static string DoesViewExist
    {
      get
      {
        return
          @"SELECT
                COUNT
           FROM
                 INFORMATION_SCHEMA.VIEWS
           WHERE
                 table_name = @viewName";
      }
    }

    public static string CreateRoomView
    {
      get
      {
        return
          // The view particulars aren't necessary here.
          @"CREATE VIEW [dbo].[RoomView]
             .
             .
             .";
      }
    }

Yikes, I hate having raw SQL in code; however, for the purposes of this article, we don’t want to get too complicated here. I have one query that checks if a view exists, and one that creates a specific view. Notice that the view checker query takes a parameter named “@viewName”.

This is just an example. I’m not making any proclamations here that modifying your schema at run-time like this is a proper upgrade strategy for your data sources, but there may be some situations where this just makes sense.

In the following code example, **DataSession** acts as our unit of work, and has a property named “Context”, which has the live **DbContext** for the session. I’m not providing the code for that; substitute any IUnitOfWork pattern implementation you can find on the net here instead, if you will.

The code in the sample checks for the existence of a view named “RoomView” and creates it if it is missing.

    private static bool ViewExists(SqlParameter viewName, ObjectContext context)
    {
      return
        0 != context.ExecuteStoreQuery<int>(SqlQueries.DoesViewExist, viewName).FirstOrDefault();
    }

    private static void VerifySchema()
    {
      // 'Strings' class is a string table/resource file/etc.
      SqlParameter roomViewName = new SqlParameter(Strings.SqlParameterViewName, Strings.SqlRoomViewName);

      using (IDataSession session = new DataSession())
      {
        // This let's us get our ObjectContext.
        IObjectContextAdapter adapter = session.Context;

        if (!ViewExists(roomViewName, adapter.ObjectContext))
          adapter.ObjectContext.ExecuteStoreCommand(SqlQueries.CreateRoomView);
      }
    }

I created a method named “ViewExists” because I’d probably have more than one view to check for, and that makes the whole process a bit cleaner.

But, as you can see, fairly simple.

 

A problem I ran into that you might encounter when working with Entity Framework 4.1 involved already existing entities being re-inserted into the database when they were being associated with new entities. Many times this would result in an error when committing the transaction (which, in retrospect), is probably the best outcome to that kind of scenario, since uninhibited insertion of duplicate data is truly on the catastrophic level of things).

Given the complexity of Entity Framework, I’ll assume that there’s more than one set of circumstances that can lead to unwanted entity re-insertions. That aside, the reason why I was getting these excessive inserts turned out to be very simple, resulting in a simple solution.

To paint a quick picture, let’s say you have a Group entity:

    public class Group
    {
      public int Id { get; set; }
      public string Name { get; set; }
    }

Ok, not very exciting there. Now, let’s add a User entity to the mix.

    public class User
    {
      public int Id { get; set; }
      public string Name { get; set; }
      public ICollection<Group> Groups { get; set; }
    }

As you can see above, User entities maintain associations with one or more groups. The groups are maintained independently of users; new users, if assigned to groups, will always be assigned to groups that of course exist prior to the creation of said user. This is only common sense people.

Going back to the issue described at the beginning of the article, I would get the issue to occur when creating a new User, assigning it one or more groups, and then saving it to the database. The error was a DbUpdateException, and the error message more or less reflected that I was trying to insert those Groups I associated to my new User as if they were new Groups! A SQL Profiling session confirmed this, where I was able to observe this egregious act.

So, if this is happening to you, the reason why may be because your Group instances are not from the currently active DbContext. If you are maintaining short-lived DbContexts, and perhaps caching some of this data to avoid unnecessary round trips, you may fall victim to this habit.

Your associated entity instances need to be from the same data context that you’re adding the new primary entity into. If you are sporting cached instances of entities, one way you can solve your issue is by attaching the old instances to the new context. I have had mixed results doing this, and I have not had the time to properly investigate proper attachment routines with EF 4.1. In the short term, I found it to be unreliable, or at least less than clear. The quickest route to safety was to simply re-fetch the associated entities.

Of course this is all just common sense — of course your associated entities need to be from the same data context as your new entity. The point is, is that it can be easy to make this mistake if you are trying to keep detached entities floating around.

Have you encountered similar excessive-insertion-type errors, but due to different reasons? I’d be interested to hear about it.

 

Often in the context of using the Entity Framework there is a one-to-one relationship between entities and database tables. While, from a functional perspective, that’s fine, entities are not restricted to representing only database tables. We can treat other things from the database as entities, such as views, as well. We can even establish cardinality between views and other entities, yielding results similar to using database tables that exhibit a type of cardinality with each other. The relationship between views and entities if established will not be entirely orthodox of course, mainly due to the inability for a view to have either a primary or foreign key. Consequently, using views with Entity Framework 4.1 (Code First) requires some unorthodox mapping.

Let’s see how we can define a model that consists of a table with references to data from a view.

I. The Domain Model…more or less…

First, to set the mood, the reason this topic entered my thoughts stems from the use of the Entity Framework with a preexisting, and very legacy, database I’ve had to tango with in various projects. However, the proposed model and implementation example detailed here is entirely fictional, at least assuming that when we say “fictional”, that we do so under the assumption that “x <= 99% non-fictional” always translates to “fictional”.

First, assume we have been given a database to work with, and we have no input on how the actual database schema should be structured. Because we are all intelligent people, we know then that debating on whether the database demonstrates good design or not is pointless.

Assume we’re dealing with an application that has a data model that, among other things, consists cities described by City objects. Let’s write out our domain class for this:

public class City
{
  public int Id { get; set; }
  public int Name { get; set; }
  public int Population { get; set; }
  public string Description { get; set; }
}

Nothing spectacular here.

Moving on, let’s assume City objects are stored in a table named CITIES.

OK. Now, let’s assume that Cities can be given a Rating. A Rating can be applied to a City, as well as pretty much every other data type in the application.

Finally, let’s assume that, for some reason, the original “designers” decided that a Rating consisted of a uniquely identifying literal, a display name, and a URL pointing to an icon representing that Rating. Let’s whip up a class for this:

    public class Rating
    {
      public string Code { get; set; }
      public string DisplayName { get; set; }
      public string ImageUrl { get; set; }
    }

Taking an additional step towards the general region of insanity, let’s assume that the data that defines a Rating itself is not stored in a dedicated table, but in a table containing other types of static data, categorized appropriately, somehow and someway. To get any use out of it, a view is used to aggregate the defining data from these indiscriminate locations into a more logical and self-contained block. Let’s assume the name of the view is RATINGS.

Not quite done yet: to complete the journey to the Land of No Reason, the decision was made that ratings would be associated to cities through the assignment of the Rating’s “Code” value to a dedicated column in CITIES table. How can we describe this strange relationship using Entity Framework? Well, before that, we need to add a reference from entity to the other in one or both of the classes.

II. Referencing the Other

Let’s first update our City class.

    public class City
    {
      public int Id { get; set; }
      public int Name { get; set; }
      public int Population { get; set; }
      public string Description { get; set; }
      public virtual Rating { get; set; }
    }

Notice that the City class now has a Rating property. What it does not have, is a property meant to contain only the Rating’s code. This is contrary to the actual legacy table, which simply has a tiny varchar column probably named something obscene, such as “cityratingcd”, dedicated to holding just the Rating’s code.

Hell, while we’re having so much fun here, let’s add a little bit to the Rating class:

    public class Rating
    {
      public string Code { get; set; }
      public string DisplayName { get; set; }
      public string ImageUrl { get; set; }
      public virtual ICollection<City> Cities { get; private set; }

      public Rating()
      {
        Cities = new ObservableCollection<City>();
      }
    }

You’ll see that we added a new property named Cities above. Hmm? Cities? Yup, and it will return all cities that currently have that particular Rating assigned to them. Now, I did say previously that there were types other than City in the system, and that Ratings could be applied to them as well; however, I don’t have anything else defined in this example, so just substitute City for a common interface in your heads if need be. Also, this is certainly not needed if you don’t want it. The association can be purely one-way, obviously. I’m using this purely for example purposes.

III. Creating the Data Model

How we actually set up some sort of relationship between these two all boils down to what we do during the model creation phase. First, let’s see how we end up defining our City type during model creation (note: I’m going to be using some extension methods I covered in some previous articles, namely for column mapping). Let’s also assume all of the corresponding column names in the legacy database are named very “legacy-like”.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      // Map City class to legacy CITIES table.
      modelBuilder.Entity<City>()
        .MapByColumnName(c => c.Id, "city_id")
        .MapByColumnName(c => c.Name, "city_name")
        .MapByColumnName(c => c.Population, "city_population")
        .MapByColumnName(c => c.Description, "city_description")
        .HasKey(c => c.Id)
        .ToTable("CITIES");
    }

The above mapping makes no mention of the “citystatuscd” column which holds the associated Rating’s code for the City here. I can define a relationship from either the City or Rating perspective during model creation. I can define it from both perspectives, but only one is needed. We’ll define it in this case from the Rating’s perspective. Obviously, if you elect to not have the collection of cities in the Rating class, you would be required to form the association from the City’s perspective instead.

Now, let’s map the Rating type itself. If you’ve been using EF 4.1 for even a little bit, you’ll probably know that an Entity is invalid if it doesn’t have an identifiable primary key. Because a VIEW cannot have a primary key, it would seem like we are in a bad situation. That would be true, if we were obligated to always be truthful to the Entity Framework. Thankfully, we’re not, so we can go ahead and tell EF that a specific property is the key for the type, even though it isn’t. The actual effect of designating one property as the key vs. another is outside the scope of this article, but is probably an interesting thing to look at.

Obviously, in our case, we’ll designate this strange “Code” property as the key.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      // Map Rating class to legacy RATINGS view.
      modelBuilder.Entity<Rating>()
        .MapByColumnName(r => r.Code, "rating_code")
        .MapByColumnName(r => r.DisplayName, "rating_display_name")
        .MapByColumnName(r => r.ImageUrl, "rating_image_url")
        .HasKey(r => r.Code)
        .ToTable("RATINGS");

      // Map City class to legacy CITIES table.
      modelBuilder.Entity<City>()
        .MapByColumnName(c => c.Id, "city_id")
        .MapByColumnName(c => c.Name, "city_name")
        .MapByColumnName(c => c.Population, "city_population")
        .MapByColumnName(c => c.Description, "city_description")
        .HasKey(c => c.Id)
        .ToTable("CITIES");
    }

The above Rating mapping will successful allow us to populate Rating instances with data reflected in RATING views. But wait, we forgot to declare the association between Rating and City in the above snippet…….

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      // Map Rating class to legacy RATINGS view.
      modelBuilder.Entity<Rating>()
        .MapByColumnName(r => r.Code, "rating_code")
        .MapByColumnName(r => r.DisplayName, "rating_display_name")
        .MapByColumnName(r => r.ImageUrl, "rating_image_url")
        .HasKey(r => r.Code)
        .ToTable("RATINGS");

      modelBuilder.Entity<Rating>()
        .HasMany(r => r.Cities)
        .WithRequired(c => c.Rating)
        .Map(x => x.MapKey("city_status_cd").ToTable("CITIES"));

      // Map City class to legacy CITIES table.
      modelBuilder.Entity<City>()
        .MapByColumnName(c => c.Id, "city_id")
        .MapByColumnName(c => c.Name, "city_name")
        .MapByColumnName(c => c.Population, "city_population")
        .MapByColumnName(c => c.Description, "city_description")
        .HasKey(c => c.Id)
        .ToTable("CITIES");
    }

This should give you data mapping functionality that will link City instances with their correct Rating and Rating instances with all the Cities that have that Rating assigned to them.

 

Somewhat of an old topic, but still merits covering given the seemingly-overwhelming ignorance on the subject.

A common layout for a configuration page in some applications involves having a list box full of potential values and another list box adjacent from the first containing active values. In between the two list boxes are buttons which are responsible for providing functionality that allows us to move an item from the potential pool to the active pool. Not the most exciting thing, and fairly basic in and of itself, but you may run into an issue if you use something like JQuery to do the moving of the items (most would agree that having to do it with a postback instead would be rather painful).

Specifically, you may find yourself seeing the following error message if you perform a postback following the moving of one or more items from the potential pool to the active pool:

Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ page enableeventvalidation=”true” %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

The reason why you are getting this is because the data being added to the active list box is being submitted from the client-side, and isn’t something that server has put there. The server is not prepared to validate this data, and because this could potentially be dangerous and unwanted data, we get the previous error thrown at us.

There are a lot of examples and forum posts online that say the best thing to do is to simply turn off event validation using <%@ page enableeventvalidation=”true” %>. Doing this essentially turns off an important layer of security ASP.NET is providing for us. I find it irresponsible to recommend this solution, and would lead me to believe someone was incompetent if I ever saw them doing it without also adding thorough alternative input validation.

The correct way to handle this is to register the control receiving the client-side data (the active item list box) for event validation. In order to do this, you need to register an event reference for validation with a unique control ID with the potential values it may receive included. It should go inside a Render override. Something like:

    protected override void Render(HtmlTextWriter writer)
    {
      ClientScript.RegisterForEventValidation(ActiveListBox.UniqueID, ...);

      base.Render(writer);
    }

The ellipsis above represent the potential values. Most examples online demonstrate the use of hardcoded values as the potential values. I’ve never come across a list box containing values known at compile with anything I’ve worked on. So what you want to do, in our example, is loop through all of the list items in the potential item list box, and register those for event validation.

One important thing to note is what property’s value from the potential list items you should be registering. Don’t register the ListItem.Text property; something I bet some might do as a simple mistake. Register the ListItem.Value property instead. Taking all of that into consideration, you’d probably want something like the following:

    protected override void Render(HtmlTextWriter writer)
    {
      foreach (ListItem item in PotentialListBox.Items)
        ClientScript.RegisterForEventValidation(ActiveListBox.UniqueID, item.Value);

      base.Render(writer);
    }

That’ll take care of your problem then! If you are ever having errors relating to bad postback-data, you can always view what’s being submitted by temporarily overriding the Page’s ProcessRequest method and looking at the provided context’s Request property while developing your solution.validation.

 

Attempting to use TypeDescriptors in order to facilitate greater elegance in data binding, I found them to not be working at all in an ASP.NET environment.

Working on a project for my company, I found myself in a situation where I needed to bind some data to a third party ASP.NET web control. This third party control expected the data being bound to it to conform to a specific structure and format.

I was not interested in changing parts of my data model in order to adhere to this control’s expectations, and I was definitely not interested in lugging around anything like a DataTable (unless they’re absolutely required, I hate DataTables). So, instead of worrying about any of that, I decided to change the nature of the instances of existing data through the use of custom TypeDescriptionProviders, TypeDescriptors, and PropertyDescriptors.

When all was said and done, I had created some custom collections that would register my custom type descriptors with each instance added to the collection. When binding the data to the control however, it would behave as if the normal type providers were still in place! If you ever try to exert an influence on the data binding process in ASP.NET, you too may experience an issue of it not working. I’ll detail how I ended up solving this issue in this article.

I. Registering the TypeDescriptionProvider

Let’s look at the code I was using in order to register the type descriptor with the individual instances. My goal here was to isolate the use of this custom type descriptor to the act of data binding — I didn’t want it to be present whenever I was doing whatever-else with the type. In this example, I’m working with UserProfile-typed data. The custom type description provider type I’m using is UserResultTypeDescriptionProvider. Basically, this provider is for describing UserProfile types returned as search results from a search where the profiles are ranked in terms of their relevancy to a provided search term (a name).

/// <summary>
/// Registers a custom <see cref="TypeDescriptionProvider"/> for the item, and then
/// inserts the item into the collection at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which item should be inserted.</param>
/// <param name="item">The object to insert. The value can be null for reference types.</param>
protected override void InsertItem(int index, UserProfile item)
{
  TypeDescriptor.AddProvider(new UserResultTypeDescriptionProvider(), item);

  base.InsertItem(index, item);
}

The custom type description provider shown above would then return a specific type of TypeDescriptor containing exposing a static array of types and instance property readers/writers that would allow the data to achieve conformance with the third party control’s data binding expectations. The implementation isn’t important, however. We can clearly see I’m registering the custom TypeDescriptionProvider with the instance; that’s good enough for the purposes of this article.

II. Binding to a DataBoundControl

The third party control offered the typical kind of data binding functionality exposed by all DataBoundControl-derived classes: Data would be attached to the DataSource property, a call would be made to DataBind, and then everything would be golden. Why would it be then, that instead of using the custom TypeDescriptionProvider/TypeDescriptor for the UserProfile type, it would end up using the default TypeDescriptionProvider/TypeDescriptor?

The reason why has to do with a very recent change to the ASP.NET framework that was made in the .NET 4.0 framework. The specific change I’m referring to was made to the DataBinder ASP.NET class, in the GetPropertyValue method. A data binding control typically will provide GetPropertyValue with the object instance and the name of the property it wants the value for. It is here, in the GetPropertyValue method, where TypeDescriptors come into play when discussing data binding.

ASP.NET returns the value by making a call to TypeDescriptor.GetProperties; a call which will give control to a custom type descriptor if one was registered to the instance or instance type. At least, that’s what it used to do more or less before .NET 4.0.

Starting in .NET 4.0, DataBinder.GetPropertyValue now makes a call to an internal method named GetPropertiesFromCache. In this new method, ASP.NET makes use of cached PropertyDescriptorCollections in order to retrieve the values from provided instances. If the proper PropertyDescriptorCollection is not available at the time of execution, then it would retrieve the appropriate TypeDescriptor, invoke GetProperties, and cache the result of that. Smart optimization; however, in my opinion, it wasn’t implemented correctly, because although the scenario described above sounds reasonable and logical, it would end up not using my custom type descriptor and deferring to the default descriptor.

How isn’t GetPropertiesFromCache implemented correctly? In order to make use of a custom type descriptor and custom property descriptors, you would need to call TypeDescriptor.GetProperties(profile), where profile is an instance of my UserProfile type. What GetPropertiesFromCache does is very different. Instead, it gets the type of the provided container first, consequently making use of a TypeDescriptor based on the provided object’ type and not the instance itself. You may remember that I earlier indicated that I wanted to isolate this custom TypeDescriptor to data binding only. Thus, registering a type descriptor to the UserProfile type itself was out of the question. Therefore, my custom type descriptor was going to get ignored here.

I think that’s a mistake in the .NET source code. Luckily for us, that’s not all the GetPropertiesFromCache method does. Before any of the above gets executed, it checks if the EnableCaching property is enabled, or if the provided container implements ICustomTypeDescriptor. The desired custom TypeDescriptor we’re looking for here implements ICustomTypeDescriptor, but the the provided UserProfile instance certainly does not. This leaves us with the EnableCaching property.

III. The Solution

I solved my problem by setting EnableCaching to false on the third party control.

I’ve read (didn’t spend much time doing so) that the EnableCaching property is disabled by default. In my case, it clearly was enabled by default. I am unaware if that’s a mistake made by the specific control, or if caching is actually enabled by default.

To sum up, if you make use of custom TypeDescriptionProviders, TypeDescriptors, and PropertyDescriptors when data binding to an ASP.NET control using .NET 4.0, and if you register these custom descriptors on the instance (not type) level, then you’ll want to make sure EnableCaching is disabled.

 

A small foray into the world of .NET DateTime format specifiers, culture, and the like.

When converting a date to a string, let’s say to ISO 8601 using the user’s current culture, you have several ways of specifying the format of the resulting string:

string formattedDate = date.ToString("s", CultureInfo.CurrentCulture);

and

string formattedDate = date.ToString(DateTimeFormatInfo.CurrentInfo.SortableDateTimePattern,
                                     CultureInfo.CurrentCulture);

We can obviously not include the CultureInfo.CurrentCulture, as that is what will be used automatically if no culture is provided, however I have a rule where I always provide a format provider if one can be provided.

Difference?

What’s the difference between the “s” specifier and the SortableDateTimePattern property? They’re both strings, so does the SortableDateTimePattern simply resolve to an “s” as well?

Actually, the SortableDateTimePattern property returns a constant of the format itself:

yyyy’ – ‘MM’ – ‘dd’T’HH’:’mm’:’ss

If you format using the specifier instead, the framework will essentially go through a large switch statement that basically pairs up the individual one-character specifier directly to a property such as SortableDateTimePattern.

Do all date format properties simply return a constant format string like SortableDateTimePattern? Certainly not, as many of the formats of course depend on the culture and calender settings. That’s the whole reason we have formats in the first place, as a short date isn’t always mm/dd/yyyy, for example.

So which is which? The following are two lists, one of formats that are constant, and one of formats that depend on the calendar settings.

Constant Format Properties

  • RFC1123Pattern
  • SortableDateTimePattern
  • UniversalSortableDateTimePattern

Format Properties Affected by Calendar Settings

  • FullDateTimePattern
  • LongDatePattern
  • ShortDatePattern
  • YearMonthPattern
  • ShortTimePattern
  • LongTimePattern

Format Specifiers vs. Format Properties

So what’s the best thing to use? That really depends. If you want one of the formats listed above, and you have an initialized DateTimeFormatInfo object, then the fastest way to get the format you want is by using one of the format properties.

When do you have an initialized DateTimeFormatInfo object? Well, obviously if you have one declared and initialized locally. Other than that, if you refer to my previous article you essentially have one already initialized for you at any time following the first access of DateTimeFormatInfo.CurrentInfo or CultureInfo.CurrentCulture.DateTimeFormat per thread, assuming a constant culture over time. You already have one initialized for you at any time following the first access of DateTimeFormatInfo.InvariantInfo or CultureInfo.InvariantInfo.DateTimeFormat per Application Domain. There are many other actions that result in the framework accessing one of these as well.

Does this matter much in the long run? Nope. Does it matter at all? The difference, although miniscule, is a difference, so unless your goal in life is to be ignorant (a common goal, even among professionals), there’s no harm in knowing and doing.

So, it’s safe to assume that we always have an instance available (expect for maybe the first attempt), so if the format I’m interested in corresponds to one of the known format properties, I’ll always use the DateTimeFormatInfo property.

If you are using a long format string where you’d like to include the specifier in the string, then feel free to just use one of the specifiers. Although the DateTimeFormatInfo class is designed in a way that would permit the specifiers to change without requiring classes using it to have to recompile, I find it very unlikely that would ever happen, as that would just cause sheer pandemonium.

Additionally, there are many formats that do not have their own format property.

Standard Format Specifiers with no Equivalent Property

  • f : Full date and time
  • g : General (short date and short time)
  • G : General (short date and long time)
  • o, O : Round-trip date/time patterns
  • U : Full date and time (long date and long time) using universal time

If you wish to use one of these formats, you’re stuck with the specifier. From there, there are many other custom, or non-standard formats that will also require the use of a specifier.

Conclusion

The most important thing is to be consistent. The second more important thing is to use common sense in when to break consistency, so you don’t hang yourself trying to maintain your policy.

That aside, I will always use date time format properties when dealing with the standard formats that map to said properties, and I will always use specifiers when dealing with custom formats.

 

If you deal with dates and cater to a world-wide audience, chances are that you understand the importance of properly formatted dates based both on the culture and using a universal, culturally-insensitive, or invariant, culture.

Much of the time you’ll be dealing with the DateTimeFormatInfo class when formatting dates. It implements the IFormatProvider interface, so an instance can be provided to any of the plethora of formatting methods that accept that interface.

There are a number of ways to get an instance of DateTimeFormatInfo, and we’re going to look at those different ways right now. The impact of this information is not significant, it is being presented to merely satisfy the reader’s nagging curiosity about some .NET internals, or perhaps assist in the solving of some very strange problem that is occurring due to advanced use of the framework.

I hope I’m not surprising you with this, but dates are formatted differently based on what part of the world you live in. During the creation of a DateTimeFormatInfo instance, it is given a specific culture it will represent throughout its life-cycle.

What if we initialize an object on our own?

DateTimeFormatInfo dtfi = new DateTimeFormatInfo();

This creates a culturally-invariant DateTimeFormatInfo that adheres to a Gregorian calendar. You’re pretty much stuck after this, you won’t be able to change the culture of this object directly.

An overload for the DateTimeFormatInfo constructor exists that allows you to provide the culture and calendar, however it is internal. This is a good thing however, as that would be a painful way to get this object.

It hopefully won’t take you long until you notice that the DateTimeFormatInfo class offers several static properties that are of some interest to us: CurrentInfo and InvariantInfo.

This looks a bit similar to the CultureInfo class, specifically the CurrentCulture and InvariantCulture properties.

Another similarity to the CultureInfo class is that CultureInfo also implements the IFormatProvider interface. On top of that, CultureInfo provides an instance of DateTimeFormatInfo with the DateTimeFormat property.

The fact that both CultureInfo and DateTimeFormatInfo implement the IFormatProvider interface may have prompted you in the past to wonder which object should be used when dealing with a method that accepts the IFormatProvider interface. What are the implications of using one over the other, and how are the four different ways of ultimately getting a DateTimeFormatInfo object that are listed above different from eachother?

DateTimeFormatInfo.CurrentInfo

This will directly return another DateTimeFormatInfo instance that is set to the current culture. It does the following in order to do this:

  1. Gets the CultureInfo from the current thread’s CurrentCulture property (Thread.CurrentThread.CurrentCulture). Note that when you are accessing the current thread’s CurrentCulture property, you are basically accessing the CultureInfo.CurrentCulture property (which simply returns Thread.CurrentThread.CurrentCulture).
  2. Returns a direct reference to the date time format if the thread’s current culture instance is the base CultureInfo type itself, and not a derivation. The DateTimeFormat property of the CultureInfo object does not come into play here; instead, what we’re directly reading from the CultureInfo object’s dateTimeInfo private field.
  3. If the thread’s current culture instance has null assigned to its date time information field, then the CultureInfo‘s GetFormat method is invoked, which returns a DateTimeFormatInfo instance which is then returned.
  4. If the current thread’s culture instance is actually an object type that derives from CultureInfo, then it will always make a call to CultureInfo.GetFormat, and never read from the CultureInfo.dateTimeInfo field directly.

So, if you’re ever dealing with objects deriving from CultureInfo and setting the thread’s current culture to use them, be aware that you can modify the way the DateTimeFormatInfo is returned by overriding the CultureInfo’s GetFormat method.

DateTimeFormatInfo.InvariantInfo

This will return another DateTimeFormatInfo instance set to the culturally-insensitive culture. It does the following to do this:

  1. If the current Application Domain already has created a culturally-insensitive DateTimeFormatInfo instance, this is returned.
  2. Otherwise, a new instance is created using the public default constructor of DateTimeFormatInfo.
  3. The Calendar exposed by new DateTimeFormatInfo instance is set to read only.
  4. The new DateTimeFormatInfo instance itself is set to readonly, and then returned.
So, unlike DateTimeFormatInfo.CurrentInfo, the InvariantInfo property is initialized once per application domain, not per thread. Not a very big surprise, but may be important to know just in the event you’re doing anything adventurous and (most likely) irresponsible.

CultureInfo.CurrentCulture.DateTimeFormat

This will return a DateTimeFormatInfo object set to use the current culture. This is achieved by the following:

  1. Because we’re accessing CultureInfo.CurrentCulture, the current thread’s CurrentCulture is used as the culture (Thread.CurrentThread.CurrentCulture).
  2. If the current thread’s culture instance already has a DateTimeFormatInfo instance initialized, that’ll be returned (i.e. if the dateTimeInfo is not null, then that is returned).
  3. Otherwise, a new DateTimeFormatInfo object is created by directly initializing a new DateTimeFormatInfo instance and passing the culture data to the constructor.
  4. The DateTimeFormatInfo instance is set to readonly.
  5. A call is made to Thread.MemoryBarrier, and then the newly initialized DateTimeFormatInfo instance is assigned to the dateTimeInfo field.

How Does CultureInfo.CurrentCulture.DateTimeFormat Relate to DateTimeFormat.CurrentInfo?

  1. The CultureInfo.CurrentCulture.DateTimeFormat property is what is responsible for actually initializing the DateTimeFormatInfo instance that gets returned; calling DateTimeFormat.CurrentInfo results in a call made to the culture’s GetFormat method, which itself will return its own CultureInfo.DateTimeFormat property. So, regardless of where you start, you seem to end up in the same place. Technically, calling CultureInfo.CurrentCulture.DateTimeFormat is more direct than calling DateTimeFormat.CurrentInfo, which will end up calling just that.
  2. Differences begin to arise when one starts talking about object types derived from CultureInfo. Let’s say we wish for our custom CultureInfo class to return a DateTimeFormatInfo instance which is modified in some fashion that differs from the norm. By override CultureInfo.GetFormat, which is a virtual method, we can achieve this for calls made to DateTimeFormat.CurrentInfo, which will call this method.
  3. However, because CultureInfo.DateTimeFormat is a static property, and because the instantiation of the DateTimeFormatInfo object is done directly inside this property, there is no way to override this behavior. Therefore, we can easily end up in a situation where DateTimeFormatInfo.CurrentInfo returns a differently composed DateTimeFormatInfo instance than what we get with CultureInfo.CurrentCulture.DateTimeFormat (assuming the current culture is our custom culture class).
  4. This makes our desire of ours one that may be impossible to fulfill (customizing the creation-related logic behind a custom culture’s date time format). Hopefully no one out there needs to do this.

CultureInfo.InvariantCulture.DateTimeFormat

  1. This will return a culturally-insensitive DateTimeFormatInfo.
  2. The invariant culture is created one per application domain, inside (indirectly) the static constructor of the CultureInfo class.
  3. Once the invariant CultureInfo instance is created, the rest of the process of creating the DateTimeFormatInfo mirrors that of the previous section.

How Does CultureInfo.InvariantCulture.DateTimeFormat Relate to DateTimeFormat.InvariantInfo?

  1. These two properties, unlike their CurrentCulture-ish brethren, are completely unrelated in how they initialize the DateTimeFormatInfo instance that they return.
  2. The DateTimeFormat.InvariantInfo property does not actually deal with culture at all. It simply initializes a new DateTimeFormatInfo instance using that class’s default constructor.
  3. Although their creation mechanisms are unlinked, they are similar in that one cannot exert any influence in the creation of these constructs from derived classes, as far as I am aware.

So what should I use, and when!?!?

Whether you should use the invariant or culturally-sensitive variant of DateTimeFormatInfo is outside the scope of this article, and has plenty of coverage.

That aside, the question you may have is, is it preferable to get a DateTimeFormatInfo instance using the static properties of the DateTimeFormatInfo class, or the CultureInfo class?

Basically, if you are primarily dealing with culture as far as what is set on the thread, you might as well just stick to using the CultureInfo static properties if you’re looking to be consistent. I find the presence of these static properties on the DateTimeFormatInfo class to be slightly redundant.

The difference in performance between the two is laughable, and barely worth discussing; but, technically speaking, again, the CultureInfo static properties are a fine choice. Things do change if you are deriving the CultureInfo class, but then again, this article should be a good case study in why that may be a bad idea.

What About Methods that Accept IFormatProvider?

Since both CultureInfo and DateTimeFormatInfo implement this interface, does it matter which one you provide?

Well, that obviously depends on the specific method that is accepting the format provider. In the case of DateTime.ToString(IFormatProvider), it invokes the static GetInstance method belonging to the DateTimeFormatInfo class, using what that returns as the format provider.

The GetInstance simply determines if it is dealing with a CultureInfo instance (and specifically a non-derived type) or a DateTimeFormatInfo instance.

If it determines that the provided IFormatProvider is neither a strictly base type CultureInfo or DateTimeFormatInfo instance, it will invoke the GetFormat method of the provided IFormatProvider in an attempt to have that return a DateTimeFormatInfo instance. If that fails to happen (returns null), then it will default to the DateTimeFormatInfo.CurrentInfo property.

This process obviously may not be consistent across different objects.

Regardless, at least as far as DateTime is concerned, you can feel free to pass in the requirements demand. Obviously, if you are trying to use a DateTimeFormatInfo which differs from either the current thread’s culture or whatever culture you have on hand, you will want to pass in that DateTimeFormatInfo instance. Otherwise, you may as well just pass in the CultureInfo as that is typically the first thing checked anyway, and less typing is involved for that in most circumstances.

That’s it. It is good to understand what you are actually working with; better than being a fool, right?

© 2012-2013 Matt Weber. All Rights Reserved. Terms of Use.