Added GetOrDefault() extension methods for state providers

In the framework ADF.NET state can be temporarily stored by calling the StateManager. The StateManager is an static façade that holds three different instances of the IStateProvider interface. These instances are:

  • Personal. State that is stored somewhere for personal use of the current user of the application. Usually in web applications an implementation is plugged in to use the Session object. in desktop applications this is more likely a Dictionary, and in Azure an implementation could be used to refer to Azure Storage.
  • Application. State that needs to be shared over all users.
  • Settings. State that can be obtained from settings, such as from environment.config or web.config.

To facilitate easier use of state, we’ve added two overloaded extension methods that operate on the interface IStateProvider.

   1: public static T GetOrDefault<T>(this IStateProvider provider, string key, Func<T> value)

   2: {

   3:     if (!provider.Has(key)) { provider[key] = value.Invoke(); }

   4:  

   5:     return (T)provider[key];

   6: }

   7:  

   8: public static T GetOrDefault<T>(this IStateProvider provider, string key, T value)

   9: {

  10:     if (!provider.Has(key)) { provider[key] = value; }

  11:  

  12:     return (T)provider[key];

  13: }

Using these extension methods will allow you to get the value for a specific key, and in case it doesn’t exist yet, first add it to the state and afterwards return it. The first overload can be used to only evaluate the func when the key is not yet present, similar to the following code example.

   1: public static DomainCollection<Company> GetAll()

   2: {

   3:     lock (cacheLock)

   4:     {

   5:         return StateManager.Personal.GetOrDefault(key, () => List(CompanyGateway.GetAll()));

   6:     }

   7: }

Here, the List() method is only invoked if no key is present.

The second overload is best used when the value does not need to be evaluated, but rather already exists.