Category Archives: C#

Using the C# generic cache: the Tester Doer pattern

In a previous post, I wrote about a generic cache class that I frequently use. I offered the code freely without providing any example use cases. The pattern that I use involves a Boolean test and the value returned in an out parameter. I googled the pattern and it in fact has a name, the “tester doer” pattern.

Let’s look an an over simplified example where we are checking the cache for a value stored in a key named “foo”.


            string foo = null;

            // test to see if we have the value in the cache already
            if(!Cache.Get("foo", out foo)) {

                // since we're here, it's obvious the cache doesn't yet have this stored

                // set the variable foo first
                foo = "bar";

                // let's store it in the cache as well
                Cache.Set("foo", foo);

            }

            // if we got here without ever going into the if block, our implementation of the cache
            // provider took care of setting the out parameter "foo"

            // in either case, we can now be assured that cache value for the foo key has been stored in the foo variable.

            // do something fun with that variable!
            Console.WriteLine(foo);

Advertisements

Database driven Asp.net MVC Model Binding, Validation, and Metadata

One of classic MVC paradigms is that you can bind class models to a view, and with attribute based annotations, you can have synchronized server and client side validations on them. This concept is absolutely brilliant! Code once and you don’t have to worry about duplicating your server side logic in the untrustworthy browser.

This is all fine and dandy if your validation logic and your models don’t change often. Consider the scenario that you are developing an application that will likely change over time. Or perhaps, you need to develop your app such that the client has put it in the requirements that they need to have control over the content long after you have completed the app. If they need to control the content and the form fields (inputs), those inputs will still need to be validated.

Enter database driven model validation, binding and metadata.

I have successfully developed implementations of the following, which accomplish exactly what I need:

ModelBinder
ModelValidationProvider
ModelMetadataProvider

My implementations heavily leverage the power of the extensible MVC DataAnnotations providers which read the attribute based metadata that you can decorate your classes with.

The code that I have written is currently in a state that is tightly bound to the database schema of the project I am currently working on. My plan is to extract the juice from the project so that the code is reusable to all.

I’m sorry to say that at this point, I have no code examples, but they will surely follow!

Simple generic C# caching class (I use this all the time)

I wanted to add this simple class that I find myself using all the time in every project that I create. It is a generic caching class:

CacheProvider`1.cs

    public abstract class CacheProvider<TCache> : ICacheProvider
    {

        public int CacheDuration
        {
            get;
            set;
        }

        private readonly int defaultCacheDurationInMinutes = 30;

        protected TCache _cache;

        public CacheProvider()
        {
            CacheDuration = defaultCacheDurationInMinutes;
            _cache = InitCache();
        }
        public CacheProvider(int durationInMinutes) 
        {
            CacheDuration = durationInMinutes;
            _cache = InitCache();
        }

        protected abstract TCache InitCache();

        public abstract bool Get<T>(string key, out T value);

        public abstract void Set<T>(string key, T value);

        public abstract void Set<T>(string key, T value, int duration);

        public abstract void Clear(string key);

        public abstract IEnumerable<KeyValuePair<string, object>> GetAll();

    }

ICacheProvider.cs

    public interface ICacheProvider
    {
        /// <summary>
        /// Retrieve cached item
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Name of cached item</param>
        /// <param name="value">Cached value. Default(T) if
        /// item doesn't exist.</param>
        /// <returns>Cached item as type</returns>
        bool Get<T>(string key, out T value);

        /// <summary>
        /// Insert value into the cache using
        /// appropriate name/value pairs
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="value">Item to be cached</param>
        /// <param name="key">Name of item</param>
        void Set<T>(string key, T value);

        /// <summary>
        /// Insert value into the cache using
        /// appropriate name/value pairs WITH a cache duration set in minutes
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Item to be cached</param>
        /// <param name="value">Name of item</param>
        /// <param name="duration">Cache duration in minutes</param>
        void Set<T>(string key, T value, int duration);

        /// <summary>
        /// Remove item from cache
        /// </summary>
        /// <param name="key">Name of cached item</param>        
        void Clear(string key);

        IEnumerable<KeyValuePair<string, object>> GetAll();

    }

I tend to use dependency injection to implement this cache. Here is a concrete implementation of my cache provider:

    public class HttpCache : CacheProvider<Cache>
    {
        protected override Cache InitCache()
        {
            return HttpRuntime.Cache;
        }

        public override bool Get<T>(string key, out T value)
        {
            try
            {
                if (_cache[key] == null)
                {
                    value = default(T);
                    return false;
                }

                value = (T)_cache[key];
            }
            catch
            {
                value = default(T);
                return false;
            }

            return true;
        }

        public override void Set<T>(string key, T value)
        {
            Set<T>(key, value, CacheDuration);
        }

        public override void Set<T>(string key, T value, int duration)
        {
            _cache.Insert(
                key,
                value,
                null,
                DateTime.Now.AddMinutes(duration),
                TimeSpan.Zero);
        }

        public override void Clear(string key)
        {
            _cache.Remove(key);
        }

        public override IEnumerable<KeyValuePair<string, object>> GetAll()
        {

            foreach (DictionaryEntry item in _cache)
            {
                yield return new KeyValuePair<string, object>(item.Key as string, item.Value);
            }

        }
    }

View the source on GitHub: Omegaluz.Caching

Update, here is a new article with an example: Using the C# generic cache: the Tester Doer pattern

Await, Async, Mvc and Impersonation

I’ve been using AsyncControllers in Asp.net mvc for quite a while now.   I’ve also been using the Tasks Parallel Library sparingly.  Only recently have I used them together, with and without the new .Net 4.5 async and await keywords.  Throw unmanaged impersonation into the mix and you’re in for a smorgasbord of technologies that don’t necessarily play well together.

I want to tell you a story, but I must first set the stage for you.

  • I was developing an internal web app for my company TempWorks Software.
  • I Wanted to make use of concurrency wherever possible.
  • The data layer needed several different elevated credentials in varying contexts, other than that of the AppPoolIdentity.

Our last release to production web product, WebCenter 6 used AsyncControllers, taking advantage of the AsyncManager, rather than Task’s with continuation. If you are unfamiliar with either, have a look at this concise outline of the evolution of Mvc asynchronous controllers here. This time, I chose to use the more straightforward, Task with Task.ContinueWith.

The first problem I encountered was trying to make my impersonation context flow through my tasks and continuations. Imagine something like the following inside one of my Actions (the important thing to note is how I am doing impersonation).

FeatureEditorViewModel viewModel;

using (ElevatedUser.Impersonate())
{
    var features = LicensingService
        .GetFeatures(false);

    viewModel = new FeatureEditorViewModel(features, versionID, productID);
}

return View(viewModel);

The IDisposable ElevatedUser object you see above is a derivative of the code in the following article: Windows Impersonation Using C#. The important part about this is that it is IDisposable in my class, and that it is calling unmananged code via DllImport to do impersonation.

Interestingly enough, I never noticed any problem with this until I deployed to production servers. The reason was, that because I was using IIS Express, my AppPoolIdentity was in fact MY user account, and I happened to have permissions on the object I was accessing. When I deployed to production, the AppPoolIdentity was no longer me, it was the App Pool user account, thus making all data calls under the wrong context.

I scoured the net in search of answers, and discovered that I had a few options.

1. Change the aspnet.config file (there are 2 of them if you have an x64 machine), setting the value “legacyImpersonationPolicy” to enabled=false, and “alwaysFlowImpersonationPolicy” to enabled=true
2. Do the same as above except in the context of the app pool only (I discovered later on that this does not work)
3. Capture the impersonation context outside of my thread, and then re-impersonate inside of my thread

I chose option 3 because I wanted to adhere to the least privilege principal. I wanted keep elevated credentials to the absolute minimum so as not to expose any overlooked security holes in my application.

I came up with my own TPL extension method class that I could use in place of the default TPL methods.

using System;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;

public static class TaskFactoryExtensions
{

    public static Task StartNewImpersonated(this TaskFactory taskFactory, Action action)
    {
        var identity = WindowsIdentity.GetCurrent();
        return taskFactory.StartNew(() =>
        {
            using (identity.Impersonate()) 
            {
                action();
            }
        });
    }

    public static Task<TResult> StartNewImpersonated<TResult>(this TaskFactory taskFactory, Func<TResult> function)
    {
        var identity = WindowsIdentity.GetCurrent();
        return taskFactory.StartNew<TResult>(() =>
        {
            using (identity.Impersonate())
            {
                return function();
            }
        });
    }

    public static Task ContinueWithImpersonated<TResult>(this Task<TResult> task, Action<Task<TResult>> continuationAction)
    {
        var identity = WindowsIdentity.GetCurrent();

        return task.ContinueWith((antecedent) =>
        {
            using (identity.Impersonate())
            {
                continuationAction(antecedent);
            }
        });
    }

    public static Task<TNewResult> ContinueWithImpersonated<TResult, TNewResult>(this Task<TResult> task, Func<Task<TResult>, TNewResult> continuationFunction)
    {
        var identity = WindowsIdentity.GetCurrent();

        return task.ContinueWith<TNewResult>((antecedent) =>
        {
            using (identity.Impersonate())
            {
                return continuationFunction(antecedent);
            }
        });
    }

    public static Task ContinueWhenAllImpersonated(this TaskFactory taskFactory, Task[] tasks, Action<Task[]> continuationAction)
    {
        var identity = WindowsIdentity.GetCurrent();

        return taskFactory.ContinueWhenAll(tasks, (antecedent) =>
        {
            using (identity.Impersonate())
            {
                continuationAction(antecedent);
            }
        });
    }

    public static Task<TResult> ContinueWhenAllImpersonated<TResult>(this TaskFactory taskFactory, Task[] tasks, Func<Task[], TResult> continuationFunction)
    {
        var identity = WindowsIdentity.GetCurrent();

        return taskFactory.ContinueWhenAll<TResult>(tasks, (antecedent) =>
        {
            using (identity.Impersonate())
            {
                return continuationFunction(antecedent);
            }
        });
    }

    public static void ForAllImpersonated<TSource>(this ParallelQuery<TSource> source, Action<TSource> action)
    {

        var identity = WindowsIdentity.GetCurrent();

        source.ForAll(new Action<TSource>((tsource) =>
        {
            using (identity.Impersonate())
            {
                action(tsource);
            }
        }));
        
    }

}

This worked great aside from the fact that everytime I needed to use a varied overload in the TPL, I needed to code a new extension method in my class.

Enter .Net 4.5… Async, await.

Before converting my app to 4.5 and the “new way” of doing things, I ingested as many Kindle books as I could find on the topic. Here is my short list:

So here I was at a cross-roads. I now had enough knowledge to start using the async and await keywords in place of “continuations” using ContinueWith and various Wait techniques. At this point however, I theorized that if I was to substitute usage of ContinueWith (or in fact, my very own ContinueWithImpersonated as noted above) with await, that the impersonation context would be lost.

I converted a couple of methods to async/await and threw in a couple of debug breakpoints. To much chagrin, I was right, the impersonation context was lost AFTER my await keyword.

Back to the drawing board! My options were few, and I still didn’t want to turn on the aspnet.config options that I mentioned earlier.

I then diagrammed my architecture:

* Controller
* Actions -> call services via Tasks (impersonate here)
* Services -> call repositories via Tasks
* Repositories

It became very apparent that because I couldn’t persist my impersonation context through tasks and continuation, that I had to move where I was doing my impersonation.

My arch then looked like this:

* Controller
* Actions -> call services via Tasks
* Services -> call repositories via Tasks
* Repositories (impersonate here)

So, now I would have to rewrite how I was calling my database, so that impersonation was done there.

I am using a variation of Oh So Simple SQL, so I created some extension method overloads to handle this.

    public static class RepositoryExtensions
    {
        // public List<O> FetchAll<O>();
        public static List<O> FetchAll<O>(this QueryBuilder<StoredProcedure> baseQuery, IElevatedUser elevatedUser)
        {
            using (elevatedUser.Impersonate())
            {
                return baseQuery.FetchAll<O>();
            }
        }
        public static List<O> FetchAll<O>(this QueryBuilder<Query> baseQuery, IElevatedUser elevatedUser)
        {
            using (elevatedUser.Impersonate())
            {
                return baseQuery.FetchAll<O>();
            }
        }

        //public O Fetch<O>();
        public static O Fetch<O>(this QueryBuilder<StoredProcedure> baseQuery, IElevatedUser elevatedUser)
        {
            using (elevatedUser.Impersonate())
            {
                return baseQuery.Fetch<O>();
            }
        }
        public static O Fetch<O>(this QueryBuilder<Query> baseQuery, IElevatedUser elevatedUser)
        {
            using (elevatedUser.Impersonate())
            {
                return baseQuery.Fetch<O>();
            }
        }

        //public void Execute();
        public static void Execute(this QueryBuilder<StoredProcedure> baseQuery, IElevatedUser elevatedUser)
        {
            using (elevatedUser.Impersonate())
            {
                baseQuery.Execute();
            }
        }
        public static void Execute(this QueryBuilder<Query> baseQuery, IElevatedUser elevatedUser)
        {
            using (elevatedUser.Impersonate())
            {
                baseQuery.Execute();
            }
        }

    }

My IElevatedUser object looks like this:

    public interface IElevatedUser : IDisposable
    {

        IElevatedUser Impersonate();
        IElevatedUser Impersonate(string account, string password);

        string Account
        {
            get;
            set;
        }

        string Password
        {
            get;
            set;
        }

    }

The moral of the story is 2-fold.

1. Impersonation doesn’t flow through the TPL automatically
2. Make sure you are doing impersonation at the right place

I’ve also compiled the impersonation classes as a gist available here.

Twin Cities Code Camp – Day 2

Expressing Yourself with C# Expression Trees – Chad Kulesa

Code == Data

  • Dynamically modify code at run time.
  • Create new code at run time.
  • Translate code to another Langauge (SQL, XPath, etc.)
  • Strongly typed.

Expression<Func<string, bool>> expression = x => x == "Value";

var x = Expresion.Parameter(typeof(string), "x");
Expression<Func<string, bool>> expression =
     Expression.Lambda<Func<string, bool>>(
          body: Expression.Equal(
               left: x,
               right: Expression.Constant("Value")),
          parameters: x);

Lambda

  • Easier to read
  • Don’t need to learn the API
  • Compiler will simplify constant expressions

API

  • Additional commands available
  • Dynamically create expression trees

Expression Trees are Immutable – you cannot change them at runtime.

Most C# programmers use expression trees all of the time without even knowing it. For example, LINQ syntax uses expression trees. Func<T, bool>

Expression trees are not useful for just querying. It also has it’s uses for what is called Fluent Configuration. The logic is that is is much better to get configuration errors at compile time rather than runtime. (Don’t know if I’m in agreement with this – I prefer web.config files for configuration changes. They recycle and restart your app when you change them. You also don’t need to recompile your code to change a configuration.)

Source code for presentation at: http://chadkulesa.com

Extending .NET Applications with MEF Plugins – J Wynia

How to extend .NET Applications with MEF plugins. Not how to create METH-amphetamines.

Why should we bother using an extensible architecture? The dominant reason is that the decision of what code to run is not known at compile time. The classic sign that you should be using a plugin based architecture is that you are using a switch statement with a ton of cases. Another, is if you have an app that needs to act differently depending on what kind of record it is in the context of. If the context matters as to what code you want to run. Another great reason is if you want other developers to build upon your product.

The reason the Microsoft focus is on MEF is because Visual Studio’s plug architecture is all MEF based as of 2010.

"I need a" = "Import"

&quotI need some" = "Import Many"

"I have a" or "I am a" = "Export"

"Match up the needs with the providers" = "Compose"

Source code dealt with a loan processing company that did just that – processed loans – console app.

Loan processors became Interfaces injected into the LoanApplication so that many types of Loan Processors can be defined.

Morphed app to use DI/IoC to import the needed LoanProcessor.

Usually, he creates a default implementation of an Export in the assembly so his app does not throw exceptions if there are no imports/exports found. Because of this, he always includes an AssemblyCatalog in the final composition catalog that contains the executing assembly. J calls this Plugin selection with fallback.

Showed an awesome way to load modules. He usually uses the ImportMany attribute to import everything and let the application choose how to load the modules. His example had a method called ChoosePlugins.

caveat. Metro apps IoC containers only work with MEF.

Source available here.

check out if this then that