The Code Slinger

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

Advertisements

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!

April 17, 2008

Euclid’s Gauntlet

Filed under: C#,Math,Project Euler — Pete @ 10:00 pm

A friend of mine recently pointed me to a very cool (read: geeky) site called Project Euler.  It’s basically a site for the subset of us programmers who enjoy solving mathematical problems (or vice versa…in the case of those true mathematicians are also spelunkers of bytes).   But it’s really more than that too.  Most of the problems one would be hard pressed to solve using anything but the raw processing power of computers. 

The interesting angle each problem takes is that it builds, for the most part, upon the previous problems, introducing ever more complex mathematical formulae and concepts.  Even more impressive is the assertion by the site’s founders that each problem issued can theoretically be solved by a computer program running on a standard PC in in under 1 minute!  So while the temptation might be there to give up on an elegant solution and brute force it using naive methods (which certainly is possible in some cases), one cannot in good conscience type in that “correct” answer knowing that your program took 30 minutes running at 100% CPU…haha!

Anyway, in keeping with the practice of the site, I will not be posting my solutions publicly to each problem as I complete it.  I will simply post notices of my progress here as time permits.  If anyone is interested in my solutions to compare algorithms, etc….feel free to contact me via the site with the problem # and the correct answer (which you must get yourself!) and I’ll be happy to compare notes.

Status so far? I just finished Problem 12.

December 17, 2007

Custom XML Serialization with LINQ

Filed under: C#,LINQ,Reflection,XLINQ — Pete @ 11:24 pm

Wouldn’t it be nice if you could automatically serialize into XML not only the structure of any class in your business framework, but the actual values at runtime of each instance? This could be used for additional logging to an offsite service, re-hydrating objects at a later time, or simply a form of custom serialization without all the overhead the native XMLSerializer has built into it.

Previously I had this type of code implemented as an interface, so that each object could serialize itself if necessary.  This was cumbersome and while in theory one might want a different XML structure per business object, typically in my uses I found that each object just needed to output the direct data it held.   So using the new 3.5 framework features like LINQ & XLINQ, let’s take a look at what a custom serializer might look like (full source is posted at the end of the article as usual).

public static class Serializer<T> where T: class, new()

{

    private static Dictionary<Type, PropertyInfo[]> props =

        new Dictionary<Type, PropertyInfo[]>();

}

First, our class will be a generic implementation, so that we can pass in any of our business entity objects.  Inside we have a static member which is simply a container for keeping track of our PropertyInfo arrays based on class type.  This keeps us, over time, from having to duplicate reflection calls unnecessarily.

public static string Serialize(T instance)

{

    Type t = typeof(T);

    PropertyInfo[] pis = null;

    lock (props)

    {

        if (!props.TryGetValue(t, out pis))

        {

            PropertyInfo[] ps = t.GetProperties(

                BindingFlags.Public |

                BindingFlags.GetProperty |

                BindingFlags.Instance);

            props.Add(t, ps);

        }

        pis = props[t];

    }

 

    XElement xd = new XElement(t.Name);

    pis.ForEach(p =>

    {

        object val = null;

        PropertyCaller<T>.GenGetter g =

            PropertyCaller<T>.CreateGetMethod(p);

        val = g(instance);

        if (val == null)

            val = “null”;

        XAttribute xa = new XAttribute(p.Name, val);

        xd.Add(xa);

    });

 

    return xd.ToString();

}

Here our Serialize method takes as input an instance of the type we are serializing. It converts the Type data, and then looks in our container to see if we have already serialized one of these previously.  If not, it gets the necessary PropertyInfo data from the Type and inserts it for future use into our container. 

Next we use the XElement class to create a new xml node named after our class type.  You could use any data you want from the class, I just chose to use the Name property.  Now, we use the extension method ForEach<T> of the PropertyInfo array to execute a lambda expression.  This expression basically just uses the PropertyCaller<T> class we created previously to get the delegate “getter” for each property on the class.  Calling this delegate will retrieve the value of the property for the instance we are serializing.  Then I simply use the name of the property and it’s value to create an XAttribute to decorate the XElement for our object.

The return value of the Serialize method is simply the string output of our XElement object in XML.

Now let’s look at how to take that string XML and turn it back into our object.

public static T Deserialize(XElement xd)

{

    Type t = typeof(T);

    PropertyInfo[] pis = null;

    lock (props)

    {

        if (!props.TryGetValue(t, out pis))

        {

            PropertyInfo[] ps = t.GetProperties(

                BindingFlags.Public |

                BindingFlags.SetProperty |

                BindingFlags.Instance);

            props.Add(t, ps);

        }

        pis = props[t];

    }

    IEnumerable<XAttribute> ix = xd.Attributes();

 

    T lilt = new T();

    pis.ForEach(p =>

    {

        string propname = p.Name;

        var att = (from xat in ix

                   where xat.Name.LocalName == p.Name

                   select xat).FirstOrDefault();

        if(att != null)

        {

            PropertyCaller<T>.GenSetter s =

                PropertyCaller<T>.CreateSetMethod(p);

            object val = Converter(p.PropertyType, att.Value);

            s(lilt, val);

        }

    });

    return lilt;

}

Our Deserialize method takes an XElement instance which represents the data for a particular instance of T.   You could also take plain string XML and load it into the XElement if you wanted, via the XElement.Parse() method.

Again, we get our PropertyInfo array so we know how to match up the XAttributes, then again using the ForEach<T> extension method, we provide a lambda expression (anonymous method) implementation which determines which XAttribute of the XElement node matches up with each property name.  Notice the LINQ query on the results of the Attributes() method off of the XElement object.  Since the results are of type IEnumerable<T>, we know that we can query them using LINQ.   In this case we simply find the FirstOrDefault (null if one doesn’t exist) value in the query in which the LocalName of the XAttribute matches our property name. 

Now if we have a matching attribute for the property, we again use our PropertyCaller<T> implementation to get the delegate “setter” for the property.  Calling this delegate with the value of our attribute, we are able to set the value of our object for the property specified.

The Converter method is simply a helper method to allow us to properly convert the string representation of the value stored in the XML into an actual object type based on the property’s type. 

public static object Converter(Type t, string value)

{

    object retval = null;

    string checkType = string.Empty;

    bool valueset = false;

    if (t.IsGenericType)

    {

        checkType = t.GetGenericArguments()[0].FullName;

        if (value == “null”)

        {

            valueset = true;

            retval = null;

        }

    }

    else

        checkType = t.FullName;

 

    if (!valueset)

    {

        switch (t.FullName)

        {

            case “System.Int32”:

                retval =

                    new Int32Converter().ConvertFrom(value);

                break;

            case “System.Double”:

                retval =

                    new DoubleConverter().ConvertFrom(value);

                break;

            case “System.Decimal”:

                retval =

                    new DecimalConverter().ConvertFrom(value);

                break;

            case “System.Boolean”:

                retval =

                    new BooleanConverter().ConvertFrom(value);

                break;

            case “System.DateTime”:

                retval =

                    new DateTimeConverter().ConvertFrom(value);

                break;

            default:

                retval = value;

                break;

        }

    }

    return retval;

}

The only real gotcha with this is that you have to implement a conversion routine (I use TypeConverters) for each type you are storing in your classes.  Typically this is limited to a relatively small set of types (mostly value types).  This particular implementation handles generic “nullable” versions of each value type listed.  In the XML serialization routine, null values are explicitly spelled out as “null”. 

Anyway, the sample project should give you a pretty clear understanding of how to put all this together.  Hopefully this has shown how to not only accomplish a potentially system-wide task with relatively little code, but how to build upon the dynamic method invocation code we put together previously in a real-world scenario.

Til next time…keep on slangin!

————————————————

Example Project Source

Next Page »

Blog at WordPress.com.