Procedural Epistemology Thinker RSS 2.0
 Wednesday, July 09, 2008

Terminal Server API Programming in C# (Part I)

 

Sorry for such a late response on my blog. Life has been very full for me. I now have a new job as a Senior Software Engineer at a awesome company named MPi (http://mpifix.com) This company is organized and sharp. I think probably the best development environment I've been in yet. (Well see how the camaraderie is).

Why do companies use RDP?

A RDP is a multi-channel protocol that allows a user to connect to a computer running Microsoft Terminal Services for the purpose of running programs installed on the server without having to install that same program on the client machine.

For example we install our application on a server hosted in their corporate office and then a bunch of other shops can run our program on their client machines without ever having to install it. Neat-o.

Scenario:

My first task at my new job was to identify a connecting Clients Public IP address, Hostname and Username.  The client can connect using RDP or thru a Citrix Farm. So I need to determine which they are connecting with and then gleam the information.

Research:

It turns out that Microsoft has a great Terminal Services API. Here is a reference link: http://msdn.microsoft.com/en-us/library/aa383468(VS.85).aspx

As I read more about RDP I found that on every server the RDP connection connects with a type listing a 3 character prefix “RDP” and any Citrix connection connected with “ICA” for example Type: RDPClient or ICAClient. Both of these are each stored in sessions on the server. Interesting don’t you think.. hmm.

Turns out the Terminal Services API has a public method named: WTSEnumerateSessions. This method has a WTS_INFO_CLASS enumeration type that contains your structure when you retrieve the information from WTSQuerySessionInformation. The method takes:

hServer: Handle to a terminal server.

Reserved: Just know this must be zero.

Version: This is the version of the enumeration request. Must be 1

ppSessionInfo: This is a pointer to a variable that receives a pointer to an array of the WTS_SESSION_INFO (another structure for the object).

pCount: A pointer to the variable that receives the number of WTS_SESSION_INFO structure.

Lets write some psuedo code utilizing the WTSEnumerateSessions.

1)      I need to use Pinvoke to import the Terminal Services API functions to use in my code.

a.       The assembling is “wtsapi32.dll

2)      The functions I need to accomplish using WTSEnumerateSessions are:

a.      WTSOpenServer

b.      WTSCloseServer

c.       WTSEnumerateSessions

d.      WTSQuerySessionInformation

                                                               i.      I need to manually pass the correct information to WTSQuerySessionInformation to setup the use of WTSEnumerateSessions.

e.       WTSFreeMemory

                                                               i.      Because I’lll be pulling the session info using pointers then after I’m finished I need to free up the buffer again using this method.

3)      WTS_SESSION_INFO: The wtsapi32 provides me with a existing structure that I can use to store information about a client session. The name of that struct is named WTS_SESSION_INFO. * *NOTE: Structs are great when all you care about is the properties of an object and they are going to be very small. Structs get put in the heap which when the object is orphaned or not used it falls off the heap. This in turn uses less memory. ^_^ less memory is a good thing. Only use what you need. Again only use Structs when it’s a small object (16 bytes or less) AND when you only care about the properties of the object.

4)      SessionInfoBag: I also want to create a public structure for my session object so I can pass it around my code. Because I only care about the properties and everything coming back from the wtsapi32 api are structs then a public struct is the perfect choice.

5)      Wrapper classes: For good design I’m going to wrap up my WTSOpenServer, WTSCloseServer and WTSQuerySessionInformation and add another layer of abstraction between the API and my code. This way if things change I can just change the wrapper class implementation and this makes code maintaince much easier.

6)      GetRDPSessions: This will be my main Public method that will utilize WTSEnumerateSessions. The meat and potatos so to speak.

 

In Part II, I’ll start implementing the code.

Wednesday, July 09, 2008 3:19:37 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
Technical | Terminal Services
 Monday, April 28, 2008

It’s my wife’s (Aprils) 30th birthday today, so bug her as much as possible. Below is an anonymous messaging control that will send a message to her MSN account when she’s online. Please, be kind and courteous, and wish her a happy birthday

 

 

Monday, April 28, 2008 4:19:09 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback

 Wednesday, March 26, 2008

Just a quick useful little addon to Visual Studio. PowerCommands. Here's the link:

http://code.msdn.microsoft.com/PowerCommands

And here is a quick description from the site:

Below is a list of the included in PowerCommands for Visual Studio 2008 version 1.0. Refer to the Readme document which includes many additional screenshots.

Collapse Projects
This command collapses a project or projects in the Solution Explorer starting from the root selected node. Collapsing a project can increase the readability of the solution. This command can be executed from three different places: solution, solution folders and project nodes respectively.

Copy Class
This command copies a selected class entire content to the clipboard, renaming the class. This command is normally followed by a Paste Class command, which renames the class to avoid a compilation error. It can be executed from a single project item or a project item with dependent sub items.

Paste Class
This command pastes a class entire content from the clipboard, renaming the class to avoid a compilation error. This command is normally preceded by a Copy Class command. It can be executed from a project or folder node.

Copy References
This command copies a reference or set of references to the clipboard. It can be executed from the references node, a single reference node or set of reference nodes.

Paste References
This command pastes a reference or set of references from the clipboard. It can be executed from different places depending on the type of project. For CSharp projects it can be executed from the references node. For Visual Basic and Website projects it can be executed from the project node.

Copy As Project Reference
This command copies a project as a project reference to the clipboard. It can be executed from a project node.

Edit Project File
This command opens the MSBuild project file for a selected project inside Visual Studio. It combines the existing Unload Project and Edit Project commands.

Open Containing Folder
This command opens a Windows Explorer window pointing to the physical path of a selected item. It can be executed from a project item node

Open Command Prompt
This command opens a Visual Studio command prompt pointing to the physical path of a selected item. It can be executed from four different places: solution, project, folder and project item nodes respectively.

Unload Projects
This command unloads all projects in a solution. This can be useful in MSBuild scenarios when multiple projects are being edited. This command can be executed from the solution node.

Reload Projects
This command reloads all unloaded projects in a solution. It can be executed from the solution node.

Remove and Sort Usings
This command removes and sort using statements for all classes given a project. It is useful, for example, in removing or organizing the using statements generated by a wizard. This command can be executed from a solution node or a single project node.
Note: The Remove and Sort Usings feature is only available for C# projects since the C# editor implements this feature as a command in the C# editor (which this command calls for each .cs file in the project).

Extract Constant
This command creates a constant definition statement for a selected text. Extracting a constant effectively names a literal value, which can improve readability. This command can be executed from the code editor by right-clicking selected text.

Clear Recent File List
This command clears the Visual Studio recent file list. The Clear Recent File List command brings up a Clear File dialog which allows any or all recent files to be selected.

Clear Recent Project List
This command clears the Visual Studio recent project list. The Clear Recent Project List command brings up a Clear File dialog which allows any or all recent projects to be selected.

Transform Templates
This command executes a custom tool with associated text templates items. It can be executed from a DSL project node or a DSL folder node.

Close All
This command closes all documents. It can be executed from a document tab.

Wednesday, March 26, 2008 3:00:13 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
Technical
 Tuesday, March 11, 2008

Went to the CodeTrip event on March 7th in Salt Lake City, UT. The topics presented was:

  • IE8 for Developers
  • Silverlight
  • Zoom Composer

Zoom Composer is really awesome, you can see it in action here at the Hard Rock Memorabilia site:

Talked to Tim Heuer and he invited me on the CodeTrip bus to go to Boise, ID. But I have a family I can't leave, otherwise Tim I would have been there.

I've been using the ASP.NET MVC Framework with Dynamic Data and the Entity Framework in my project for some new software (yes early adoptor). I think I could have made a nice demo for other developers.

Anyway here are some pictures:

Classroom:

 

The CODE BUS!

 

Inside the CodeBus:

 

Me and TIM Heuer (this guy had a hard time with camera, stood there like 3 minutes waiting):

 

Way to be so photogentic Tim.

 

Tuesday, March 11, 2008 9:45:43 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
Silverlight | Technical
 Tuesday, February 26, 2008

Sorry don't have much time for a longer blog right now, but wanted to throw something out there. This person created a nice little Google Cheat Sheet that if you haven't seen yet, is pretty nifty. The link for it is here: http://junkinfo.us

Quick picture:

Tuesday, February 26, 2008 5:07:43 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
Technical
 Monday, February 11, 2008

Even though ScottGu and others have written about ASP.NET MVC I figured I’d add a series of notations about URL Routing, Controllers and Controller Actions, Rendering Helpers and Understanding the Model.

Who knows maybe the way I explain it will drive the point home.

Part 1 is just my overview of the ASP.NET MVC Framework

ASP.NET MVC Framework (Part 2): Understanding URL Routing

Background

WebForms

In ASP.NET Forms we used Server controls that must appear between a <form> tag. Each server control had to use a runat=”server” attribute to tell the server to process that form on the server.

ViewState

In classic ASP when forms were submitted all form values were cleared. Unfortunately if the form had an error then you lost all that information you submitted. In ASP.NET the form is able to return with all the form values.  ViewState is a way for the server to know the status of the page.

                Event Driven Programming

ASP.NET objects (server controls) on the webpage exposed events that allowed a programmer to process ASP.NET code. By having a Load, Click or Change event handled by code made coding much simpler and much better organized.

                ASP.NET 2.0

In ASP.NET 2.0 we received Master Pages, Themes and Web Parts, more server controls for navigation or security. The provider patterns for Roles, personalization or memberships, etc .

MVC Execution Process

With ASP.NET MVC Framework a web request now passes to an UrlRoutingModule object (HTTP module) which is then parses and a route is selected. Then an MvcHandler take the object and selects a controller instance that will call that controllers Execute method.

 

Stages of the Mvc Web Project

 Initial request

 In Global.asax file, routes are added to the RouteTable object

 Routing

 The UrlRoutingModule creates the RouteData object. RouteData is used to determine which controller to request and which action to invoke

 Map to Controller

 The MvcRouteHandler handler attempts to create the type name for the controller, based on data in the RouteData instance

 Invoke ControllerBuilder   

 The handler calls the global static CreateController method of the ControllerBuilder class, obtaining an IController instance.

 Create Controller

 The ControllerBuilder instance creates a new controller directly, or uses a IControllerFactory object to create the controller

 Execute Controller

The MvcHandler instance is added to the context and calls the controller’s Execute method.

 

 

 So instead of Event Handlers we now have Controller Classes and instead of ViewState exposing certain sequences of events for programming, we now have full control over the behavior of an application.

 

Default Naming Conventions

 Pretty simple, if you have a controller name it UrlPathController  this is so the UrlRoutingModule and MvcHandler can determine which controllers to invoke. Any controller class has to implement the System.Web.MVC.IController. By implementing this IController you will gain access to using the [ControllerAction] Attribute, which we’ll get into next writing.

 

Mapping URLs to the Controllers

        MVC Framework has a default URL convention it follows to map URL’s. The syntax is:

                     URL = [Controller] / [Action] / [id]


      This means your URLs will look like: 

http://domain/site/controller-name/action-method-name/parameters

   NOTE: If you see a controller-name.mvc this is required for anybody running IIS 6.0 as their web server

Global.asax

This file is used to define route mappings. You do this in the Application_Start event. The syntax is:

      // Note: Change Url= to Url="[controller].mvc/[action]/[id]"

      // to enable automatic support on IIS 6.0.

 

      RouteTable.Routes.Add(new Route

      {

        Url = "[controller]/[action]/[id]",

        Defaults = new { action = "Index", id = (string)null },

        RouteHandler = typeof(MvcRouteHandler)

      });

 

      RouteTable.Routes.Add(new Route

          {

            Url = "Default.aspx",

            Defaults = new { controller = "Home", action = "Index",

                id = (string)null },

            RouteHandler = typeof(MvcRouteHandler)

          });

 

This is saying Add a route to the RouteTable which lists my controller and action. Notice you are not required to give it a parameter or id initially.

Here are some example URLs to drive the point home:

URL   

 RouteData object values

 /domain/site/blog 

 Controller=”blog”, Action=”index”, id=null

 /domain/site/blog/ShowEntry

 Controller=”blog”, Action=”ShowEntry”, id=null

 /domain/site/blog/ShowEntry/20

 Controller=”blog”, Action=”ShowEntry”, id=”123”

Next blog we’ll get into the Controllers and Controllers Actions.

Monday, February 11, 2008 10:52:29 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
MVC | Technical
 Monday, January 28, 2008

Hooray to MS Press who has put together a Free E-Book that includes excerpts from these 3 books.

The free e-book includes content from three recent publications from Microsoft Press:

Introducing Microsoft LINQ by Paolo Pialorsi and Marco Russo (ISBN: 9780735623910)
This practical guide covers Language Integrated Query (LINQ) syntax fundamentals, LINQ to ADO.NET, and LINQ to XML. The e-book includes the entire contents of this printed book!

Introducing Microsoft ASP.NET AJAX by Dino Esposito (ISBN: 9780735624139)
Learn about the February 2007 release of ASP.NET AJAX Extensions 1.0, including an overview and the control toolkit.

Introducing Microsoft Silverlight 1.0 by Laurence Moroney (ISBN: 9780735625396)
Learn how to use Silverlight to simplify the way you implement compelling user experiences for the Web. Discover how to support an object-oriented program model with JavaScript.

I haven't read it yet, but it's free so no complaining.

Learn more about it here.

Monday, January 28, 2008 10:05:55 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
AJAX | LINQ | Silverlight | Technical
 Monday, January 21, 2008
Although this isn't techincal. I have to show it off anyway.

My buddy from college made me and my wife this painting. Its called "Misty Lake"




The artist name is "Scot Vorwaller" If interested you can find his artist blog here: http://vorwaller.blogspot.com/ He gives a very fair price for his paintings.
Monday, January 21, 2008 2:18:23 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback

Archive
<July 2008>
SunMonTueWedThuFriSat
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789
About the Author/Disclaimer
Currently I am a Senior Software Engineer at Mobile Productive Inc a automotive tech company. Check us out at http://www.mpifix.com

Experience
  • Project Management: 4 Years (Apple Computers)
  • Computer Instructor: 2 Years (CompUSA)
  • Developer: 4 Years (RemedyMD, HRN, MPi)

  • Education
  • B.S in Computer Science from Neumont University
  • Certificate of Continuing Education from MIT

  • Linkedin

    Disclaimer
    The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

    © Copyright 2009
    Joshua T Stroup
    Sign In
    Statistics
    Total Posts: 19
    This Year: 0
    This Month: 0
    This Week: 0
    Comments: 5
    All Content © 2009, Joshua T Stroup