The Code Slinger

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!
Advertisements

October 28, 2008

LINQKit: PredicateBuilder<T> Goodness

Filed under: Uncategorized — Pete @ 2:52 pm
Tags: , ,

Remember the good ol’ days when you wanted to create a query that had dependencies that were unknown at runtime? You’d create a nice StringBuilder instance, and start building your own SQL to handle the complex logic of ever possible permutation that you allowed via your UI.  Or you create the hairiest stored procedure known to man with umpteen variables and then tried not only to not screw it up internally, but to make every scenario as fast as possible.  Yeah, those days were fun weren’t they?

With LINQ, such tasks are still moderately tough, but now that I’ve found the very nice PredicateBuilder<T> class that comes in the free LINQKit, the ease with which one can create dynamic SQL calls is significantly easier. 

As an example, supposed you have a table which contains a description column.  And you want to implement a sort of “smart search” on that column such that if your user types in:

Include: Dog Cat
Exclude: Hamster

you code translates that into a query such as:

SELECT * FROM Pets
WHERE Description LIKE ‘%Dog%’
AND Description LIKE ‘%Cat%’
AND Description NOT LIKE ‘%Hamster%’

Behold, PredicateBuilder<T>.

            //First get a list of keywords that match the description entered.

            string[] parts = txtInclude.Text.Split(new[] {‘ ‘});

            string[] noparts = null;

            if(txtButNot.Text.Trim().Length > 0)

                noparts = txtExclude.Text.Trim().Split(new[] {‘ ‘});

 

            var pred = PredicateBuilder.True<Pet>();

            parts.ForEach(p => pred = pred.And(pl => pl.description.Contains(p)));

            if(noparts != null)

                noparts.ForEach(p => pred = pred.And(pl => !pl.description.Contains(p)));

 

            var pets = from s in db.Pets.Where(pred)

                        select s;

Notice that it doesn’t matter what order the user types the keywords in, nor does it matter how many there are.    Obviously this is a trivial example, and I don’t really have a table that stores pet names 😉  However, I do have some pretty complex requirements to create a way to backtrack and find potential buyers in our system based on previous items they’ve shown interest in.  Sounds like a nice use for this gem of a find.

Til next time….keep on slangin!

October 22, 2008

LINQDataSource and Optional Parameters

Filed under: Uncategorized — Pete @ 1:20 pm
Tags: , ,

The combination of LINQDataSource and GridView makes a nice quick way to provide basic search capabilities for your users.  Providing a user the ability to search on multiple criteria for a single entity is quick and painless.  However, I ran into an issue where one of the columns I was searching by allowed NULL in the table. 

My fields looked something like:

                <tr>

                    <td>Company:&nbsp; </td>

                    <td><asp:TextBox ID=”txtCompNameSearch” runat=”server”></asp:TextBox></td>

                </tr>

                <tr>

                    <td>Phone: &nbsp;</td>

                    <td><asp:TextBox ID=”txtPhoneSearch” runat=”server”></asp:TextBox></td>

                </tr>

My LINQDataSource:

 

    <asp:LinqDataSource ID=”ldsCompanies” runat=”server”

        ContextTypeName=”DataContext”

        TableName=”REG_Companies” EnableUpdate=”True”

        Where=”CompanyName.StartsWith(@CompanyName) &amp;&amp; Phone.StartsWith(@PhoneNumber)”>

        <WhereParameters>

            <asp:ControlParameter ConvertEmptyStringToNull=”false” ControlID=”txtCompNameSearch” Name=”CompanyName”

                PropertyName=”Text” Type=”String” />

            <asp:ControlParameter ConvertEmptyStringToNull=”false” ControlID=”txtPhoneSearch” Name=”PhoneNumber”

                PropertyName=”Text” Type=”String” />

        </WhereParameters>

    </asp:LinqDataSource>

If both CompanyName and Phone fields didn’t allow nulls, this would work just fine.  However, like my scenario, the Phone field (for whatever reason) allowed NULL values in the database, this would still work but if you left txtPhoneSearch empty, it would only return records in which the Phone field was NOT NULL.

So, the next logical thing to do would be to change the ConvertEmptyStringToNull value to true for that parameter.  Ah, but if you do that you get the following error when you try to load the page the code is on:

No applicable method ‘StartsWith’ exists in type ‘String’

So, this is what I came up with to fix it so you can search optionally on columns that allow nulls using the standard ControlParameter in the LINQDataSource.  Leave the ConvertEmptyStringToNull=”false” as you would with non-nullable columns.  However, modify your Where clause to the following:

        Where=”CompanyName.StartsWith(@CompanyName) &amp;&amp; (@PhoneNumber == String.Empty || (@PhoneNumber != String.Empty &amp;&amp; Phone.StartsWith(@PhoneNumber)))”>

You’re effectively just giving the query an option to exit early if the @PhoneNumber parameter is empty, but if it is not, then you’re adding the comparison to the dynamic SQL logic.

Til next time….keep on slangin!

October 6, 2008

DBML File Issue

Filed under: DBML,LINQ to SQL,VS.NET 2008 SP1 — Pete @ 1:06 pm

If you edit an existing DBML file (e.g. Foo.dbml) and save it, then notice that your entire Foo.designer.cs is gone and you’re using VS 2008 SP1, then the issue (which it took me quite a while to figure out) is that you have your using statements OUTSIDE of your namespace declaration within the Foo.designer.cs AND any other partial class declarations of the Food class. 

Absolutely asinine I know.

September 30, 2008

Randomization & LINQ

Filed under: Uncategorized — Pete @ 3:21 pm
Tags: , ,

Ran into a problem today in which I had a List<T> of items, and I needed to return a number X of them back, but I wanted a random sampling of the original list.  There are plenty of traditional ways to do this, however I figured I’d learn something new and figure out how to do this using LINQ.

Here’s my solution, which I turned into an extension method for future use……

        public static List<T> GetRandom<T>(this List<T> objs, int count)

        {

            var ret = new List<T>();

 

            if(objs.Count() <= count)

                return objs.ToList();

 

            var used = new List<int>();

            var seq = (Enumerable.Range(1, count)

                        .Select(a =>

                            {

                                var num = (from b in Enumerable.Range(0, objs.Count()-1)

                                           orderby Guid.NewGuid()

                                           where !(from u in used

                                                  select u).Contains(b)

                                           select b).First();

                                used.Add(num);

                                return num;

                            })).ToList();

 

            foreach (int s in seq) { ret.Add(objs[s]); }

            return ret;

        }

 

Basically the thinking is that since I’m dealing with randomizing what’s in the list, I don’t really care about data specific to the type “T”.  I’m just randomizing the index count from the original list based on how many I want, then using those indexes I get back from the randomization part to pull the actual objects.

The only thing I don’t like about it is the fact that I have to create a separate variable ( “used” ) to keep track of which items in the original list that I’ve already used. Seems there should be a better way to do this within the LINQ query, but at this point I am drawing a blank on that one.

Also…did you notice I am doing randomization without even using the System.Random class? Yeeaaa for me! 😉

As always….Keep on Slangin!

« Previous PageNext Page »

Blog at WordPress.com.