Entity Framework 6 and Async

At a previous company that I worked for, one of my colleagues, Paul Czywczynski referred to Entity Framework as “Database Crack”. I can see where he was coming from. There is no substitute for a database developer who knows how to write a Common Table Expression. These days however, to be a well-rounded back-end developer, you’re a step ahead of the rest if you can write your own SQL code. Entity Framework is great for getting up and going quickly. The dynamic query generation is much better today than it was just a few years ago. Code-First has come a long way, especially with the introduction of Database Migrations.

The Task Parallel Library (TPL) is good. Async is great. Await is even better.

Recently, the EF team has brought asynchronous operations to the EF API. You now see extension methods for everything that executes a query; FirstOrDefaultAsync, SingleAsync, ToListAsync, etc… AWESOME right?

Not so fast…

Check this out, directly from the EF 6 Codeplex site:

For the moment, EF will detect if the developer attempts to execute two async operations at one time and throw.

Basically what this is saying, is that you cannot access the result of an async operation until you have awaited the previous. Doesn’t that effectively defeat the power and purpose of async operations in EF? I believe the problem at hand is that DbContext or ObjectContext is not thread safe. In other words, because EF manages change tracking behind the scenes, making it async is a no-no. If you change something on one thread, what happens to that object on the other thread? This is not a problem that I personally want to solve, but I hope that someone at Microsoft does. If they truly want to make the EF 6 API async, then they must tackle this as well.

These days, Microsoft is making their newer API’s task based. My advice to anyone reading this, is that if you are developing against the Microsoft stack, it would greatly benefit you to brush up on your async skills.

*** UPDATE ***

I filed a “bug” on the CodePlex site last week regarding this. Technically, it wasn’t a bug, but I wanted to see what they would say: CodePlex Entity Framework Work Item #1279

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);

GooPh – a Google Voice client for Windows Phone 8

CatalogueImage

Last week while recovering from neck surgery, I used my down time to develop an extremely simple Windows Phone 8 app; my very own Google Voice client. The app is certified and available for purchase in the store!

This was a fun little project that allowed me to see how the whole Windows Store certification process worked. It was surprisingly easy. The hardest part was waiting the 4 days until my app was certified.

There is very little to the user interface aside from a basic login page, and a phone dialer. You can check out GooPh in the Windows Phone store, or visit the GooPh home page.

WXGA-Screenshot4-Dialer3

Web API, HttpError and the behavior of Exceptions – ‘An error has occurred’

Api Error

When you deploy an ASP.Net Web Api project to a server in RELEASE mode configuration and you have Custom Errors set to On, you’ll likely notice that your once nicely formatted error responses are no longer so friendly.

During local development web api errors are formatted nicely with messages, stack trace, etc.

XML
<Error><Message>An error has occurred.</Message><ExceptionMessage>The method or operation is not implemented.</ExceptionMessage><ExceptionType>System.NotImplementedException</ExceptionType><StackTrace> at AppCenter.Web.Controllers.ApplicantsController.&lt;Post&gt;d__a.MoveNext() in e:\Sample.Web\Controllers\HomeController.csline 86</StackTrace></Error>

JSON
{
"Message":"An error has occurred.",
"ExceptionMessage":"The method or operation is not implemented.",
"ExceptionType":"System.NotImplementedException",
"StackTrace":" at AppCenter.Web.Controllers.ApplicantsController.d__a.MoveNext() in e:\Sample.Web\Controllers\HomeController.cs:line 86"
}

And here is the same thing when deployed:

XML
<Error><Message>An error has occurred.</Message></Error>

JSON
{
"Message":"An error has occurred."
}

As you can see, if you want your errors to flow to the consuming app, this is not ideal. You likely will (and should) want to return your errors in an object that has a friendly error message, and optionally, detailed message, error code, and even an error reference for lookup.

Here is an excerpt from the Apigee e-book “Web API Design – Crafting Interfaces that Developers Love”:

How to think about errors in a pragmatic way with REST?

Let’s take a look at how three top APIs approach it.

Facebook
HTTP Status Code: 200
{
“type”:”OauthException”,
“message”:”(#803) Some of the aliases you requested do not exist: foo.bar”
}

Twilio
HTTP Status Code: 401
{
“status”:”401″,
“message”:”Authenticate”,
“code”:20003,
“more info”:”http://www.twilio.com/docs/errors/20003&#8243;
}

SimpleGeo
HTTP Status Code: 401
{
“code”:401,
“message”:”Authentication Required”
}

I like these patterns, but I especially like the following format:
{
"developerMessage":"Verbose, plain language description of the problem for the app developer with hints about how to fix it.",
"userMessage":"Pass this message on to the app user if needed.",
"errorCode":12345,
"more info":"http://dev.teachdogrest.com/errors/12345"
}

When dealing with web api and exceptions, there are a few things that you must realize:

ALL errors eventually are serialized into an HttpError object.

* manually thrown exceptions
* uncaught exceptions
* responses created using the Request.CreateErrorResponse extension method

HttpResponseException’s are treated as “caught” or handled errors

That means that when you manually throw an HttpResponseException OR you use Request.CreateErrorResponse – the errors will not flow to any ExceptionFilterAttributes you may have created. That means, if you use a library like Elmah to handle your Exception reporting, these will NOT be reported.

The Ideal Developer Experience for Exceptions and Errors (at least this is my ideal)

I want to be able to consistently report my exceptions in a consistent and friendly format.
I don’t want to have to worry about the different overloads of Request.CreateErrorResponse.
I want to be able to configure the way exceptions are dealt with. I don’t want developers on my projects to have to worry about getting creative with their exception handling and reporting. I don’t want it done one way here, one way there, etc.

My Solution

I created an ExceptionFilterAttribute that allows me to configure all my exceptions in one central place a static class in the App_Start folder (this is the preferred method these days it seems).

Here is my code:


    public class MvcApplication : System.Web.HttpApplication
    {

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            WebApiExceptionConfig.RegisterExceptions(
                 GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }


using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Http;
using System.Web.Security;

    public static class WebApiExceptionConfig
    {
        public static void RegisterExceptions(HttpConfiguration config)
        {

            /* /// this is the easiest way to shove the exception messages into the httperror message property for ALL unhandled exceptions
            
            config.Filters.Add(new GlobalApiExceptionFilterAttribute(catchUnfilteredExceptions: true));
            
            */

            config.Filters.Add(new GlobalApiExceptionFilterAttribute(new List<GlobalApiExceptionDefinition>
            {

                /* /// Example 1 -- setting the error code and reference properties
                new GlobalApiExceptionDefinition(typeof(NotImplementedException)) { ErrorCode = "123456.cows", ErrorReference = "http://www.google.com?q=cows" },
                */

                /* /// Example 2 -- using the friendly message string overload
                new GlobalApiExceptionDefinition(typeof(NotImplementedException), "This method is really wonky", HttpStatusCode.NotAcceptable) { ErrorCode = "123456.cows", ErrorReference = "http://www.google.com?q=cows" },
                */

                /* /// Example 3 -- using the friendly message predicate overload
                new GlobalApiExceptionDefinition(typeof(MembershipCreateUserException), (ex) => MembershipHelper.MembershipCreateStatusToString((ex as MembershipCreateUserException).StatusCode), HttpStatusCode.Conflict)
                */

                new GlobalApiExceptionDefinition(typeof(MembershipCreateUserException)) 
                {
                    Handle = (ex) => // we want to make sure the server error status codes are respected - we want to send back a 500
                    {
                        if (ex is MembershipCreateUserException) 
                        {
                            var mex = ex as MembershipCreateUserException;
                            switch (mex.StatusCode)
                            {
                                case MembershipCreateStatus.DuplicateProviderUserKey:
                                case MembershipCreateStatus.InvalidProviderUserKey:
                                case MembershipCreateStatus.ProviderError:
                                    return true;
                                default:
                                        break;
                            }
                        }
                        return false;
                    }
                },
                new GlobalApiExceptionDefinition(typeof(MembershipCreateUserException), statusCode: HttpStatusCode.Conflict) // this will send back a 409, for all other types of membership create user exceptions
            }, catchUnfilteredExceptions: true));
        }
    }


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Filters;


    public class GlobalApiExceptionFilterAttribute : ExceptionFilterAttribute
    {

        const string ERROR_CODE_KEY = "ErrorCode";
        const string ERROR_REFERENCE_KEY = "ErrorReference";

        List<GlobalApiExceptionDefinition> exceptionHandlers;
        bool catchUnfilteredExceptions;

        public GlobalApiExceptionFilterAttribute(
            List<GlobalApiExceptionDefinition> exceptionHandlers = null, bool catchUnfilteredExceptions = false)
        {
            this.exceptionHandlers = exceptionHandlers ?? new List<GlobalApiExceptionDefinition>();
            this.catchUnfilteredExceptions = catchUnfilteredExceptions;
        }

        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            var exception = actionExecutedContext.Exception;
            GlobalApiExceptionDefinition globalExceptionDefinition = null;
            HttpStatusCode statusCode = HttpStatusCode.InternalServerError;

            if (LookupException(actionExecutedContext.Exception, out globalExceptionDefinition) || catchUnfilteredExceptions)
            {
                // set the friendly message
                string friendlyMessage = globalExceptionDefinition != null ? globalExceptionDefinition.FriendlyMessage(exception) : exception.Message;

                // create the friendly http error
                var friendlyHttpError = new HttpError(friendlyMessage);

                // if we found a globalExceptionDefinition then set properties of our friendly httpError object accordingly
                if (globalExceptionDefinition != null)
                {
                    
                    // set the status code
                    statusCode = globalExceptionDefinition.StatusCode;

                    // add optional error code
                    if (!string.IsNullOrEmpty(globalExceptionDefinition.ErrorCode))
                    {
                        friendlyHttpError[ERROR_CODE_KEY] = globalExceptionDefinition.ErrorCode;
                    }

                    // add optional error reference
                    if (!string.IsNullOrEmpty(globalExceptionDefinition.ErrorReference))
                    {
                        friendlyHttpError[ERROR_REFERENCE_KEY] = globalExceptionDefinition.ErrorReference;
                    }

                }

                // set the response to our friendly http error
                actionExecutedContext.Response = actionExecutedContext.Request.CreateErrorResponse(statusCode, friendlyHttpError);

            }

            // flow through to the base
            base.OnException(actionExecutedContext);
        }

        private bool LookupException(Exception exception, out GlobalApiExceptionDefinition exceptionMatch)
        {
            exceptionMatch = null;

            var possibleMatches = exceptionHandlers.Where(e => e.ExceptionType == exception.GetType());
            foreach (var possibleMatch in possibleMatches)
            {
                if (possibleMatch.Handle == null || possibleMatch.Handle(exception))
                {
                    exceptionMatch = possibleMatch;

                    return true;
                }
            }

            return false;
        }
        
    }

    public class GlobalApiExceptionDefinition
    {

        const string ARGUMENT_NULL_EXCEPTION_FMT = "Argument '{0}' cannot be null.";
        const string ARGUMENT_MUST_INHERIT_FROM_FMT = "Type must inherit from {0}.";

        public Type ExceptionType { get; private set; }
        public Func<Exception, string> FriendlyMessage { get; private set; }

        public Func<Exception, bool> Handle { get; set; }
        public HttpStatusCode StatusCode { get; set; }

        public string ErrorCode { get; set; }
        public string ErrorReference { get; set; }

        public GlobalApiExceptionDefinition(Type exceptionType, string friendlyMessage = null, HttpStatusCode statusCode = HttpStatusCode.InternalServerError) :
            this(exceptionType, (ex) => friendlyMessage ?? ex.Message, statusCode) { }

        public GlobalApiExceptionDefinition(Type exceptionType, Func<Exception, string> friendlyMessage, HttpStatusCode statusCode = HttpStatusCode.InternalServerError)
        {

            AssertParameterIsNotNull(friendlyMessage, "friendlyMessage");
            AssertParameterIsNotNull(exceptionType, "exceptionType");
            AssertParameterInheritsFrom(exceptionType, typeof(Exception), "exceptionType");

            ExceptionType = exceptionType;
            FriendlyMessage = friendlyMessage;
            StatusCode = statusCode;
        }

        #region "Argument Assertions"

        private static void AssertParameterInheritsFrom(Type type, Type inheritedType, string name)
        {
            if (!type.IsSubclassOf(inheritedType))
            {
                throw new ArgumentException(string.Format(ARGUMENT_MUST_INHERIT_FROM_FMT, inheritedType.Name), name);
            }
        }

        private static void AssertParameterIsNotNull(object parameter, string name)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(name, string.Format(ARGUMENT_NULL_EXCEPTION_FMT, name));
            }
        }

        #endregion

    }

You can download the source here.

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

Andy Cohen

April 14, 2012

I attended the Social Media presentation given by Brandy Favilla just before lunch.  I’m torn between the following presentations:

Each has it’s benefits. I’m trying to weigh in on which technologies I might actually leverage in upcoming apps and my level of enthusiasm for each.

I’m thinking that the Async talk on the upcoming features of .NET 4.5 will be discussed would be the most broad. Probably on the table will be the Async CTP that should be going RTM by October.

On the other hand, I’m involved in a ton of web apps. SignalR is an emerging technology I’ve wanted to pursue since attending KRTConf in Portland late last year.

Alternatively, considering Dart, which I’ve never heard of – the possibility of a programming alternative to JavaScript is a little daunting. Recently I’ve worked with .less, an abstraction of css which ultimately renders css. It has come not without it’s hiccups. If Dart is anything similar, I do not see wide adoption. Dotless (.less) is a compiled form of less. Without native support in the browser, I do not see this going very far.

Hmm… choices.