The Code Slinger

January 31, 2011

Client Specific Metadata in your MVC Application

Filed under: MVC — Pete @ 12:21 pm

Recently I was working on a new requirement for one of our systems in which each different client may refer to the same data types differently.  For example, ClientA might refer to roadways as a “Parkways” whereas ClientB and ClientC might refer to them as “Highways”.   Changes like these obviously aren’t big enough to warrant separate Views for each screen in which data types like these are referenced or mentioned, however sometimes small things like that make a big difference to the client and makes the application feel more in line with their existing business processes.

So, in order to make it so that my application is still a single code-base that will work for all the various clients that might come along and their varying terminologies, here is what I came up with that I think integrates nicely into an existing MVC application and requires only slight modifications.

First off, here is my interface and concrete implementation of a dictionary wrapper that I will use to not only store the key/value pairs which represent the data types but which will be what my Views utilize as an appendage to their ViewModel instances.

    public interface IMeta

    {

        MetaDictionary Meta { get; set; }

    }

 

    public class MetaDictionary

    {

        private Dictionary<string, KeyValuePair<string,string>> dict;

        public MetaDictionary()

        {

            dict = new Dictionary<string, KeyValuePair<string, string>>();

        }

 

        public void Add(string key, KeyValuePair<string,string> value)

        {

            if (!dict.ContainsKey(key))

                dict.Add(key, value);

            else

                dict[key] = value;

        }

        public void Remove(string key)

        {

            if (dict.ContainsKey(key))

                dict.Remove(key);

        }

 

        public string GetValue(string key)

        {

            if(dict.ContainsKey(key))

                return dict[key].Key;

            else

                return "";

        }

        public string GetValueAbbrev(string key)

        {

            if(dict.ContainsKey(key))

                return dict[key].Value;

            else

                return "";

        }

    }

Next, I need to write an action filter that will fetch the appropriate key/value pairs relevant to the currently logged in user and which client they belong to.  Please note that this is where your logic goes to determine A) where to retrieve your key/value pairs to begin with (DB, XML, config file, etc) and B) what differentiating factor(s) you might have which would determine how your application knows each client.  In my situation, I currently have a variable which would store the ClientID in a pre-existing injected Session wrapper.  Also note, I’m using StructureMap as my DI container.

    public class ClientMetaAttribute : ActionFilterAttribute, IActionFilter

    {

        private readonly IControllerDependency Services;

        public ClientMetaAttribute():this(ObjectFactory.GetInstance<IControllerDependency>())

        {

        }

        public ClientMetaAttribute(IControllerDependency service)

        {

            Services = service;

        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)

        {

            //Lookup all appropriate attributes.

            int? clientid = Services.SessionHandler.ClientID;

            var metadict = new MetaDictionary();

            //FILL YOUR META dictionary here!!

 
           ((IMeta)((ViewResultBase)filterContext.Result).ViewData.Model).Meta = metadict;

            base.OnResultExecuting(filterContext);

        }

 

        public override void OnResultExecuted(ResultExecutedContext filterContext)

        {

            base.OnResultExecuted(filterContext);

        }

Now, once I’ve implemented IMeta in the ViewModel used for my action method:

    public class ClientViewModel: IMeta

    {

        public MetaDictionary Meta { get; set; }

        //Rest of model class definition…

    }

Then I simply need to update any hardcoded references within View(s) which use this ViewModel such as:

<h4><%: Model.Meta.GetValue("roadname") %> (<%: Model.Meta.GetValueAbbrev("roadname") %>)</h4>

Which for ClientA will give me

Parkway (PKWY)

and for for ClientB & ClientC will give

Highway (HWY)

Obviously this could be expanded in terms of the dictionary value storage to include a host of other information that may be specific to your needs, however this example shows the intent.  Additionally, another enhancement would be to extend this for use in a localization scenario where multiple languages may be necessary as well. 

December 28, 2010

Expression based RenderAction HtmlHelper extension (with Authorization)

Filed under: ASP.NET,C#,MVC — Pete @ 11:39 am

        public static void RenderAuthorizedAction<TController>(this HtmlHelper helper, Expression<Action<TController>> action) where TController : Controller

        {

            var routeValuesFromExpression = Microsoft.Web.Mvc.Internal.ExpressionHelper.GetRouteValuesFromExpression<TController>(action);

 

            if(helper.IsAuthorized(action))

                helper.RenderAction(routeValuesFromExpression["Action"].ToString(), routeValuesFromExpression);

        }

 

        public static bool IsAuthorized<TController>(this HtmlHelper helper, Expression<Action<TController>> action)

        {

            var call = action.Body as MethodCallExpression;

 

            if (call == null) return false;

 

            var authorizeAttributes = call.GetAttributes<IAuthorizationFilter>();

            if (authorizeAttributes.Length == 0) return true;

 

            var controllerContext = helper.ViewContext.Controller.ControllerContext;

            var controllerDescriptor = new ReflectedControllerDescriptor(typeof(TController));

            var actionDescriptor = new ReflectedActionDescriptor(call.Method, call.Method.Name, controllerDescriptor);

 

            return authorizeAttributes.All(a => IsAuthorized(a, controllerContext, actionDescriptor));

        }

I’m sure this is coming in MVC 3, however I needed it now and it’s fairly straightforward.  To use it, simply call from your View as:

<% Html.RenderAuthorizedAction<MyController>(a => a.MyActionMethod()); %>

November 17, 2008

Color Transitions in Winform Controls

Filed under: .NET,C#,Tuples,Winform — Pete @ 3:02 pm

If you’ve ever used web-sites like the hosted WordPress blogs (like this one!) and others, you’ve noticed the new sweet hotness is to have screens give feedback on success or failure of an operation by showing color gradient transitions.  The most common is simply “Green to White” (success!) or “Red to Pink” (failure!).  This is a quick way to let the user know they can move along and do more work or whether they had an issue.  Granted, more detailed logging and/or messages are needed on the “fail” side of things, however since code slingers like us write perfect code all the time….we are just gonna go with quick feedback for now 😉

So, being as I’ve only started in the last few months writing winform/WPF apps, I thought there must be an easy way to do these gradients on forms and other controls quite easily.  No so.  Sure, there are ForeColor and BackColor properties, however transitioning in a gradient-like fashion from one color to the next isn’t “built in” in any way that I could tell.  NOTE: Yes, I’m well aware of the fact that WPF is going to take over the world.  But for now this is a Winform app, and until such time as WPF becomes the de-facto standard, it will remain as such.  Accordingly, please don’t comment about how WPF can handle this with ease.  I know.

So here’s what I came up with:

        public static void UpdateColor(Control ctl, Color from, Color to)

        {

            int step = 1; //Increase if you want the transition to be faster.

            var fromT = new Tuple<int, int, int>(

                Convert.ToInt32(from.R),

                Convert.ToInt32(from.G),

                Convert.ToInt32(from.B));

            var toT = new Tuple<int, int, int>(

                Convert.ToInt32(to.R),

                Convert.ToInt32(to.G),

                Convert.ToInt32(to.B));

            var curT = new Tuple<int, int, int>(fromT);

            var done = new Tuple<bool, bool, bool>(false, false, false);

 

            while (true)

            {

                //Red

                if (curT.First >= toT.First)

                    done.First = true;

                else

                {

                    var tempval = curT.First < toT.First ? curT.First += step : curT.First -= step;

                    curT.First = tempval > toT.First ? toT.First : tempval;

                }

                //Green

                if (curT.Second >= toT.Second)

                    done.Second = true;

                else

                {

                    var tempval = curT.Second < toT.Second ? curT.Second += step : curT.Second -= step;

                    curT.Second = tempval > toT.Second ? toT.Second : tempval;

                }

                //Blue

                if (curT.Third >= toT.Third)

                    done.Third = true;

                else

                {

                    var tempval = curT.Third < toT.Third ? curT.Third += step : curT.Third -= step;

                    curT.Third = tempval > toT.Third ? toT.Third : tempval;

                }

 

                if (done.First && done.Second && done.Third)

                {

                    ctl.BackColor = to;

                    ctl.Refresh();

                    break;

                }

                ctl.BackColor = Color.FromArgb(curT.First, curT.Second, curT.Third);

                ctl.Refresh();

            }

        }

So, basically I’m just getting the integer values of the RGB color scheme for the from and to colors passed in, looping through adding/subtracting from the start values (from) until I get to the end values (to), refreshing the control along the way.  Not too terribly difficult, but interesting none-the-less and quite a nice little UI feature that doesn’t look like most winform applications.

Also, note I’ve added a step variable that you can tweak to adjust how fast or slow the transition occurs.  It’s a pretty significant jump from say 1 to 3, so if you want more granular timing, you could adjust the int storage to decimal and account for parts of steps (such as += 0.3).  Or you could implement a true timing system that would force the transition to take place within a specific time construct (perhaps the next article on this topic??).  But for my needs currently, this is more than sufficient.

And of course, I’m using my handy little Tuple<T1,T2,T3> class, since tuples (or at least the concept of them) rock.  Hint hint…please make this concept a part of C# 4.0 Anders…puuuleeeeeease?

    public class Tuple<T1,T2,T3>

    {

        public T1 First { get; set;}

        public T2 Second { get; set; }

        public T3 Third { get; set; }

 

        public Tuple(T1 t, T2 k, T3 l)

        {

            First = t;

            Second = k;

            Third = l;

        }

        public Tuple(Tuple<T1,T2,T3> t)

        {

            First = t.First;

            Second = t.Second;

            Third = t.Third;

        }

    }

 

Til next time….keep on slangin!

 

November 12, 2008

Impersonation & IDisposable

Filed under: .NET,C#,IDisposable,Impersonation — Pete @ 11:25 am

I’ve used an impersonation helper class for a while now, basically to encapsulate changing the current identity context while executing certain code.  This worked well, however I always got sick of having to remember to call the “undo()” method of my current implementation once I was done with executing my code under whatever login I was impersonating.

So, I updated the class to implement IDisposable so that I can now utilize this within the using() construct provided in C#.   Here’s the class in it’s entirety:

using System;

using System.Runtime.InteropServices;

using System.Security.Principal;

 

namespace Support.Win32

{

    public class Impersonate : IDisposable

    {

        public const int LOGON32_LOGON_INTERACTIVE = 2;

        public const int LOGON32_PROVIDER_DEFAULT = 0;

 

        WindowsImpersonationContext impersonationContext;

 

        public Impersonate()

        {

            //Default login is used.

            this.impersonateValidUser(“username”, “domain”, “password”);

        }

 

        public Impersonate(string username, string domain, string password)

        {

            this.impersonateValidUser(username, domain, password);

        }

 

        [DllImport(“advapi32.dll”)]

        private static extern int LogonUserA(String lpszUserName,

            String lpszDomain,

            String lpszPassword,

            int dwLogonType,

            int dwLogonProvider,

            ref IntPtr phToken);

        [DllImport(“advapi32.dll”, CharSet = CharSet.Auto, SetLastError = true)]

        private static extern int DuplicateToken(IntPtr hToken,

            int impersonationLevel,

            ref IntPtr hNewToken);

 

        [DllImport(“advapi32.dll”, CharSet = CharSet.Auto, SetLastError = true)]

        private static extern bool RevertToSelf();

 

        [DllImport(“kernel32.dll”, CharSet = CharSet.Auto)]

        private static extern bool CloseHandle(IntPtr handle);

 

        private bool impersonateValidUser(string userName, string domain, string password)

        {

            WindowsIdentity tempWindowsIdentity;

            IntPtr token = IntPtr.Zero;

            IntPtr tokenDuplicate = IntPtr.Zero;

 

            if (RevertToSelf())

            {

                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,

                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)

                {

                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)

                    {

                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);

                        impersonationContext = tempWindowsIdentity.Impersonate();

                        if (impersonationContext != null)

                        {

                            CloseHandle(token);

                            CloseHandle(tokenDuplicate);

                            return true;

                        }

                    }

                }

            }

            if (token != IntPtr.Zero)

                CloseHandle(token);

            if (tokenDuplicate != IntPtr.Zero)

                CloseHandle(tokenDuplicate);

            return false;

        }

 

        private void undoImpersonation()

        {

            impersonationContext.Undo();

        }

 

        public void Dispose()

        {

            Dispose(true);

            GC.SuppressFinalize(this);

        }

 

        ~Impersonate()

        {

            Dispose(false);

        }

 

        protected virtual void Dispose(bool disposing)

        {

            if(disposing)

            {

                //Dispose of managed resources.

                if(impersonationContext != null)

                {

                    this.undoImpersonation();

                    impersonationContext.Dispose();

                    impersonationContext = null;

                }

            }

        }

    }

}

 

Basically, now my code can use the following construct in order to execute code in an impersonated context:

 

                using(var imp = new Impersonate(“username”, “domain”, “password”))

                {

                    //Code that I want to run under this account.

                }

 
That’s it! Now I can be lazy and not have to worry about everything getting “cleaned up”.  What’s more, is I’ve made private the actual calls to impersonateValidUser expressly so that it forces me to use this with the using construct. 
 
Til next time…..keep on slangin!

December 27, 2007

SOSEX – New .NET Extensions for WinDBG

Filed under: .NET,SOS,WinDBG — Pete @ 3:43 pm

Somehow I missed this until today, but Steve Johnson has a nice write-up on some extensions he’s written for debugging managed code with WinDBG/SOS.

I find it easier to debug logic and performance issues using other tools like AntsProfiler, Perfmon logs/counters and VS.NET for the most part, however I do use WinDBG/SOS for occasional issues that only crop up in production environments (such as those caused by heavy load, multi-user deadlocks, etc). 

There is a bit of a learning curve to WinDBG, however once you realize how much information is contained within it (e.g. within a full user stack dump of the aspnet worker process), it is often quite easy to find exactly where the issue in the original managed source lies.

There are already commands like !gcroot and !dumpheap that one could use to track some of these issues down.  However of keen interest to a limited WinDBG user such as myself are the new !refs and !dlk commands.

!refs

Though not a replacement, the !refs command supplements SOS’s !gcroot command by allowing you to view  the immediate references from and to a given object.

0:000> !refs 0000000080000db8
Objects referenced by 0000000080000db8 (System.Threading.Mutex):
0000000080000ef0         32    Microsoft.Win32.SafeHandles.SafeWaitHandle

Objects referencing 0000000080000db8 (System.Threading.Mutex):
0000000080000e08         72    System.Threading.Mutex+<>c__DisplayClass3
0000000080000e50         64    System.Runtime.CompilerServices.RuntimeHelpers+CleanupCode

The sample output above shows only heap references, but !refs will also list all references from handles, stacks, registers and the freachable queues.

 

!dlk

The !dlk command allows you to easily spot deadlocks in your application if you suspect deadlock to be the cause of an application hang. If !dlk detects deadlock, the output will list the sync blocks that are held as well as the sync blocks for which each thread is waiting, as well as the type, method, IL offset, and, if symbols are available, the source code and line number at which each thread is waiting:

0:010> !dlk
Deadlock detected:
CLR thread 4 holds sync block 00000000024c6970 OBJ:000000007fff0f80[System.String] STRVAL=SYNC1
             waits sync block 00000000024c6928 OBJ:000000007fff0fa8[System.String] STRVAL=SYNC2
CLR thread 5 holds sync block 00000000024c6928 OBJ:000000007fff0fa8[System.String] STRVAL=SYNC2
             waits sync block 00000000024c6970 OBJ:000000007fff0f80[System.String] STRVAL=SYNC1
CLR Thread 4 is waiting at ConsoleTestApp.ConsoleTestApp.MonitorDeadlockThreadProc()+0xa4(IL) [C:\dev\ConsoleTestApp\ConsoleTestApp.cs, line 195]
CLR Thread 5 is waiting at ConsoleTestApp.ConsoleTestApp.MonitorDeadlockThreadProc()+0xa4(IL) [C:\dev\ConsoleTestApp\ConsoleTestApp.cs, line 195]

1 deadlock detected.

As you can see, !dlk makes it dead simple to troubleshoot this common kind of deadlock in managed code. One important caveat holds true for !dlk: it only works for deadlocks on “sync blocks”. Put more simply, it will only spot locks created by Monitor.Enter (which is used by the C# lock keyword). !dlk will not catch deadlock on other types of synchronization objects, such as mutexes and semaphores.

Very cool stuff.  Thanks Steve!

Next Page »

Create a free website or blog at WordPress.com.