Procedural Epistemology Thinker RSS 2.0
 Friday, October 17, 2008

I received a very interesting bug that’s been plaguing our product for a long time now. The problem is that intermittently our WinForm client users would view an image using the WebBrowser Control that would cause the program to crash. Listing this error:

 

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

 

This problem happen when our users attempted to use a SVG Viewer or Tiff Viewer ActiveX object. (Which worked perfectly in IE outside of our app) and this did not occur on every machine. Some machines would work, others would not. We were finally able to narrow it down to those using MS Vista’s 32 bit operating system.

 

After loads of research I was able to narrow it down to Vistas Data Execution Prevention (DEP).

 

Snippet from Wikipedia about this:

 

Data Execution Prevention (DEP) is a security feature that is intended to prevent an application or service from executing code from a non-executable memory region. This helps prevent certain exploits that store code via a buffer overflow, for example. DEP runs in two modes: hardware-enforced DEP for CPUs that can mark memory pages as nonexecutable, and software-enforced DEP with a limited prevention for CPUs that do not have hardware support. Software-enforced DEP does not protect from execution of code in data pages, but instead from another type of attack (SEH overwrite).

DEP was introduced in Windows XP Service Pack 2 and is included in Windows XP Tablet PC Edition 2005, Windows Server 2003Service Pack 1 and later,[1] Windows Vista, and Windows Server 2008.

 

Software configuration

 

So how does one configure DEP. There are multiple ways of configuring this. Boot.ini (XP and VISTA) ,command line and using Microsoft’s ACT 5.0. By far the easiest method is to use the command line.

 

1)      Find your Command prompt and right click and select “run as administrator

2)      Then type “bcdedit.exe /set {current} nx XXXXXXX”

a.       Where XXXXXXX can be the following:

OptIn ( 2 ): This setting is the default configuration for Windows XP. On systems with processors that can implement hardware-enforced DEP, DEP is enabled by default for limited system binaries and programs that "opt-in." With this option, only Windows system binaries are covered by DEP by default.

OptOut( 3 ): This setting is the default configuration for Windows 2003 SP1. DEP is enabled by default for all processes. A list of specific programs that should not have DEP applied can be entered using the System dialog box in Control Panel. Network administrators can use the Application Compatibility Toolkit to "opt-out" one or more programs from DEP protection. System compatibility fixes, or shims, for DEP do take effect. Also note that Windows silently disables DEP for certain executables, such as those packaged with ASPack. [5]

AlwaysOn( 1 ): This setting provides full DEP coverage for the whole system. All processes always run with DEP applied. The exceptions list to exempt specific programs from DEP protection is not available. System compatibility fixes for DEP do not take effect. Programs that have been opted-out by using the Application Compatibility Toolkit run with DEP applied.

AlwaysOff( 0 ): This setting does not provide any DEP coverage for any part of the system, regardless of hardware DEP support. (except in Windows Vista Ultimate)

 

So your commandline might look something like this:

bcdedit.exe /set {current} nx AlwaysOff

Once you are done with this you will need to restart your computer.

 

To check the status of your DEP Policy you can run this command:

 

wmic os get dataexecutionprevention_supportpolicy” This will return a number value.  See values above to see what numbers mean.

 

Now this is how we defined what the problem was. But turning off DEP entirely isn’t a viable solution since that will expose your computer to many evil virus and hacking code.

 

Vista provides an interface to select specific programs to be marked as DEP non compliance. You can get to it by going to:

 

1)      Start

2)      Right Click “My Computerà Properties

3)      Advanced System Settings

4)      Advanced Tab

5)      Under Performance select “Settings

6)      Select the tab “Data Execution Prevention

 

Here is where you are able to add DEP for all programs and services except those I select. This will set your DEP Policy to 3 (OptOut). You can then select the exe programs that enable you to mark that program as DEP noncompliant.

 

Well that might work for other people, but it didn’t work for me on my machine.  Everytime I tried to select my program’s exe, I got the message “This program must run with data execution protection(DEP) enabled. You cannot turn off DEP for this program.

 

Later I found a website that lists a NXCOMPAT and the C# compiler.

Turns out that you can add this switch to your postbuild event of your project and it will mark your compiled project as DEP non compliant.

 

1) Right click on project in Visual Studio

2) Properties

3) Build Events

4) Edit Post Build ...

 

REM Mark project as DEP Noncompliant

call "$(DevEnvDir)..\..\VC\bin\vcvars32.bat"

call "$(DevEnvDir)..\..\VC\bin\editbin.exe" /NXCOMPAT:NO "$(TargetPath)"

 

Another way to do this is to open up the Visual Studio command prompt, browse to your exe location and type:

editbin.exe /NXCOMPAT:NO YourProgram.exe

 

That’s it, now our product will compile and it fixes many crash log errors we were receiving previously.

 

Friday, October 17, 2008 8:57:44 PM (GMT Standard Time, UTC+00:00)  #    Comments [3] - Trackback
Article | Technical
 Friday, August 15, 2008

Terminal Server API Programming in C# (Part 2)

This is Part II of my Terminal Server API Programming. You can read Part I here.

As to my Terminal Services code I have found that an enumeration thru the sessions was going to give me more overhead then I wanted. Therefore I found you can use the WTSQuerySessionInformation once you have the session you want. To get the session that I want I find the processId  that my current application is running and from that I use a ProcessIdToSessionId from the kernel32 assembly.

Add one more p/invoke:

[DllImport("kernel32.dll")]

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

Download Code Here:

Let’s review the code.

First off I created a NativeMethods.cs class that houses all my Imported Dll’s I have separated this class into a safe and UnsafeNativeMethods. Any method that uses the UnmanagedType Gets placed in the UnsafeNativeMethods, which at the top of the class I use the [SuppressUnmanagedCodeSecurity] attribute.

In the SessionInfoHelper.cs Class, everything in this class supports the call to SessionInfoBag GetClientInfo(). My company wanted to make one call to this and return all the information to be used. SessionInfoBag is my custom object that houses the structure of data that I need.  Currently you will find:

SessionInfoBag:

·         SessionId – The final sessionId that the current client is using.

·         Type – Is this a RDP or ISA (Citrix)

·         User – The connected username used

·         Machine – The machine of the connected session

·         ProcessId  - Current application ProcessId

·         IsRemoteLogin – Is this connection a remote login (RDP or Citrix) or not.

I also have a ProcessInfoBag k which contains the ProcessId and the ProcessSessionId

In the Session Helper class I also wrapped the OpenServer and CloseServer Invokes just to add another level of abstraction.

Lets walk thru the control of the class.

1)      Call GetClientInfo()

a.       Create Structures

b.      Get Process Information

c.       ProcessInfoBag GetCurrentProcessInfo()//Populates ProcessInfoBag

d.      Check for a Remote Connection and set the bool if it is

                                                               i.      If this is a remote session then let’s call “GetSession” and pass in the info (we have found the correct sessionId by this point)

                                                             ii.      Else let’s populate the SessionInfoBag object with local variables.

e.      Return Client Info

In the GetSession ():

1)      Open Server

2)      Since we now know the exact session we want on the server we use a point target search. This is done with the UnsafeNativeMethods.WTSQuerySessionInformation

a.       When done with that we populate the SessionInfoBag with this returned data.

b.      Close the Server

c.       FreeUpMemory

 

It’s a fairly straight forward solution utilizing the WTS Services for both Citrix and RDP in one class.

 

 

 

Thursday, August 14, 2008 11:28:26 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
Technical | Terminal Services
 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
Archive
<November 2008>
SunMonTueWedThuFriSat
2627282930311
2345678
9101112131415
16171819202122
23242526272829