Saturday, November 7, 2009

Archive – Debugging WindowsIdentity and IsInRole

This is one of those invaluable little utility functions, you never need it until you face a problem trying to determine why IsInRole is returning and unexpected value when you run your application in a non development production environment. Using this function you can quickly determine the list of roles or groups that IsInRole is matching against.

Framework 2.0 and Later
public string[] GetWindowsIdentityRoles(WindowsIdentity identity)
{
if (identity == null) throw new ArgumentNullException("identity");

IdentityReferenceCollection groups = identity.Groups.Translate(typeof(NTAccount));
string[] roles = new string[groups.Count];
for (int i = 0; i < groups.Count; ++i)
{
roles[i] = groups[i].Value;
}

return roles;
}


Framework 1.0/1.1 (For that legacy code)


public static string[] GetWindowsIdentityRoles( WindowsIdentity identity )
{
object result = typeof(WindowsIdentity).InvokeMember( "_GetRoles",
BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.NonPublic,
null, identity, new object[]{identity.Token}, null );

return (string[])result;
}



Sunday, November 1, 2009

Archive - Thread Local Storage in .NET

Another repost from my original blog.
Those of you familiar with the intricacies of Win32 multi-threaded programming will be intimately familiar with thread local storage (TLS). And you might have wondered how .NET exposes this often useful construct.
Before we begin I would like to offer a brief description of what TLS is, for those of you that might not have had the fortune of learning Win32 multi-threaded programming. TLS is a means of storing data on a per-thread basis. Any methods accessing the data will access the data associated with the thread in which the method is running. And this is achieved without the method having any special knowledge of the thread in which it is executing.
Now the real question, how can we achieve the same results in the .NET managed environment? Well depending on your situation there are a number of options available. I will describe only 3 options here. First I will describe the more commonly known CallContext and then what in my experience is less widely known Thread Static variables and finally there is the thread data slots.

The CallContext
Most of you are probably familiar with the CallContext class and how it relates to .NET remoting. A CallContext is used to flow data across multiple calls with out having to pass the data along as some part of the argument list of each called method. And if the stored data implements the ILogicalThreadAffinative interface the data will flow across machine boundaries.
A call context is maintained by the .NET framework for each logical thread of execution. By storing data in the call context you are essentially storing data specific to the thread currently executing the method, and any method called in that thread of execution has access to the threads call context. As a simple example, if you wanted to maintain a count of the number of times a function was called per thread you could do some thing like the following.
class Class1
{
static void Main(string[] args)
{
System.Threading.Thread t1 = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadFunction));
System.Threading.Thread t2 = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadFunction));

// Start the threads
t1.Start();
t2.Start();

// Wait for the threads to complete
t1.Join();
t2.Join();

System.Console.Read();
} 

private const string PerThreadCallCounterKey = "CallCounter";
private static Random Rnd = new Random();

private static void ThreadFunction()
{
// Initialize the per-thread CallCounter
System.Runtime.Remoting.Messaging.CallContext.SetData(PerThreadCallCounterKey, 0);
// Pick a randon number of times to call the target method
int iterations = Rnd.Next(255); 
// Call the method iteration number of times
for (int i = 0; i < iterations; ++i)
{
DoTheWork();
}
DisplayCounterValue();
}

private static void DoTheWork()
{
// Get the current threads CallCounter from the CallContext
int counter = (int)System.Runtime.Remoting.Messaging.CallContext.GetData(PerThreadCallCounterKey);

// Increment the counter and store the new value in the CallContext
// Notice the pre-increment (++counter).
System.Runtime.Remoting.Messaging.CallContext.SetData(PerThreadCallCounterKey, ++counter);

//OK, so we updated the counter now do the real work of this method
//...
}

private static void DisplayCounterValue()
{
// Get the current threads CallCounter from the CallContext
int counter = (int)System.Runtime.Remoting.Messaging.CallContext.GetData(PerThreadCallCounterKey);
System.Console.WriteLine("The method was called {0} times from this thread", counter);
}
}


Notice how neither the DoTheWork or DisplayCounterValue methods have any knowledge of the calling thread. They are only aware of context information which is thread specific.

Thread Static Members
As an alternative to using the CallContext class, .NET provides support for what I call Thread Static Members. Thread static members for the most part act like normal static members except that they have per-thread storage rather than per-AppDomain. Declaring a thread static member is very similar to declaring a normal static member, except that the ThreadStaticAttribute attribute is applied to the declaration as follows.



[ThreadStatic]
private static int PerThreadCallCounter;

From this point on any thing that is done to the PerThreadCallCounter member affects the instance of this member associate with the current thread of execution. The following achieves the same results as the earlier example, only this time rather than using the CallContext class a thread static member is used.

class Class1
{
static void Main(string[] args)
{
System.Threading.Thread t1 = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadFunction));
System.Threading.Thread t2 = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadFunction));

// Start the threads
t1.Start();
t2.Start();

// Wait for the threads to complete
t1.Join();
t2.Join();
System.Console.Read();
} 


[ThreadStatic]
private static int PerThreadCallCounter;

private static Random Rnd = new Random();

private static void ThreadFunction()
{ 
// Pick a randon number of times to call the target method 
int iterations = Rnd.Next(255); 

// Call the method iteration number of times
for (int i = 0; i < iterations; ++i)
{
DoTheWork();
}
DisplayCounterValue();
}

private static void DoTheWork()
{
// Increment the static member associated with the current thread
PerThreadCallCounter++;

//OK, so we updated the counter now do the real work of this method
//...
}

private static void DisplayCounterValue()
{
// Display the value of the thread static member to the user
System.Console.WriteLine("The method was called {0} times from this thread", PerThreadCallCounter);
}
}


As you can see and I am sure you will agree this is a much simpler solution. However a word of caution, with this example the naming of the instance becomes critical, sooner or later you will need to come back to a piece of code and if you loose site of the fact that a particular static member is bound to a thread rather than the entire AppDomain you could be in for some interesting debugging in the early hours of the morning.


While thread static members appear to work just like there normal static member counter parts, there are a few caveats. Firstly you might be tempted to initialize your thread static members in a static constructor. Unfortunately the results might surprise you. At first inspection it might appear that your initialization was ignored, however this is not the case, it is just that the static constructor is not run per-thread, but per-AppDomain. That is it is only executed once which means that the Thread Static member is only initialized for one thread, the and the rest are left untouched. And no, you can not apply the ThreadStaticAttribute to the constructor, this attribute can only be applied to member variables (fields).


Of course as apposed to the CallContext solution the ThreadStatic member is limited to the AppDomain boundary, which for most requirements is sufficient.


Thread Data Slots

Thread data slots are allocated once for every thread by using the Thread.AllocateDataSlot(). Once a data slot has been allocated the slot can be used from any thread to access the data stored in the data slot for the executing thread. This most closely matches the workings of the TLS APIs in the Win32 API. Rather than bore you with another rendition of the demonstration application I will leave it to the reader to investigate this solution which is adequately documented in the MSDN documentation.



See Also:

Along similar lines as the ThreadStaticAttribute, you might also want to take a look at the ContextStaticAttribute. Especially for those of you interested in the potential of AOP offered by context bound objects.

Color Gradient

Here is a quick routine I put together which is used to calculate discrete transitions from a start color to an end color in 255 steps. You could call this function in a loop to generate all the color transitions from the start color to the end color.

public Color Gradient(Color from, Color to, byte step)
{
double stepFactor = (double)step / 255;
return Color.FromArgb(
(int)(from.R + ((to.R - from.R) * stepFactor)),
(int)(from.G + ((to.G - from.G) * stepFactor)),
(int)(from.B + ((to.B - from.B) * stepFactor)));
}



Saturday, September 26, 2009

Re-throw InnerException and preserve the original StackTrace

Repost from my original blog at the dotnetjunkies (03 March 2004)

One of the problems when throwing a new exception from with-in a catch handler is that the stack trace information captured for the initial exception is lost and a new stack trace is built from the point of the throw. Of course when throwing the new exception all that is required to circumvent this problem is to set the inner exception of the new exception to the initial exception that was caught by the catch handler.

However, on occasion, you want to throw the InnerException it self. Recently on the SADeveloper forum exactly this scenario arose. A poster on the forum was using reflection to invoke a method. The poster realized that exceptions thrown by methods invoked through reflection were wrapped in the InnerException of a TargetInvocationException. Now what the poster wanted to do was to catch the TargetInvocationException and then re-throw the InnerException. I assume the reason for this was that the caller of the method, which performed the reflection invoke, was not concerned with the current implementation detail and was only required to deal with the original exceptions. The only problem with this solution is that once the InnerException is rethrown, the stack trace no longer contained the original stack trace information.

Naturally curiosity got the better of me and I set out to see if I could find a solution. After all, this is what I enjoy most about my free time (between 2-3 in the morning), I get to do things I enjoy and that is learn how the internals work. On this occasion, I got lucky and the first idea I had worked. I new that the remoting infrastructure in fact did something very similar. When an exception is throw from the remoting server, the server side stack trace is preserved on the client side. This is done by setting the private member _remoteStackTraceString to the server side stack trace. Then when the StackTrace property of the exception is called, the _remoteStackTraceString is concatenated with the _stackTraceString and returned to the caller. So I figured that all that was required was the set the _remoteStackTraceString of the InnerException to the current StackTrace of the InnerException. Then when the InnerException is re thrown, the stack trace is replaced with the new stack trace, but the _remoteStackTraceString is preserved. And the end result is a complete stack trace as if the original exception being throw never even saw a TargetInvocationException. So the question is how do we go about manipulating the private _remoteStackTraceString, well you guessed it, reflection.

As usual, before I present the code for this I have to say, just because something works does not mean it is the right thing to do. But is was Fun... And now I know a little more about how the remoting mechanism and exceptions fit together.

public void test1()
{
// Throw an exception for testing purposes
throw new ArgumentException( "test1" );
}

void test2()
{
try
{
MethodInfo mi = typeof(Form1).GetMethod( "test1" );
mi.Invoke( this, null );
}
catch( TargetInvocationException tiex )
{
// NB: Error checking etc. excluded
// Get the _remoteStackTraceString of the Exception class
FieldInfo remoteStackTraceString = typeof(Exception).GetField("_remoteStackTraceString",
BindingFlags.Instance | BindingFlags.NonPublic );

// Set the InnerException._remoteStackTraceString to the current InnerException.StackTrace
remoteStackTraceString.SetValue( tiex.InnerException,
tiex.InnerException.StackTrace + Environment.NewLine );

// Throw the new exception
throw tiex.InnerException;
}
}

...

// Test the effect of the above code by calling test2() and handling
// the exception that is thrown
try
{
test2(); // Call the method that uses reflection to call another method
}
catch ( Exception ex )
{
Console.WriteLine( ex.ToString() );
}

Thursday, September 24, 2009

Silverlight – Ray casting engine

I have been writing a little ray casting engine for Silverlight, this is a topic that I was very interested in some 12 or so years ago and the last time I did anything like this was all in C++. So I whipped out those old notes and references as started out writing the basic engine. So far it can handle multi-height textured walls, textured floors and ceilings, background textures, very basic lighting and in game objects that can be interacted with.

While testing the engine I found that my test cases resembled a pac man type game in a “3d” world so I thought what the heck and added some basic scoring, lives and a compass. The results can be seen here

ScreenshotMashoo

Make no mistake, this is no master piece it is mostly some test code that I was using to test the engine. There are still some minor rendering artefacts that can sometimes be seen in the distance between the walls and the textured floors. The engine still suffers from minor cumulative rounding errors that degrades the quality of the generated scene, but all in good time.

Saturday, August 22, 2009

Silverlight – SpriteSheet management with WriteableBitmap

As part of my Silverlight education process I have been writing some games. First a few basic things like Sildoku and Peg Solitaire. Now I am advancing to something a bit more challenging, I am writting a small 2d racing game. For this I started with some of the fun parts, writing a Sprite manager, while this is still in the early stages I thought I would share one of my basic classes the SpriteSheet class.
For those of you who do not know what a sprite sheet is, it is an set of images placed in a grid layout and composed into one larger image. Often sequential images in the grid will represent frames in an animation of some action such as walking etc. Take a look at this Wikipedia link.
My sprite manager at this stage supports both static and animated sprites, using one or more sprite sheets as a source of the images. Here is the code for the SpriteSheet class.
public class SpriteSheet
{
  private BitmapSource _spriteSheetSource;
  private WriteableBitmap _spriteSheetBitmap;
  private int _sheetWidth;
  private int _sheetHeight;    

  public SpriteSheet(BitmapSource spriteSheetSource)
  {
    if (spriteSheetSource == null) throw new ArgumentNullException("spriteSheetSource");

    _spriteSheetSource = spriteSheetSource;
    _spriteSheetBitmap = new WriteableBitmap(_spriteSheetSource);
    _sheetWidth = _spriteSheetBitmap.PixelWidth;
    _sheetHeight = _spriteSheetBitmap.PixelHeight;
  }

  public WriteableBitmap GetBitmap(int x, int y, int width, int height)
  {
    WriteableBitmap destination = new WriteableBitmap(width, height);      
    GetBitmap(destination, x, y, width, height);
    return destination;
  }

  public void GetBitmap(WriteableBitmap targetBitmap, int x, int y, int width, int height)
  {
    // Validate incomming data
    if (targetBitmap == null) throw new ArgumentNullException("targetBitmap");
    if (x < 0 || x >= _sheetWidth) throw new ArgumentOutOfRangeException("x");
    if (y < 0 || y >= _sheetHeight) throw new ArgumentOutOfRangeException("y");
    if (width < 0 || (x + width > _sheetWidth)) throw new ArgumentOutOfRangeException("width");
    if (height < 0 || (y + height > _sheetHeight)) throw new ArgumentOutOfRangeException("height");

    // Get pixel buffers for the sprite sheet and the target bitmap
    int[] sourcePixels = _spriteSheetBitmap.Pixels;
    int[] targetPixels = targetBitmap.Pixels;

    // Calculate starting offsets into the pixel buffers      
    int sourceOffset = x + (y * _sheetWidth);      
    int targetOffset = 0;

    // Note that the offsets and widths are multiplied by 4, this is because Buffer.BlockCopy requires
    // byte offsets into the buffers and our buffers are integer buffers. To optimize this I have 
    // premultiplied to values so that the multiplication is removed from the loop
    int sourceByteOffset = sourceOffset << 2;
    int sheetByteWidth = _sheetWidth << 2;
    int targetByteWidth = width << 2;
    for (int row = 0; row < height; ++row)
    {
      Buffer.BlockCopy(sourcePixels, sourceByteOffset, targetPixels, targetOffset, targetByteWidth);
      sourceByteOffset += sheetByteWidth;
      targetOffset += targetByteWidth;
    }      
  }    

  public int Width
  {
    get { return _sheetWidth; }
  }

  public int Height
  {
    get { return _sheetHeight; }
  }
}
The interesting function in this class is the GetBitmap(WriteableBitmap targetBitmap, int x, int y, int width, int height) overload. This function is the work horse of the class. It is responsible for transferring a region of the source image starting at x, y to the new WriteableBitmap. The GetBitmap(int x, int y, int width, int height) overload calls this function with a pre-allocated WriteableBitmap of the correct dimensions.
Using the class is quite simple. Assume you have a couple of standard Image controls declared on your page, something like the following.

<UserControl x:Class="Vulcan.SL.TestApplication.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
  <Canvas x:Name="LayoutRoot">  
    <Image x:Name="mySprite1" Width="100" Height="100" Canvas.Left="0"/>
    <Image x:Name="mySprite2" Width="100" Height="100" Canvas.Left="110"/>
  </Canvas>
</UserControl>
You will notice that I have not set the Source of the images, we will do this in code using the GetBitmap function of the SpriteSheet class.
Next in the code behind file we need to load the image that and create an instance of the SpriteSheet class passing the image. The trick here is that you should only create the SpriteSheet instance once the image has been fully downloaded. Here is one way of doing this.
public MainPage()
{
  InitializeComponent();

  BitmapImage spriteSheetBitmap = new BitmapImage(new Uri("/Images/WindmillLeft.png", UriKind.Relative));      
  spriteSheetBitmap.CreateOptions = BitmapCreateOptions.None;
  spriteSheetBitmap.ImageOpened += new EventHandler<RoutedEventArgs>(image_ImageOpened);       
}

void image_ImageOpened(object sender, RoutedEventArgs e)
{
  BitmapImage spriteSheetBitmap = sender as BitmapImage;

  SpriteSheet spriteSheet = new SpriteSheet(spriteSheetBitmap);

  // Set the source of the mySprite1 to an image extracted from the SpriteSheet
  mySprite1.Source = spriteSheet.GetBitmap(0, 0, 224, 240);

  // Set the source of the mySprite2 to an image extracted from the SpriteSheet
  mySprite2.Source = spriteSheet.GetBitmap(2240, 0, 224, 240);
}
Here I create a BitmapImage class and set the CreateOptions to BitmapCreateOptions.None. This ensures that the image is created without delay, however the creation still takes place asynchronously so we need attach a handler to the ImageOpened event which indicates that the image has been downloaded and decoded, indicating that we can now use the image.
In the ImageOpened event handler we can construct our SpriteSheet and used the GetBitmap function to extract the regions of interest and assign them to the relevant Image instances. I have purposely not used instance members in these examples so that each piece of code is self contained, and of course I have forgone error checks etc. for the sake of clarity.
Note that the SpriteSheet does not perform any kind of caching of the regions that are extracted, this means that if you request the same region multiple times with the GetBitmap function you will receive new instances of WriteableBitmaps for each call. In my case I take care of the caching at a higher level. I have a SpriteFrameSet class which is a cache of the frames used for an animation sequence, internally this class uses the SpriteSheet to build an array of images ie. frames, and from that point on the array is referenced to retrieve each frame from the frame set.
As my code for the Sprite and AnimatedSprite classes matures I will hopefully find some time to release that on this blog.

Wednesday, August 19, 2009

Silverlight – My first Silverlight games published

To day is somewhat of a milestone for me, after more than 15 years in the industry I have never released anything I have written into the wild. More than that, I do very little UI work, focusing mainly on backend server components.

So what is all my excitement about, well I have written 2 small Silverlight games and submitted them to Silver Arcade. Neither game is really ground breaking, they have served as an avenue gaining some basic experience with Silverlight. Each game was written in less than 24 hours so there are no fancy bells and whistles, heck they do not even have sound (Mostly because I do not even have speakers attached to my computer, no I do not play games :))

The first game is called Sildoku, yes you guessed it, it is a Sudoku clone. It has 4 levels of difficulty and each game is randomly generated on the fly. Try it here

ScreenshotSmall 

The second game is Peg Solitaire. Which you can try here

Promotional

Tuesday, August 18, 2009

Archive – Hacking my way across the process boundary

This is another one of the posts that I am migrating from my previous blog. The post is based on an answer I provided on a news group post. A subsequent post provides a similar solution for .NET. This post was put up in early 2004.

About 2 years ago a C++/MFC question appeared on the news groups asking how to send windows messages to a ListView control in another process and receive the data returned in the LVITEM structure. At the time I came up with what I thought to be an imaginative solution and it worked for the op. Recently this question reappeared but this time for the .NET environment, a quick Google search and I pointed the OP to the original post, leaving the conversion to .NET as an exercise for the reader. Since the routine did the job again and I remember having some fun playing around with the routine so I thought I would revive it here. Now I just need to get around to converting it to .NET :)

In short you allocate a block of memory in the target process using VirtualAllocEx, this block must be big enough to hold both the LVITEM structure and any string data you expect back. You also declare an instance of the structure in your local process and setup all the necessary fields; the only field that is configured differently is the pszText member, which is defined as pointing to the block of memory in the target process offset by the sizeof the LVITEM structure. Then the local structure is moved to the target process using WriteProcessMemory. Once all the structures are in place and in the correct process all that remains is to send the message using SendMessage, and passing the address of the structure in the remote process as the lParam. On successful return of the SendMessage the remote process should contain the requested data and you can copy the data back to the local process using ReadProcessMemory. Once again the pszText pointer has to be fixed up in the local process to reference the local buffer offset again by the sizeof LVITEM.

The following C++ code provides an example of getting a item from a ListView hosted in another process.

const DWORD dwBufSize = 1024;

DWORD dwProcessID;
DWORD dwResult;
HANDLE hProcess;

BYTE *lpRemoteBuffer;

LVITEM lvItem = {0};

BYTE lpLocalBuffer[dwBufSize] = {0};

// Get the process id owning the window
::GetWindowThreadProcessId( hwndListView, &dwProcessID );

// Open the process wih all access (You may not have the rights to do this)
hProcess = ::OpenProcess( PROCESS_ALL_ACCESS, FALSE, dwProcessID );

// Allocate a buffer in the remote process
lpRemoteBuffer = (BYTE*)::VirtualAllocEx( hProcess, NULL, dwBufSize,
MEM_COMMIT, PAGE_READWRITE );

// Fill in the LVITEM struct, this is in your own process
// Set the pszText member to somewhere in the remote buffer,
// For the example I used the address imediately following the LVITEM stuct
lvItem.mask = LVIF_TEXT;
lvItem.iItem = 0;
lvItem.cchTextMax = 50;

// Point to after LVITEM in the remote buffer
lvItem.pszText = (LPTSTR)(lpRemoteBuffer + sizeof( LVITEM ));

// Copy the local LVITEM to the remote buffer
::WriteProcessMemory( hProcess, (LPVOID)lpRemoteBuffer,
&lvItem, sizeof(LVITEM), NULL );

// Send the message
::SendMessage( hwndListView, LVM_GETITEM, 0, (LPARAM)lpRemoteBuffer);

// Read the struct back from the remote process into local buffer
::ReadProcessMemory( hProcess, (LPVOID)lpRemoteBuffer, lpLocalBuffer,
dwBufSize, NULL );

//Fix pszText to point to same offset in local buffer
lvItem.pszText = (LPTSTR)(lpLocalBuffer + sizeof( LVITEM ));

// Clean-up
::VirtualFreeEx( hProcess, (LPVOID)lpRemoteBuffer, 0, MEM_RELEASE );
::CloseHandle( hProcess );

Saturday, August 15, 2009

Silverlight – WriteableBitmap SetPixel extension method

I am in the process of writing two interesting controls (At least interesting to me). For one of the controls I needed a way to directly set pixels on the WriteableBitmap with full support for alpha blending, the result is the following extension method.

using System;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace ExtensionMethods
{
public static class WriteableBitmapExtensions
{
public static void SetPixel(this WriteableBitmap wb, int x, int y, Color color)
{
// Validate that the x,y coordinates are within the bounds of the bitmap
if (x < 0 || x >= wb.PixelWidth || y < 0 || y >= wb.PixelHeight) return;

int offset = (y * wb.PixelWidth) + x;
int pixel;
int[] buffer = wb.Pixels;

if (color.A == 255)
{
// Since no alpha blending is required we can directly use the incomming color
// compose the integer that needs to be written to the pixel buffer.
pixel = (color.A << 24) | (color.R << 16) | (color.G << 8) | color.B;
}
else
{
// Get the current pixle in the pixel buffer that we need to blend with
pixel = buffer[offset];

// calculate the alpha channel ratios used for the blend of
// the source and destination pixels
double sourceAlpha = color.A / 255.0;
double inverseSourceAlpha = 1 - sourceAlpha;

// Extract the color components of the current pixel in the buffer
byte destA = (byte)(pixel >> 24);
byte destR = (byte)(pixel >> 16);
byte destG = (byte)(pixel >> 8);
byte destB = (byte)pixel;

// Calculate the color components of the new pixel.
// This is the blend of the destination pixel and the new source pixel
byte pixelA = (byte)((color.A * sourceAlpha) + (inverseSourceAlpha * destA));
byte pixelR = (byte)((color.R * sourceAlpha) + (inverseSourceAlpha * destR));
byte pixelG = (byte)((color.G * sourceAlpha) + (inverseSourceAlpha * destG));
byte pixelB = (byte)((color.B * sourceAlpha) + (inverseSourceAlpha * destB));

// Reconstitute the color components into an int to be written to the pixel buffer
pixel = (pixelA << 24) | (pixelR << 16) | (pixelG << 8) | pixelB;
}

// Write new pixel to the pixel buffer
buffer[offset] = pixel;
}
}
}


If you are interested, the 2 controls I have written are




  1. TextureSurface – A control which supports direct manipulation of the pixel buffer. The convenience is that there is no need for the developer to manage the WriteableBitmap and the Image control and there are precooked functions for setting pixels with alpha channel support etc.


  2. ImageEx – This is an enhanced Image control which supports rendering only a portion of the source image, the purpose is to provide a means of rendering regions from a source image to be used like a sprite sheet.



Both controls are quite functional, but being quite new to Silverlight and not having done any WPF I am a little concerned that I have not made the most efficient use of the Control life cycle and feel like I have hacked a few things to work. Anyone out there willing to take a look at the code and make a few recommendations?

Friday, August 14, 2009

Silverlight – Set focus to the silverlight control

When loading a web page which hosts a Silverlight application, I noticed that before interacting with the Silverlight application the user was required to first click on the application so that it got input focus. It was immediately obvious that I would need to use a small piece of java script to set the focus to the control. This is how I got it to work.

1. Give the <object> element in the web page an ID
2. Pass the ‘onLoad’ parameter on the Silverlight application assigning a JavaScript function that will focus to application in the browser.

<object id="silverlightControl" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
<param name="source" value="ClientBin/DragSnapDemo.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="onLoad" value="silverlightControlHost_Load" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="3.0.40624.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration:none">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style:none"/>
</a>
</object>


3. Finally write the JavaScript function that is called when the Silverlight application has be loaded



function silverlightControlHost_Load(sender, args) 
{
var control = document.getElementById("silverlightControl");
control.focus();
}


The trick here is that the JavaScript function is only called once the Silverlight application has been fully downloaded and loaded into the browser. To achieve this I used the onLoad event of the application.

Monday, April 20, 2009

Range<> data type - Examples for XNA

During the course of some hobby projects I like to take the time to investigate ways I might be able to provide cleaner more intuitive interfaces between the various components of the software. Currently I am building a small game and decided to write everything from scratch, mostly as a learning experience. Currently I am working on the Particle System, and besides the fact that there a hundreds of implementations out there, and I have personally written more than a few over the years, I always seem to learn something new.

As with most particle systems I would imagine, I have a class that provides the initial setup of the particle system, the values that the particle emitter works with to select the initial starting point, velocity, colour, size, lifespan etc, and how those values change over the life of the particle. Typically such a class might look something like the following fragment

  public class ParticleSystemSettings
{
public Color MinColorStart
{
get;
set;
}

public Color MaxColorStart
{
get;
set;
}

public Color MinColorEnd
{
get;
set;
}

public Color MaxColorEnd
{
get;
set;
}

public float MinLifeSpan
{
get;
set;
}

public float MaxLifeSpan
{
get;
set;
}
}


Using the above settings class the particle emitter would randomly select a starting colour between MinColorStart and MaxColorStart, likewise it would randomly select the final target colour for the particle in the range of MinColorEnd and MaxColorEnd. The lifespan of the particle would randomly be selected to fall between MinLifeSpan and MaxLifeSpan and so on.



As you can imagine a fully fleshed out Settings class can become quite elaborate, so I thought I would create a Range type class something that would allow me to write code along the following lines.



  public class ParticleSystemSettings
{
public Range<Color> StartColorRange
{
get;
set;
}

public Range<Color> EndColorRange
{
get;
set;
}


public Range<float> LifeSpanRange
{
get;
set;
}
}


Clearly this is much less noisy, but besides the arguably more readable interface I also hope to gain some functional enhancements, especially when it comes to selecting values between the ranges and interpolating from one value to the next.



For example, the following code demonstrates how I would like to be initializing an instance of the ParticleSystemSettings class.



ParticleSystemSettings settings = new ParticleSystemSettings();

settings.StartColorRange = new Range<Color>(Color.Yellow, Color.Orange);
settings.EndColorRange = new Range<Color>(Color.Orange, Color.Red);
settings.LifeSpanRange = new Range<float>(0.2f, 0.5f);


And the the following is an example of how a new particle could be initialized



Particle particle = new Particle();
particle.LifeSpan = settings.LifeSpanRange.Random();
particle.ColorRange = new Range<Color>(
settings.StartColorRange.Random(),
settings.EndColorRange.Random());


And the final piece of the puzzle, calculating the appropriate value from the particles ranges based on the current progression of the particle through it’s lifespan. The following would typically be done in the Update method of the particle.



float lerpAmount = particle.Age / particle.LifeSpan;

Color renderColor = particle.ColorRange.Lerp(lerpAmount);
float renderSize = particle.SizeRange.Lerp(lerpAmount);


From these examples, you should be notice that the goal for our Range type implementation is to provide not only a container for start and end points of a range, but also methods to select a random value from the range as well as perform a linear interpolation (lerp) on the range. And most importantly the Range type should support this for any number of base types ranging from floats, Colors, Vector2, Vector3 even between dates if you so desired.



So with a basic outline of what I wanted to achieve I went through essentially two iterations before settling on a final solution. I will share both solutions and highlight a few of the pros and cons I have come across. I will start with saying that neither is perfect, but they do achieve the core goals albeit with some caveats.



Below is the complete code for my first implementation of the Range type.



  public struct Range<T>
{
private T _start;
private T _end;
private Func<T, T, float, T> _lerp;

public Range(T value, Func<T, T, float, T> lerp)
: this(value, value, lerp)
{
}

public Range(T start, T end, Func<T, T, float, T> lerp)
{
_start = start;
_end = end;
_lerp = lerp;
}

public T Start
{
get { return _start; }
}

public T End
{
get { return _end; }
}

public T Lerp(float amount)
{
if (_lerp == null) return _start;
return _lerp(_start, _end, amount);
}

public T Random()
{
return Lerp(Utilities.GetRandomFloat());
}
}


First some things you will notice,




  1. The type is defined as a struct, since literally hundreds if not thousands of particles will be initialized per frame I wanted to ensure that the minimum of objects are created on the heap.


  2. The range constructor requires that an appropriate Lerp functor is provided. This deviates from my initial construction syntax and was one of the motivators to explore alternative implementations. This signature of the lerp argument matches the implementation of Lerp on the XNA Vector2, Vector3 and Color types, but I will need to provide a custom implementation for interpolating floats or any other type that does not provide a ready made Lerp function of sorts.


  3. The Utilities.GetRandomFloat() just returns a random float value between 0.0f and 1.0f.



The next bit of code shows a few examples of how this implementation of the Range type would be used. For this example I have used a simple Lambda expression to provide the Lerp implementation for the float data type, later we will explore a more reusable solution.



// Initialize a few ranges
Range<Vector2> positionRange = new Range<Vector2>(Vector2.Zero, Vector2.One, Vector2.Lerp);
Range<Color> colorRange = new Range<Color>(Color.White, Color.Black, Color.Lerp);
Range<float> floatRange = new Range<float>(0.0f, 5.0f,
(start, end, amount) => { return start + ((end - start) * amount); });

// Get a value midway through the range
Vector2 position = positionRange.Lerp(0.5f);
Color color = colorRange.Lerp(0.5f);
float value = floatRange.Lerp(0.5f);


Of course having to pass a Lambda expression every time you wanted to use a Range on a type that does not provide a Lerp function in some form or the other would be very error prone. The obvious solution is to create some static helper methods in a static class and as we require additional lerp functions we can build on this library. We could go one step further and provide factory functions to create type specific Ranges that would provide the Lerp function internally that way we do not need to pass it every time. An example of this might look like the following.



public static class Range
{
// Factory Functions
public static Range<Vector2> CreateVector2(Vector2 start, Vector2 end)
{
return new Range<Vector2>(start, end, Vector2.Lerp);
}

public static Range<Color> CreateColor(Color start, Color end)
{
return new Range<Color>(start, end, Color.Lerp);
}

public static Range<float> CreateFloat(Color start, Color end)
{
return new Range<Color>(start, end, LerpFloat);
}

// Custom Lerp functions
public static float LerpFloat(float start, float end, float amount)
{
return start + ((end - start) * amount);
}

}


You will notice that I named the class Range, this seems to conflict with the name of the generic struct, however the CS compiler is “smart” enough to distinguish which type is being referenced in the code and while a name like RangeHelper or something similar might be a safer option, I liked the symmetry in the following code.



// Initialize a few ranges
Range<Vector2> positionRange = Range.CreateVector2(Vector2.Zero, Vector2.One);
Range<Color> colorRange = Range.CreateColor(Color.White, Color.Black);
Range<float> floatRange = Range.CreateFloat(0.0f, 5.0f);


There you have it, the first iteration of a passable Range type that met most of the goals I initially set out to achieve. I only have one major concern, and that is of performance. I do not even own an XBOX 360 so I have no idea what the performance impact is of calling Func<> delegate thousands of times per frame. On the notebook I am using to write this post, the code easily achieves about 30,000 (thirty thousand) calls per frame, but I have no clue how efficient this would be on the XBOX 360. So what are my alternatives?



Well, having used C and latter C++ since ‘89 I grew with the evolution of C++ templates and one aspect of template that would have come in handy here would have been support for template specialization. Essentially you can provide a specialized implementation of a template for a specific type, then when ever you declare a template of that type the specialized implementation is used rather than the “generic” implementation. Cool, but generics do not offer this functionality so what can I do?



One option might be to make the Range type a class (reference type), and provide specialized implementations which inherit from Range<T>, for example class FloatRange : Range<float>. The big problem with this is that I would end up creating millions of objects on the heap that need to be garbage collected resulting in significant performance degradation. Of course I could work around this as well since my particles are cached, I could make sure I reuse the member instances rather than recreate new ones each time. Maybe this is the route I should have gone. My only concern is this would require the developer to be very conscious of how the type is used to ensure optimal performance, no I would like to stick to the struct option.



So the next take on the solution required basically to declarations, the Range type and extension methods which provided the illusion of “type specialization”. The Range type is significantly simplified and no longer provides an implementation of Lerp or Random, these have been delegated to the realm of extension methods.



Here is the new code for the Range type



public struct Range<T>
{
private T _start;
private T _end;

public Range(T value)
: this(value, value)
{
}

public Range(T start, T end)
{
_start = start;
_end = end;
}

public T Start
{
get { return _start; }
set { _start = value; }
}

public T End
{
get { return _end; }
set { _end = value; }
}
}


As you will notice, the Range type now only contains the start and end points of the range without any implied functionality. The following set of extension methods provide the functionality we expect from the Range type and is specialized for each type.



public static class XnaRangeExtensions
{
public static float Lerp(this Range<float> range, float amount)
{
return range.Start + ((range.End - range.Start) * amount);
}

public static Vector2 Lerp(this Range<Vector2> range, float amount)
{
return Vector2.Lerp(range.Start, range.End, amount);
}

public static Vector3 Lerp(this Range<Vector3> range, float amount)
{
return Vector3.Lerp(range.Start, range.End, amount);
}

public static Color Lerp(this Range<Color> range, float amount)
{
return Color.Lerp(range.Start, range.End, amount);
}

public static float Random(this Range<float> range)
{
return Lerp(range, Utilities.GetRandomFloat());
}

public static Vector2 Random(this Range<Vector2> range)
{
return Lerp(range, Utilities.GetRandomFloat());
}

public static Vector3 Random(this Range<Vector3> range)
{
return Lerp(range, Utilities.GetRandomFloat());
}

public static Color Random(this Range<Color> range)
{
return Lerp(range, Utilities.GetRandomFloat());
}

public static bool IsEmpty(this Range<float> range)
{
return range.Start == range.End;
}

public static bool IsEmpty(this Range<Vector2> range)
{
return range.Start == range.End;
}

public static bool IsEmpty(this Range<Vector3> range)
{
return range.Start == range.End;
}

public static bool IsEmpty(this Range<Color> range)
{
return range.Start == range.End;
}
}


Since this is the implementation I went with there are a few additional methods like the IsEmpty methods which identify empty Ranges. Lets see how this implementation of the Range class would be used.



// Initialize a few ranges
Range<Vector2> positionRange = new Range<Vector2>(Vector2.Zero, Vector2.One);
Range<Color> colorRange = new Range<Color>(Color.White, Color.Black);
Range<float> floatRange = new Range<float>(0.0f, 5.0f);

// Get a value midway through the range
Vector2 position = positionRange.Lerp(0.5f);
Color color = colorRange.Lerp(0.5f);
float value = floatRange.Lerp(0.5f);


Syntactically this code matches exactly our original requirements, even if it required the syntactic sugar of extension methods, but to be honest, I was not dissatisfied with syntax imposed by the first implementation. So which option is better, well you can rest assured I will be evolving my thinking on this as well as possible implementation routes, hopefully with the aid of your input. As new and better alternatives evolve I will definitely post updates.

Saturday, April 11, 2009

SQL Injection - Are parameterized queries safe?

This is a repost and rework of a popular blog entry from my previous blog, the original post can be found here.

SQL Injection is one of those vulnerabilities that crop up without even realizing it. Attackers potentially use SQL Injection to

  • Bypass authentication
  • Gain access to sensitive information
  • Interrupt system availability by tampering with or destroying data
  • Elevate privileges by tampering with data

As most developers already know, a few of the key ways to protect against SQL injection is to

  1. Validate user input to ensure that the input conforms to the business requirements, and ensure that suspicious input is filtered to reduce the possible attack vectors.
  2. Apply the principals of least privilege to further limit the scope of a successful hack
  3. Use parameterized SQL queries rather than building SQL statements dynamically using string concatenation

Following the above guidelines will go along way to protect your software from a range of strategies used by potential hackers to penetrate your systems. This is not a complete guide, it is just a starting point, I am not even talking about the various web site vulnerabilities like cross site scripting etc.

The goal of this post is to demonstrate a scenario where parameterized queries could still pose a potential vulnerability. Using the following code as an example, a .NET developer might feel that the code is reasonably secure, using a nice parameterized query to a stored procedure.

oCmd.CommandText = "VulnerableDynamicSQL";
oCmd.CommandType = CommandType.StoredProcedure;
oCmd.Parameters.Add( "@userName", strUserName);
using (oCon)
{
oCon.Open();
string result = (string)oCmd.ExecuteScalar();
}

Everything seems fine, but unfortunately the code in the stored procedure could still pose a problem to the unsuspecting caller. The following rather contrived implementation of the stored procedure would leave the door wide open to SQL injection.

create proc VulnerableDynamicSQL(@userName nvarchar(25)) as
declare @sql nvarchar(255)
set @sql = 'select TelephoneNumber from users where UserName = ''' + @userName + ''''
exec sp_executesql @sql

go

For example, the user input below, passed to the above stored procedure demonstrates a simple SQL Injection attack

';drop table users --

This input would result in the procedure formulating and executing the following SQL statement;
select TelephoneNumber from users where UserName = '';drop table users –-'

I have chosen the above for simplicity and obviously this would require adequate permissions to be successful, however this does not make the example any less significant. Had the procedure been a procedure used to authenticate users of a system; only a slightly more complex injection would be required to bypass the authentication and gain unauthorized admin access to the system.

As I mentioned above, the procedure could be written without using dynamic SQL, and resulted in more secure implementation. However there are situations in which dynamic SQL is indispensible and this raises the question, Can dynamic SQL be used more securely? The answer is a definite ‘YES’. Firstly you should always consider if you require dynamic SQL normally there is an alternate solution that does not require dynamic SQL. However if you have exhausted all possibilities and the only recourse is dynamic SQL then there is a safer way to use it. Just like we are able to use parameters for our SQL statements from within .NET, so can you use parameters for your dynamic SQL. The following procedure is a reimplementation using parameterized dynamic SQL.

create proc SaferDynamicSQL(@userName nvarchar(25))  as
declare @sql nvarchar(255)
set @sql = 'select TelephoneNumber from users where UserName = @p_userName'
exec sp_executesql @sql, N'@p_userName nvarchar(25)', @p_userName = @userName

go

As you can see in this case I have defined a parameter to be used in the dynamic SQL statement called @p_userName. This parameter is defined as part of the call to sp_executesql and its value set in the same call.

Don’t make the mistake of thinking that security alone will prevent users from performing a successful SQL injection. It might prevent the user from dropping your tables, but you will still be open to many other forms of attack. When ever you concatenate strings to build SQL statements think carefully of the potential implications. Security requires a mindset where you are always questioning the implications of your decisions and even questioning things you might not have been responsible for.



And most importantly: Always validate user input.

Extension Methods: In<> and Between<>

For my first real post I thought I would kick off with something light. I was writing some code recently and realized that the code readability would benefit from two simple extension methods, In<> and Between<>.

I often find myself writing code along the lines of

if (x >= 0 && x <= 10) ...
or
if (new[] {1,2,3}.Contains(x)) ...

So I thought I would throw two extension methods at the problem, I was looking for something that would give me the following syntax.

if (x.Between(0, 10)) ...
and
if (x.In(1,2,3)) ...

The result of my first attempt is the code below, note there are a few overloads to support various alternatives and customizing the comparison.

using System;
using System.Linq;
using System.Collections.Generic;

namespace DotNetWarrior
{
public static class ExtensionMethods
{
public static bool In<T>(this T value, params T[] values)
{
return ExtensionMethods.In(value, null, values);
}

public static bool In<T>(this T value, IEqualityComparer<T> comparer, params T[] values)
{
return In(value, comparer, values as IEnumerable<T>);
}

public static bool In<T>(this T item, IEnumerable<T> values)
{
return In(item, null, values);
}

public static bool In<T>(this T value, IEqualityComparer<T> comparer, IEnumerable<T> values)
{
return values.Contains(value, comparer);
}

public static bool Between<T>(this T item, T min, T max)
{
return ExtensionMethods.Between(item, null, min, max);
}

public static bool Between<T>(this T item, IComparer<T> comparer, T min, T max)
{
if (comparer == null)
{
comparer = Comparer<T>.Default;
}
if (comparer.Compare(min, max) == 1) throw new ArgumentException("min must be less than or equal to max.");

return (comparer.Compare(item, min) >= 0) && (comparer.Compare(item, max) <= 0);
}
}
}

Well, I hope you find this useful. Till I blog again.

Welcome to my new Blog

Well it has been nearly two years since I last actively blogged. Recently I felt inspired to try and pickup on my community involvement, so I thought why not start blogging again. This is the start of that experiment.

For the most part I will be blogging about .NET and some C++. Though these days my focus is probably less techie than I would like it to be I will try to blog about the hobby tasks that I do and which inspire me to continue learning more about the technologies I am involved with. Mostly it will cover the random things I toy with in my own time.

I hope you will find what I share interesting and most importantly I hope to see your comments on my posts, especially if you have inputs that help me learn more about a topic.