WELCOME

This blog is where I post about my consulting work with Microsoft Technologies, and other random tidbits that don't fit in my Photo Blog or my Iraq Blog.

Wednesday, June 18, 2008

Determining your Terminal Server Session ID from C#

I ran into an interesting .NET Remoting problem yesterday: Users on Terminal Services were stomping on each other running an app with a "private" remoting server that hadn't taken into account the possibility that multiple user could be trying to run it simultaneously on the same computer.

So the next question became: How do we uniquely identify separate instances on the same server? The quick answer was username, but that would fail if a user had multiple terminal server sessions. The better answer was to use the terminal server session id. Here's a code sample to determine your session id:

[DllImport("kernel32.dll")]

static extern bool ProcessIdToSessionId(uint dwProcessId, out uint pSessionId);

static void Main(string[] args)

{

Process _currentProcess = Process.GetCurrentProcess();

uint _processID = (uint)_currentProcess.Id;

uint _sessionID;

bool _result = ProcessIdToSessionId(_processID, out _sessionID);

Console.WriteLine("ProcessIdToSessionId Result: " + _result.ToString());

Console.WriteLine("Process ID = " + _processID.ToString());

Console.WriteLine("Session ID = " + _sessionID.ToString());

Console.ReadLine();

}



Notes:
  1. On a standalone workstation the session id is zero (0).
  2. The console session on a server is also zero (0).

3 comments:

Thomas said...

Great! I run into the same problem today and you saved me a good amount of time. Thanks!

Maverick said...

In .NET 2.0 Framework this can be simplified into:

Console.WriteLine("Process ID = " + System.Diagnostics.Process.GetCurrentProcess().Id.ToString());
Console.WriteLine("Session ID = " + System.Diagnostics.Process.GetCurrentProcess().SessionId.ToString());

Dan Dar3 said...

Thank you both Eric and Maverick, it helped me to create this.

http://dandar3.blogspot.com/2010/03/single-instance-application-in-c-per.html