You’re Just an Imposter!

October 27, 2006

[Warning: This is one of those technical articles where the writer (me) tries to be all witty and stuff instead of just getting to the point. Sorry. I couldn't help myself.]

[Warning #2: WordPress is a pain in the patula oblongata about formatting. I spent waaay too much time trying to get the code snippets in this post looking good, only to have WordPress reformat everything the next time I saved. AAaaiiiiggh!! So if the code snippets look stanky, sorry... I tried!]

I mentioned in an earlier post that I was working on a little console utility to launch an application using a particular user’s credentials. That right there is what I like to call impersonation. Come to think of it, everyone else calls it impersonation too, but no matter. In this post I’ll show you, dear reader, the very innards of impersonation, and hopefully when you’re done reading this post you’ll be as excited about the subject as I am! Yeah! Go Team Go! And stuff!

The .Net Framework provides everything you need to get at useful tidbits like the currently logged on user, role membership and so forth, but to do full fledged impersonation you have to do a little Win32 api work. If you’re using Mono.Net on Linux, um… I’m sorry, you should stop reading now, ’cause this article won’t help you on a non-Windows platform. Sorry. But really, who uses Linux anyway? I mean, c’mon you guys, Linux is just sooo OS2. Just like the Macintosh. Yeah, nobody uses the Mac anymore either.

But anyway, where was I before I waxed controversial? Oh yeah, impersonation. If you need to know how to do impersonation (on Windows), look no further for the source of power! This post should provide everything you need to be well on your way to… uh, impostering. I mean impersonatering. Or something.

So let’s take a look at the problem from up around a thousand feet. Yeah, I speak management speak, too. I’m bilingual like that. But any way, from way up here in the stratosphere we can rest our chins on our hands and hypothesize that there are really two ways to approach impersonation…

  1. Impersonation when launching a new process – for example, when you want to run a program as a particular user.
  2. Impersonation when running a piece of code – for example, when you want to execute a method as a particular user.

At the end of this post I’ve provided, free of charge and limitations, the full source code to a C# class that makes it fairly easy to impersonate using either approach. Some of the methods are unsafe, so if you use the code in your own application you must compile using the /unsafe switch.

So let’s talk about the first approach, which is the simpler of the two. In a nutshell, it involves calling the CreateProcessWithLogonW API method, as shown in the below snippet taken from my Impersonator class. You’ll notice this method doesn’t allow you to specify a username and password because those are provided when you call the Impersonator class’s constructor, not shown (see the file download).

So to run another app as a particular user, you just create a new Impersonator object, and call the RunAs method, and off the new process goes on its merry way, running happily as another user (provided the username and password you supplied in the constructor are correct).

[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public unsafe bool RunAs(string ApplicationName, string CommandLine, string CurrentDirectory)
{
  StartupInfo si
= new StartupInfo();
  si.cb
= Marshal.SizeOf(typeof(StartupInfo));
  si.title
= m_strUsername; ProcessInfo pi = new ProcessInfo(); try
  {
 
if (CreateProcessWithLogonW(m_strUsername, m_strDomain, m_strPassword,
 
0, //LogonFlags.LOGON_WITH_PROFILE,
ApplicationName, CommandLine,
 
0, IntPtr.Zero, CurrentDirectory,
  ref si, out pi))
  {
  CloseHandle(pi.hProcess);
  CloseHandle(pi.hThread);
 
return true;
  }
 
else
  {
 
return false;
}
  }
 
catch
  {
 
return true;
  }
}

I’ve provided a handy dandy method called Validate() that will return true if the specified credentials are valid. The Validate() method returns the result of the LogonUser API method, and looks like this…
public bool Validate()
{
  IntPtr tokenHandle
= new IntPtr(0);
return LogonUser(m_strUsername, m_strDomain, m_strPassword,
  LogonFlags.LOGON32_LOGON_INTERACTIVE, LogonFlags.LOGON32_PROVIDER_DEFAULT,
 
ref tokenHandle);
}

And so finally, let’s talk about second way to perform impersonation, which is by executing a block of code as a particular user.This method of impersonation is performed in the Impersonate method. If you open up the Impersonator class and look at this method you’ll notice (or if not, I’ll tell you now, hehe), that the Impersonate function takes care of rolling back the impersonation context after impersonation is complete (or if an error occurs), which is good because you don’t want other code in your application suddenly running under a login context you didn’t expect. You’ll also notice that impersonation code must be executed before (to impersonate) and immediately after (to undo the impersonation) the code you want to execute. To make this work in a reusable code library (such as I have provided for you to download at the end of this article), the Impersonate method accepts as a parameter a delegate of type ImpersonateCallback, which is called if impersonation succeeds.

In my not so humble opinion, this little class takes a lot of the headache out of impersonation. Give it a try, and if you have any feedback or questions feel free to post a comment.

And here’s the link to Download Impersonator.cs


Jason Calacanis

October 26, 2006

Jason Calacanis’ keynote address at Blog Business Summit is the latest hot topic. Jason Calacanis is the CEO and co-founder of Weblogs, Inc, a network of some of the coolest and spiffiest blogs out there (including Engadget).

Click the link for a summary of the keynote, which is basically a slew of excellent reasons why you should be blogging. Now. This very instant.


Command-Line Goodness

October 25, 2006

I’m in the process of writing a “RunAs” command-line utility that will execute an app using a set of login credentials provided by a third-party application. That’s fuel for another post, but I found this awesome command-line parser written by uber-coder Ray Hayes. With Ray’s class library all you have to do to parse your args is decorate your properties with a simple .Net attribute, and all of the un-fun stuff is done automagically.

Simple. Elegant. I like it a lot.

If you’re doing any command-line development, you’ve got to check this out.


Get Creative

October 25, 2006

Most software developers are complete klutzes when it comes to elements of design and stuff like that. I’m not one of them. Believe it or not, I actually have a B.A. in Art (I minored in Computer Science) – a weird and strange combination to be sure. “How in the world did that happen?”, you ask. Weeelll, I once fostered imaginings and dreams of one day being a Disney-style animator, but then around about my Junior year in college I stumbled across the wonderful world of Computer Science, and was hooked. But it would’ve cost too much moolah to stay in school long enough to change my major (probably another year) so I opted to just minor in C.S. I even took a few math classes for good measure (Calculus and Discrete Math), which I quickly purged from my memory as soon as I graduated.

But back to my original point - if you’re one of those developers that never took a semester’s worth of 2D design, and couldn’t tell the difference between gouache and acrylic if your life depended on it, here’s a nifty little tool that may save your bacon. It chooses color combinations that supposedly make artfully colored web sites. For the most part, I think it works fairly well, especially if you’re aiming for one of those flashy, artsy-fartsy art-nouveau web sites (like this one).

And while you’re at it, you might want to try out this nifty .Net version of Photoshop – Paint.Net. Yeppers, it’s free.

And for even more palette choices, try the Web 2.0 Colour Palette, available here. You know it must be good because Colour has that extra U, and that just makes it all fancy and arty and stuff like that.

Have fun!


Google Co-op

October 24, 2006

Everyone’s going Gonzo over Google’s latest invention, Google Co-op, which lets you build your own personalized search engine.

Vik Singh shows how he did it here. The coolness factor here is through the roof.


Syntax Highlighter

October 24, 2006

For all my fellow codin’ bloggers out there, this little tool is really nifty.

It’s too bad you can’t use it in on the hosted version of WordPress, which doesn’t allow you to create your own templates.


Sort it, Flip it, Fry it in SQL Server

October 24, 2006

I just found a little article in the .Net Framework 2.0 SDK Documentation called Reliability Best Practices (when authoring assemblies for use within SQL Server), which contained a little snippet I found interesting.

You may read along with me here.

 As a little backgrounder, in the latest and greatest version of SQL Server, SQL Server 2005, you have da powah to create Stored Procs, Funcs, Triggers, and even new types, using the CLR. The process, in a nutshell, is:

  • Create a CLR class with some functions and compile it to an assembly
  • Create a stored procedure, function or whatever using the normal syntax (CREATE PROC, or whatever), with a few extra syntax-ual extras that tell SQL Server to run the function in your little CLR assembly whenever the sql proc is called.

You can read more about that in your spare time, but as I was saying, according to the SDK you need to be careful when writing CLR-based code that will run within SQL Server 2005. And by careful I (and they) mean don’t use pointers. Unless it’s wrapped in a SafeHandle.

 In the case of an AppDomain unload, you cannot depend on finally blocks or finalizers being executed, so it is important to abstract all operating system resource access through the SafeHandle class rather than IntPtr, HandleRef, or similar classes. This allows the CLR to track and close the handles you use even in the AppDomain tear-down case. SafeHandle will be using a critical finalizer which the CLR will always run.

And further down the page, we’re instructed to ensure finalizers and finally clauses do not have to run to prevent leaking operating system resources.

So basically, I think what they’re trying to say is: don’t be bringin’ your ol’ nasty pointers around SQL Server. That’s how I interpret it. Yeah, you could use a SafeHandle, but a stored proc doesn’t seem like a healthy place to be doing pointer arithmetic or grabbing handles to system resources.

Actually, the more I think about it, the more I fail to see a good reason to run .Net code within SQL Server at all. I mean, hey, the coolness factor here is sky high, but how often do you really need to be able to fill a DataSet, sort it flip it and fry it, all within SQL Server?

Is this really a conspiracy by Microsoft to “dumb-down” SQL? So that those developers referred to by Joel Spolsky as “commodity developers” can circumvent writing complex SQL queries by just moving stuff into a CLR HashTable or an ArrayList and looping through it over and over until they get the right daters, right there within SQL Server?

Ah well. I’ll probably end up using this feature on my next project.

Onward. 


PNGCrush

October 24, 2006

IE 7 was just released last week. Now with all these newfangled browsers that support the PNG image format, maybe we should start looking at some nifty PNG tools, like this one, that supposedly can really really compress PNG files down to really small sizes. Really small.

Unfortunately, I’m too lazy to actually try it out. I’m just letting you know that it’s available. And that it’s open-source, which is all hip these days. 

So yeah… that’s my review of PNGCrush. The web site looks like it might be useful. 


Blast from the Past

October 24, 2006

Someone just sent me a link to an article I wrote many moons ago for ASPToday.com. Actually, almost 7 years ago. Wowzers. Suffice to say – I don’t look like the guy in that picture anymore.

Funny that people are still using SQL Server 2000, and maybe even getting some insight from this article. According to the site, the going rate is $300 per article. Back then they were paying $800 an article. Which may be part of the reason why they went out of business (they were purchased by Apress just before the death knell finished ringing).

Hmm… maybe I should crack the ol’ writer’s knuckles again?


DB Encrypt ‘n’ Zip

October 17, 2006

I’ve added a new Downloads page, and provided a link to a little utility I put together way back many moons ago that will both zip up and encrypt a database backup.

Check it out – the Downloads tab above you.


Dotfuscator Update

October 14, 2006

I wrote in an earlier post how that Dotfuscator Community Edition wouldn’t obfuscate a .Net 2.0 assembly that referenced a .Net 1.0 assembly. Well yesterday I registered my copy of Dotfuscator Community Edition, which let me download available updates, and lo and behold the update I installed fixed the problem.

So yeah, if you’re using Dotfuscator Community Edition you may want to get the latest updates. I would’ve checked for updates before if the registration screen hadn’t been between me and the updates download page.

Ah well, at least it’s working now. 


MS-DOS 6.0 Source Code Revealed!

October 11, 2006

Is this what I think it is? Is the source code for MS-DOS 6.0 publicly available on Google Code Search?

Now, that’s just gnarly. I should make some printouts for my next extended bathroom visit. Or late night fireside read with a hot cuppa.

And stuff like that right thar. 

[Update 10-27-07: it appears that this entry has been removed from Google Code Search's search results. Ah well. Like I had the time to read this anyway.]


Votive 3

October 11, 2006

A new version of Votive for WiX has been released. Almost a month ago. Yeah, I’m a little late, but this will make editing WiX files waaay-hay-hay easier.

I like it a lot.


A Windows Forms Console App

October 11, 2006

That sounds like an oxymoron don’t it? 

When you create a new console project, VS.Net takes care of wiring up your app to attach to an existing console, if there is one, or creates a new one, if necessary. Right off the bat you can read from and write to the console window, and everything just works beautifully.

But what if you want to write a Windows Forms app that can also be executed from a command-line? For example, say you want to run in “console mode” if any command-line arguments are passed to the exe, otherwise you want to launch a form as normal. You may be surprised to discover that a Windows Forms app does not automatically create its own console window, so reading from or writing to the console won’t work. Give it a try if you don’t believe me.

Here’s the way around the problem. In your Windows Forms app, when you’ve determined, through whatever devices are appropriate, that the time has arrived to run in console mode, you can use these two Win API methods.

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AttachConsole(int dwProcessId);

[ DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FreeConsole();

AttachConsole attaches to an existing process’s console, or, if -1 is specified, attaches to the existing console window (for example the console used to launch your app, which is usually the one you want to attach to). After you’ve called AttachConsole you can use the System.Console like you normally would.

Example: AttachConsole(-1);

FreeConsole “detaches” from your app from a console window. You should call this when your app is finished reading/writing  to/from a console.

Example: FreeConsole();

Have fun! 


CodeToaster Intellisense

October 11, 2006

Can I say Intellisense without getting a “letter” from Microsoft? I’ll give it a shot and see what happens.

I found out why CodeToaster wouldn’t work after being obfuscated. It was a bug in my code, caused by DotFuscator inserting namespaceless (I just made that word up!) attributes and such-like into my assemblies. Attributes with no namespace. Not having a namespace, in other words.

CodeToaster populates its Intellisense cache differently for assemblies than for uncompiled C# code. It’s much more difficult to build the cache from uncompiled C# code because the code has to be parsed, and the Intellisense has to be aware of inherited classes and all that good stuff. But to cache a compiled assembly you just iterate through all of the types in the assembly (I’m oversimplifying, but that’s really the gist). And yes, CodeToaster is building its Intellisense cache from both compiled and uncompiled code.

Here’s a slimmed-down snippet of the code that was breaking after my assemblies had been obfuscated. This code loops through the types in an assembly and caches each namespace (if it hasn’t been cached already). Unfortunately, it assumes that each Type will be in a namespace, which may not always be true. For a Type that does not belong in a namespace, the Namespace property will return null. 

foreach (System.Type type in typeList){
CacheNamespace(type.Namespace);
}

Being the good coder that I am, I  “fixed” the problem by ignoring (and not caching) namespaceless types. I can probably get away with this because, frankly, I’ve never come across a .Net Type that didn’t have a namespace (VS.Net even includes a namespace automatically when creating a new code file), and this code’s effect on such a case would be minimal, since the code would still compile in CodeToaster – the Type just wouldn’t appear in Intellisense.

I’ll probably revisit this later, but for now I’m just trying to release CodeToaster to the masses. Oddly, packaging the nasty thing up into an installable package seems to be taking longer than it did to write the app.

But more on Intellisense. Currently CodeToaster keeps a parse tree in-memory for Intellisense. It’s blazing fast, but unfortunately can take up a good chunk of memory. For subsequent versions I’m thinking of using something like SQL Server 2005 Everywhere Edition to bring memory utilization way down while retaining the current lightning-fast response times, which would involve moving the cache into an Everywhere Edition database: basically a complete rewrite of the current Intellisense engine which would take a significant amount of time, so I’m going to wait and see how folks feel Intellisense performance and memory utilization before putting that on my tackling that.

That’s enough for now. Hopefully I can have this cool tool packaged up and ready to ”ship” in a few days. 

- Later.


Google Code Search

October 10, 2006

So Google decided to buy YouTube. Yeah yeah, whatever.

I’m fascinated and excited over my most recent find: Google Code Search, which makes it easy to find regular expressions, search by language, and just… all kinds of stuff!

I’m guessing they’ll need to redesign the Google Labs page if they keep adding nifty stuff. It’s starting to get crowded. Not a bad thing though… not a bad thing at all.

Hurray for Google!

[Correction: Google Code Search lets you search using regular expressions. At first glance I thought it had the capability to search specifically for regular expressions. This is a very powerful tool, and quite honestly must've been difficult to code. How do you search millions and millions of documents using a custom regular expression, and do it within the blink of an eye? Just...just...wowzers.]


Web 2.0 Corners

October 10, 2006

With the proliferation of all things Web 2.0, all things must be rounded. All corners anyway, that is, if you want your web site to look all Web 2.0-ish and stuff.

For just the longest time I thought the only way to make round corners was by making an image in Photoshop (or your favorite paint prog) and slicing and dicing it just so, and then building a nifty HTML table around said images just so. And then, of course, wrestling with the different browser versions that would insert padding where you didn’t want it and such-like.

But there’s an easier way! You can make round corners with nothing more than good ol’ CSS!

No way!

Yes way! 

And here’s a link to the very simple instructions, provided most benefactorily by Alessandro Fulciniti. 


Five Questions, There Are

October 9, 2006

Today I interviewed a candidate (phone screen actually) that could actually answer all 5 of my questions! Sort of. I had to explain to him what I meant by the term(s?) “many-to-many relationship” before he could tell me how you would model one. All I wanted to hear was something, anything, about a third table, somewhere in between the other two, and I was ready to mark it as answered correctly. And he got it! Hurray!

So what, you may be wondering, are the five questions I ask during phone screenings? Here they are, in all their shocking horror. If you can answer all five questions you have done far far better than everyone I’ve spoken to thus far.

Q. What is the difference between a DataSet and a DataView?

Q Can you describe how a many-to-many relation is represented in a database ?
 
Q. How does the XML Serializer work?
 
Q. What is the difference between a Debug and Release build?
 
Q. What is boxing?

I figure (actually me, the DBA, and another developer) figure that if you can answer these queshuns you must be pretty good. Notice that, for the most part, it would be pretty hard to find the answers in a book. Yes, believe it or not, some of the folks we’ve interviewed on the phone were actually heard leafing through books after each question was posed.

And speaking of interview questions, I found this great set of questions to ask if you find yourself on the seeking side of the interview table, following the interview. You know, when they ask, “Do you have any questions for us?”, these here questions are the ones to ask.

And right here’s the link: The Link


Peak-a-Boo!

October 9, 2006

I was just trying to download an evaluation copy of the latest and greatest version of XMLSpy, when I suddenly got the distinct impression I was being watched. Like when Bugs Bunny is being hunted, and he looks at the camera and asks, “Did you ever get the distinct impression you were being watched? That a million eyes were upon you?”

Then my gaze slowly floated upwards until… AH!

I was being watched! By Miss Sneaky (or whatever)… see screen-shot below. What this has to do with XML is beyond me. I guess some bright egg in Marketing got the idea that developers are easily influenced into purchasing software by sexy eyes peering over a menu bar. Or maybe it’s Altova’s way of making XML seem stylish. A cross between Vogue and Dr. Dobbs perhaps?

Anyway, I’m off to evaluate XMLSpy, mostly indifferent to the fact that I was being observed whilst downloading said trial copy.

Altova

Source: www.altova.com


Mommy Microsoft

October 9, 2006

I’ve about had it with the VS.Net 2005 installer project… thingy. I don’t want VS.Net to try to locate dependencies for each assembly!

“Why not?”, you ask.

Because every time I rebuild my project, the installer project won’t build because it can’t locate all the dependencies. And I have to re-adding them back to the project. They’re still in the same place, with the same file names, but something gets “out-of-sync”.

Stop it Microsoft! Stop the pain! Stop the hurting! Stop assuming I want you to automatically locate all my files and build my installer project for me!

I’ve come to the obviously rather dramatic conclusion that VS.Net installer projects are fantastic for small, maybe internal applications with a few dependencies and whatnot, but for something like CodeToaster, which frankly is turning into a monster app, you need something obedient. Something that will do what it’s told. Something like…WiX.

Yes, my friends, it looks like I’ll be learning WiX after all. Because it lets me do exactly what I want to do, without automatically assuming I’m one of those developers that needs software to hold my hand. Like my little cousin, whose Mommy always held his hand while he went potty.

Hand holding is all good and stuff when you’re an infant (or young developer). But after years of, er… experience… hand-holding gets kind of freaky. In the real world, we have the option to say, “I don’t want you holding my hand, Mom! You’re weirding me out!”

And so on that note, I say to Mommy Microsoft: Git yo’ hand away from me! I don’t need your help!


Developer Developers… Developers?

October 4, 2006

Where are the good candidates? We’re not exactly looking for rocket scientists, but seriously – I wonder why the people I’ve interviewed so far even call themselves developers.

Q: What is a linked list?

A: Ummm… uh…

Q: What is normalization?

A: Der… uh…

Every single resume has looked fabulous – you’d think we were about to interview a star developer from Yale or somewhere. Which is why I don’t even look at resumes anymore. 9 times out of 10, it’s just one big lie. One guy we interviewed had a university degree and a Microsoft certification on his resume, both of which he admitted to not actually having completed during the interview.

I dunno. When I first started interviewing, the whole “lying” thing was a pretty big thing to me. I wanted to find someone with integrity and all that. Now I just want to find someone who knows what a database is and why a “developer” would need to know.

Maybe the problem is that I work for a mega law firm instead of one of those cool little Web 2.0 shops with the bean bags and whatnot.

*Sigh*