Archive for August, 2007

Will the Real User Please Stand Up

Without wearing any mask we are conscious of, we have a special face for each friend. - Oliver Wendell HolmesIn my previous article, Impersonation Class, I had provided code that allowed you to impersonate a user for critical parts of your program. Another common use of impersonation is when an application needs to run under a different ID than the currently logged in user. This is usually done by the system administrator to allow a program to access resources that regular users are locked out of, for example, the registry or a remote network drive.

This can create a problem if your program needs to log the current user to the database or file or needs the real users name for other reasons while impersonation is active. If you use the My.User.Name property it will return the name of the current, impersonated, user, not the user who is logged into the computer. Related .NET Framework methods will do the same. Fortunately, we’re not limited to only looking at our own process to determine who the real user is.

The System.Management Namespace provides easy access to the Windows Management Instrumentation (WMI) infrastructure. This allows us to gather a lot of information about the system, including who the owner of a specified process is. In our case, we want to look for explorer.exe, the Windows shell program.

To begin with, we will need to add a reference to System.Management to our project. Next, to look for this process, we will use the ManagementObjectSearcher. This object retrieves a collection of management objects from a WMI query. These queries look very much like standard SQL queries. In our case, we’re going to return all of the running processes. Once we have this collection, we’re going to search through it for explorer.exe, extract the user name from the object, and return it.

The Code

Public Function GetActualUserName() As String
    Dim ActualUserName As String = ""
    Dim ProcessSearch As New Management.ManagementObjectSearcher("Select * from Win32_Process")
    Dim CurrentProcesses As Management.ManagementObjectCollection = ProcessSearch.Get
    For Each ProcessItem As Management.ManagementObject In CurrentProcesses
        Dim ProcessOwner(2) As String
        ProcessItem.InvokeMethod("GetOwner", ProcessOwner)
        If (ProcessItem("Name").ToString = "explorer.exe") Then
            ActualUserName = ProcessOwner(0).ToString
            Exit For
        End If
    Next
    Return ActualUserName
End Function

Limitations

Using the System.Management objects does require having fully trusted code and sufficient security on the target system. Usually this isn’t a problem because most of the time impersonated processes will be running at a higher level of security. However, you need to bear this in mind for your design.

Another limitation would be on terminal service systems or other situations where multiple users might be logged in and have a desktop session. This may require more WMI queries to narrow down the specific user you want to capture or it may not be doable in this manner and you’ll have to try something else.

I hope you’ve found this code example helpful. Let me know if you did or didn’t or if I left something important out or if you want more details on this subject area or whatever by leaving me a comment.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

1 comment August 27th, 2007

How To Conduct a VB.NET Job Interview

Yeah, managed code is when my boss tells me what to write

Back in 1999 when I first started a VB related web site, then on a free dotcom era host, I wrote this article, VB Interview Questions, that provided a list of interview questions for VB6 related jobs. The article hasn’t been revised in years but is still one of the most popular of my archived site’s articles. So, I thought I’d revisit the programmer interview process. I went through several interviews last year as part of a job search, some good, some bad. I’m not going to get so much into specific questions here but more into what kinds of questions to ask and the interview process as a whole.

Getting a Good Start

In my original article, I said, “The interview should be conducted by someone who knows VB well preferably someone involved with the project the person is being hired for.”  I still think this is true. While a Human Resources department can be valuable in doing some initial and background screening, it should be up to the hiring manager to do the initial technical screening of candidates. This helps insure that you don’t frustrate qualified candidates and don’t waste a lot of time on those you don’t. For example, for one job a HR rep gave me a 25 question multiple choice test on .NET over the phone. I did quite well and got a face-to-face interview lined up. However, when I came in for the interview, it quickly came out that they were looking for someone with more of a C#/C++ background than VB. So, we ended up wasting each other’s time.

Certifications or No Certifications? Tests or No Tests?

My opinion is that certifications don’t mean that much in the long run. They’re somewhat helpful in eliminating those with inferior skills but, by insisting on them, you may also miss out on excellent programmers. From what I’ve seen from the system administrator side of the IT house, certifications are not a good indicator of future success within a company nor technical competence beyond the ability to regurgitate trivia. They’re a plus but shouldn’t be a make or break criteria.

Should you give written or online tests prior to an interview? I’d have to recommend against this. This used to work somewhat back in the pre-Internet days but today, with answers just a Google away, it’s mostly a waste of time and money. If you want a pre-test for screening, I’d suggest going with an open ended, personal level, model like, “Describe how you coded some of the major features of your latest VB.NET program?” or “Which array or collection methods do you find yourself using most often?”. This increases the likelihood of getting back a meaningful response rather than a borrowed blog or forum post.

The Interview

You can do the interview over the phone or in person. As both the giver and receiver of interviews, I prefer a phone interview first. This is usually a big time saver for all involved and has the advantage of being ‘green’ since no extra gasoline will be required. It also can be conducted after hours from home as well, making it more convenient for all. Just don’t try to do an interview on a cell phone while driving please!

Trivia Time

OK, so you’ve started the interview so let’s start with some trivia questions. These questions can be as few as 3 or 4 or as many as 25. I suggest starting with some softball questions like, “In .NET, what is an Object?” and build up to more difficult ones like, “Explain how to multicast delegates.” You can probably find a number of good questions you can put together from my VB Tutorial articles as well as on other VB.NET related sites. The point of this part of the interview is to see how well they know the basics. Don’t ask pure trivia like “How many overloads does the String.Format function have?” or a set list of standard questions. Instead, ask questions that will give you a good idea of what the interviewee knows without trying to purposely trip them up and ones that track well with the apparent skill level of the candidate.

In most cases, you’ll know within about 10 questions if the person has the knowledge level you are seeking. If they don’t, it’s probably best to wind up the interview at this point quickly and politely. If they do, move on to the next phase.

What Have You Done and What Can You Do For Me?

Now that trivia time is done, you can get into the meat of the interview. In this part of the interview you want to find out what the candidate has done on projects in the past as well as getting an idea of how their skills might apply to your projects.

I’ve found it best to ask questions that allow them to describe their previous work. Most will be enthusiastic about it and give you a lot of detail about it. Ask leading questions like, “What did you use for your database layer?”, “How do you debug problems in your web service?” or “How did you document your code?” With these questions you should be able to gauge the level of participation the candidate had on these projects and where their head is at from a coding perspective and how they would fit within your department.

Also, now that you know how they stand with something they should know, their own work, give them a situation from your problem domain. For example, if you deal with importing randomly formatted ASCII data files into a database, ask them how they would approach this problem. You don’t have to make it complex but get them to describe the basics of how they would handle it. In a face-to-face interview, have them write it out on a whiteboard or paper to also test their presentation skills.

Should they show you a code portfolio? Given that it can be faked rather easily these days, I don’t think it’s of much value anymore. However, it is a good idea to ask if they have any samples of their they could send you or that you could download. Just don’t give it a lot of weight.

Should they know something about your company? Yes. The Internet works both ways. They should have researched your company prior to the interview. If they haven’t, well, you aren’t that important to them so maybe they shouldn’t rank so high in your book either.

Do You Fit?

This is really the key question once you’ve determined that you’re interviewing a good programmer. As I mentioned in my old article, I like to see if someone has a spark of creativity and a sense of humor. While they don’t have to be a musician who’s also a Monty Python and Star Wars fan it makes the days go smoother if they don’t give you a blank stare when you bring up a bit of popular geek trivia.

Essentially you’re looking for someone that you wouldn’t mind working with on a project. They’re probably looking for the same thing. Throw out some light conversation as you wrap things up to get a feel for this.

What Do You Want To Know About Us?

Another key part of the interview is to make it two way. Have them ask questions. You can get a feel for where they’re at from this as well. For example, if they ask “When do I get days off?” or “How did you get out of that recent FTC investigation?” you might want to be a bit cautious but if they ask questions like “What is a typical work day like here?” or “What do you use for source control?” this could be taken as a good sign.

Finishing Up

Let them know what the next step in the process is and when they should hear back from your company. Try not to leave them hanging. Nothing is worse as a job candidate than having an excellent interview and not hearing back from the company until after you’ve already had to accept another position. If they didn’t do well, let them know although you should make it as non-personal as possible.

That’s all for this article. It went on a little longer than I thought it would but I hope it’s helpful to you. I had some other ideas I wanted to include but I’ll just put them in a follow-up article. Let me know if you have any thoughts or questions on the interview process by leaving me a comment or using the contact me button to send me an email.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

3 comments August 26th, 2007

Site News for 8/19/07 through 8/25/07

Hover over these pictures for interesting hidden captions!New Categories: VB.NET Tutorials and Project Management

In this new category, VB.NET Tutorials, I’ll be writing articles that go over the basics of various namespaces and objects with the novice VB.NET programmer in mind. I’m trying to shoot for something more than just a listing of commands and something with a bit more clairity and less dryness than the MSDN entries. Please leave me a comment to let me know how I’m doing with this, if I should have more or less detail, better examples, simplier examples, you got it wrong, you got it right, it is useful, it’s not useful, etc. I appreciate any feedback I get from you either through comments, contact me, or the ratings stars.

I’ve also added a category for Project Management. I’m going to use it for articles that include basic project management while keeping the Development Teams category for those on personel management. Of course, those that overlap both topics will be in both.

Most Popular Posts

Here are the most popular individual posts from this week:

  1. 10 Ways To Insure Project Failure
  2. Marine Corps Leadership Secrets - Part I
  3. Marine Corps Leadership Secrets - Part II
  4. Marine Corps Leadership Secrets - Part III
  5. Marine Corps Leadership Secrets - Part IV
  6. Marine Corps Leadership Secrets - Part V
  7. Marine Corps Leadership Secrets - Part VI
  8. How To Uninstall a Failed Windows Service Installation
  9. How To Convert a WinForms App To A Windows Service
  10. Introduction To VB.NET Delegates

If you want to let others in the .NET world know about an article of mine you liked, click on DotNetKicks icon on the social bookmarking bar at the bottom of the post to give it a ‘kick’.

Advertising

Yes, the necessary evil.

I dumped the AdGridWork block after about a week because so many of the ads were for unrelated spammy sites, yuck.

As for new ads, I place ads for Vonage internet phone service on the site over this weekend. If you make a lot of long distance phone calls, particularly international ones, this can be a huge money saver for you. I recently switched to their service and I highly recommend them.

Coming Up Next Week

Next week I’m going to write a few more articles on generic collections. Some people new to VB.NET, coming over from VB6 or just new to programming, have expressed an interest in them. I may also have some more tips on Windows or Web services coming up soon.

Maybe I’ll finish up the article on Code Walk-Throughs I’ve been working on soon as well as a few other development team and project management articles.

If there is a topic that you would like for me to cover or if you have anything that I didn’t cover well enough or accurately, please leave me a comment and let me know. Check back often to see what I’m going to talk about or just subscribe to my RSS feed to have it delivered to you by a reader or email.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Add comment August 26th, 2007

R. Lee Ermey’s VB.NET Boot Camp

I ran across this video while looking around on YouTube this afternoon. Given my series on applying Marine Corps leadership traits to software development team leadership and Coding Horror’s Jeff Atwood using some stills from Full Metal Jacket on a couple of his posts, it just seemed like a great coincidence to find this. It may make you appreciate your manager more, that’s for sure. (scroll down for video)
.
.
.
BTW, Gunny Ermey was an actual Drill Instructor back in the 60’s and did some combat time in Vietnam. He’s the real deal.
.
.
.

Direct link to video

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Add comment August 25th, 2007

Introduction To VB.NET Delegates

I read that using delegates will make you even more productiveIn my previous article, How to Use the Action and Predicate Delegates, I touched on the subject of delegates. MikeP sent me an email asking me to cover a little more general information about delegates and how to use them so I put together this article.

What is a Delegate

Essentially a delegate is a function pointer, the memory address of where a routine’s code starts in memory. If we were programming in a low level language like C/C++ we would be working with these memory positions directly. If the programmer gets these pointers wrong a crash is a common result. Fortunately for us, .NET shields us from this often dangerous complexity by encapsulating the memory address of functions in the type-safe, object oriented, delegates. The .NET Framework uses delegates a lot behind the scenes when you call a routine or an event is fired. In this article we will look at some ways to use delegates in your own code.

A Simple Delegate Example

To begin with, a Delegate is declared like this:

Private Delegate Sub WriteToDisk()
.......
Private Delegate Function UpdateFile(ByVal fileName As String) As Boolean

In this example we have two delegates, one is a sub with no parameters and the second is a function with one parameter. Now we can write our actual routines. Note that the routines we plan to use with the delegate that matches the signature of the delegate. Here are two example prototype routines for our delegates above:

Private Sub WriteUserFile()
    'code to write user file data goes here
End Sub

Private Function UpdateUserAddress(ByVal userFileName As String) As Boolean
    'code to update address field goes here
End Function

Now, use the delegate, we would use the following code:

Dim DoUpdate As UpdateFile
DoUpdate = New UpdateFile(AddressOf UpdateUserAddress)
DoUpdate.Invoke(CurrentUserFileName)

These lines would create a new delegate, set the pointer to the address of the appropriate routine and then invoke it.

When and Where To Use a Delegate

Of course, our example above is a little silly. After all, why don’t you just call the desired routine directly? In ‘real world’ coding you should only use delegates when you don’t know the function you’re going to call until the program is running. You don’t want to have the extra overhead and increase the complexity of your code by using them without a reason. So when would you use them?

One delegate trick is to use them to give access to any function from any class. For example, if you had a private function in a class, you could create a delegate of that function and pass it to another class. Under normal conditions, even if you passed in a reference to the class, the private function could not be accessed. However, by using a delegate, it can be executed. It might look something like this:

Dim DoUpdate As UpdateFile = New UpdateFile(AddressOf UpdateUserAddress)
Dim UpdateRunner As New Updater(DoUpdate)

Where “UpdateUserAddress” is a private function that’s passed to another class as a delegate.

You can even make this quite generic by using a Delegate parameter, like so:

Function UpdateAdditionalFields(ByVal routineToCall As [Delegate]) As Boolean
    routineToCall.DynamicInvoke(MyLocalData)
End Function

This is kind of risky and has some significant conversion overhead but if you need a lot of flexibility, this is a way to get it. Notice that here we use the DynamicInvoke method rather than Invoke since we don’t know exactly what we will be working with until runtime. Some additional type checking would also be in order here as well.

Another common usage of delegates is in using delegates to update a form’s user interface when threading. As you may know, you can’t update a form’s UI from a background worker thread. So, instead, you pass a delegate function to the background that can update the UI as needed. Since the delegate is actually operating in the parent’s UI thread it can do the updates without a problem.

One other way you’ll see delegates used is with Events. VB.NET already does a lot of stuff behind the scenes this way. You can leverage this to create custom events. Another is the Action, Predicate and other such methods that I mentioned in my previous article.

Multicast For More Power

A powerful feature of delegates is that you aren’t limited to pointing to just one function. The System.Delegate type has an Invocation List that holds references to the functions to be called by the delegate. This allows you to mix and match your delegate calls as needed. For our example here, let’s assume we have three functions that need to be called to update an object. Here’s how you would combine them into a delegate:

Dim Addr As New UpdateUserInfo(AddressOf UpdateAddress)
Dim Phone As New UpdateUserInfo(AddressOf UpdatePhone)
Dim Email As New UpdateUserInfo(AddressOf UpdateEmail)

Dim Updates As UpdateUserInfo = DirectCast([Delegate].Combine(Addr, Phone, Email), UpdateUserInfo)

Updates.Invoke(CurrentUser)

You can also add additional delegates to the list or remove existing ones as shown here:

Dim UserName As New UpdateUserInfo(AddressOf UpdateName)
Updates = DirectCast([Delegate].Combine(Updates, UserName), UpdateUserInfo)

.........

Updates = DirectCast([Delegate].Remove(Updates, UserName), UpdateUserInfo)

As you can imagine, using this technique can be very powerful when you want to dynamically call routines. Note that the delegates are executed synchronously in the order they were added to the list. Also, should one of the methods called encounter an exception, then the delegate operation stops at that point.

I hope this gives you some ideas on how to use Delegates in your programs. If you would like for me to get into more detail about some of the ways to use delegates in a future article or have your own ideas about how to use them, please leave a comment or send me an email.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

6 comments August 24th, 2007

Next Posts Previous Posts


Visit Me At My New Site, Programming In C#

Most Popular Articles

Highest Rated Articles

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives