Tag Archives: C#

.NET Wrapper for COM Elevation

Microsoft has ramped up the security in their latest operating system – Windows Vista, which means that developers now have to pay more attention to certain security constraints imposed by the operating system when developing applications.   Those of you readers who have read my prior posts on User Access Control in Vista (and the further reading article), may be interested in this small software project I put together. 

The Problem in a Nutshell

Vista requires that ALL users (even administrators) obtain an elevated security token before being permitted to execute protected API calls or accessing protected system resources (the registry for example).  In prior versions of Windows, system administrators were given a privileged security token at login and permitted to perform any task without further confirmation from the interactive user.  Windows Vista now allocates a low security token by default to all users and administrators, and an elevated token is only obtained with credentials (users) or confirmation (administrators) when required.

Elevation request is determined by Vista before any process is loaded – so if a particular process is running non-elevated then access to protected resources and APIs within that process is denied.  This is an important caveat, as it affects the way in which software developers approach application design.

How does one Elevate their Process?

There are several articles on the Internet about developing elevated processes in Vista, so I’ll not dwell on the steps here (my previous articles cover this subject), but essentially elevation request involves decorating .NET assemblies and WIN32 executables with elevation status in the application manifest file (may be embedded or side-by-side).

The COM Elevation Moniker is another method for obtaining elevation.  Using the CEM it is possible to host a COM (Component Object Model) component in elevated state using the dedicated system process – DLLHost.exe.  The Windows Vista SDK provides details on adding the necessary code to your project to elevate an out-of-proc component and making it available to your non-elevated application.

So why use the COM Elevation Moniker?

The CEM permits a non-elevated process to execute protected API calls and access protected resources by calling across process boundaries into an elevated process.  This is how Vista achieves mid-application elevation – look for the shield symbols in forms and property pages, to get an idea of what I am talking about. 

So what’s the big deal?

Development of a CEM component typically involves some work in C++.  Development of COM components in VB and .NET is of course possible, but when it comes down to accessing WIN32 calls to perform COM elevation most of the examples are published in C++.  Developing a managed CEM is possible but involves some work to get it operating correctly.

What about cross boundary communication? – This is the klutz of the problem with authoring CEM components, how to communicate across process boundaries?  COM development answered this problem a long time ago, and the same is true now as it was then – marshalling data and cross process communication is handled by the COM infrastructure.  But what about managed code?  If you’ve managed to solve the problem of invoking a .NET assembly as a COM CEM component, you still have to communicate over .NET interop, which may not be ideal.

Surely someone must have a way to perform elevation in the managed world?

The .NET Wrapper for COM Elevation

I wanted a way for managed developers to attribute their code classes in such away that embedded methods of these classes would request elevation from the Vista operating system before execution of such methods.  So I went about developing a library to encapsulate the complexities of the COM Elevation Moniker.  The end result is available to download from here.

After downloading the ZIP files and unpacking it, the library is packaged as an MSI installer file, which must be installed as an administrator to make use of the library functionality.  The installer also installs some example code to demonstrate use of the library.

How does the Managed Wrapper Library Work?

Essentially, the wrapper library exists as a managed and non-managed server.  The non-managed COM server provides the infrastructure to elevate managed code by hosting it’s own .NET AppDomain.  The managed server assembly is loaded into the elevated AppDomain and executes code developed by the end user of my library.

Communication between the hosted managed server and client code is achieved using an IPC (Inter-Process Communication) channel developed against WCF (Windows Communication Foundation).  The exact specifics of this set up is beyond the scope of this blog post, but involves the use of CodeDOM (dynamic code generation) to create a dynamic messaging system between elevated code and non-elevated client proxy. 

My wrapper library is very much “beta” at present.  I’ve published my library in the hope that I can attract a number of developers to use it and let me know their initial thoughts.  Documentation is sparse, but I am working on publishing a technical manual. It is important to understand that end-users of my library require no knowledge of WCF development, C++, or COM expertise, which makes my library versatile and easy to use by managed developers of different skill-level.

For now, I’ll end this post with a thank-you – for taking an interest in my project.  I look forward to receiving feedback (good and bad), especially any pertaining to security aspects.

Pass by Reference

Contrary to the beliefs of some developers, .Net reference types do not need to be passed as reference parameters (ref in C#, ByRef in VB) when a method is going to alter the contents of an object instance.

Passing a object reference by reference parameter just means the method can reassign the reference to a new object instance. The following reference parameter shown below is unnecessary:

class foo
{
public int i;
}

… void fooMethod(ref foo fooInst)
{
fooInst.i = 10;
}

.Net is smart enough to pass object instances using address – not the whole object across the stack. In C++ land, the parameter should be passed as a pointer or explicit reference (using &).

C# Value Types and Ranges

Just because it’s good to know…..

Keyword

Class

Range

bool

System.Boolean

true and false

byte

System.Byte

0 to 255

sbyte

System.SByte

-128 to 127

short

System.Int16

-32768 to 32767

ushort

System.Uint16

0 to 65535

int

System.Int32

-2,147,483,648 to 2,147,483,647

uint

System.UInt32

0 to 4,294,967,295

long

System.Int64

-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

ulong

System.UInt64

0 to 18,446,744,073,709,551,615

decimal

System.Decimal

-79,228,162,514,264,337,593,543,950,335
to 79,228,162,514,264,337,593,543,950,335

double

System.Double

-1.79769313486232e308 to
1.79769313486232e308

float

System.Single

-3.402823e38 to 3.402823e38

char

System.Char

0 to 65535

Access modifiers on property get/set

To some I may be stating the obvious, but today I was happy to find out that C# lets you set a different access level on the get and set for a property. The example below will help to illustrate what I’m talking about:

public DateTime UpdateDate
{
get
{
object data = ViewState["UpdateDate"];
return (null == data ? DateTime.Now : (DateTime)data);
}
private set
{
ViewState["UpdateDate"] = value;
}
}

Why on Earth would you want to do this? Well, I found a perfect situation where I needed the above code. I wanted to expose a property that is essentially read only to any callers that use it, but writable to the encapsulating class. In the above case, I do not use a private field to store the property value, but the ViewState instead (property is part of a server control class), the private set allows the class to write a value to the ViewState for the property.  Now, I could have written to the ViewState directly from my class and done away with the property set altogether, but this would have resulted in many statements throughout my class code.  This way, if I want to change the logic in how my property value is persisted I can make the necessary changes in one spot.  The alternative is to use a private set function, but a private property set is so much nicer. :)

From C++ to C#

I have gone back in time this week to work on a legacy ISAPI
application.  The ISAPI application is being developed in C++ and
makes use of MSXML to read an XML configuration file.  Below is
some code in C++ to open the XML file and read two text values,
contained in element nodes:

BOOL GetConfigDetails(string &userName, string &domain)
{
BOOL result = FALSE;
if (0 != configFilename && _tcslen(configFilename) > 0)
{
try
{
// Create a DOM Document.
// CComPtr smart pointer will release our COM handle.
CComPtr pItfcDoc = 0;
HRESULT hr = pItfcDoc.CoCreateInstance(__uuidof(MSXML2::DOMDocument60));
if (SUCCEEDED(hr))
{
// Load the config file.
if (VARIANT_TRUE == pItfcDoc->load(configFilename))
{
// Look for the username and domain nodes.
CComPtr pItfcNode = 0;
pItfcNode = pItfcDoc->selectSingleNode(_bstr_t(“/ISAPIStub/username”));
userName = 0 != pItfcNode ? pItfcNode->Gettext() : _bstr_t(“”);
pItfcNode = pItfcDoc->selectSingleNode(_bstr_t(“/ISAPIStub/domain”));
domain = 0 != pItfcNode ? pItfcNode->Gettext() : _bstr_t(“”);
result = TRUE;
}
}
}
catch (_com_error)
{
result = FALSE;
}
}
return result;
}

Now, here is the code in C#:

public bool GetConfigDetails(out string userName, out string domain)
{
bool result = false;
userName = domain = String.Empty;
if (!String.IsNullOrEmpty(configFilename))
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(configFilename);
XmlNode node = doc.SelectSingleNode(“/ISAPIStub/username”);
userName = (null != node) ? node.InnerText : String.Empty;
node = doc.SelectSingleNode(“/ISAPIStub/domain”);
domain = (null != node) ? node.InnerText : String.Empty;
}
catch
{
result = false;
}
}
return result;
}

Much easier huh?  See how far we’ve come as developers. 
Whilst writing my ISAPI application I had to remember to go back and
clean up my memory allocations because there is no friendly garbage
collector doing it for me – doh.

Multicast Delegate Events as Properties

The saying goes “you learn something new every day”, and today is no
exception.  I’m not sure how I missed this, but never less, this
post shows how to gain finer control over adding and removing of event
handlers to public multicast delegate events.

Typically, most C# developers are used writing event code as follows:

using System;
public delegate void MyDelegate(); // delegate declaration

public interface I
{
event MyDelegate MyEvent;
void FireAway();
}

public class MyClass: I
{
public event MyDelegate MyEvent;

public void FireAway()
{
if (MyEvent != null)
MyEvent();
}
}

public class MainClass
{
static private void f()
{
Console.WriteLine(“This is called when the event fires.”);
}

static public void Main ()
{
I i = new MyClass();

i.MyEvent += new MyDelegate(f);
i.FireAway();
}
}

The above code exposes a public multicast delegate event, which client callers subscribe to by adding handlers using the +=
operator.  However, it is possible to define a multicast delegate
event as a property, where the developer can control the adding and
removal of event handlers with add and remove accessor
decelerations. 

The example below defines properties for each event, and the accessor
decelerations on each property manages the storage of event handlers
using a private hash table. This approach is usually undertaken when a
class defines many events, where the developer expects most of the
events to be unimplemented, thus saving some overhead in creating
multicast delegate event instances that are never assigned a handler.

using System;
using System.Collections;

public delegate void MyDelegate1(int i);
public delegate void MyDelegate2(string s);
public delegate void MyDelegate3(int i, object o);
public delegate void MyDelegate4();

public class PropertyEventsSample
{
private Hashtable eventTable = new Hashtable();

public event MyDelegate1 Event1
{
add
{
eventTable["Event1"] = (MyDelegate1)eventTable["Event1"] + value;
}
remove
{
eventTable["Event1"] = (MyDelegate1)eventTable["Event1"] – value;
}
}

public event MyDelegate1 Event2
{
add
{
eventTable["Event2"] = (MyDelegate1)eventTable["Event2"] + value;
}
remove
{
eventTable["Event2"] = (MyDelegate1)eventTable["Event2"] – value;
}
}

public event MyDelegate2 Event3
{
add
{
eventTable["Event3"] = (MyDelegate2)eventTable["Event3"] + value;
}
remove
{
eventTable["Event3"] = (MyDelegate2)eventTable["Event3"] – value;
}
}

public event MyDelegate3 Event4
{
add
{
eventTable["Event4"] = (MyDelegate3)eventTable["Event4"] + value;
}
remove
{
eventTable["Event4"] = (MyDelegate3)eventTable["Event4"] – value;
}
}

public event MyDelegate3 Event5
{
add
{
eventTable["Event5"] = (MyDelegate3)eventTable["Event5"] + value;
}
remove
{
eventTable["Event5"] = (MyDelegate3)eventTable["Event5"] – value;
}
}

public event MyDelegate4 Event6
{
add
{
eventTable["Event6"] = (MyDelegate4)eventTable["Event6"] + value;
}
remove
{
eventTable["Event6"] = (MyDelegate4)eventTable["Event6"] – value;
}
}
}

C# 2.0 and the ‘yield’ keyword

Another nice addition to C# 2.0 is the yield keyword. Yield enables iterator blocks to provide values to an enumerated result, see the following example.

// yield-example.cs
using System;
using System.Collections;
public class List
{
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while(counter++ < exponent)
{
result = result * number;
yield return result;
}
}

static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach(int i in Power(2, 8))
Console.Write(“{0} “, i);
}
}

What does this mean in English? Essentially, iterator blocks can
implicitly create an array of results, which supports IEnumerable,
without having to declare an array data type and populating it.

The following line will signal the end of the iteration.

yield break;

Nullable Types in C# 2.0

I was reading about Nullable Types in the C# 2.0 specification for the
.NET Framework 2.0 today. I am surprised I didn’t find out about this
feature long ago, goes to show that you learn something new every day.

So what are Nullable Types?

Simply put, Nullable Types are value types that a can be assigned null. The following line of C# will give you a compiler error:

int y = null;

A System.Int32 is not a reference type (it is a value type), and can
therefore not be assigned a null value, however, the next line of code
will compile under the 2.0 framework:

int? y = null;

Adding a question mark after the type turns the System.Int32 value type
into a Nullable Type. The line above, is in fact, shorthand for the line
below:

System.Nullable<int> y = null;

The System.Nullable<T> generic class is used to create value type variables that contain an undefined state. The HasValue property of this class will return true if the contained variable has an assigned value, or false if it null.  The Value property will return the value of the property, or throw a System.InvalidOperationException if the contained variable is unassigned.

Why use Nullable Types?

How many times have you defined an integer in your code, and assigned it to -1 in the constructor (or definition) as meaning undefined
What happens of your code needs to change to allow negative numbers,
but you still need to determine if a value has been assigned to your
variable?  With Nullable Types, you can assign null to your
variable and test to see if the variable has been assigned at runtime.

I am presently writing a piece of code that uses reflection to get a
list of properties in a class, and then output an XML tag for each
property if the property value is not null.  Using Nullable
Types, I do not have to worry about value types outputting if their
value has not been assigned.

Casting from Nullable Type to value type.  The following lines of code will fail compilation

int? y = null;
int x = y;

The following will compile, but throw an exception if y is null:

int? y = null;
int x = (int)y;

The following will also compile, but throw an exception if y is null:

int? y = null;
int x = y.Value;

What is needed in the above examples, is an operator that will assign a
default value if the nullable variable type is unassigned.  It
just so happens that one exists. The following line will assign -1 to x
if y is null:

int? y = null;
int x = y ?? -1;

Nullable types work fine with most of the basic operators, bool& is an interesting one.  The table below defines how logical and and logical or work with two boolean nullable types:

bool? x, y;

x

y

x&y

x|y

true

true

true

true

true

false

false

true

true

null

null

true

false

true

false

true

false

false

false

false

false

null

false

null

null

true

null

true

null

false

false

null

null

null

null

null

So what are you waiting for? It’s time to start using the .NET
Framework 2.0, with it’s array of nice new features, including Nullable
Types.

Firing multicast delegate events

I am currently writing an ASP.NET server control, which exposes a
number of custom events.  I was looking through my code archives
for a helper class, which will safely call handler methods of a
multicast delegate, when an event is triggered.  I found the class
I was looking for, and decided to publish it here on my blog for future
reference.

A quick note on multicast delegates – Multicast delegates are delegate
instances that are derived from System.MulticastDelegate
and can have
more than one instance in their invocation list – essentially they are
delegates
that allow assignment of multiple handler methods. When dealing with
multicast delegates, a question arises about how to deal with
exceptions thrown in handler methods. When the framework executes a
multicast delegate, all handler methods in the invocation list are
executed sequentially.  If one of the invoked handler methods
should throw an exception, the remaining handlers in the
list, yet to be executed, are not invoked.

So, let’s say that we have a custom event on a control (events are
multicast delegates). The containing code of the control subscribes to
the control’s event with two different event handlers.  The event
fires, causing the first handler to be invoked, which then happens to
throw an exception.  The second event handler will never get
called, which could cause serious malfunction or resource leakage in
the application if the handler had an important part to play. The
helper class, posted below, alleviates this problem by invoking the
handler methods in a delegate invocation list dynamically, whilst
trapping exceptions.

The helper class exposes methods to execute a multicast delegate, both
synchronously and asynchronously.  The synchronous method returns
the list of thrown exceptions, whilst calling all handlers in the
invocation list.  The asynchronous method ignores any exceptions
and calls each handler in the invocation list on a separate thread.

public class EventHelper
{
///
/// Asynchronous delegate.
///
private delegate void AsyncFire(Delegate del, object[] args);

///
/// Static instance of asynchronous delegate.
///
private static AsyncFire _asyncFire = new AsyncFire(InvokeDelegate);

///
/// Call back for asynchronous delegate call.
///
private static AsyncCallback _asyncCallback = new AsyncCallback(InvokeDone);

///
/// Fire synchronously.
///
/// If an event handler throws an exception ignore it and move onto the next handler.
/// Multicast delegate.
/// Args.
public static Exception[] Fire(Delegate del, params object[] args)
{
List exceptions = new List();
// If delegate has no handlers then do nothing.
if (null != del)
{
// Iterate the handlers.
Delegate[] delegates = del.GetInvocationList();
foreach (Delegate sink in delegates)
{
try
{
// Invoke.
sink.DynamicInvoke(args);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
}
return exceptions.ToArray();
}

///
/// Fire asynchronously.
///
/// Each handler is fired in an thread from the thread pool.
/// Multicast delegate.
/// Args.
public static void FireAsync(Delegate del, params object[] args)
{
// If delegate has no handlers then do nothing.
if (null != del)
{
// Iterate the handlers.
// Cannot call multicast delegate asyncronously, must process
// each handler separate.
Delegate[] delegates = del.GetInvocationList();
foreach (Delegate sink in delegates)
{
// Invoke using a thread from the pool.
_asyncFire.BeginInvoke(sink, args, _asyncCallback, null);
}
}
}

///
/// Invoke container delegate.
///
/// Delegate.
/// Args.
static void InvokeDelegate(Delegate del, object[] args)
{
del.DynamicInvoke(args);
}

///
/// Called when asynchronous delegate call complete.
///
/// Asynchronous result.
private static void InvokeDone(IAsyncResult ar)
{
// Clean up.
_asyncFire.EndInvoke(ar);
}
}

Code Comments

I have lost count of the number of times that I have been asked to work
on a piece of software written by another developer, only to find out
that the code had no comments. What typically follows is hours spent
wading through lines and lines of complex instruction to determine how
the software was intended to work before I could make any
modifications.  I can hear the groans, yes it’s the old “code
comments” debate that has been going on between software developers
since the first lines of code was punched into a machine capable of
storing and editing of instructions.

In my honest opinion I see no real good reason for the absence of code
comments.  The days of programming in a vacuum are long gone,
also are the days of programming software, which is never to be
maintained once it reaches production.  There is a strong
probability that any code that you develop today will be reviewed
and/or maintained by someone else tomorrow. Yet, there are still plenty
of developers who believe that this simplistic approach to software
documentation is a hindrance to their productivity and refuse to
comment.

Below are the excuses that I have heard from other software developers when asked why their code has no comments:

1. “I had a deadline to meet and did not have time to add comments.”
Adding code comments at the time of writing adds very little to the
overall development time of a project.  I would argue that it
actually saves time because it saves the developer having to remember
what they wrote a few days ago when coming back to a previously written
module. Comments will also save hours of work down the line when the
same piece of software is maintained or enhanced. The time required to
add comments should be considering in the original implementation
estimate.

2. “I’ll add the comments later after our software is released to production.”
Comments are an inherent part of the software implementation process,
and should not be considered as an after thought.  Adding code
comments as you develop software is easier than having to go back and
add them later. Greater accuracy of comments is guaranteed if comments
are added while the intended operation of code is fresh in the mind of
the developer.  Often is the case that developers rarely go back
and add comments to production code.

3. “Comments slow down my compilation.”
Nope! most preprocessors and compilers are optimized to skip comments
when translating code into machine instructions or intermediate
language code.  Code comments no more slow down compilation than
adding white space characters between lines of code.

4. “If no-one knows how my software works I’ll have job security.”
False! If your employer has a need to terminate your agreement, writing
uncommented code will not save your butt. Sure, it’ll cost more time
and money having someone else follow your work, but in the long run
your code will get replaced with code that is easier to maintain,
saving time and money overall.

5. “I am just too damn lazy to add comments to my code.”
If you cannot take enough pride in your work to write a good piece of
software with comments, which others can continue developing against
after your done, then you should consider another profession and stop
making life difficult for other developers who need to follow you.

6. “I plan on stiffing my employer by creating unmaintainable code and then leaving.”
You’re not going to hurt your employer, just the poor developer who follows you, which might be me.

The following are all good reasons why code comments are a good thing:

1. Your code can be maintained by someone else after you’ve moved on.
2. You’ll be harassed less by your employer if someone else can work on your code in your absence.
3. Forget what you wrote yesterday? Read your own comments, you should be able to understand them.
4. Comments above classes and methods help break up code and distinguish one method or class from another.
5. Any special circumstances or quirks in the code will be obvious to someone editing your code.
6.  Software change requests and bug numbers can be indicated in the code, linking the code with a bug tracking system.
7. Public API code is easier to use by 3rd parties.
8. If you can comment your code then you can demonstrate a greater understanding during code reviews.


Finally, for those of you developing C# or Visual Basic .Net
applications, using Visual Studio 2005, I have created a macro to make
the task of code commenting easier:

1. Download the zip file, containing a VB macro file, from here.
2. Open the macro explorer in Visual Studio 2005.
3. Create a new macros project.
4. Create a new macro in the project and overwrite the VB code (all
macros are written in VB) with the XmlComments.vb code downloaded in
the zip file.
5. Customize VS.Net by adding a keyboard short cut to the “CommentMe” macro in the new project you just created.

So, what does my macro code do that the regular doc comments built into VS.Net (/// in C#) do not already do?

1. Comments are added above classes, methods and properties, depending
on the current cursor position. This makes for faster development, e.g.
when adding comment, just execute the macro when inside the curly
braces. No need for moving the cursor above the method, property or
class to trigger the built-in doc comments.

2. My macro detects parameter types and adds cref tags to the parameter comments.

3. Any exceptions used in a method or property are detected and
automatically commented in the comments above the method or property
using the exception tag.

4. Existing comments are not overwritten by my macro, instead my macro adds missing comment tags to existing comments.

5. When overriding methods and properties from a base class, my macros
code will use the same comment from the base class version.

6. VS.Net adds empty tags when using the built-in doc comments, my macro has a stab at suggesting a default comment.

Follow

Get every new post delivered to your Inbox.

Join 294 other followers

%d bloggers like this: