<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-4927779461366619687</id><updated>2024-11-06T04:58:07.256+02:00</updated><category term=".NET Micro Framework"/><category term="Gadgeteer"/><category term="Generics"/><category term="Queue"/><category term="Silverlight"/><category term="TypeScript"/><title type='text'>std::string strMyBlog = &quot;Chris Taylor&quot;;</title><subtitle type='html'>//TODO: Ramblings of a software development enthusiast</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default?start-index=26&amp;max-results=25&amp;redirect=false'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>28</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-8693852067405437391</id><published>2018-06-17T00:29:00.002+03:00</published><updated>2018-06-17T00:29:54.276+03:00</updated><title type='text'>AMD64/X86_64 General Purpose Registers</title><content type='html'>The 64 Bit registers consist of 16 general purpose registers, made up of the original 8 registers included in the original 16 and 32 bit CPU and still available in the 16 bit and 32 bit modes.&lt;br /&gt;
&lt;br /&gt;
The original AX, BX, CX and DX registers are further subdivided into high-low pairs AH/AL, BH/BL, CH/CL, DH/DL, however the use of the high portion is not supported by all of the operations, which is indicated by those registers shaded in light grey in the tables below.&lt;br /&gt;
&lt;br /&gt;
The registers are expanded to 64 Bit and are accessed by prefixing the original 16 Bit register names with &#39;R&#39;, as in RAX, RBX, RCX, RDX etc. in addition 8 new general purpose registers have been introduced simply as numbered registers R8..R15. The new registers also provide additional registers used to access the sub elements of the registers by adding B, W, D suffix to the register name to access the least significant 8 bits, 16 bits and 32 bits respectively.&lt;br /&gt;
&lt;br /&gt;
In addition to the expanded registers set R8..R15, new registers SIL, DIL, BPL and SPL have been added in 64 bit mode to provide access to the least significant 8 bits of the RSI, RDI, RBP and RSP registers&lt;br /&gt;
&lt;br /&gt;
The addition of the new registers and the improved uniformity introduced for accessing the sub elements of the registers have made register management much simpler. Code can be made more efficient by using the faster registers to store intermediate data, needing to spill over to slower memory less frequently.&lt;br /&gt;
&lt;span style=&quot;font-size: x-small;&quot;&gt;&lt;/span&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAYJzQEHIOSB1p6YiOf0MVT6Ztn6mxUT8ZsdfNxsYBIva5-5imRQvRK01G2-lpOMLyRM9X6Lkxq1l4_mqctpHsefA8tupw3tjMYUL0GcmRO8dYTg7hUVghCc10xn74aPZB1Q-NRgEbQ55Q/s1600/X64+-+General+Purpose+Registers.png&quot; imageanchor=&quot;1&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1600&quot; data-original-width=&quot;415&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAYJzQEHIOSB1p6YiOf0MVT6Ztn6mxUT8ZsdfNxsYBIva5-5imRQvRK01G2-lpOMLyRM9X6Lkxq1l4_mqctpHsefA8tupw3tjMYUL0GcmRO8dYTg7hUVghCc10xn74aPZB1Q-NRgEbQ55Q/s1600/X64+-+General+Purpose+Registers.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/8693852067405437391/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2018/06/amd64x8664-general-purpose-registers.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/8693852067405437391'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/8693852067405437391'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2018/06/amd64x8664-general-purpose-registers.html' title='AMD64/X86_64 General Purpose Registers'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAYJzQEHIOSB1p6YiOf0MVT6Ztn6mxUT8ZsdfNxsYBIva5-5imRQvRK01G2-lpOMLyRM9X6Lkxq1l4_mqctpHsefA8tupw3tjMYUL0GcmRO8dYTg7hUVghCc10xn74aPZB1Q-NRgEbQ55Q/s72-c/X64+-+General+Purpose+Registers.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-5775060782723403857</id><published>2016-11-06T01:27:00.000+02:00</published><updated>2016-11-28T07:16:09.218+02:00</updated><title type='text'>Cross Compile for Raspberry PI on Windows 10</title><content type='html'>Cross Compiling for Raspberry PI or other ARM based devices capable of running Linux, on Windows 10 using the &quot;Window subsystem for Linux&quot; (aka Bash on Windows) is now as simple as cross compiling on native Linux.&lt;br /&gt;
&lt;br /&gt;
To learn more about the Windows subsystem for Linux and how to activate it you can follow the instructions &lt;a href=&quot;http://www.howtogeek.com/249966/how-to-install-and-use-the-linux-bash-shell-on-windows-10/&quot;&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Once you have completed that you can follow these steps to install the toolchain required to cross compile for the Raspberry PI.&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;Step 1&lt;/b&gt; - Make sure your environment is up to date&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
$ sudo apt-get update&lt;br /&gt;
$ sudo apt-get upgrade&amp;nbsp;&lt;/blockquote&gt;
&lt;b&gt;Step 2&lt;/b&gt; - Install the development tools&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
$ sudo apt-get install -y build-essential gcc-arm-linux-gnueabi g++-arm-linux-gnueabi&amp;nbsp;&lt;/blockquote&gt;
For the very basics, that is it...&lt;br /&gt;
&lt;br /&gt;
Let&#39;s try build some code and get it to run on the Raspberry PI&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Step 3&lt;/b&gt; - Create a source directory&lt;br /&gt;
&lt;br /&gt;
In the bash shell you can create a &quot;source&quot; folder in the user directory and switch to the directory by issuing the following commands&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
$ mkdir ~/source&lt;br /&gt;
$ cd ~/source&lt;/blockquote&gt;
The first command will create a &quot;source&quot; directory in the current users home directory, the second will change the current directory to the newly created &quot;source&quot; directory.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Step 4&lt;/b&gt; - Write some code&lt;br /&gt;
&lt;br /&gt;
First we will launch the nano text editor, in the Windows bash shell, by issuing the following&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
$ nano test.cpp&amp;nbsp;&lt;/blockquote&gt;
This command will open the nano editor and set the file name to &quot;test.cpp&quot;. Enter the following code in the editor window&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
#include &amp;lt;iostream&amp;gt;&lt;br/&gt;
int main()&amp;nbsp;&lt;/iostream&gt;&lt;iostream&gt;&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;&lt;/iostream&gt;&lt;iostream&gt;&amp;nbsp; &amp;nbsp;std::cout &amp;lt;&amp;lt; &quot;Hello from your Raspberry PI!&quot; &amp;lt;&amp;lt; std::endl;&lt;br /&gt;&amp;nbsp;&lt;/iostream&gt;&lt;iostream&gt;&amp;nbsp; &amp;nbsp;return 0;&amp;nbsp;&lt;/iostream&gt;&lt;iostream&gt;&lt;br /&gt;}&amp;nbsp;&lt;/iostream&gt;&lt;/blockquote&gt;
&lt;iostream&gt;&lt;br /&gt;&lt;/iostream&gt;
&lt;iostream&gt;Press &quot;Ctrl-X&quot; followed by &quot;y&quot; followed by &quot;enter&quot;.&amp;nbsp;&lt;/iostream&gt;&lt;br /&gt;
&lt;iostream&gt;&lt;br /&gt;&lt;/iostream&gt;
&lt;iostream&gt;Now you should be back at the command prompt in the source directory we created earlier. Issuing the &quot;ls&quot; command should show that we have a new file called &quot;test.cpp&quot;.&amp;nbsp;&lt;/iostream&gt;&lt;br /&gt;
&lt;iostream&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/iostream&gt;
&lt;iostream&gt;&lt;b&gt;Step 5&lt;/b&gt; - Compiling using the cross compiler&lt;/iostream&gt;&lt;br /&gt;
&lt;iostream&gt;&lt;br /&gt;&lt;/iostream&gt;
&lt;iostream&gt;Next, we can compile the code for the Raspberry PI using the following command &amp;nbsp;&lt;/iostream&gt;&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
&lt;iostream&gt;$ arm-linux-gnueabi-g++ test.cpp -o test&amp;nbsp;&lt;/iostream&gt;&lt;/blockquote&gt;
&lt;iostream&gt;This will start the compiler, which will compile the test.cpp file and if you have entered the code correctly, create an executable binary file called &quot;test&quot;. If you have any errors you can go back to step 4 above and use the same commands to edit the file and fix any errors you might have encountered.&amp;nbsp;
&lt;/iostream&gt;&lt;br /&gt;
&lt;iostream&gt;&lt;br /&gt;&lt;/iostream&gt;
&lt;iostream&gt;Assuming you had no errors, you should now have a binary file on your machine called &quot;test&quot;. This is the executable that is ready to run on an ARM based device running Linux, like your Raspberry PI. We can confirm that it is indeed not compatible with the x64 architecture of your Windows machine by trying to execute the code as follow.&amp;nbsp;&lt;/iostream&gt;&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
&lt;iostream&gt;$ ./test&amp;nbsp;&lt;/iostream&gt;&lt;/blockquote&gt;
&lt;iostream&gt;The application should fail to execute and give a messages along the lines of&amp;nbsp;&lt;/iostream&gt;&lt;br /&gt;
&lt;iostream&gt;&lt;i&gt;&lt;br /&gt;&lt;/i&gt;&lt;/iostream&gt;
&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
&lt;iostream&gt;&lt;i&gt;bash: ./test: cannot execute binary file: Exec format error.&lt;/i&gt;&amp;nbsp;&lt;/iostream&gt;&lt;/blockquote&gt;
&lt;iostream&gt;&lt;br /&gt;&lt;/iostream&gt;
&lt;iostream&gt;This is because the binary is not in the correct format for the platform you are trying to execute it on. We need to copy the binary over to your Raspberry PI and try execute the binary there&lt;/iostream&gt;.&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;Step 6&lt;/b&gt; - Copy the binary to the Raspberry PI&lt;br /&gt;
&lt;br /&gt;
I am going to assume that you already have your Raspberry PI on the network and have identified the IP address, if not you can use Google or Bing to go get to that point.&lt;br /&gt;
&lt;br /&gt;
In my case, my Raspberry PI is on the network and has been assigned an IP address of 192.168.0.50.&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;&amp;nbsp; Note:&lt;/b&gt;You need to replace the IP addresses below with the IP address of &amp;nbsp;&lt;b&gt;your &lt;/b&gt;Raspberry PI.&lt;br /&gt;
&lt;br /&gt;
To copy the binary from your windows machine to the Raspberry PI we can use secure copy (scp), this is a Unix/Linux command to securely copy files between two machines using a secure shell. The Windows subsystem for Linux makes these commands available to you &quot;natively&quot; from within the bash shell.&lt;br /&gt;
&lt;br /&gt;
Enter the command below to copy the file from the Windows machine to your Raspberry PI (remember to change the IP address to the IP of your Raspberry PI)&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
$ scp test pi@192.168.0.50:/home/pi&amp;nbsp;&lt;/blockquote&gt;
If this is the first time you are setting up a secure connection to the Raspberry PI from bash, either using scp or ssh you will be prompted to confirm that you trust the target machine, you can enter &quot;yes&quot; to have the host signature entered into your local known hosts file.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Note:&lt;/b&gt; If you took too long to confirm the host, the underlying connection might have been broken, in that case you can just reissue the scp command above.&lt;br /&gt;
&lt;br /&gt;
Next you will need to enter the password, the default password for the &quot;pi&quot; user is &quot;raspberry&quot; which you can enter in response to the password prompt. When the command completes without errors, the binary should be copied over to your Raspberry. Let&#39;s go check...&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Step 7&lt;/b&gt; - Executing the binary on the Raspberry PI&lt;br /&gt;
&lt;br /&gt;
From within the bash shell on your Windows machine, you can now ssh to to the Raspberry PI. If you prefer you could use Putty, but since we have the capability to use the Windows bash shell to do this I am going to stick with that. The next command will open a ssh session to your Raspberry PI, again, remember to use the IP address for your Raspberry and not the IP address in the example (unless of course your IP matches the on in the example :) )&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
$ ssh pi@192.168.0.50&lt;/blockquote&gt;
Next, you will be prompted for the password for the user &quot;pi&quot;, enter &quot;raspberry&quot; and you should now have an interactive secure session with your Raspberry PI. You can identify that you are interacting with the Raspberry and not the local shell by looking at the prompt, it should be a bright green prompt with the following text.&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
pi@raspberrypi:~ $&amp;nbsp;&lt;/blockquote&gt;
If you see the above, you know you are now remotely interacting with the Raspberry. Entering &quot;ls&quot; command should list the &quot;test&quot; file, also in bright green, that you copied from the Windows machine.&lt;br /&gt;
&lt;br /&gt;
Lets try executing the binary and see if we have more luck than we did when executing it earlier on the Windows machine.&lt;br /&gt;
&lt;br /&gt;
At the prompt enter &quot;./test&quot;, you should then see the following&lt;br /&gt;
&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
pi@raspberrypi:~ $ ./test&lt;br /&gt;
Hello from your Raspberry PI!&amp;nbsp;&lt;/blockquote&gt;
&lt;br /&gt;
If you see that then it worked! You compiled a source file on your Windows machine, using the ARM tools to target an ARM based Linux distribution, copied the file to the target device and executed it. How awesome is that???&lt;br /&gt;
&lt;br /&gt;
There is still much more to this, but this should get you started cross compiling on Windows for your Raspberry PI. Best of all, this will also work for other ARM based devices capable of running Linux, like the BeagleBone Black for example.&lt;br /&gt;
&lt;br /&gt;
For a more complete experience, take a look at:&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;http://visualgdb.com/&quot;&gt;VisualGDB &lt;/a&gt;- Use Visual Studio to target a range of embedded devices and Linux devices&lt;br /&gt;
&lt;a href=&quot;https://visualstudiogallery.msdn.microsoft.com/725025cf-7067-45c2-8d01-1e0fd359ae6e&quot;&gt;Visual C++ for Linux development&lt;/a&gt; - Use Visual Studio to compile and deploy to ARM based Linux devices</content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/5775060782723403857/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2016/11/cross-compile-for-raspberry-pi-on.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/5775060782723403857'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/5775060782723403857'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2016/11/cross-compile-for-raspberry-pi-on.html' title='Cross Compile for Raspberry PI on Windows 10'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-277085575100961135</id><published>2016-02-09T05:41:00.001+02:00</published><updated>2016-02-09T05:54:10.010+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Generics"/><category scheme="http://www.blogger.com/atom/ns#" term="Queue"/><category scheme="http://www.blogger.com/atom/ns#" term="TypeScript"/><title type='text'>Learning a little TypeScript - Implementing a generic Queue collection</title><content type='html'>Not being much of a JavaScript guy, other than dabbling when I needed a little client side script, I thought I should probably join the rest of the world and move away from the comfort of C/C++ and C#. Taking baby steps I&amp;nbsp;tried my&amp;nbsp;hand at TypeScript first. I thought others might find my first attempt useful.&lt;br /&gt;
&lt;br /&gt;
Wanting to try out classes and generics, I decided to implement a toy collection class. The snippet&amp;nbsp; is loosely based on the .NET generic Queue&lt;t&gt; collection interface and implements a similar collection in TypeScript.&lt;/t&gt;&lt;br /&gt;
&lt;br /&gt;
Without further ado, here is my very first TypeScript snippet.&lt;br /&gt;
&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/anonymous/8f73e96a7e9682a9d4e4.js&quot;&gt;&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
And here is a quick and dirty sample showing how the queue could be used&lt;br /&gt;
&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/anonymous/fa01f36de3ce992343b4.js&quot;&gt;&lt;/script&gt;&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/277085575100961135/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2016/02/learning-little-typescript-implementing.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/277085575100961135'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/277085575100961135'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2016/02/learning-little-typescript-implementing.html' title='Learning a little TypeScript - Implementing a generic Queue collection'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-7501862504890327493</id><published>2014-07-09T02:42:00.003+03:00</published><updated>2014-07-09T02:42:37.513+03:00</updated><title type='text'>Taking my hobby playing with embedded devices to the next level</title><content type='html'>I have been playing around with all sorts of embedded micro-controllers, ranging from the Atmel AVRs on the Arduino boards, to the powerful ARM Cortex processors running .NETMF and plenty of native code in-between. I recently decided I wanted to try my hand at FPGA, it looked totally foreign and it is not like anything else I had ever done.&lt;br /&gt;
&lt;br /&gt;
All I can say is I am hooked, having the power to construct a processor or logic array to your liking just feels cool. I started off just over a week ago and I took it slow, implementing half-adders then full-adders until I eventually build a full ALU. My goal is to build a custom processor designed to run the Pascal PCode generated by the original UCSD-Pascal compilers.&lt;br /&gt;
&lt;br /&gt;
So far I have not had much to show for it, everything toggles a few LEDs drives a few 7-Segment displays etc. Today I thought I would start playing with the clock management features, the thing with the clocks is without an oscilloscope you cannot really see if things are happening the way you expect. So I thought I would kill two birds with one stone. I will eventually need to generate video output and I need a custom clock to generate the right frequency to get the monitor to display the video data at the target resolution.&lt;br /&gt;
&lt;br /&gt;
The Paplio board that I am using has a Xilinx Spartan 6 FPGA which is being clocked at 32MHz, I was able to synthesize a frequency of 64MHz, close enough to the 65MHz required to support VGA 1024x768 signal. This is not the limit, I am sure it can still go higher, I just have not tried it yet.&lt;br /&gt;
&lt;br /&gt;
Here is a quick video of the system in action
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;iframe allowfullscreen=&#39;allowfullscreen&#39; webkitallowfullscreen=&#39;webkitallowfullscreen&#39; mozallowfullscreen=&#39;mozallowfullscreen&#39; width=&#39;320&#39; height=&#39;266&#39; src=&#39;https://www.youtube.com/embed/Maf5a1D23ds?feature=player_embedded&#39; frameborder=&#39;0&#39;&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
Here is a link to the hardware that I am using&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
http://papilio.cc/index.php?n=Papilio.Hardware&lt;/div&gt;
&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/7501862504890327493/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2014/07/taking-my-hobby-playing-with-embedded.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/7501862504890327493'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/7501862504890327493'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2014/07/taking-my-hobby-playing-with-embedded.html' title='Taking my hobby playing with embedded devices to the next level'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-865806332910138637</id><published>2012-09-08T11:42:00.000+03:00</published><updated>2012-09-08T11:42:20.579+03:00</updated><title type='text'>New Gadgeteer Hardware and More...</title><content type='html'>Christmas came early...

I ordered a bunch of kit that arrived yesterday, just in time for the weekend.

&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEAn9STOuC1EPKniGvduorcgC7TLVbI5EUojZ84TBvMLCkPrSr5fd7aakgntxCRAh7j3QlZ-yklsaehA6CKPVxunDI5tofvbNj51L5QX1kkdKFhx0Jox7mZyBbv7BhUM_wIoWkT_kErD0x/s1600/EarlyChristmas.JPG&quot; imageanchor=&quot;1&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;240&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEAn9STOuC1EPKniGvduorcgC7TLVbI5EUojZ84TBvMLCkPrSr5fd7aakgntxCRAh7j3QlZ-yklsaehA6CKPVxunDI5tofvbNj51L5QX1kkdKFhx0Jox7mZyBbv7BhUM_wIoWkT_kErD0x/s320/EarlyChristmas.JPG&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;

&lt;br /&gt;
&lt;strong&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;Development Boards&lt;/strong&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.ghielectronics.com/catalog/product/332&quot; target=&quot;_blank&quot;&gt;FEZ Hydra Basic Kit&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.ghielectronics.com/catalog/product/349&quot; target=&quot;_blank&quot;&gt;FEZ Cerberus Mainboard&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.st.com/internet/evalboard/product/252419.jsp&quot; target=&quot;_blank&quot;&gt;ST Development Board (STM32F4Discovery)&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Modules&lt;/strong&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.newhavendisplay.com/nhd0420d3znswbbwv3-p-5745.html&quot; target=&quot;_blank&quot;&gt;Newhaven - LCD Character Display&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.ghielectronics.com/catalog/product/330&quot; target=&quot;_blank&quot;&gt;USB Client SP Module&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.ghielectronics.com/catalog/product/355&quot; target=&quot;_blank&quot;&gt;RS232 Module&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.ghielectronics.com/catalog/product/343&quot; target=&quot;_blank&quot;&gt;OLED Display Module (128x128)&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.ghielectronics.com/catalog/product/333&quot; target=&quot;_blank&quot;&gt;Ethernet ENC28 Module&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.ghielectronics.com/catalog/product/273&quot; target=&quot;_blank&quot;&gt;Extender Module&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
So far&amp;nbsp;I have tested the OLED, it is much smaller than I expected but it is really a nice little screen. I can see it being very useful for low volume data that needs to be displayed.&lt;br /&gt;
&lt;br /&gt;
The real fun so far was the Newhaven LCD Character display. I am a software guy, so having to solder does not make me feel comfortable. Don&#39;t get me wrong, soldering a few header pins on to a board is no issue.&lt;br /&gt;
&lt;br /&gt;
The data sheet for the display refers to jumpers being set to select the communication mode for the display. but when I opened the device there were no jumpers to be found. A quick Bing search and it turns out that what they call jumper are really two pads on the board that need to be shorted. And those pads sit right next to the processor on the display controller. &lt;br /&gt;
&lt;br /&gt;
When I finally decided to bite the bullet and drop a little solder between the pads, my 11 year old daughter came to check-up on what I was doing. She saw the tiny area I was tackling with what seems like a huge soldering iron and promptly offered to help, she suggested I put that the board under a magnifying glass, which I did and the end result I finally wrote a &#39;Hello World&#39; .NETMF application.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhrMAdPScLHimbGh_xFadUBmZ9zM9ZgeF7IXWx4qXby-RGXEHYyGUaw255SeGMcEC3rItnw-KiK43X6QfMrUSfAb22QcY25dyUed6Ii2gHoHwvrMLk3if10tTI1NyH8wYD-rP1WMBberOq1/s1600/Display-HelloWorld.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;166&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhrMAdPScLHimbGh_xFadUBmZ9zM9ZgeF7IXWx4qXby-RGXEHYyGUaw255SeGMcEC3rItnw-KiK43X6QfMrUSfAb22QcY25dyUed6Ii2gHoHwvrMLk3if10tTI1NyH8wYD-rP1WMBberOq1/s320/Display-HelloWorld.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&amp;nbsp;&lt;/div&gt;
&lt;br /&gt;
Let me tell you I was quite relieved when it all worked. &lt;br /&gt;
&lt;br /&gt;
Now to start playing with the STM32F4 Discovery board... &lt;br /&gt;
</content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/865806332910138637/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2012/09/new-gadgeteer-hardware-and-more.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/865806332910138637'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/865806332910138637'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2012/09/new-gadgeteer-hardware-and-more.html' title='New Gadgeteer Hardware and More...'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEAn9STOuC1EPKniGvduorcgC7TLVbI5EUojZ84TBvMLCkPrSr5fd7aakgntxCRAh7j3QlZ-yklsaehA6CKPVxunDI5tofvbNj51L5QX1kkdKFhx0Jox7mZyBbv7BhUM_wIoWkT_kErD0x/s72-c/EarlyChristmas.JPG" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-6431267595502406680</id><published>2012-05-26T12:32:00.001+03:00</published><updated>2012-05-26T12:32:44.910+03:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET Micro Framework"/><category scheme="http://www.blogger.com/atom/ns#" term="Gadgeteer"/><title type='text'>Mini-Pacman on Miniature Arcade Console</title><content type='html'>&lt;p&gt;I recently &lt;a href=&quot;http://taylorza.blogspot.com/2012/05/playing-with-net-micro-framework-and.html&quot;&gt;blogged&lt;/a&gt; about some of the stuff I am playing with on the .NET Micro Framework Gadgeteer platform. Kenny Spade from the &lt;a href=&quot;http://www.tinyclr.com&quot;&gt;TinyCLR&lt;/a&gt; community forums has kindly built a miniature arcade and put up a video of Mini-Pacman running on the arcade.&lt;/p&gt; &lt;iframe height=&quot;315&quot; src=&quot;http://www.youtube.com/embed/3OmvOt-V0Yg&quot; frameborder=&quot;0&quot; width=&quot;560&quot; allowfullscreen=&quot;allowfullscreen&quot;&gt;&lt;/iframe&gt;  &lt;p&gt;It is so cool to see your work move from a bunch of loose pieces lying around on a desk to something that looks so polished. Thanks Kenny!&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/6431267595502406680/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2012/05/mini-pacman-on-miniature-arcade-console.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/6431267595502406680'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/6431267595502406680'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2012/05/mini-pacman-on-miniature-arcade-console.html' title='Mini-Pacman on Miniature Arcade Console'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/3OmvOt-V0Yg/default.jpg" height="72" width="72"/><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-7967211856683685104</id><published>2012-05-20T15:45:00.001+03:00</published><updated>2012-05-20T16:03:48.610+03:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET Micro Framework"/><category scheme="http://www.blogger.com/atom/ns#" term="Gadgeteer"/><title type='text'>Playing with .NET Micro Framework and Gadgeteer</title><content type='html'>I am sure most people have heard about the .NET Micro Framework and more recently Gadgeteer. While I have had a keen interest for sometime, I never got around to purchasing any of the hardware until about 3 weeks ago. &lt;br /&gt;
&lt;br /&gt;Here are a few things I have done in my endeavor to learn more about the framework and the embedded devices. &lt;br /&gt;&lt;br /&gt;
The first application I developed was a little Pac man clone, I made the source for this available on codeplex just follow this link &lt;a href=&quot;http://chrismcstuff.codeplex.com/&quot; title=&quot;http://chrismcstuff.codeplex.com/&quot;&gt;http://chrismcstuff.codeplex.com/&lt;/a&gt;&lt;br /&gt;
&lt;iframe width=&quot;420&quot; height=&quot;315&quot; src=&quot;http://www.youtube.com/embed/lrjgm6SnuLM&quot; frameborder=&quot;0&quot; allowfullscreen&gt;&lt;/iframe&gt;&lt;br /&gt;
More recently, I have been writing a ray-casting engine in the style of Wolfenstein 3D. Eventually I hope to release this as well, with a simple interface that others can use to develop games of this style.&lt;br /&gt;&lt;br /&gt;
Here is the latest video of the ray-casting engine.&lt;br /&gt;
&lt;iframe allowfullscreen=&quot;allowfullscreen&quot; frameborder=&quot;0&quot; height=&quot;315&quot; src=&quot;http://www.youtube.com/embed/8_8V_ulJcTc&quot; width=&quot;420&quot;&gt;&lt;/iframe&gt;  &lt;br /&gt;
I will post updates as I make more progress.&lt;br /&gt;&lt;br /&gt;
I am doing this on the &lt;a href=&quot;http://www.ghielectronics.com/catalog/product/297&quot;&gt;FEZ Spider&lt;/a&gt; from &lt;a href=&quot;http://www.ghielectronics.com/&quot;&gt;GHI Electronics&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/7967211856683685104/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2012/05/playing-with-net-micro-framework-and.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/7967211856683685104'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/7967211856683685104'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2012/05/playing-with-net-micro-framework-and.html' title='Playing with .NET Micro Framework and Gadgeteer'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://img.youtube.com/vi/lrjgm6SnuLM/default.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-7426433653005541880</id><published>2011-10-02T19:04:00.001+03:00</published><updated>2011-10-02T19:37:23.600+03:00</updated><title type='text'>My first attempt at using the HTML 5 Canvas</title><content type='html'>&lt;p&gt;Today I found myself wondering what kind of performance I can get with Javascript and the new HTML 5 Canvas. Looking for something fun to implement quickly I dug up some code for a demo I did of the Silverlight WriteableBitmap and started porting that to Javascript.&lt;/p&gt;  &lt;p&gt;Now I am not much of a Javascript guy, in fact I can safely say that this is probably the most Javascript I have written, probably more than all other previous attempts at playing with Javascript put together. &lt;/p&gt;  &lt;p&gt;So why am I writing about this if I lack so much experience, well to be honest, it is because I was actually quite surprised by the results and I thought it would be worth sharing. &lt;/p&gt;  &lt;p&gt;I did the initial development using IE 9, and I was impressed by the performance, I hit the test page using Firefox 7, Google Chrome 14 and Safari 5.1. By far Firefox was the slowest, IE 9, Chrome and Safari all performed really well on my Window 7 box. So if you are viewing this in Firefox, try it with IE 9 and see if your experience is similar.&lt;/p&gt;  &lt;iframe width=&quot;360&quot; height=&quot;280&quot; src=&quot;http://dotnetwarrior.com/demos/metaballs/metaballs.htm&quot; frameborder=&quot;0&quot;&gt; &lt;/iframe&gt;  </content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/7426433653005541880/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2011/10/my-first-attempt-at-using-html-5-canvas.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/7426433653005541880'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/7426433653005541880'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2011/10/my-first-attempt-at-using-html-5-canvas.html' title='My first attempt at using the HTML 5 Canvas'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-8892447985346793041</id><published>2010-12-23T14:12:00.002+02:00</published><updated>2011-08-23T20:40:07.285+03:00</updated><title type='text'>Visualizing Big-O complexity functions</title><content type='html'>I quickly threw this little Silverlight application together to help visualize some of the common Big-O complexity functions often quoted in any discusion on Data Structures and Algorithms.&lt;br /&gt;
&lt;br /&gt;
&lt;div id=&quot;silverlightControlHost&quot; style=&quot;height:400px&quot;&gt;&lt;object data=&quot;data:application/x-silverlight-2,&quot; type=&quot;application/x-silverlight-2&quot; width=&quot;100%&quot; height=&quot;100%&quot;&gt;     &lt;param name=&quot;source&quot; value=&quot;http://dotnetwarrior.com/Silverlight/BigOVisualizer/BigOVisualizer.xap&quot;/&gt;&lt;param name=&quot;onError&quot; value=&quot;onSilverlightError&quot; /&gt;&lt;param name=&quot;background&quot; value=&quot;white&quot; /&gt;&lt;param name=&quot;minRuntimeVersion&quot; value=&quot;4.0.50826.0&quot; /&gt;&lt;param name=&quot;maxFrameRate&quot; value=&quot;10&quot; /&gt;&lt;param name=&quot;autoUpgrade&quot; value=&quot;true&quot; /&gt;&lt;a href=&quot;http://go.microsoft.com/fwlink/?LinkID=149156&amp;v=4.0.50826.0&quot; style=&quot;text-decoration:none&quot;&gt;       &lt;img src=&quot;http://go.microsoft.com/fwlink/?LinkId=161376&quot; alt=&quot;Get Microsoft Silverlight&quot; style=&quot;border-style:none&quot;/&gt;     &lt;/a&gt;      &lt;/object&gt;&lt;iframe id=&quot;_sl_historyFrame&quot; style=&quot;visibility:hidden;height:0px;width:0px;border:0px&quot;&gt;&lt;/iframe&gt;&lt;br /&gt;
&lt;/div&gt;&lt;i&gt;&lt;small&gt;This works on Linux Firefox with &lt;a href=&quot;http://www.go-mono.com/moonlight/prerelease.aspx&quot;&gt;Moonlight 3 Preview Release&lt;/a&gt; it is a little slow but it works.&lt;/small&gt;&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
The following is a brief summary of the functions demonstrated in the application. You can get more detail &lt;a href=&quot;http://en.wikipedia.org/wiki/Big_O_notation&quot;&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;table border=&quot;1&quot;&gt;&lt;tr&gt;     &lt;th&gt;Function&lt;/th&gt;&lt;th&gt;Description&lt;/th&gt;&lt;th&gt;Example&lt;/th&gt;   &lt;/tr&gt;
&lt;tr&gt;     &lt;td&gt;O(1)&lt;/td&gt;     &lt;td&gt;Constant complexity regardless of the domain size.&lt;/td&gt;     &lt;td&gt;&lt;a href=&quot;http://en.wikipedia.org/wiki/Array_data_structure&quot;&gt;Array direct indexing&lt;/a&gt;, &lt;a href=&quot;http://en.wikipedia.org/wiki/Hash_table&quot;&gt;Hash table&lt;/a&gt;&lt;/td&gt;   &lt;/tr&gt;
&lt;tr&gt;     &lt;td&gt;O(n)&lt;/td&gt;     &lt;td&gt;Linear complexity. As the domain size increases, the time/complexity increases linearly. If you double the items the complexity will double.&lt;/td&gt;     &lt;td&gt;&lt;a href=&quot;http://en.wikipedia.org/wiki/Sequential_search&quot;&gt;Sequential search&lt;/a&gt;&lt;/td&gt;   &lt;/tr&gt;
&lt;tr&gt;     &lt;td&gt;O(log n)&lt;/td&gt;     &lt;td&gt;Logarithmic complexity. As the domain size increases, the time/complexity increases logorithmically&lt;/td&gt;     &lt;td&gt;&lt;a href=&quot;http://en.wikipedia.org/wiki/Binary_search_algorithm&quot;&gt;Binary Search&lt;/a&gt; on sorted data, Lookup in &lt;a href=&quot;http://en.wikipedia.org/wiki/Red-black_tree&quot;&gt;balanced binary tree&lt;/a&gt;&lt;/td&gt;   &lt;/tr&gt;
&lt;tr&gt;     &lt;td&gt;O(n log n)&lt;/td&gt;     &lt;td&gt;Log Linear complexity. As the domain size increases, the time/complexity increases at a log linear or geometric rate.&lt;/td&gt;     &lt;td&gt;&lt;a href=&quot;http://en.wikipedia.org/wiki/Heapsort&quot;&gt;Heap Sort&lt;/a&gt;, &lt;a href=&quot;http://en.wikipedia.org/wiki/Merge_sort&quot;&gt;Merge Sort&lt;/a&gt;, &lt;a href=&quot;http://en.wikipedia.org/wiki/Quicksort&quot;&gt;Quick Sort&lt;/a&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/td&gt;   &lt;/tr&gt;
&lt;tr&gt;     &lt;td&gt;O(n&amp;#178;)&lt;/td&gt;     &lt;td&gt;Quadratic complexity. As the domain size increases, the time/complexity increases quadratically.&lt;/td&gt;     &lt;td&gt;&lt;a href=&quot;http://en.wikipedia.org/wiki/Bubble_sort&quot;&gt;Bubble Sort&lt;/a&gt;, &lt;a href=&quot;http://en.wikipedia.org/wiki/Insertion_sort&quot;&gt;Insertion sort&lt;/a&gt;&lt;/td&gt;   &lt;/tr&gt;
&lt;tr&gt;     &lt;td&gt;O(n&amp;#179;)&lt;/td&gt;     &lt;td&gt;Cubic complexity. As the domain size increases, the time/complexity increases at a cubic rate.&lt;/td&gt;     &lt;td&gt;Naive multiplication of two nxn matrices.&lt;/td&gt;   &lt;/tr&gt;
&lt;tr&gt;     &lt;td&gt;O(2&amp;#8319;)&lt;/td&gt;     &lt;td&gt;Exponential complexity. As the domain size increases, the time/complexity increases exponentialy.&lt;/td&gt;     &lt;td&gt;Some graph algoritms like finding the exact solution to the &lt;a href=&quot;http://en.wikipedia.org/wiki/Traveling_salesman_problem&quot;&gt;traveling salesman problem&lt;/a&gt;.&lt;/td&gt;   &lt;/tr&gt;
&lt;/table&gt;&lt;i&gt;&lt;sup&gt;1&lt;/sup&gt;Quick sort has best and average case of O(n log n) but worst case of O(n&amp;#178;)&lt;/i&gt;</content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/8892447985346793041/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2010/12/visualizing-big-o-complexity-functions.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/8892447985346793041'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/8892447985346793041'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2010/12/visualizing-big-o-complexity-functions.html' title='Visualizing Big-O complexity functions'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-456160839185215831</id><published>2010-09-25T01:08:00.001+03:00</published><updated>2010-09-25T01:12:15.174+03:00</updated><title type='text'>Code Share: Finding controls by control type.</title><content type='html'>&lt;p&gt;On stackoverflow.com the question was asked, how to &lt;a href=&quot;http://stackoverflow.com/questions/3788399/find-contentplaceholders-in-master-page/3788493#3788493&quot;&gt;‘Find ContentPlaceHolders in Master Page’&lt;/a&gt;.&amp;#160; &lt;/p&gt;  &lt;p&gt;In this case the OP wanted to work with a Master Page other than the one that was already The first part of the problem was getting the Master Page loaded in memory so that the Control tree could be interrogated. &lt;/p&gt;  &lt;p&gt;Fortunately loading the Master Page is quite simple, you can use &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.web.ui.templatecontrol.aspx&quot;&gt;LoadControl&lt;/a&gt; to load the Master Page just like you would load any other user control.&lt;/p&gt;  &lt;p&gt;For example in the Page_Load handler you could use something like the following to load the Master Page.&lt;/p&gt;  &lt;div id=&quot;codeSnippetWrapper&quot;&gt;   &lt;pre style=&quot;border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px&quot; id=&quot;codeSnippet&quot;&gt;var site1Master = LoadControl(&lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;Site1.Master&amp;quot;&lt;/span&gt;);&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;The next part, finding all the controls of a specific type, requires a simple recursive routine to search the control tree for all the controls of the type that you are interested in. Here is a simple implementation of just such a routine.&lt;/p&gt;&lt;br /&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;br /&gt;  &lt;pre style=&quot;border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px&quot; id=&quot;codeSnippet&quot;&gt;&lt;span style=&quot;color: #0000ff&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;class&lt;/span&gt; WebHelper&lt;br /&gt;{&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;static&lt;/span&gt; IList&amp;lt;T&amp;gt; FindControlsByType&amp;lt;T&amp;gt;(Control root) &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;where&lt;/span&gt; T : Control&lt;br /&gt;  {&lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;if&lt;/span&gt; (root == &lt;span style=&quot;color: #0000ff&quot;&gt;null&lt;/span&gt;) &lt;span style=&quot;color: #0000ff&quot;&gt;throw&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;new&lt;/span&gt; ArgumentNullException(&lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;root&amp;quot;&lt;/span&gt;);&lt;br /&gt;&lt;br /&gt;    List&amp;lt;T&amp;gt; controls = &lt;span style=&quot;color: #0000ff&quot;&gt;new&lt;/span&gt; List&amp;lt;T&amp;gt;();&lt;br /&gt;    FindControlsByType&amp;lt;T&amp;gt;(root, controls);&lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;return&lt;/span&gt; controls;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;private&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;void&lt;/span&gt; FindControlsByType&amp;lt;T&amp;gt;(Control root, IList&amp;lt;T&amp;gt; controls)&lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;where&lt;/span&gt; T : Control&lt;br /&gt;  {&lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;foreach&lt;/span&gt; (Control control &lt;span style=&quot;color: #0000ff&quot;&gt;in&lt;/span&gt; root.Controls)&lt;br /&gt;    {&lt;br /&gt;      &lt;span style=&quot;color: #0000ff&quot;&gt;if&lt;/span&gt; (control &lt;span style=&quot;color: #0000ff&quot;&gt;is&lt;/span&gt; T)&lt;br /&gt;      {&lt;br /&gt;        controls.Add(control &lt;span style=&quot;color: #0000ff&quot;&gt;as&lt;/span&gt; T);&lt;br /&gt;      }&lt;br /&gt;      &lt;span style=&quot;color: #0000ff&quot;&gt;if&lt;/span&gt; (control.Controls.Count &amp;gt; 0)&lt;br /&gt;      {&lt;br /&gt;        FindControlsByType&amp;lt;T&amp;gt;(control, controls);&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;Using the tow pieces of code above, finding all the ContentPlaceHolders on the Master Page can be done like this.&lt;/p&gt;&lt;br /&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;br /&gt;  &lt;pre style=&quot;border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px&quot; id=&quot;codeSnippet&quot;&gt;&lt;span style=&quot;color: #008000&quot;&gt;// Load the Master Page&lt;/span&gt;&lt;br /&gt;var site1Master = LoadControl(&lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;Site1.Master&amp;quot;&lt;/span&gt;);&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: #008000&quot;&gt;// Find the list of ContentPlaceHolder controls&lt;/span&gt;&lt;br /&gt;var controls = WebHelper.FindControlsByType&amp;lt;ContentPlaceHolder&amp;gt;(site1Master);&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: #008000&quot;&gt;// Do something with each control that was found&lt;/span&gt;&lt;br /&gt;&lt;span style=&quot;color: #0000ff&quot;&gt;foreach&lt;/span&gt; (var control &lt;span style=&quot;color: #0000ff&quot;&gt;in&lt;/span&gt; controls)&lt;br /&gt;{&lt;br /&gt;  Response.Write(control.ClientID);&lt;br /&gt;  Response.Write(&lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;&amp;lt;br /&amp;gt;&amp;quot;&lt;/span&gt;);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;Hope someone finds this useful. I thought I would share it since I took the few moments to write it and did not want it to go to waste.&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/456160839185215831/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2010/09/code-share-finding-controls-by-control.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/456160839185215831'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/456160839185215831'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2010/09/code-share-finding-controls-by-control.html' title='Code Share: Finding controls by control type.'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-6902220327516819781</id><published>2010-06-27T18:25:00.001+03:00</published><updated>2010-06-27T18:25:42.842+03:00</updated><title type='text'>Crossing the process boundary with .NET</title><content type='html'>&lt;h4&gt;&amp;#160;&lt;/h4&gt;  &lt;p&gt;Every so often my post &lt;a&gt;Hacking my way across the process boundary&lt;/a&gt; gets some attention. Mostly in the form of requests for a .NET version of this technique. Now out of laziness more than anything else I have not actually taken the time or effort to do the conversion until now. So for those that need to access ListView or TreeView data from another process here is a simple example of one possible way to do it. Since I used C# for the example, I could very well have used unsafe code blocks to do some of the work, however I decided to avoid this making this example applicable to VB.NET developers as well. If you would like to see a version using unsafe code blocks, drop me a note and I will get round to it. To keep the sample short I have removed anything but the most rudimentary error checking. For an explanation of this code, please refer to the original post sighted above.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;div id=&quot;codeSnippetWrapper&quot;&gt;   &lt;pre style=&quot;border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px&quot; id=&quot;codeSnippet&quot;&gt;&lt;span style=&quot;color: #0000ff&quot;&gt;using&lt;/span&gt; System;&lt;br /&gt;&lt;span style=&quot;color: #0000ff&quot;&gt;using&lt;/span&gt; System.Runtime.InteropServices;&lt;br /&gt;&lt;span style=&quot;color: #0000ff&quot;&gt;using&lt;/span&gt; System.Text;&lt;br /&gt;&lt;span style=&quot;color: #0000ff&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;class&lt;/span&gt; CrossProcessMemory&lt;br /&gt;{&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;const&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt; LVM_GETITEM = 0x1005;&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;const&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt; LVM_SETITEM = 0x1006;&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;const&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt; LVIF_TEXT   = 0x0001;&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;const&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;uint&lt;/span&gt; PROCESS_ALL_ACCESS = (&lt;span style=&quot;color: #0000ff&quot;&gt;uint&lt;/span&gt;)(0x000F0000L | 0x00100000L | 0xFFF);&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;const&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;uint&lt;/span&gt; MEM_COMMIT         = 0x1000;&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;const&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;uint&lt;/span&gt; MEM_RELEASE        = 0x8000;&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;const&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;uint&lt;/span&gt; PAGE_READWRITE     = 0x04;&lt;br /&gt;&lt;br /&gt;  [DllImport(&lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;user32.dll&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;extern&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;bool&lt;/span&gt; SendMessage(IntPtr hWnd, Int32 msg, Int32 wParam, IntPtr lParam);&lt;br /&gt;  &lt;br /&gt;  [DllImport(&lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;user32&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;extern&lt;/span&gt; IntPtr GetWindowThreadProcessId( IntPtr hWnd, &lt;span style=&quot;color: #0000ff&quot;&gt;out&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt; lpwdProcessID );    &lt;br /&gt;  &lt;br /&gt;  [DllImport(&lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;kernel32&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;extern&lt;/span&gt; IntPtr OpenProcess(&lt;span style=&quot;color: #0000ff&quot;&gt;uint&lt;/span&gt; dwDesiredAccess, &lt;span style=&quot;color: #0000ff&quot;&gt;bool&lt;/span&gt; bInheritHandle, &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt; dwProcessId);&lt;br /&gt;&lt;br /&gt;  [DllImport(&lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;kernel32&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;extern&lt;/span&gt; IntPtr VirtualAllocEx( IntPtr hProcess, IntPtr lpAddress, &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt; dwSize, &lt;span style=&quot;color: #0000ff&quot;&gt;uint&lt;/span&gt; flAllocationType, &lt;span style=&quot;color: #0000ff&quot;&gt;uint&lt;/span&gt; flProtect);&lt;br /&gt;&lt;br /&gt;  [DllImport(&lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;kernel32&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;extern&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;bool&lt;/span&gt; VirtualFreeEx( IntPtr hProcess, IntPtr lpAddress, &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt; dwSize, &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;uint&lt;/span&gt; dwFreeType );&lt;br /&gt;&lt;br /&gt;  [DllImport(&lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;kernel32&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;extern&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;bool&lt;/span&gt; WriteProcessMemory( IntPtr hProcess, IntPtr lpBaseAddress, &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;ref&lt;/span&gt; LV_ITEM buffer, &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt; dwSize, IntPtr lpNumberOfBytesWritten );&lt;br /&gt;&lt;br /&gt;  [DllImport(&lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;kernel32&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;extern&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;bool&lt;/span&gt; ReadProcessMemory( IntPtr hProcess, IntPtr lpBaseAddress, &lt;br /&gt;    IntPtr lpBuffer, &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt; dwSize, IntPtr lpNumberOfBytesRead );&lt;br /&gt;&lt;br /&gt;  [DllImport(&lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;kernel32&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;extern&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;bool&lt;/span&gt; CloseHandle( IntPtr hObject );&lt;br /&gt;&lt;br /&gt;  [StructLayout(LayoutKind.Sequential)]&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;struct&lt;/span&gt; LV_ITEM&lt;br /&gt;  {&lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;uint&lt;/span&gt;   mask; &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt;    iItem; &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt;    iSubItem; &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;uint&lt;/span&gt;   state; &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;uint&lt;/span&gt;   stateMask; &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;public&lt;/span&gt; IntPtr pszText; &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt;    cchTextMax; &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt;    iImage;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span style=&quot;color: #0000ff&quot;&gt;public&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;static&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;string&lt;/span&gt; ReadListViewItem( IntPtr hWnd, &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt; item )&lt;br /&gt;  {&lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;const&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt; dwBufferSize = 1024;&lt;br /&gt;          &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;int&lt;/span&gt;         dwProcessID;&lt;br /&gt;    LV_ITEM     lvItem;      &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;string&lt;/span&gt;      retval;&lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;bool&lt;/span&gt;        bSuccess;&lt;br /&gt;    IntPtr      hProcess        = IntPtr.Zero;&lt;br /&gt;    IntPtr      lpRemoteBuffer  = IntPtr.Zero;&lt;br /&gt;    IntPtr      lpLocalBuffer   = IntPtr.Zero;&lt;br /&gt;    IntPtr      threadId        = IntPtr.Zero;&lt;br /&gt;          &lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;try&lt;/span&gt;&lt;br /&gt;    {&lt;br /&gt;      lvItem = &lt;span style=&quot;color: #0000ff&quot;&gt;new&lt;/span&gt; LV_ITEM();&lt;br /&gt;      lpLocalBuffer = Marshal.AllocHGlobal(dwBufferSize);&lt;br /&gt;      &lt;span style=&quot;color: #008000&quot;&gt;// Get the process id owning the window&lt;/span&gt;&lt;br /&gt;      threadId = GetWindowThreadProcessId( hWnd, &lt;span style=&quot;color: #0000ff&quot;&gt;out&lt;/span&gt; dwProcessID );&lt;br /&gt;      &lt;span style=&quot;color: #0000ff&quot;&gt;if&lt;/span&gt; ( (threadId == IntPtr.Zero) || (dwProcessID == 0) )&lt;br /&gt;        &lt;span style=&quot;color: #0000ff&quot;&gt;throw&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;new&lt;/span&gt; ArgumentException( &lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;hWnd&amp;quot;&lt;/span&gt; );&lt;br /&gt;&lt;br /&gt;      &lt;span style=&quot;color: #008000&quot;&gt;// Open the process with all access&lt;/span&gt;&lt;br /&gt;      hProcess = OpenProcess( PROCESS_ALL_ACCESS, &lt;span style=&quot;color: #0000ff&quot;&gt;false&lt;/span&gt;, dwProcessID );&lt;br /&gt;      &lt;span style=&quot;color: #0000ff&quot;&gt;if&lt;/span&gt; ( hProcess == IntPtr.Zero )&lt;br /&gt;        &lt;span style=&quot;color: #0000ff&quot;&gt;throw&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;new&lt;/span&gt; ApplicationException( &lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;Failed to access process&amp;quot;&lt;/span&gt; );&lt;br /&gt;&lt;br /&gt;      &lt;span style=&quot;color: #008000&quot;&gt;// Allocate a buffer in the remote process&lt;/span&gt;&lt;br /&gt;      lpRemoteBuffer = VirtualAllocEx( hProcess, IntPtr.Zero, dwBufferSize, MEM_COMMIT, &lt;br /&gt;        PAGE_READWRITE );&lt;br /&gt;      &lt;span style=&quot;color: #0000ff&quot;&gt;if&lt;/span&gt; ( lpRemoteBuffer == IntPtr.Zero )&lt;br /&gt;        &lt;span style=&quot;color: #0000ff&quot;&gt;throw&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;new&lt;/span&gt; SystemException( &lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;Failed to allocate memory in remote process&amp;quot;&lt;/span&gt; );&lt;br /&gt;      &lt;br /&gt;      &lt;span style=&quot;color: #008000&quot;&gt;// Fill in the LVITEM struct, this is in your own process&lt;/span&gt;&lt;br /&gt;      &lt;span style=&quot;color: #008000&quot;&gt;// Set the pszText member to somewhere in the remote buffer,&lt;/span&gt;&lt;br /&gt;      &lt;span style=&quot;color: #008000&quot;&gt;// For the example I used the address imediately following the LVITEM stuct&lt;/span&gt;&lt;br /&gt;      lvItem.mask = LVIF_TEXT;&lt;br /&gt;      lvItem.iItem = item;&lt;br /&gt;      lvItem.pszText = (IntPtr)(lpRemoteBuffer.ToInt32() + Marshal.SizeOf(&lt;span style=&quot;color: #0000ff&quot;&gt;typeof&lt;/span&gt;(LV_ITEM)));&lt;br /&gt;      lvItem.cchTextMax = 50;&lt;br /&gt;&lt;br /&gt;      &lt;span style=&quot;color: #008000&quot;&gt;// Copy the local LVITEM to the remote buffer&lt;/span&gt;&lt;br /&gt;      bSuccess = WriteProcessMemory( hProcess, lpRemoteBuffer, &lt;span style=&quot;color: #0000ff&quot;&gt;ref&lt;/span&gt; lvItem, &lt;br /&gt;        Marshal.SizeOf(&lt;span style=&quot;color: #0000ff&quot;&gt;typeof&lt;/span&gt;(LV_ITEM)), IntPtr.Zero );&lt;br /&gt;      &lt;span style=&quot;color: #0000ff&quot;&gt;if&lt;/span&gt; ( !bSuccess )&lt;br /&gt;        &lt;span style=&quot;color: #0000ff&quot;&gt;throw&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;new&lt;/span&gt; SystemException( &lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;Failed to write to process memory&amp;quot;&lt;/span&gt; );&lt;br /&gt;&lt;br /&gt;      &lt;span style=&quot;color: #008000&quot;&gt;// Send the message to the remote window with the address of the remote buffer&lt;/span&gt;&lt;br /&gt;      SendMessage( hWnd, LVM_GETITEM, 0, lpRemoteBuffer);&lt;br /&gt;      &lt;br /&gt;      &lt;span style=&quot;color: #008000&quot;&gt;// Read the struct back from the remote process into local buffer&lt;/span&gt;&lt;br /&gt;      bSuccess = ReadProcessMemory( hProcess, lpRemoteBuffer, lpLocalBuffer, dwBufferSize, &lt;br /&gt;        IntPtr.Zero );&lt;br /&gt;      &lt;span style=&quot;color: #0000ff&quot;&gt;if&lt;/span&gt; ( !bSuccess )&lt;br /&gt;        &lt;span style=&quot;color: #0000ff&quot;&gt;throw&lt;/span&gt; &lt;span style=&quot;color: #0000ff&quot;&gt;new&lt;/span&gt; SystemException( &lt;span style=&quot;color: #006080&quot;&gt;&amp;quot;Failed to read from process memory&amp;quot;&lt;/span&gt; );&lt;br /&gt;      &lt;br /&gt;      &lt;span style=&quot;color: #008000&quot;&gt;// At this point the lpLocalBuffer contains the returned LV_ITEM structure&lt;/span&gt;&lt;br /&gt;      &lt;span style=&quot;color: #008000&quot;&gt;// the next line extracts the text from the buffer into a managed string&lt;/span&gt;&lt;br /&gt;      retval = Marshal.PtrToStringAnsi((IntPtr)(lpLocalBuffer.ToInt32() + &lt;br /&gt;        Marshal.SizeOf(&lt;span style=&quot;color: #0000ff&quot;&gt;typeof&lt;/span&gt;(LV_ITEM))));&lt;br /&gt;    }&lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;finally&lt;/span&gt;&lt;br /&gt;    { &lt;br /&gt;      &lt;span style=&quot;color: #0000ff&quot;&gt;if&lt;/span&gt; ( lpLocalBuffer != IntPtr.Zero )&lt;br /&gt;        Marshal.FreeHGlobal( lpLocalBuffer );&lt;br /&gt;      &lt;span style=&quot;color: #0000ff&quot;&gt;if&lt;/span&gt; ( lpRemoteBuffer != IntPtr.Zero )&lt;br /&gt;        VirtualFreeEx( hProcess, lpRemoteBuffer, 0, MEM_RELEASE ); &lt;br /&gt;      &lt;span style=&quot;color: #0000ff&quot;&gt;if&lt;/span&gt; ( hProcess != IntPtr.Zero )&lt;br /&gt;        CloseHandle( hProcess );&lt;br /&gt;    }&lt;br /&gt;    &lt;span style=&quot;color: #0000ff&quot;&gt;return&lt;/span&gt; retval;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;  &lt;br /&gt;&lt;/div&gt;  </content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/6902220327516819781/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2010/06/crossing-process-boundary-with-net.html#comment-form' title='15 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/6902220327516819781'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/6902220327516819781'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2010/06/crossing-process-boundary-with-net.html' title='Crossing the process boundary with .NET'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>15</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-7082894442411206270</id><published>2010-06-06T10:57:00.001+03:00</published><updated>2010-06-06T11:08:46.589+03:00</updated><title type='text'>Visual Studio 2010 – Box Selection</title><content type='html'>&lt;p&gt;This has been blogged about and promoted everywhere and it is true, it is a super cool feature that even the pre-.NET IDE supported, but VS2010 breaths new life into the feature with some great enhancements. For a very cool intro to the functionality take a look &lt;a href=&quot;http://www.youtube.com/watch?v=qp2WuJ2rEE4&quot;&gt;here&lt;/a&gt; where a member of the IDE team demonstrates the enhancements.&lt;/p&gt;  &lt;p&gt;So, why on earth would I be blogging about “old” news. Well one thing that I found “missing” with this feature until now was the ability to use the keyboard to perform a block selection. Now with VS 2010 you can use &lt;strong&gt;Shift&lt;/strong&gt;+&lt;strong&gt;Alt&lt;/strong&gt;+[&lt;strong&gt;Up&lt;/strong&gt;, &lt;strong&gt;Down&lt;/strong&gt;, &lt;strong&gt;Left&lt;/strong&gt;, &lt;strong&gt;Right&lt;/strong&gt;] to perform a block selection. This is a great enhancement, and worth knowing about if you are a keyboard junkie.&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/7082894442411206270/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2010/06/visual-studio-2010-box-selection.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/7082894442411206270'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/7082894442411206270'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2010/06/visual-studio-2010-box-selection.html' title='Visual Studio 2010 – Box Selection'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-909388696117524541</id><published>2010-04-17T14:37:00.002+03:00</published><updated>2010-04-17T14:48:38.527+03:00</updated><title type='text'>Archive: Binary data from a Structure</title><content type='html'>&lt;p&gt;For this post, I will be using the binary structure used by the trusty old DBF file structure.&lt;/p&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;[StructLayout(LayoutKind.Sequential, Pack = 1)]
&lt;span class=&quot;kwrd&quot;&gt;struct&lt;/span&gt; DBFHeader
{
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; Tag;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; Year;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; Month;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; Day; 
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; RecCount;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;short&lt;/span&gt; HeaderSize;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;short&lt;/span&gt; RecSize;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;short&lt;/span&gt; Reserved1;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; Trans;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; Encrypt;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;long&lt;/span&gt; Reserved2_1;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;short&lt;/span&gt; Reserved2_2;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; MDX;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; LangId;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;short&lt;/span&gt; Reserved3;
}&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Given the above structure, our challenge now is to transfer it from its in memory binary format to a stream. The stream may be a physical file, memory stream even a network stream. The most important aspect of all the techniques that I will investigate here is that the resulting binary data format is consistent with the format expected by the reader.&lt;/p&gt;&lt;p&gt;After looking at the interface provided by the Stream class, from which all streams inherit, I came to the conclusion that I would have to convert the structure to a byte array (&lt;b&gt;byte[]&lt;/b&gt;). &lt;/p&gt;&lt;p&gt;Again our first stop is the interop services provided by the .NET framework. The following piece of code will convert a structure to a &lt;b&gt;byte[]&lt;/b&gt; that can then be written to a stream.&lt;/p&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;DBFHeader hdr = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; DBFHeader(); 
&lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt;[] data = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt;[Marshal.SizeOf(hdr)];
&lt;span class=&quot;kwrd&quot;&gt;unsafe&lt;/span&gt;
{
  DBFHeader *p = &amp;amp;hdr;
  Marshal.Copy( (IntPtr)p, data, 0, data.Length ); 
} &lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This code requires that you compile with unsafe code allowed. This can be done either by supplying the &lt;b&gt;/unsafe&lt;/b&gt; switch to the command line compiler or in the Visual Studio .NET project properties under Configuration Properties&amp;gt;Build, you can set the &lt;b&gt;Allow Unsafe Code Blocks&lt;/b&gt; to True.&lt;/p&gt;&lt;p&gt;After creating a instance of the structure &lt;b&gt;DBFHeader&lt;/b&gt; a &lt;b&gt;byte[]&lt;/b&gt; is created large enough to hold the contents of the structure. At that point we need to transfer the contents of the &lt;b&gt;DBFHeader&lt;/b&gt; instance to the &lt;b&gt;byte[]&lt;/b&gt;. To accomplish this, I declared an unsafe block and assigned the address of the structure, being a &lt;b&gt;ValueType &lt;/b&gt;the structure is allocated on the local stack and is therefore implicitly &lt;b&gt;pinned&lt;/b&gt;. Then the &lt;b&gt;Marshal.Copy &lt;/b&gt;method is used to copy the data from an address in memory to the &lt;b&gt;byte[]&lt;/b&gt;. Now we are free to write the byte array to a stream using the &lt;b&gt;Write&lt;/b&gt; method provided by the stream. &lt;/p&gt;&lt;p&gt;There are a number of things that count against this technique. Using unsafe code blocks means that the assembly can not be verified and the caller would require the &lt;b&gt;SkipVerification&lt;/b&gt; permission. The use of the &lt;b&gt;Marshal &lt;/b&gt;methods requires that the immediate caller has &lt;b&gt;SecurityPermissionAttribute.UnmanagedCode&lt;/b&gt;. This technique also requires that the data be moved in two stages, from the structure to the &lt;b&gt;byte[]&lt;/b&gt; an then from there to the &lt;b&gt;stream&lt;/b&gt;, this could be costly for large structures.&lt;/p&gt;&lt;p&gt;The first problem of the code being non-verifiable can be overcome by using a technique very similar to the above technique, without the requirement for unsafe code blocks. The following code demonstrates this technique. &lt;/p&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;DBFHeader hdr = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; DBFHeader(); 
&lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt;[] data = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt;[Marshal.SizeOf(hdr)];
IntPtr p = Marshal.AllocHGlobal( Marshal.SizeOf(hdr) );
Marshal.StructureToPtr( hdr, p, &lt;span class=&quot;kwrd&quot;&gt;false&lt;/span&gt; );
Marshal.Copy( (IntPtr)p, data, 0, data.Length ); 
Marshal.FreeHGlobal( p );&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Notice that it still requires that the data be moved in two stages and the use of the Marshal class carries the same security requirements as earlier. The only benefit is that the resulting assembly remains verifiable, not requiring the &lt;b&gt;/unsafe &lt;/b&gt;option. However, allocating memory from the unmanaged heap carries with it additional performance overheads.&lt;/p&gt;&lt;p&gt;And finally the pure managed code solution that while not as easy as the prior techniques, it does benefit from the fact that the code is easily ported to other .NET languages and does not have the same security restrictions as the other two techniques. The solution is to use the &lt;b&gt;BinaryWriter &lt;/b&gt;class to write each bit of information from the structure to the stream. &lt;/p&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;using&lt;/span&gt; (BinaryWriter wr = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; BinaryWriter( stm ))
{
  wr.Write( hdr.Tag );
  wr.Write( hdr.Year );
  wr.Write( hdr.Month );
  wr.Write( hdr.Day );
  wr.Write( hdr.RecCount );
  wr.Write( hdr.HeaderSize );
  wr.Write( hdr.RecSize );
  wr.Write( hdr.Reserved1 );
  wr.Write( hdr.Trans );
  wr.Write( hdr.Encrypt );
  wr.Write( hdr.Reserved2_1 );
  wr.Write( hdr.Reserved2_2 );
  wr.Write( hdr.MDX );
  wr.Write( hdr.LangId );
  wr.Write( hdr.Reserved3 ); 
}&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This code first creates a &lt;b&gt;BinaryWriter&lt;/b&gt; that provides binary methods to access the underlying stream. In this case the underlying stream is designated by the &lt;b&gt;stm &lt;/b&gt;argument passed to the &lt;b&gt;BinaryWriter&lt;/b&gt; constructor. Then using the binary writer, each member of the structure is written in order to the stream through the &lt;b&gt;BinaryWriter &lt;/b&gt;instance. I have already mentioned the clear advantages of this technique, but it does carry with it a share of disadvantages. The first and most obvious is that it requires you to write out each member individually, and with larger structures, this can be a tedious and error prone task. This brings me to the second disadvantage, if the data is not written out in the exact order expected by the reader, the reader will either fail to read the structure or even worse, corrupt data.&lt;/p&gt;&lt;p&gt;Just as a closing note, the final technique could also be used to get a &lt;b&gt;byte[]&lt;/b&gt; by writing to a &lt;b&gt;MemoryStream&lt;/b&gt; and then calling the &lt;b&gt;GetBuffer&lt;/b&gt; method provided by &lt;b&gt;MemoryStream&lt;/b&gt; to access the underlying &lt;b&gt;byte[].&lt;/b&gt; &lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;b&gt;&lt;/b&gt;&lt;br /&gt;
&lt;p&gt;Conclusion&lt;/p&gt;&lt;p&gt;As with every design, it is a series of compromises that determines the ultimate chooses we make. The above techniques provide a number of alternative ranging from simplicity of code to flexibility of implementation. I believe that the final option is most likely the more purist and from a reusability standpoint the more effective solution. &lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/909388696117524541/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2010/04/archive-binary-data-from-structure.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/909388696117524541'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/909388696117524541'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2010/04/archive-binary-data-from-structure.html' title='Archive: Binary data from a Structure'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-2929360607743542059</id><published>2010-04-17T14:06:00.005+03:00</published><updated>2010-04-17T14:45:48.434+03:00</updated><title type='text'>Archive: Structure from Binary Data</title><content type='html'>&lt;p&gt;Original Post Date: 8 Jan 2004&lt;/p&gt;&lt;p&gt;The question of moving stream data into a structure seems to be addressed every so often on the newsgroups. While I was building a front-end for a small packet sniffing application I was faced with these same questions. While I was aware of the standard approaches I decided to investigate what the alternative options where. This article is a summary of the primary ways I looked at of mapping binary data to a structure.&lt;/p&gt;&lt;h3&gt;Defining the structure&lt;/h3&gt;&lt;p&gt;The first thing that I did was to define the structure, for this example I am going to use the IP header. Deciding on the correct definition of the structure is dependent on the solution or approach taken to solve this problem.&lt;/p&gt;&lt;p&gt;Given that I have spent a considerable amount of time familiarizing myself with the intricacies of the P/Invoke or interoperability services, my first solution was to use &lt;b&gt;System.Runtime.InteropServices&lt;/b&gt; to marshal the data into a structure. I promptly defined the following structure to handle the marshaled data.&lt;/p&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;[StructLayout(LayoutKind.Sequential, Pack = 1)]
&lt;span class=&quot;kwrd&quot;&gt;struct&lt;/span&gt; IpHeader
{
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; VerLen;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; TOS;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;short&lt;/span&gt; TotalLength; 
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;short&lt;/span&gt; ID;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;short&lt;/span&gt; Offset;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; TTL;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; Protocol;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;short&lt;/span&gt; Checksum;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; SrcAddr;
  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; DestAddr;
}
&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The two things to note about the definition of the structure is that it is defined as a sequential structure which ensures that the order of the members and relative location of these members are not altered by the CLR. &lt;/p&gt;&lt;p&gt;Now that the structure is defined the next step is to populate the structure with data. In this case the data came from a call to the &lt;b&gt;Receive&lt;/b&gt; method of the &lt;b&gt;Socket&lt;/b&gt; class. To read IP header the socket was created using &lt;b&gt;SocketType.Raw&lt;/b&gt;. The &lt;b&gt;Receive&lt;/b&gt; method fills a byte array with the data and it is the first 20 bytes of this data that makes up the IP header. Because the structure that I have defined, and the structure of the data in these 20 bytes are a one to one match, using a language like C++ reading this data would be a relatively simple task requiring only a cast.&lt;/p&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;IpHeader *pHeader = (IpHeader*)packet;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;With the structure of the &lt;b&gt;IpHeader&lt;/b&gt; overlayed on the memory stream it is a matter of accessing the members of the structure. Unfortunately our structure is stored in managed memory and using code like the above in C# would require entering an unsafe code block. The following piece of code demonstrates how this could be achieved in C#.&lt;/p&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;IpHeader iphdr;
&lt;span class=&quot;kwrd&quot;&gt;unsafe&lt;/span&gt;
{
  &lt;span class=&quot;kwrd&quot;&gt;fixed&lt;/span&gt; ( &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; *pData = packet)
  {
    iphdr = *(IpHeader*)pData;
  }
}
&lt;span class=&quot;rem&quot;&gt;//Use iphdr...&lt;/span&gt;
&lt;/pre&gt;For the above code to compile successfully you will have to flip the switch to allow unsafe code to be compiled. This can be achieved using either the &lt;b&gt;/unsafe&lt;/b&gt; switch for the command line compiler or in the Visual Studio .NET project properties under &lt;b&gt;Configuration Properties&amp;gt;Build&lt;/b&gt; you can set the &lt;b&gt;Allow Unsafe Code Blocks&lt;/b&gt; to &lt;b&gt;true&lt;/b&gt;.&lt;/div&gt;&lt;p&gt;The code in the unsafe block uses the &lt;b&gt;fixed&lt;/b&gt; keyword to pin the packet structure in memory ensuring that the garbage collector does not shift the memory around under our feet. Because the memory is fixed it can now be used much like a standard C/C++ pointer allowing us to cast the block of memory to an &lt;b&gt;IpHeader*&lt;/b&gt; and assign the pointer to &lt;b&gt;iphdr&lt;/b&gt; structure. &lt;/p&gt;&lt;p&gt;Though this is a relatively simple piece of code there are a few points to be noted about this solution. First whenever we allow unsafe code blocks in a C# application we inhibit the CLR’s ability to verify the code. In this case, by fixing the data in memory and accessing it like a pointer the CLR can no longer check the array bounds and our code is open to a buffer overrun. The second point of concern with the fixed memory is that the garbage collector cannot shift this memory impacting the garbage collection process and the performance of the garbage collector if a collection is required. And finally this solution, as far as I know, can not be done in VB.NET, so it would have to be written in C# and the assembly referenced from VB.NET.&lt;/p&gt;&lt;p&gt;That brings me to the solution of using the marshaling provided by interop services. The clear advantage of this solution is that it can be applied in both C# and VB.NET and it does not require the use of unsafe code blocks therefore the code remains verifiable. Before I discuss this solution any further let me present a code snippet that demonstrates the solution. &lt;/p&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;IntPtr pIP = Marshal.AllocHGlobal( len );
Marshal.Copy( packet, 0, pIP, len );
iphdr = (IpHeader)Marshal.PtrToStructure( pIP, &lt;span class=&quot;kwrd&quot;&gt;typeof&lt;/span&gt;(IpHeader) );
Marshal.FreeHGlobal( pIP );
&lt;/pre&gt;Now the moment I wrote this piece of code it felt like a knife stabbing into my back. The first thing that happens is that a block of memory is allocated on the unmanaged heap. Since the memory is allocated from the unmanaged heap it does not impact the garbage collector in anyway. The problem is that the packet is stored in the managed heap so we need to first copy the data from the buffer in the managed heap to the buffer in the unmanaged heap using &lt;b&gt;Marshal.Copy&lt;/b&gt;. Once the data resides in the unmanaged heap we can use the &lt;b&gt;Marshal.PtrToStructure&lt;/b&gt; to marshal the data back to the managed heap in the form of our &lt;b&gt;IpHeader&lt;/b&gt; structure. And finally we must free the unmanaged memory that we allocated.&lt;/div&gt;&lt;p&gt;This really gave me a sour taste in my mouth. Every packet that I picked up needs to be shifted from the managed heap to the unmanaged heap and then be marshaled back to managed heap. Are there words to describe this? Clearly I was not satisfied with this solution.&lt;/p&gt;&lt;p&gt;The options investigated so far have required somehow side stepping the way the CLR normally would go about its business. Introducing risks such as buffer overruns or even memory leaks if we fail to free the unmanaged memory we have allocated.&lt;/p&gt;&lt;p&gt;So is there a completely managed solution to the problem? Well yes there is and at first this might seem like it is really the long way around in comparison to the options we have explored so far. However after I present the code I will demonstrate why in this particular case it was actually less code than the previous solutions. This solution makes use of the &lt;b&gt;BinaryReader&lt;/b&gt; to read the data directly into the structures members.&lt;/p&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;System.IO.MemoryStream stm = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; System.IO.MemoryStream( packet, 0, len );
System.IO.BinaryReader rdr = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; System.IO.BinaryReader( stm );
iphdr.VerLen = rdr.ReadByte();
iphdr.TOS = rdr.ReadByte();
iphdr.TotalLength = rdr.ReadInt16();
iphdr.ID = rdr.ReadInt16();
iphdr.Offset = rdr.ReadInt16();
iphdr.TTL = rdr.ReadByte();
iphdr.Protocol = rdr.ReadByte();
iphdr.Checksum = rdr.ReadInt16();
iphdr.SrcAddr = rdr.ReadInt32();
iphdr.DestAddr = rdr.ReadInt32();
&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This solution has it’s own set of advantages and disadvantages. Firstly the structure definition can loose the StructLayoutAttribute since the physical layout of the structure is no longer important. The primary advantage in my opinion of this code is that we are working with code that is 100% managed and there are no cute tricks that could end up tripping us up, although there are other aspects to this solution that could. Another advantage is particular to the case of reading network data, which I will address shortly.&lt;/p&gt;&lt;p&gt;The code creates a &lt;b&gt;MemoryStream&lt;/b&gt; on the existing packet buffer and a &lt;b&gt;BinaryReader&lt;/b&gt; is created to read the data from the &lt;b&gt;MemoryStream&lt;/b&gt;. Then byte for byte (and now and then a &lt;b&gt;int&lt;/b&gt; or &lt;b&gt;short&lt;/b&gt;) the data is read into an instance of the structure. &lt;/p&gt;&lt;p&gt;As I said earlier, the next advantage is specific to the requirements of this particular case. As you know when reading data from a socket the data is in network byte order or big-endian form. This byte ordering is incompatible with Intel processors, which expect multi-byte numeric data types to be represented in little-endian form. Since the packet’s data is in big-endian we are required to convert each &lt;b&gt;Int16&lt;/b&gt; and &lt;b&gt;Int32&lt;/b&gt; (&lt;b&gt;short&lt;/b&gt; and &lt;b&gt;int&lt;/b&gt;) to little-endian form. I use &lt;b&gt;IPAddress.NetworkToHostOrder&lt;/b&gt; to do the byte swapping for me, since this is required regardless of which of the above solutions where chosen, this would mean calling the function on each non-byte member of the struct. Using the last solution we investigated this could be accomplished in one step while filling the structure.&lt;/p&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;iphdr.VerLen = rdr.ReadByte();
iphdr.TOS = rdr.ReadByte();
iphdr.TotalLength = IPAddress.NetworkToHostOrder(rdr.ReadInt16());
iphdr.ID = IPAddress.NetworkToHostOrder(rdr.ReadInt16());
iphdr.Offset = IPAddress.NetworkToHostOrder(rdr.ReadInt16());
iphdr.TTL = rdr.ReadByte();
iphdr.Protocol = rdr.ReadByte();
iphdr.Checksum = IPAddress.NetworkToHostOrder(rdr.ReadInt16());
iphdr.SrcAddr = IPAddress.NetworkToHostOrder(rdr.ReadInt32());
iphdr.DestAddr = IPAddress.NetworkToHostOrder(rdr.ReadInt32());
&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The most obvious concern using this solution is the possibility of misaligned reads, e.g. reading a &lt;b&gt;Byte&lt;/b&gt; where you should have read an &lt;b&gt;Int&lt;/b&gt;. One mistake of this kind and all the data after that point are misaligned and make no sense. This solution also requires that you maintain both the structure and the code that populates the structure, if the structure changes in someway the code to read the structure needs to be updated. And even with medium sized structures you end up doing a lot of byte counting and checking that every read is performed in the correct order, which is very error prone.&lt;/p&gt;&lt;p&gt;I have found that including a constructor and/or a static method provides an elegant means of hiding the actual method used to perform the de-serialization. The following pieces of code demonstrate the two possible ways of creating a de-serialized packet using either a static method or constructor.&lt;/p&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;IpHeader iphdr = IpHeader.FromPacket( packet, len );&lt;/pre&gt;Or&lt;/div&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;IpHeader iphdr = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; IpHeader( packet, len );&lt;/pre&gt;Typically I implement both, and the static method just creates an instance of the structure using the appropriate constructor.&lt;/div&gt;&lt;h3&gt;Conclusion&lt;/h3&gt;&lt;p&gt;Though the above solutions are not the only solutions, most other solutions are some form of one of these. Alternatively you could use managed C++ and get the best of both worlds and the expense of verifiable code. The presented solutions are applicable whenever you want to read binary data into a structured form; regardless of the source of the data, be it a network byte stream, or data from a disk file. &lt;/p&gt;&lt;p&gt;Selecting an appropriate solution is dependent on your requirements and constraints; personally I tend towards using unsafe code blocks especially if the structures are large (call me lazy) or the final solution of reading the data byte for byte. I just can’t feel good about moving perfectly good memory all over the show.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/2929360607743542059/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2010/04/archive-structure-from-binary-data.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/2929360607743542059'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/2929360607743542059'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2010/04/archive-structure-from-binary-data.html' title='Archive: Structure from Binary Data'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-3540321462958306424</id><published>2009-11-07T17:32:00.001+02:00</published><updated>2009-11-07T17:50:49.612+02:00</updated><title type='text'>Archive – Debugging WindowsIdentity and IsInRole</title><content type='html'>&lt;p&gt;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.&lt;/p&gt; &lt;strong&gt;Framework 2.0 and Later&lt;/strong&gt;   &lt;div id=&quot;codeSnippetWrapper&quot; class=&quot;csharpcode-wrapper&quot;&gt;   &lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;string&lt;/span&gt;[] GetWindowsIdentityRoles(WindowsIdentity identity)&lt;br /&gt;{&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;if&lt;/span&gt; (identity == &lt;span class=&quot;kwrd&quot;&gt;null&lt;/span&gt;) &lt;span class=&quot;kwrd&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class=&quot;str&quot;&gt;&amp;quot;identity&amp;quot;&lt;/span&gt;);&lt;br /&gt;&lt;br /&gt;  IdentityReferenceCollection groups = identity.Groups.Translate(&lt;span class=&quot;kwrd&quot;&gt;typeof&lt;/span&gt;(NTAccount));&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;string&lt;/span&gt;[] roles = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;string&lt;/span&gt;[groups.Count]; &lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;for&lt;/span&gt; (&lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; i = 0; i &amp;lt; groups.Count; ++i)&lt;br /&gt;  {&lt;br /&gt;    roles[i] = groups[i].Value; &lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; roles;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;strong&gt;Framework 1.0/1.1 (For that legacy code)&lt;/strong&gt; &lt;br /&gt;&lt;br /&gt;&lt;div id=&quot;codeSnippetWrapper&quot; class=&quot;csharpcode-wrapper&quot;&gt;&lt;br /&gt;  &lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;string&lt;/span&gt;[] GetWindowsIdentityRoles( WindowsIdentity identity )&lt;br /&gt;{&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;object&lt;/span&gt; result = &lt;span class=&quot;kwrd&quot;&gt;typeof&lt;/span&gt;(WindowsIdentity).InvokeMember( &lt;span class=&quot;str&quot;&gt;&amp;quot;_GetRoles&amp;quot;&lt;/span&gt;,&lt;br /&gt;    BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.NonPublic,&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;null&lt;/span&gt;, identity, &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;object&lt;/span&gt;[]{identity.Token}, &lt;span class=&quot;kwrd&quot;&gt;null&lt;/span&gt; );&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; (&lt;span class=&quot;kwrd&quot;&gt;string&lt;/span&gt;[])result; &lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;  &lt;br /&gt;&lt;/div&gt;  </content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/3540321462958306424/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2009/11/archive-debugging-windowsidentity-and.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/3540321462958306424'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/3540321462958306424'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2009/11/archive-debugging-windowsidentity-and.html' title='Archive – Debugging WindowsIdentity and IsInRole'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-2997976491425137598</id><published>2009-11-01T15:21:00.002+02:00</published><updated>2009-11-15T21:12:57.658+02:00</updated><title type='text'>Archive - Thread Local Storage in .NET</title><content type='html'>&lt;span style=&quot;color: blue;&quot;&gt;Another repost from my original blog.&lt;/span&gt;&lt;br /&gt;
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.&lt;br /&gt;
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. &lt;br /&gt;
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.&lt;br /&gt;
&lt;b&gt;&lt;/b&gt;&lt;br /&gt;
The CallContext &lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;div class=&quot;csharpcode-wrapper&quot;&gt;&lt;pre class=&quot;csharpcode&quot; id=&quot;codeSnippet&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;class&lt;/span&gt; Class1
{
&lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;void&lt;/span&gt; Main(&lt;span class=&quot;kwrd&quot;&gt;string&lt;/span&gt;[] args)
{
System.Threading.Thread t1 = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; System.Threading.Thread(&lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; System.Threading.ThreadStart(ThreadFunction));
System.Threading.Thread t2 = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; System.Threading.Thread(&lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; System.Threading.ThreadStart(ThreadFunction));

&lt;span class=&quot;rem&quot;&gt;// Start the threads&lt;/span&gt;
t1.Start();
t2.Start();

&lt;span class=&quot;rem&quot;&gt;// Wait for the threads to complete&lt;/span&gt;
t1.Join();
t2.Join();

System.Console.Read();
} 

&lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;string&lt;/span&gt; PerThreadCallCounterKey = &lt;span class=&quot;str&quot;&gt;&quot;CallCounter&quot;&lt;/span&gt;;
&lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; Random Rnd = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Random();

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

&lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;void&lt;/span&gt; DoTheWork()
{
&lt;span class=&quot;rem&quot;&gt;// Get the current threads CallCounter from the CallContext&lt;/span&gt;
&lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; counter = (&lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt;)System.Runtime.Remoting.Messaging.CallContext.GetData(PerThreadCallCounterKey);

&lt;span class=&quot;rem&quot;&gt;// Increment the counter and store the new value in the CallContext&lt;/span&gt;
&lt;span class=&quot;rem&quot;&gt;// Notice the pre-increment (++counter).&lt;/span&gt;
System.Runtime.Remoting.Messaging.CallContext.SetData(PerThreadCallCounterKey, ++counter);

&lt;span class=&quot;rem&quot;&gt;//OK, so we updated the counter now do the real work of this method&lt;/span&gt;
&lt;span class=&quot;rem&quot;&gt;//...&lt;/span&gt;
}

&lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;void&lt;/span&gt; DisplayCounterValue()
{
&lt;span class=&quot;rem&quot;&gt;// Get the current threads CallCounter from the CallContext&lt;/span&gt;
&lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; counter = (&lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt;)System.Runtime.Remoting.Messaging.CallContext.GetData(PerThreadCallCounterKey);
System.Console.WriteLine(&lt;span class=&quot;str&quot;&gt;&quot;The method was called {0} times from this thread&quot;&lt;/span&gt;, counter);
}
}
&lt;/pre&gt;&lt;br /&gt;
&lt;/div&gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Thread Static Members&lt;/b&gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;csharpcode-wrapper&quot; id=&quot;codeSnippetWrapper&quot;&gt;&lt;br /&gt;
&lt;pre class=&quot;csharpcode&quot; id=&quot;codeSnippet&quot;&gt;[ThreadStatic]
&lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; PerThreadCallCounter;&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;csharpcode-wrapper&quot; id=&quot;codeSnippetWrapper&quot;&gt;&lt;pre class=&quot;csharpcode&quot; id=&quot;codeSnippet&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;class&lt;/span&gt; Class1
{
&lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;void&lt;/span&gt; Main(&lt;span class=&quot;kwrd&quot;&gt;string&lt;/span&gt;[] args)
{
System.Threading.Thread t1 = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; System.Threading.Thread(&lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; System.Threading.ThreadStart(ThreadFunction));
System.Threading.Thread t2 = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; System.Threading.Thread(&lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; System.Threading.ThreadStart(ThreadFunction));

&lt;span class=&quot;rem&quot;&gt;// Start the threads&lt;/span&gt;
t1.Start();
t2.Start();

&lt;span class=&quot;rem&quot;&gt;// Wait for the threads to complete&lt;/span&gt;
t1.Join();
t2.Join();
System.Console.Read();
} 


[ThreadStatic]
&lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; PerThreadCallCounter;

&lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; Random Rnd = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Random();

&lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;void&lt;/span&gt; ThreadFunction()
{ 
&lt;span class=&quot;rem&quot;&gt;// Pick a randon number of times to call the target method &lt;/span&gt;
&lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; iterations = Rnd.Next(255); 

&lt;span class=&quot;rem&quot;&gt;// Call the method iteration number of times&lt;/span&gt;
&lt;span class=&quot;kwrd&quot;&gt;for&lt;/span&gt; (&lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; i = 0; i &amp;lt; iterations; ++i)
{
DoTheWork();
}
DisplayCounterValue();
}

&lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;void&lt;/span&gt; DoTheWork()
{
&lt;span class=&quot;rem&quot;&gt;// Increment the static member associated with the current thread&lt;/span&gt;
PerThreadCallCounter++;

&lt;span class=&quot;rem&quot;&gt;//OK, so we updated the counter now do the real work of this method&lt;/span&gt;
&lt;span class=&quot;rem&quot;&gt;//...&lt;/span&gt;
}

&lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;void&lt;/span&gt; DisplayCounterValue()
{
&lt;span class=&quot;rem&quot;&gt;// Display the value of the thread static member to the user&lt;/span&gt;
System.Console.WriteLine(&lt;span class=&quot;str&quot;&gt;&quot;The method was called {0} times from this thread&quot;&lt;/span&gt;, PerThreadCallCounter);
}
}
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
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).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Of course as apposed to the CallContext solution the ThreadStatic member is limited to the AppDomain boundary, which for most requirements is sufficient.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Thread Data Slots&lt;br /&gt;
&lt;br /&gt;
&lt;/strong&gt;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 &lt;u&gt;API&lt;/u&gt;. 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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;/b&gt;&lt;br /&gt;
See Also:&lt;br /&gt;
&lt;br /&gt;
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.</content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/2997976491425137598/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2009/11/archive-thread-local-storage-in-net.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/2997976491425137598'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/2997976491425137598'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2009/11/archive-thread-local-storage-in-net.html' title='Archive - Thread Local Storage in .NET'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-4663778536225404720</id><published>2009-11-01T15:12:00.001+02:00</published><updated>2009-11-01T15:12:06.652+02:00</updated><title type='text'>Color Gradient</title><content type='html'>&lt;p&gt;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.&lt;/p&gt;  &lt;div id=&quot;codeSnippetWrapper&quot; class=&quot;csharpcode-wrapper&quot;&gt;   &lt;pre id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; Color Gradient(Color from, Color to, &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; step)&lt;br /&gt;{&lt;br /&gt;   &lt;span class=&quot;kwrd&quot;&gt;double&lt;/span&gt; stepFactor = (&lt;span class=&quot;kwrd&quot;&gt;double&lt;/span&gt;)step / 255;&lt;br /&gt;   &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; Color.FromArgb(&lt;br /&gt;      (&lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt;)(from.R + ((to.R - from.R) * stepFactor)),&lt;br /&gt;      (&lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt;)(from.G + ((to.G - from.G) * stepFactor)),&lt;br /&gt;      (&lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt;)(from.B + ((to.B - from.B) * stepFactor)));&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;  &lt;br /&gt;&lt;/div&gt;  </content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/4663778536225404720/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2009/11/color-gradient.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/4663778536225404720'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/4663778536225404720'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2009/11/color-gradient.html' title='Color Gradient'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-7013264991897807029</id><published>2009-09-26T12:01:00.001+03:00</published><updated>2009-09-26T12:01:32.257+03:00</updated><title type='text'>Re-throw InnerException and preserve the original StackTrace</title><content type='html'>&lt;h4&gt;Repost from my original blog at the dotnetjunkies (03 March 2004)&lt;/h4&gt;  &lt;p&gt;One of the problems when throwing a &lt;strong&gt;new&lt;/strong&gt; 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.&lt;/p&gt;  &lt;p&gt;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. &lt;/p&gt;  &lt;p&gt;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. &lt;/p&gt;  &lt;p&gt;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.&lt;/p&gt;  &lt;pre class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;void&lt;/span&gt; test1()&lt;br /&gt;{&lt;br /&gt;  &lt;span class=&quot;rem&quot;&gt;// Throw an exception for testing purposes&lt;/span&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; ArgumentException( &lt;span class=&quot;str&quot;&gt;&amp;quot;test1&amp;quot;&lt;/span&gt; ); &lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;kwrd&quot;&gt;void&lt;/span&gt; test2()&lt;br /&gt;{&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;try&lt;/span&gt;&lt;br /&gt;  {  &lt;br /&gt;    MethodInfo mi = &lt;span class=&quot;kwrd&quot;&gt;typeof&lt;/span&gt;(Form1).GetMethod( &lt;span class=&quot;str&quot;&gt;&amp;quot;test1&amp;quot;&lt;/span&gt; );&lt;br /&gt;    mi.Invoke( &lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt;, &lt;span class=&quot;kwrd&quot;&gt;null&lt;/span&gt; );&lt;br /&gt;  }&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;catch&lt;/span&gt;( TargetInvocationException tiex )&lt;br /&gt;  { &lt;br /&gt;    &lt;span class=&quot;rem&quot;&gt;// NB: Error checking etc. excluded&lt;/span&gt;&lt;br /&gt;    &lt;span class=&quot;rem&quot;&gt;// Get the _remoteStackTraceString of the Exception class&lt;/span&gt;&lt;br /&gt;    FieldInfo remoteStackTraceString = &lt;span class=&quot;kwrd&quot;&gt;typeof&lt;/span&gt;(Exception).GetField(&lt;span class=&quot;str&quot;&gt;&amp;quot;_remoteStackTraceString&amp;quot;&lt;/span&gt;,&lt;br /&gt;      BindingFlags.Instance | BindingFlags.NonPublic );&lt;br /&gt;&lt;br /&gt;    &lt;span class=&quot;rem&quot;&gt;// Set the InnerException._remoteStackTraceString to the current InnerException.StackTrace&lt;/span&gt;&lt;br /&gt;    remoteStackTraceString.SetValue( tiex.InnerException, &lt;br /&gt;      tiex.InnerException.StackTrace + Environment.NewLine );&lt;br /&gt;&lt;br /&gt;    &lt;span class=&quot;rem&quot;&gt;// Throw the new exception&lt;/span&gt;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;throw&lt;/span&gt; tiex.InnerException;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;...&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// Test the effect of the above code by calling test2() and handling &lt;/span&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// the exception that is thrown&lt;/span&gt;&lt;br /&gt;&lt;span class=&quot;kwrd&quot;&gt;try&lt;/span&gt;&lt;br /&gt;{&lt;br /&gt;  test2(); &lt;span class=&quot;rem&quot;&gt;// Call the method that uses reflection to call another method&lt;/span&gt;&lt;br /&gt;}&lt;br /&gt;&lt;span class=&quot;kwrd&quot;&gt;catch&lt;/span&gt; ( Exception ex )&lt;br /&gt;{&lt;br /&gt;  Console.WriteLine( ex.ToString() );&lt;br /&gt;}&lt;/pre&gt;  </content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/7013264991897807029/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2009/09/re-throw-innerexception-and-preserve.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/7013264991897807029'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/7013264991897807029'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2009/09/re-throw-innerexception-and-preserve.html' title='Re-throw InnerException and preserve the original StackTrace'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-5942254829326090006</id><published>2009-09-24T22:38:00.001+03:00</published><updated>2009-09-24T22:38:25.013+03:00</updated><title type='text'>Silverlight – Ray casting engine</title><content type='html'>&lt;p&gt;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. &lt;/p&gt;  &lt;p&gt;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 &lt;a href=&quot;http://www.silverarcade.com/games/taylorza/labyrinth&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;http://www.silverarcade.com/games/taylorza/labyrinth&quot;&gt;&lt;img style=&quot;border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px&quot; title=&quot;ScreenshotMashoo&quot; border=&quot;0&quot; alt=&quot;ScreenshotMashoo&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhx0JxPO3jqX9QzY58lQYiZdf0hYQgeWEWt5_oDV2lY3KDXeoBgTeLXwfEl3FVAmbiibLJ7Cj5WHpMFyOoIHRl5DVDadgtC4s-VBsSNqsoHGXc3_OBLkZfCOTxhyFNxiCXTJDgvkv1f1xNg/?imgmax=800&quot; width=&quot;244&quot; height=&quot;186&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;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.&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/5942254829326090006/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2009/09/silverlight-ray-casting-engine.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/5942254829326090006'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/5942254829326090006'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2009/09/silverlight-ray-casting-engine.html' title='Silverlight – Ray casting engine'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhx0JxPO3jqX9QzY58lQYiZdf0hYQgeWEWt5_oDV2lY3KDXeoBgTeLXwfEl3FVAmbiibLJ7Cj5WHpMFyOoIHRl5DVDadgtC4s-VBsSNqsoHGXc3_OBLkZfCOTxhyFNxiCXTJDgvkv1f1xNg/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-7467683580253890570</id><published>2009-08-22T15:41:00.003+03:00</published><updated>2011-07-06T06:02:51.821+03:00</updated><title type='text'>Silverlight – SpriteSheet management with WriteableBitmap</title><content type='html'>As part of my Silverlight education process I have been writing some games. First a few basic things like &lt;a href=&quot;http://www.silverarcade.com/games/taylorza/sildoku&quot; target=&quot;_blank&quot;&gt;Sildoku&lt;/a&gt; and &lt;a href=&quot;http://www.silverarcade.com/games/taylorza/peg-solitaire&quot; target=&quot;_blank&quot;&gt;Peg Solitaire&lt;/a&gt;. 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.&lt;br /&gt;
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 &lt;a href=&quot;http://en.wikipedia.org/wiki/Sprite_sheet&quot; target=&quot;_blank&quot;&gt;Wikipedia&lt;/a&gt; link.&lt;br /&gt;
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.&lt;br /&gt;
&lt;pre class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;class&lt;/span&gt; SpriteSheet
{
&lt;span class=&quot;kwrd&quot;&gt;  private&lt;/span&gt; BitmapSource _spriteSheetSource;
&lt;span class=&quot;kwrd&quot;&gt;  private&lt;/span&gt; WriteableBitmap _spriteSheetBitmap;
&lt;span class=&quot;kwrd&quot;&gt;  private&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; _sheetWidth;
&lt;span class=&quot;kwrd&quot;&gt;  private&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; _sheetHeight;    

&lt;span class=&quot;kwrd&quot;&gt;  public&lt;/span&gt; SpriteSheet(BitmapSource spriteSheetSource)
  {
&lt;span class=&quot;kwrd&quot;&gt;    if&lt;/span&gt; (spriteSheetSource == &lt;span class=&quot;kwrd&quot;&gt;null&lt;/span&gt;) &lt;span class=&quot;kwrd&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class=&quot;str&quot;&gt;&quot;spriteSheetSource&quot;&lt;/span&gt;);

    _spriteSheetSource = spriteSheetSource;
    _spriteSheetBitmap = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; WriteableBitmap(_spriteSheetSource);
    _sheetWidth = _spriteSheetBitmap.PixelWidth;
    _sheetHeight = _spriteSheetBitmap.PixelHeight;
  }

&lt;span class=&quot;kwrd&quot;&gt;  public&lt;/span&gt; WriteableBitmap GetBitmap(&lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; x, &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; y, &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; width, &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; height)
  {
    WriteableBitmap destination = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; WriteableBitmap(width, height);      
    GetBitmap(destination, x, y, width, height);
&lt;span class=&quot;kwrd&quot;&gt;    return&lt;/span&gt; destination;
  }

&lt;span class=&quot;kwrd&quot;&gt;  public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;void&lt;/span&gt; GetBitmap(WriteableBitmap targetBitmap, &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; x, &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; y, &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; width, &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; height)
  {
&lt;span class=&quot;rem&quot;&gt;    // Validate incomming data&lt;/span&gt;
&lt;span class=&quot;kwrd&quot;&gt;    if&lt;/span&gt; (targetBitmap == &lt;span class=&quot;kwrd&quot;&gt;null&lt;/span&gt;) &lt;span class=&quot;kwrd&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class=&quot;str&quot;&gt;&quot;targetBitmap&quot;&lt;/span&gt;);
&lt;span class=&quot;kwrd&quot;&gt;    if&lt;/span&gt; (x &amp;lt; 0 || x &amp;gt;= _sheetWidth) &lt;span class=&quot;kwrd&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; ArgumentOutOfRangeException(&lt;span class=&quot;str&quot;&gt;&quot;x&quot;&lt;/span&gt;);
&lt;span class=&quot;kwrd&quot;&gt;    if&lt;/span&gt; (y &amp;lt; 0 || y &amp;gt;= _sheetHeight) &lt;span class=&quot;kwrd&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; ArgumentOutOfRangeException(&lt;span class=&quot;str&quot;&gt;&quot;y&quot;&lt;/span&gt;);
&lt;span class=&quot;kwrd&quot;&gt;    if&lt;/span&gt; (width &amp;lt; 0 || (x + width &amp;gt; _sheetWidth)) &lt;span class=&quot;kwrd&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; ArgumentOutOfRangeException(&lt;span class=&quot;str&quot;&gt;&quot;width&quot;&lt;/span&gt;);
&lt;span class=&quot;kwrd&quot;&gt;    if&lt;/span&gt; (height &amp;lt; 0 || (y + height &amp;gt; _sheetHeight)) &lt;span class=&quot;kwrd&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; ArgumentOutOfRangeException(&lt;span class=&quot;str&quot;&gt;&quot;height&quot;&lt;/span&gt;);

&lt;span class=&quot;rem&quot;&gt;    // Get pixel buffers for the sprite sheet and the target bitmap&lt;/span&gt;
&lt;span class=&quot;kwrd&quot;&gt;    int&lt;/span&gt;[] sourcePixels = _spriteSheetBitmap.Pixels;
&lt;span class=&quot;kwrd&quot;&gt;    int&lt;/span&gt;[] targetPixels = targetBitmap.Pixels;

    &lt;span class=&quot;rem&quot;&gt;// Calculate starting offsets into the pixel buffers      &lt;/span&gt;
&lt;span class=&quot;kwrd&quot;&gt;    int&lt;/span&gt; sourceOffset = x + (y * _sheetWidth);      
&lt;span class=&quot;kwrd&quot;&gt;    int&lt;/span&gt; targetOffset = 0;

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

&lt;span class=&quot;kwrd&quot;&gt;  public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; Width
  {
    get { &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; _sheetWidth; }
  }

&lt;span class=&quot;kwrd&quot;&gt;  public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; Height
  {
    get { &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; _sheetHeight; }
  }
}&lt;/pre&gt;The interesting function in this class is the &lt;strong&gt;GetBitmap(WriteableBitmap targetBitmap, int x, int y, int width, int height)&lt;/strong&gt; 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 &lt;strong&gt;GetBitmap(int x, int y, int width, int height) &lt;/strong&gt;overload calls this function with a pre-allocated WriteableBitmap of the correct dimensions. &lt;br /&gt;
Using the class is quite simple. Assume you have a couple of standard Image controls declared on your page, something like the following.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;csharpcode&quot;&gt;&amp;lt;UserControl x:Class=&lt;span class=&quot;str&quot;&gt;&quot;Vulcan.SL.TestApplication.MainPage&quot;&lt;/span&gt;
xmlns=&lt;span class=&quot;str&quot;&gt;&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;&lt;/span&gt; 
xmlns:x=&lt;span class=&quot;str&quot;&gt;&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&lt;/span&gt;
xmlns:d=&lt;span class=&quot;str&quot;&gt;&quot;http://schemas.microsoft.com/expression/blend/2008&quot;&lt;/span&gt; xmlns:mc=&lt;span class=&quot;str&quot;&gt;&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;&lt;/span&gt;
mc:Ignorable=&lt;span class=&quot;str&quot;&gt;&quot;d&quot;&lt;/span&gt; d:DesignWidth=&lt;span class=&quot;str&quot;&gt;&quot;640&quot;&lt;/span&gt; d:DesignHeight=&lt;span class=&quot;str&quot;&gt;&quot;480&quot;&lt;/span&gt;&amp;gt;
  &amp;lt;Canvas x:Name=&lt;span class=&quot;str&quot;&gt;&quot;LayoutRoot&quot;&lt;/span&gt;&amp;gt;  
    &amp;lt;Image x:Name=&lt;span class=&quot;str&quot;&gt;&quot;mySprite1&quot;&lt;/span&gt; Width=&lt;span class=&quot;str&quot;&gt;&quot;100&quot;&lt;/span&gt; Height=&lt;span class=&quot;str&quot;&gt;&quot;100&quot;&lt;/span&gt; Canvas.Left=&lt;span class=&quot;str&quot;&gt;&quot;0&quot;&lt;/span&gt;/&amp;gt;
    &amp;lt;Image x:Name=&lt;span class=&quot;str&quot;&gt;&quot;mySprite2&quot;&lt;/span&gt; Width=&lt;span class=&quot;str&quot;&gt;&quot;100&quot;&lt;/span&gt; Height=&lt;span class=&quot;str&quot;&gt;&quot;100&quot;&lt;/span&gt; Canvas.Left=&lt;span class=&quot;str&quot;&gt;&quot;110&quot;&lt;/span&gt;/&amp;gt;
  &amp;lt;/Canvas&amp;gt;
&amp;lt;/UserControl&amp;gt;&lt;/pre&gt;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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;pre class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; MainPage()
{
  InitializeComponent();

  BitmapImage spriteSheetBitmap = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; BitmapImage(&lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Uri(&lt;span class=&quot;str&quot;&gt;&quot;/Images/WindmillLeft.png&quot;&lt;/span&gt;, UriKind.Relative));      
  spriteSheetBitmap.CreateOptions = BitmapCreateOptions.None;
  spriteSheetBitmap.ImageOpened += &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; EventHandler&amp;lt;RoutedEventArgs&amp;gt;(image_ImageOpened);       
}

&lt;span class=&quot;kwrd&quot;&gt;void&lt;/span&gt; image_ImageOpened(&lt;span class=&quot;kwrd&quot;&gt;object&lt;/span&gt; sender, RoutedEventArgs e)
{
  BitmapImage spriteSheetBitmap = sender &lt;span class=&quot;kwrd&quot;&gt;as&lt;/span&gt; BitmapImage;

  SpriteSheet spriteSheet = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; SpriteSheet(spriteSheetBitmap);

&lt;span class=&quot;rem&quot;&gt;  // Set the source of the mySprite1 to an image extracted from the SpriteSheet&lt;/span&gt;
  mySprite1.Source = spriteSheet.GetBitmap(0, 0, 224, 240);

&lt;span class=&quot;rem&quot;&gt;  // Set the source of the mySprite2 to an image extracted from the SpriteSheet&lt;/span&gt;
  mySprite2.Source = spriteSheet.GetBitmap(2240, 0, 224, 240);
}&lt;/pre&gt;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. &lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
As my code for the Sprite and AnimatedSprite classes matures I will hopefully find some time to release that on this blog.</content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/7467683580253890570/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2009/08/silverlight-spritesheet-management-with.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/7467683580253890570'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/7467683580253890570'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2009/08/silverlight-spritesheet-management-with.html' title='Silverlight – SpriteSheet management with WriteableBitmap'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-2412394062858681886</id><published>2009-08-19T02:33:00.001+03:00</published><updated>2009-08-19T02:33:56.822+03:00</updated><title type='text'>Silverlight – My first Silverlight games published</title><content type='html'>&lt;p&gt;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. &lt;/p&gt;  &lt;p&gt;So what is all my excitement about, well I have written 2 small Silverlight games and submitted them to &lt;a href=&quot;http://www.silverarcade.com&quot; target=&quot;_blank&quot;&gt;Silver Arcade&lt;/a&gt;. 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 :))&lt;/p&gt;  &lt;p&gt;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 &lt;a href=&quot;http://www.silverarcade.com/games/taylorza/sildoku&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtfCBina-Od1XbqB3MFOEYkezGUFddnCgDoRULP0PNfTmT5wb0nW8eqlqZAC4H-yjbArsfpXBf2qE0VgXX7pnfPSjrJNC39Y9jHQIvz0BfRu2c4zyec-MiHbW39YU4ge1Ke7r4MS2NAhhA/s1600-h/ScreenshotSmall%5B2%5D.png&quot;&gt;&lt;img style=&quot;border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px&quot; title=&quot;ScreenshotSmall&quot; border=&quot;0&quot; alt=&quot;ScreenshotSmall&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhzXMnp6bcBIya-Vb7VY7Z1meZkS9gwTfi0XNbHVxwTrI5-5dFfLHQQMCqV9XmklbN_hiA6KzP2obJ3ENwba4Jbj10PaOTy-VjJIXYxwZkJb3a52GyzyLNTllrnlZ65x-4KWgRhy-PxAYr5/?imgmax=800&quot; width=&quot;164&quot; height=&quot;164&quot; /&gt;&lt;/a&gt;&amp;#160; &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;The second game is Peg Solitaire. Which you can try &lt;a href=&quot;http://www.silverarcade.com/games/taylorza/peg-solitaire&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg8rbztfnxDkqmaAO-32gV-enRRHIe5Sgz-hFC0n9vferK42cxpt3EE9RGpPUARuLH7EyeiZ6aEXts3-z3Xo1MXs2mteamNpJ86PeCIm9-7rTBMPs_J9UNtBkUgSckJWo2PHi6gn8eWYIa1/s1600-h/Promotional%5B2%5D.jpg&quot;&gt;&lt;img style=&quot;border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px&quot; title=&quot;Promotional&quot; border=&quot;0&quot; alt=&quot;Promotional&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiwwyNp-yLC8Qd_rQDZT4coxLZN0dcJbgGtHYt6z3P33lS7OuaNOMHJLtmIv-NRvc5ZvHA9uiZFS25K1s-OJb1T2wQMDTzzJ3UAsRJOb1UWZKKtoX8O4SBF_p2r6YzIsnBNxezC0u0JCiw/?imgmax=800&quot; width=&quot;162&quot; height=&quot;162&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/2412394062858681886/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2009/08/silverlight-my-first-silverlight-games.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/2412394062858681886'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/2412394062858681886'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2009/08/silverlight-my-first-silverlight-games.html' title='Silverlight – My first Silverlight games published'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhzXMnp6bcBIya-Vb7VY7Z1meZkS9gwTfi0XNbHVxwTrI5-5dFfLHQQMCqV9XmklbN_hiA6KzP2obJ3ENwba4Jbj10PaOTy-VjJIXYxwZkJb3a52GyzyLNTllrnlZ65x-4KWgRhy-PxAYr5/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-1915756186954885843</id><published>2009-08-18T13:00:00.002+03:00</published><updated>2009-09-27T15:27:18.692+03:00</updated><title type='text'>Archive – Hacking my way across the process boundary</title><content type='html'>&lt;p&gt;&lt;font color=&quot;#0000ff&quot;&gt;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.&lt;/font&gt;&lt;/p&gt;  &lt;p&gt;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 :) &lt;/p&gt;  &lt;p&gt;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. &lt;/p&gt;  &lt;p&gt;The following C++ code provides an example of getting a item from a ListView hosted in another process.&lt;/p&gt;  &lt;pre class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;const&lt;/span&gt; DWORD dwBufSize = 1024;&lt;br /&gt;&lt;br /&gt;DWORD dwProcessID;&lt;br /&gt;DWORD dwResult;&lt;br /&gt;HANDLE hProcess;&lt;br /&gt;&lt;br /&gt;BYTE *lpRemoteBuffer;&lt;br /&gt;&lt;br /&gt;LVITEM lvItem = {0};&lt;br /&gt;&lt;br /&gt;BYTE lpLocalBuffer[dwBufSize] = {0};&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// Get the process id owning the window&lt;/span&gt;&lt;br /&gt;::GetWindowThreadProcessId( hwndListView, &amp;amp;dwProcessID );&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// Open the process wih all access (You may not have the rights to do this)&lt;/span&gt;&lt;br /&gt;hProcess = ::OpenProcess( PROCESS_ALL_ACCESS, FALSE, dwProcessID );&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// Allocate a buffer in the remote process&lt;/span&gt;&lt;br /&gt;lpRemoteBuffer = (BYTE*)::VirtualAllocEx( hProcess, NULL, dwBufSize,&lt;br /&gt;MEM_COMMIT, PAGE_READWRITE );&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// Fill in the LVITEM struct, this is in your own process&lt;/span&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// Set the pszText member to somewhere in the remote buffer,&lt;/span&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// For the example I used the address imediately following the LVITEM stuct&lt;/span&gt;&lt;br /&gt;lvItem.mask = LVIF_TEXT;&lt;br /&gt;lvItem.iItem = 0;&lt;br /&gt;lvItem.cchTextMax = 50;&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// Point to after LVITEM in the remote buffer&lt;/span&gt;&lt;br /&gt;lvItem.pszText = (LPTSTR)(lpRemoteBuffer + &lt;span class=&quot;kwrd&quot;&gt;sizeof&lt;/span&gt;( LVITEM )); &lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// Copy the local LVITEM to the remote buffer&lt;/span&gt;&lt;br /&gt;::WriteProcessMemory( hProcess, (LPVOID)lpRemoteBuffer, &lt;br /&gt;  &amp;amp;lvItem, &lt;span class=&quot;kwrd&quot;&gt;sizeof&lt;/span&gt;(LVITEM), NULL );&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// Send the message&lt;/span&gt;&lt;br /&gt;::SendMessage( hwndListView, LVM_GETITEM, 0, (LPARAM)lpRemoteBuffer);&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// Read the struct back from the remote process into local buffer&lt;/span&gt;&lt;br /&gt;::ReadProcessMemory( hProcess, (LPVOID)lpRemoteBuffer, lpLocalBuffer,&lt;br /&gt;  dwBufSize, NULL );&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;//Fix pszText to point to same offset in local buffer&lt;/span&gt;&lt;br /&gt;lvItem.pszText = (LPTSTR)(lpLocalBuffer + &lt;span class=&quot;kwrd&quot;&gt;sizeof&lt;/span&gt;( LVITEM ));&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// Clean-up&lt;/span&gt;&lt;br /&gt;::VirtualFreeEx( hProcess, (LPVOID)lpRemoteBuffer, 0, MEM_RELEASE ); &lt;br /&gt;::CloseHandle( hProcess );&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/1915756186954885843/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2009/08/archive-hacking-my-way-across-process.html#comment-form' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/1915756186954885843'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/1915756186954885843'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2009/08/archive-hacking-my-way-across-process.html' title='Archive – Hacking my way across the process boundary'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-4978505800018868492</id><published>2009-08-15T16:36:00.001+03:00</published><updated>2009-08-15T16:36:45.254+03:00</updated><title type='text'>Silverlight – WriteableBitmap SetPixel extension method</title><content type='html'>&lt;p&gt;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.&lt;/p&gt;  &lt;pre class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;using&lt;/span&gt; System;&lt;br /&gt;&lt;span class=&quot;kwrd&quot;&gt;using&lt;/span&gt; System.Windows.Media;&lt;br /&gt;&lt;span class=&quot;kwrd&quot;&gt;using&lt;/span&gt; System.Windows.Media.Imaging;&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;kwrd&quot;&gt;namespace&lt;/span&gt; ExtensionMethods&lt;br /&gt;{&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;class&lt;/span&gt; WriteableBitmapExtensions&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;void&lt;/span&gt; SetPixel(&lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt; WriteableBitmap wb, &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; x, &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; y, Color color)&lt;br /&gt;    {&lt;br /&gt;      &lt;span class=&quot;rem&quot;&gt;// Validate that the x,y coordinates are within the bounds of the bitmap&lt;/span&gt;&lt;br /&gt;      &lt;span class=&quot;kwrd&quot;&gt;if&lt;/span&gt; (x &amp;lt; 0 || x &amp;gt;= wb.PixelWidth || y &amp;lt; 0 || y &amp;gt;= wb.PixelHeight) &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt;;&lt;br /&gt;      &lt;br /&gt;      &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; offset = (y * wb.PixelWidth) + x; &lt;br /&gt;      &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt; pixel;&lt;br /&gt;      &lt;span class=&quot;kwrd&quot;&gt;int&lt;/span&gt;[] buffer = wb.Pixels;&lt;br /&gt;&lt;br /&gt;      &lt;span class=&quot;kwrd&quot;&gt;if&lt;/span&gt; (color.A == 255)&lt;br /&gt;      {                &lt;br /&gt;        &lt;span class=&quot;rem&quot;&gt;// Since no alpha blending is required we can directly use the incomming color&lt;/span&gt;&lt;br /&gt;        &lt;span class=&quot;rem&quot;&gt;// compose the integer that needs to be written to the pixel buffer.&lt;/span&gt;&lt;br /&gt;        pixel = (color.A &amp;lt;&amp;lt; 24) | (color.R &amp;lt;&amp;lt; 16) | (color.G &amp;lt;&amp;lt; 8) | color.B;&lt;br /&gt;      }&lt;br /&gt;      &lt;span class=&quot;kwrd&quot;&gt;else&lt;/span&gt;&lt;br /&gt;      {&lt;br /&gt;        &lt;span class=&quot;rem&quot;&gt;// Get the current pixle in the pixel buffer that we need to blend with&lt;/span&gt;&lt;br /&gt;        pixel = buffer[offset];&lt;br /&gt;          &lt;br /&gt;        &lt;span class=&quot;rem&quot;&gt;// calculate the alpha channel ratios used for the blend of &lt;/span&gt;&lt;br /&gt;        &lt;span class=&quot;rem&quot;&gt;// the source and destination pixels&lt;/span&gt;&lt;br /&gt;        &lt;span class=&quot;kwrd&quot;&gt;double&lt;/span&gt; sourceAlpha = color.A / 255.0;&lt;br /&gt;        &lt;span class=&quot;kwrd&quot;&gt;double&lt;/span&gt; inverseSourceAlpha = 1 - sourceAlpha;&lt;br /&gt;&lt;br /&gt;        &lt;span class=&quot;rem&quot;&gt;// Extract the color components of the current pixel in the buffer&lt;/span&gt;&lt;br /&gt;        &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; destA = (&lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt;)(pixel &amp;gt;&amp;gt; 24);&lt;br /&gt;        &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; destR = (&lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt;)(pixel &amp;gt;&amp;gt; 16);&lt;br /&gt;        &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; destG = (&lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt;)(pixel &amp;gt;&amp;gt; 8);&lt;br /&gt;        &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; destB = (&lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt;)pixel;&lt;br /&gt;        &lt;br /&gt;        &lt;span class=&quot;rem&quot;&gt;// Calculate the color components of the new pixel. &lt;/span&gt;&lt;br /&gt;        &lt;span class=&quot;rem&quot;&gt;// This is the blend of the destination pixel and the new source pixel&lt;/span&gt;&lt;br /&gt;        &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; pixelA = (&lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt;)((color.A * sourceAlpha) + (inverseSourceAlpha * destA));&lt;br /&gt;        &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; pixelR = (&lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt;)((color.R * sourceAlpha) + (inverseSourceAlpha * destR));&lt;br /&gt;        &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; pixelG = (&lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt;)((color.G * sourceAlpha) + (inverseSourceAlpha * destG));&lt;br /&gt;        &lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt; pixelB = (&lt;span class=&quot;kwrd&quot;&gt;byte&lt;/span&gt;)((color.B * sourceAlpha) + (inverseSourceAlpha * destB));&lt;br /&gt;&lt;br /&gt;        &lt;span class=&quot;rem&quot;&gt;// Reconstitute the color components into an int to be written to the pixel buffer&lt;/span&gt;&lt;br /&gt;        pixel = (pixelA &amp;lt;&amp;lt; 24) | (pixelR &amp;lt;&amp;lt; 16) | (pixelG &amp;lt;&amp;lt; 8) | pixelB;&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      &lt;span class=&quot;rem&quot;&gt;// Write new pixel to the pixel buffer&lt;/span&gt;&lt;br /&gt;      buffer[offset] = pixel;&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;If you are interested, the 2 controls I have written are&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;  &lt;li&gt;&lt;strong&gt;TextureSurface&lt;/strong&gt; – 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.&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;  &lt;li&gt;&lt;strong&gt;ImageEx&lt;/strong&gt; – 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.&lt;/li&gt;&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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? &lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/4978505800018868492/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2009/08/silverlight-writeablebitmap-setpixel.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/4978505800018868492'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/4978505800018868492'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2009/08/silverlight-writeablebitmap-setpixel.html' title='Silverlight – WriteableBitmap SetPixel extension method'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-4795304401792078989</id><published>2009-08-14T12:26:00.001+03:00</published><updated>2009-08-14T12:31:08.915+03:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Silverlight"/><title type='text'>Silverlight – Set focus to the silverlight control</title><content type='html'>&lt;p&gt;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.&lt;/p&gt;  &lt;p&gt;1. Give the &amp;lt;object&amp;gt; element in the web page an ID    &lt;br /&gt;2. Pass the ‘onLoad’ parameter on the Silverlight application assigning a JavaScript function that will focus to application in the browser.&lt;/p&gt;  &lt;pre class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;html&quot;&gt;object&lt;/span&gt; &lt;strong&gt;&lt;em&gt;&lt;span class=&quot;attr&quot;&gt;id&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;silverlightControl&amp;quot;&lt;/span&gt;&lt;/em&gt;&lt;/strong&gt; &lt;span class=&quot;attr&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;data:application/x-silverlight-2,&amp;quot;&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;application/x-silverlight-2&amp;quot;&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;100%&amp;quot;&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;height&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;100%&amp;quot;&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;html&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;source&amp;quot;&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;ClientBin/DragSnapDemo.xap&amp;quot;&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;html&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;onError&amp;quot;&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;onSilverlightError&amp;quot;&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;strong&gt;&lt;em&gt;&lt;span class=&quot;kwrd&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;html&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;onLoad&amp;quot;&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;silverlightControlHost_Load&amp;quot;&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;/&amp;gt;&lt;/span&gt;&lt;/em&gt;&lt;/strong&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;html&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;background&amp;quot;&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;white&amp;quot;&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;html&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;minRuntimeVersion&amp;quot;&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;3.0.40624.0&amp;quot;&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;html&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;autoUpgrade&amp;quot;&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;true&amp;quot;&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;html&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;href&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;http://go.microsoft.com/fwlink/?LinkID=149156&amp;amp;v=3.0.40624.0&amp;quot;&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;style&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;text-decoration:none&amp;quot;&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;html&quot;&gt;img&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;src&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;http://go.microsoft.com/fwlink/?LinkId=108181&amp;quot;&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;alt&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;Get Microsoft Silverlight&amp;quot;&lt;/span&gt; &lt;span class=&quot;attr&quot;&gt;style&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;=&amp;quot;border-style:none&amp;quot;&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span class=&quot;html&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span class=&quot;kwrd&quot;&gt;&amp;lt;/&lt;/span&gt;&lt;span class=&quot;html&quot;&gt;object&lt;/span&gt;&lt;span class=&quot;kwrd&quot;&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;3. Finally write the JavaScript function that is called when the Silverlight application has be loaded&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;function&lt;/span&gt; silverlightControlHost_Load(sender, args) &lt;br /&gt;{&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;var&lt;/span&gt; control = document.getElementById(&lt;span class=&quot;str&quot;&gt;&amp;quot;silverlightControl&amp;quot;&lt;/span&gt;);&lt;br /&gt;  control.focus();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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.&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/4795304401792078989/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2009/08/silverlight-set-focus-to-silverlight.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/4795304401792078989'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/4795304401792078989'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2009/08/silverlight-set-focus-to-silverlight.html' title='Silverlight – Set focus to the silverlight control'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4927779461366619687.post-1050497164055586723</id><published>2009-04-20T16:01:00.005+03:00</published><updated>2009-04-22T19:09:47.049+03:00</updated><title type='text'>Range&amp;lt;&amp;gt; data type - Examples for XNA</title><content type='html'>&lt;p&gt;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.&lt;/p&gt;&lt;p&gt;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&lt;/p&gt;&lt;pre class=&quot;csharpcode&quot;&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;class&lt;/span&gt; ParticleSystemSettings&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; Color MinColorStart&lt;br /&gt;    {&lt;br /&gt;      get;&lt;br /&gt;      set;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; Color MaxColorStart&lt;br /&gt;    {&lt;br /&gt;      get;&lt;br /&gt;      set;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; Color MinColorEnd&lt;br /&gt;    {&lt;br /&gt;      get;&lt;br /&gt;      set;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; Color MaxColorEnd&lt;br /&gt;    {&lt;br /&gt;      get;&lt;br /&gt;      set;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; MinLifeSpan&lt;br /&gt;    {&lt;br /&gt;      get;&lt;br /&gt;      set;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; MaxLifeSpan&lt;br /&gt;    {&lt;br /&gt;      get;&lt;br /&gt;      set;&lt;br /&gt;    }&lt;br /&gt;  }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;csharpcode&quot;&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;class&lt;/span&gt; ParticleSystemSettings&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; Range&amp;lt;Color&amp;gt; StartColorRange&lt;br /&gt;    {&lt;br /&gt;      get;&lt;br /&gt;      set;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; Range&amp;lt;Color&amp;gt; EndColorRange&lt;br /&gt;    {&lt;br /&gt;      get;&lt;br /&gt;      set;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;  &lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; Range&amp;lt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt;&amp;gt; LifeSpanRange&lt;br /&gt;    {&lt;br /&gt;      get;&lt;br /&gt;      set;&lt;br /&gt;    }&lt;br /&gt;  }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;For example, the following code demonstrates how I would like to be initializing an instance of the ParticleSystemSettings class.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;csharpcode&quot;&gt;ParticleSystemSettings settings = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; ParticleSystemSettings();&lt;br /&gt;&lt;br /&gt;settings.StartColorRange = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Range&amp;lt;Color&amp;gt;(Color.Yellow, Color.Orange);&lt;br /&gt;settings.EndColorRange = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Range&amp;lt;Color&amp;gt;(Color.Orange, Color.Red);&lt;br /&gt;settings.LifeSpanRange = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Range&amp;lt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt;&amp;gt;(0.2f, 0.5f);&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;And the the following is an example of how a new particle could be initialized&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;csharpcode&quot;&gt;Particle particle = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Particle();&lt;br /&gt;particle.LifeSpan = settings.LifeSpanRange.Random();&lt;br /&gt;particle.ColorRange = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Range&amp;lt;Color&amp;gt;(&lt;br /&gt;  settings.StartColorRange.Random(),&lt;br /&gt;  settings.EndColorRange.Random());&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; lerpAmount = particle.Age / particle.LifeSpan;&lt;br /&gt;&lt;br /&gt;Color renderColor = particle.ColorRange.Lerp(lerpAmount);&lt;br /&gt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; renderSize = particle.SizeRange.Lerp(lerpAmount);&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Below is the complete code for my first implementation of the Range type. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;csharpcode&quot;&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;struct&lt;/span&gt; Range&amp;lt;T&amp;gt;&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; T _start;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; T _end;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; Func&amp;lt;T, T, &lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt;, T&amp;gt; _lerp;&lt;br /&gt; &lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; Range(T &lt;span class=&quot;kwrd&quot;&gt;value&lt;/span&gt;, Func&amp;lt;T, T, &lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt;, T&amp;gt; lerp)&lt;br /&gt;      : &lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt;(&lt;span class=&quot;kwrd&quot;&gt;value&lt;/span&gt;, &lt;span class=&quot;kwrd&quot;&gt;value&lt;/span&gt;, lerp)&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; Range(T start, T end, Func&amp;lt;T, T, &lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt;, T&amp;gt; lerp)&lt;br /&gt;    {&lt;br /&gt;      _start = start;&lt;br /&gt;      _end = end;&lt;br /&gt;      _lerp = lerp;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; T Start&lt;br /&gt;    {&lt;br /&gt;      get { &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; _start; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; T End&lt;br /&gt;    {&lt;br /&gt;      get { &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; _end; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; T Lerp(&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; amount)&lt;br /&gt;    {&lt;br /&gt;      &lt;span class=&quot;kwrd&quot;&gt;if&lt;/span&gt; (_lerp == &lt;span class=&quot;kwrd&quot;&gt;null&lt;/span&gt;) &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; _start;&lt;br /&gt;      &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; _lerp(_start, _end, amount);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; T Random()&lt;br /&gt;    {&lt;br /&gt;      &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; Lerp(Utilities.GetRandomFloat());&lt;br /&gt;    }&lt;br /&gt;  }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;First some things you will notice,&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;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. &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;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. &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;li&gt;The Utilities.GetRandomFloat() just returns a random float value between 0.0f and 1.0f. &lt;/li&gt;&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;rem&quot;&gt;// Initialize a few ranges&lt;/span&gt;&lt;br /&gt;Range&amp;lt;Vector2&amp;gt; positionRange = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Range&amp;lt;Vector2&amp;gt;(Vector2.Zero, Vector2.One, Vector2.Lerp);&lt;br /&gt;Range&amp;lt;Color&amp;gt; colorRange = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Range&amp;lt;Color&amp;gt;(Color.White, Color.Black, Color.Lerp);&lt;br /&gt;Range&amp;lt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt;&amp;gt; floatRange = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Range&amp;lt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt;&amp;gt;(0.0f, 5.0f,&lt;br /&gt;  (start, end, amount) =&amp;gt; { &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; start + ((end - start) * amount); });&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// Get a value midway through the range&lt;/span&gt;&lt;br /&gt;Vector2 position = positionRange.Lerp(0.5f);&lt;br /&gt;Color color = colorRange.Lerp(0.5f);&lt;br /&gt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;value&lt;/span&gt; = floatRange.Lerp(0.5f);&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;class&lt;/span&gt; Range&lt;br /&gt;{&lt;br /&gt;  &lt;span class=&quot;rem&quot;&gt;// Factory Functions&lt;/span&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; Range&amp;lt;Vector2&amp;gt; CreateVector2(Vector2 start, Vector2 end)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Range&amp;lt;Vector2&amp;gt;(start, end, Vector2.Lerp);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; Range&amp;lt;Color&amp;gt; CreateColor(Color start, Color end)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Range&amp;lt;Color&amp;gt;(start, end, Color.Lerp);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; Range&amp;lt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt;&amp;gt; CreateFloat(Color start, Color end)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Range&amp;lt;Color&amp;gt;(start, end, LerpFloat);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;rem&quot;&gt;// Custom Lerp functions&lt;/span&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; LerpFloat(&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; start, &lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; end, &lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; amount)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; start + ((end - start) * amount);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;rem&quot;&gt;// Initialize a few ranges&lt;/span&gt;&lt;br /&gt;Range&amp;lt;Vector2&amp;gt; positionRange = Range.CreateVector2(Vector2.Zero, Vector2.One);&lt;br /&gt;Range&amp;lt;Color&amp;gt; colorRange = Range.CreateColor(Color.White, Color.Black);&lt;br /&gt;Range&amp;lt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt;&amp;gt; floatRange = Range.CreateFloat(0.0f, 5.0f);&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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&amp;lt;&amp;gt; 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?&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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?&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;One option might be to make the Range type a class (reference type), and provide specialized implementations which inherit from Range&amp;lt;T&amp;gt;, for example class FloatRange : Range&amp;lt;float&amp;gt;. 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.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Here is the new code for the Range type&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;struct&lt;/span&gt; Range&amp;lt;T&amp;gt;&lt;br /&gt;{&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; T _start;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;private&lt;/span&gt; T _end;&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; Range(T &lt;span class=&quot;kwrd&quot;&gt;value&lt;/span&gt;)&lt;br /&gt;    : &lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt;(&lt;span class=&quot;kwrd&quot;&gt;value&lt;/span&gt;, &lt;span class=&quot;kwrd&quot;&gt;value&lt;/span&gt;)&lt;br /&gt;  {&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; Range(T start, T end)&lt;br /&gt;  {&lt;br /&gt;    _start = start;&lt;br /&gt;    _end = end;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; T Start&lt;br /&gt;  {&lt;br /&gt;    get { &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; _start; }&lt;br /&gt;    set { _start = &lt;span class=&quot;kwrd&quot;&gt;value&lt;/span&gt;; }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; T End&lt;br /&gt;  {&lt;br /&gt;    get { &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; _end; }&lt;br /&gt;    set { _end = &lt;span class=&quot;kwrd&quot;&gt;value&lt;/span&gt;; }&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;class&lt;/span&gt; XnaRangeExtensions&lt;br /&gt;{&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; Lerp(&lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt; Range&amp;lt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt;&amp;gt; range, &lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; amount)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; range.Start + ((range.End - range.Start) * amount);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; Vector2 Lerp(&lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt; Range&amp;lt;Vector2&amp;gt; range, &lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; amount)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; Vector2.Lerp(range.Start, range.End, amount);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; Vector3 Lerp(&lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt; Range&amp;lt;Vector3&amp;gt; range, &lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; amount)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; Vector3.Lerp(range.Start, range.End, amount);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; Color Lerp(&lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt; Range&amp;lt;Color&amp;gt; range, &lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; amount)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; Color.Lerp(range.Start, range.End, amount);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; Random(&lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt; Range&amp;lt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt;&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; Lerp(range, Utilities.GetRandomFloat());&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; Vector2 Random(&lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt; Range&amp;lt;Vector2&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; Lerp(range, Utilities.GetRandomFloat());&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; Vector3 Random(&lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt; Range&amp;lt;Vector3&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; Lerp(range, Utilities.GetRandomFloat());&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; Color Random(&lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt; Range&amp;lt;Color&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; Lerp(range, Utilities.GetRandomFloat());&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;bool&lt;/span&gt; IsEmpty(&lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt; Range&amp;lt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt;&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; range.Start == range.End;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;bool&lt;/span&gt; IsEmpty(&lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt; Range&amp;lt;Vector2&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; range.Start == range.End;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;bool&lt;/span&gt; IsEmpty(&lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt; Range&amp;lt;Vector3&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; range.Start == range.End;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class=&quot;kwrd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;bool&lt;/span&gt; IsEmpty(&lt;span class=&quot;kwrd&quot;&gt;this&lt;/span&gt; Range&amp;lt;Color&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class=&quot;kwrd&quot;&gt;return&lt;/span&gt; range.Start == range.End;&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;csharpcode&quot;&gt;&lt;span class=&quot;rem&quot;&gt;// Initialize a few ranges&lt;/span&gt;&lt;br /&gt;Range&amp;lt;Vector2&amp;gt; positionRange = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Range&amp;lt;Vector2&amp;gt;(Vector2.Zero, Vector2.One);&lt;br /&gt;Range&amp;lt;Color&amp;gt; colorRange = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Range&amp;lt;Color&amp;gt;(Color.White, Color.Black);&lt;br /&gt;Range&amp;lt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt;&amp;gt; floatRange = &lt;span class=&quot;kwrd&quot;&gt;new&lt;/span&gt; Range&amp;lt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt;&amp;gt;(0.0f, 5.0f);&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;rem&quot;&gt;// Get a value midway through the range&lt;/span&gt;&lt;br /&gt;Vector2 position = positionRange.Lerp(0.5f);&lt;br /&gt;Color color = colorRange.Lerp(0.5f);&lt;br /&gt;&lt;span class=&quot;kwrd&quot;&gt;float&lt;/span&gt; &lt;span class=&quot;kwrd&quot;&gt;value&lt;/span&gt; = floatRange.Lerp(0.5f);&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;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. &lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://taylorza.blogspot.com/feeds/1050497164055586723/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://taylorza.blogspot.com/2009/04/range-utility-data-type-for-cleaner-xna.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/1050497164055586723'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4927779461366619687/posts/default/1050497164055586723'/><link rel='alternate' type='text/html' href='http://taylorza.blogspot.com/2009/04/range-utility-data-type-for-cleaner-xna.html' title='Range&amp;lt;&amp;gt; data type - Examples for XNA'/><author><name>Chris Taylor</name><uri>http://www.blogger.com/profile/16376474093485672479</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWmGJau50Mb_ke84AHS1CQJuw-7T6ko614IqkP0aLGTWTSClmteMdUXXPcUcqYKMButpVnwPKa1Kd4LBw9f0XWJkSilSmyrs38uHnWkHyaCIAuXYIP62_kHeGnH_qwFA/s220/Family.bmp'/></author><thr:total>0</thr:total></entry></feed>