<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" gd:etag="W/&quot;DUABRng4fip7ImA9WhRRFE4.&quot;"><id>tag:blogger.com,1999:blog-4927779461366619687</id><updated>2011-11-28T01:49:17.636+02:00</updated><category term="Algoritms" /><category term="Data Structures" /><category term="Silverlight" /><title>std::string strMyBlog = "Chris Taylor";</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="alternate" type="text/html" href="http://taylorza.blogspot.com/" /><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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>23</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/taylorza_blogspot" /><feedburner:info uri="taylorza_blogspot" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry gd:etag="W/&quot;CUMAQng7eCp7ImA9WhdUFUo.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2011-10-02T19:37:23.600+03:00</app:edited><title>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="360" height="280" src="http://dotnetwarrior.com/demos/metaballs/metaballs.htm" frameborder="0"&gt; &lt;/iframe&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-7426433653005541880?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/LGMIVrJp1em020uHJ7XyyvyS7lc/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/LGMIVrJp1em020uHJ7XyyvyS7lc/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/LGMIVrJp1em020uHJ7XyyvyS7lc/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/LGMIVrJp1em020uHJ7XyyvyS7lc/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/DKUbxAfCrX4" height="1" width="1"/&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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/7426433653005541880?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/DKUbxAfCrX4/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2011/10/my-first-attempt-at-using-html-5-canvas.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C08FQXkzeyp7ImA9WhdWE0U.&quot;"><id>tag:blogger.com,1999:blog-4927779461366619687.post-2029591181925174781</id><published>2011-09-06T18:39:00.001+03:00</published><updated>2011-09-07T10:50:10.783+03:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-09-07T10:50:10.783+03:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Data Structures" /><category scheme="http://www.blogger.com/atom/ns#" term="Algoritms" /><title>Practical Algorithms and Data Structures : Arrays–Part 1</title><content type="html">&lt;p&gt;To understand arrays, you first need to understand some basic concepts of how computer memory is managed. This is going to be a very high-level explanation with many over simplifications, basically I hope to share just enough to ensure that you don’t get lost when we get into the details of arrays. &lt;/p&gt;  &lt;p&gt;You can think of computer memory as a collection of blocks which are placed sequentially one after the other in a row. Each block is uniquely identified by a number, this number in known as a memory address. For example, the first block would be at memory address 0 the next at memory address 1 and so on until you reach the last block.&lt;/p&gt;  &lt;p&gt;Each of of these blocks or memory locations can store a single piece of data, this piece of data is known as a byte. A byte is made-up of 8 bits where each bit can have a binary state of either ‘1’ or ‘0’, 256 unique combinations of 1s and 0s can be formed for a byte. The interpretation or meaning associated to each of these patterns depends on what part of the system is looking at the data and how it has chosen to interpret the data. For example if your application is interpreting the data in the memory area as letters of the alphabet you might choose to interpret the bit pattern 01000001 as the upper case letter ‘A’. If on the other hand your application is treating the data as a numerical quantity representing someone's age for example, that same bit pattern would be interpreted as the numeric value 65. (See note 1 below)&lt;/p&gt;  &lt;p&gt;More complex data can be represented by combining the patterns of multiple memory locations and interpreting those patterns appropriately. Let me give you an example.&lt;/p&gt;  &lt;p&gt;Suppose you wanted to store a string of characters in memory, you could choose to store that string with a length prefix which indicates how many characters are in the string, and the subsequent memory locations would contain the bytes that represent each character of the string. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh5.ggpht.com/-S9JIRpI-6jo/TmY-sYYlRkI/AAAAAAAAAyA/1d_xVv6Lg_k/s1600-h/String-in-memory5.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="String in memory" border="0" alt="String in memory" src="http://lh3.ggpht.com/-gm_dRZLjT08/TmY-tOnkNKI/AAAAAAAAAyE/YWRFac4P_3w/String-in-memory_thumb1.png?imgmax=800" width="205" height="70" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;The above image represents a string stored in memory with a length prefix of 5. Memory location 0 contains the bit pattern for the number 5 indicating that the next 5 memory locations contain the character data of the string. Memory location 1 contains the bit pattern 01100011 which has the numeric value of 99, but because we know this is a character of a string we will map this to the character ‘c’ (We are using an ASCII mapping here, see note 2 below), the ‘r at memory address 3 is encoded as 01110010 which represents the numeric value 114. This mapping is done for the 5 memory locations after the length prefix. &lt;/p&gt;  &lt;p&gt;Similarly we need encoding mechanisms to store large numeric integer values, real numbers which can represent fractions of a whole number etc. As you might have already realized, the data stored in a single memory location can be quite limiting having only 256 possible values. That is not much to work with, it might be fine for storing your age, but what about the population of a country? As with the example above where we used multiple memory locations to store a string, a similar solution can be found for storing larger numbers that will require multiple memory locations which when interpreted as a whole represent a larger numeric value. For example, using 4 memory locations we have a total of 32 bits of data which gives you 4,294,967,295 unique bit patterns which covers us for the population for any country in the world, we need to go even bigger if we want to store the entire population of the world however. &lt;/p&gt;  &lt;p&gt;The important thing here is that you know up front how to interpret the various pieces of information stored in the memory and how many bytes make up a single unit of information.&lt;/p&gt;  &lt;p&gt;As you can imagine, these encodings get quite complex, fortunately you rarely need to deal with these low level details, for the most part the details are nicely taken care of for us by the higher level tools that we use to write our software. &lt;/p&gt;  &lt;p&gt;The important take away from this post, is that more complex data representations can require multiple memory locations to store a single instance of data. &lt;/p&gt;  &lt;hr /&gt;  &lt;p&gt;&lt;a href="http://taylorza.blogspot.com/2011/07/practical-algorithms-and-data.html"&gt;Prev – Introduction&lt;/a&gt;&lt;/p&gt;  &lt;hr /&gt;  &lt;p&gt;* Notes: &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;The bit patterns are not random, they follow a numbering scheme known as the binary system. Read more about this &lt;a href="http://en.wikipedia.org/wiki/Binary_numeral_system"&gt;here&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;Interpreting the bit patterns as characters is done using a look-up table, in this case I have used the ASCII table which you can read more about &lt;a href="http://en.wikipedia.org/wiki/Ascii"&gt;here&lt;/a&gt;. &lt;/li&gt; &lt;/ol&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-2029591181925174781?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/VXBThnP2Kh0YKMVEEn7nXa7ExJ8/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/VXBThnP2Kh0YKMVEEn7nXa7ExJ8/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/VXBThnP2Kh0YKMVEEn7nXa7ExJ8/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/VXBThnP2Kh0YKMVEEn7nXa7ExJ8/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/a-zrhJBFGeQ" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://taylorza.blogspot.com/feeds/2029591181925174781/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://taylorza.blogspot.com/2011/09/practical-algorithms-and-data.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/2029591181925174781?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/2029591181925174781?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/a-zrhJBFGeQ/practical-algorithms-and-data.html" title="Practical Algorithms and Data Structures : Arrays–Part 1" /><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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh3.ggpht.com/-gm_dRZLjT08/TmY-tOnkNKI/AAAAAAAAAyE/YWRFac4P_3w/s72-c/String-in-memory_thumb1.png?imgmax=800" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2011/09/practical-algorithms-and-data.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C04DQHs9fCp7ImA9WhdWE0U.&quot;"><id>tag:blogger.com,1999:blog-4927779461366619687.post-8156669110721072984</id><published>2011-07-09T21:28:00.000+03:00</published><updated>2011-09-07T10:52:51.564+03:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-09-07T10:52:51.564+03:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Data Structures" /><category scheme="http://www.blogger.com/atom/ns#" term="Algoritms" /><title>Practical Algorithms and Data Structures : Introduction</title><content type="html">&lt;p&gt;Welcome to the first of hopefully many posts on Algorithms and Data Structures.&lt;/p&gt;  &lt;p&gt;One of the areas of computer science that I have always felt drawn to is the study of algorithms. That is not to say that I have developed any kind of specialized expertise in the field, but I do find it tremendously interesting and continuously strive to expand on my understanding and ability to apply algorithms effectively.&lt;/p&gt;  &lt;p&gt;For me at least, the best way to evolve my knowledge of a topic is to attempt to explain some aspect of the particular topic to someone else. On countless occasions I have found that by answering questions and having my explanations challenged, has enabled me to reach new levels of that “Aha” moment when suddenly a topic that I thought I understood just became that much clearer. &lt;/p&gt;  &lt;p&gt;Now you might be wondering why I would even bother writing something like this, especially given all the material out there covering this specific area. Well other than my selfish motivation to learn more in the process, I have also realized that so many developers today lack the basics in terms of even the simplest algorithms. They might know the terminology and sometimes not even that, but as soon as you start probing on the specifics of the algorithms, how to decide which algorithm to use under which circumstance etc. things start to go sideways.&lt;/p&gt;  &lt;p&gt;Why is it the case, that so many practicing developers today find themselves lacking in this area? Well I guess, the truth is that with all the excellent tooling and libraries accompanying&amp;#160; most languages and development platforms today, very few people need to actually delve into the depths of the algorithms and data structures they use. Everything is right there, got a list and want to find something in it, just call Find, Search, IndexOf or whatever function is documented to find an item in the list and be done with it. There is definitely nothing wrong with this, these libraries are professionally developed, robust and already used by thousands of developers so they are well QA’d. There is however tremendous value in having a good understanding of the algorithms and data structures you use. &lt;/p&gt;  &lt;p&gt;If you understand your data, and you know what it is you need to do with that data, the next step is selecting the most appropriate data structure to store your data. Algorithms and data structures are tightly coupled together, often the data structures you use to store your data will determine which algorithms can be used efficiently on the data. While most data structures can be searched, what will vary is how efficiently that search can be performed, depending on the underlying data structure or even the ordering of the data in the structure. Having an understanding of the various data structures and the corresponding algorithms can help you choose the most efficient way to work with your data and ensure your software does not buckle under the pressure of huge data volumes just because you selected the wrong data structure and/or algorithm to manipulate and manage your data. Selecting the right algorithm for the job often it the key to a successful outcome, but to do that you need to understand the pros and cons of what is available to you.&lt;/p&gt;  &lt;p&gt;With this series of blog posts I hope to share some of my learning's and at the same time gain a deeper level of understanding as we explore the algorithms and data structures together. I invite you to participate in this series, if you know a better way to implement something or have a better approach to explaining a specific algorithm, please share with us and help enrich our journey.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;&lt;font size="4"&gt;What are Data Structures?&lt;/font&gt;&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Data structures are the containers that you use to store and manage the data for your application.&lt;/p&gt;  &lt;p&gt;As we design and develop software, one of the decisions we need to make is what data types to use to store the application specific data. If we where developing a simple contact management system, in which we can enter contact information and later retrieve that information, we would need to define how the contacts would be represented internally within the system i.e. the data elements that represent a contact, such as first name, last name, address, email address, mobile number, date of birth etc. as well as the data types used to store each of these elements, how multiple contacts will be maintained and managed within the system, all of which help define the data structures that will be required to build a functional system. &lt;/p&gt;  &lt;p&gt;However simply looking at the data requirements is not always enough, we also need to look at the algorithms we intend to apply to these data structures, how will we manipulate the data, perform searches, sort the data etc.. As we will discover through this series, the intended algorithms will have a bearing on the data structures we might select to represent the data in the system.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;&lt;font size="4"&gt;What is an Algorithm?&lt;/font&gt;&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;An algorithm is a recipe or set of instructions that can be followed to solve a specific type of problem. &lt;/p&gt;  &lt;p&gt;Assume we have chosen to store our contacts from earlier in a list in which we can access each contact by walking through the list item by item, like paging through a book. We now need to find an algorithm we can use to search through the list to locate a contact by last name. How would you go about that? Given what we know about the data structure, the obvious solution would be to iterate through the list of contacts comparing the last name element to the search key. If you find a match you can stop the iteration and return the instance of the contact that was found, otherwise if you reach the end of the list and no match was found you return some indication that the contact does not exist. These steps describe what is known as a Sequential Search.&lt;/p&gt;  &lt;p&gt;There are situations where using the simple Sequential Search algorithm might not be the best option and could severely hurt the performance of your system. For example, if the list in question contained a significant number of items and you need to perform frequent searches to determine the existence of an item in the list, this could quickly become a bottleneck. Every time we search for an item that does not exist, we will be iterating through the entire list just to determine that the item does not exist, in the best case the item we are searching for is found quickly within the first few items of the list, while on other occasions the item might only be found towards the end of the list. We will look at this in a little more depth in the section on Big-O notation.&lt;/p&gt;  &lt;p&gt;Let’s look at one possible alternative, we could use a Binary Search. This algorithm can be significantly more efficient than a Sequential Search, especially in the worst case scenarios where the item being searched is either not in the list or it exists far from the beginning of the list. However, to be able to use the Binary Search, the collection of items will need to conform to the basic requirements of the Binary Search.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;The list of items must be sorted &lt;/li&gt;    &lt;li&gt;The list structure must support what is often called random access. i.e. we should be able to access item 83 in a list of 100 items without needing to iterate over the first 82 items. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Given the above constraints are met, for the moment we will ignore the cost of ensuring the data is sorted, while not insignificant, for the purposes of the discussion we will choose to ignore it for now, we can use the Binary Search algorithm to introduce some significant optimization. &lt;/p&gt;  &lt;p&gt;Here is a quick introductory example of the basics of the Binary Search algorithm.&lt;/p&gt;  &lt;p&gt;First you select the item in the middle of the list, in a list of 100 items that will be item 50. Now compare item 50 (the midpoint item) to the search key, if it is a match we can terminate the search and return item, if the search key is greater than the midpoint item then we know that, &lt;strong&gt;if the item exists&lt;/strong&gt;, it must be in the second half of the list. We know this because the list is sorted, therefore if the the search key is greater than the midpoint item, if must be greater than all the items preceding the midpoint item. And visa versa, if the search key is less than the midpoint item, then a potentially matching item would be in the first half of the list. Can you see how with a single comparison we have eliminated half of the items to be searched?&lt;/p&gt;  &lt;p&gt;Having determined which half of the list the item might be in, you can repeat the same logic on that subset of the data. Having narrowed the list of items down to a subset of 50, you can again select the midpoint item and compare it to the search key, which will either be a match or indicate that the search key potentially exists in the top or bottom half of the subset. After 2 comparisons we have eliminated roughly 75% of the items to be searched. You can continue until you either find the item or run out of items to search which would indicate that the item does not exist in the list.&lt;/p&gt;  &lt;p&gt;We will cover both the Sequential and Binary Search in more detail later, for now I just want to use this to demonstrate how selecting the right algorithm for the job can make a difference and how the nature of the data might influence the algorithms you can use. And it also leads us into the next topic and that is Big-O notation.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;&lt;font size="4"&gt;Big-O notation&lt;/font&gt;&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;I am sure you have at some point seen or read about Big-O notation even if you did not know what it meant. If you spent anytime reading about algorithms you might have seen something like the following &lt;strong&gt;O(n)&lt;/strong&gt;, &lt;strong&gt;O(log n)&lt;/strong&gt; or &lt;strong&gt;O(n&lt;sup&gt;3&lt;/sup&gt;)&lt;/strong&gt;. And if you wondered what it all means, I will try to give a very brief non-mathematical description of how you can make some basic sense of this notation.&lt;/p&gt;  &lt;p&gt;When selecting an algorithm there are a number of factors that you might have to take into consideration. For desktops or server based applications your primary criteria might be performance, where you want to select the algorithm that is going to give you the best performance regardless of the amount of memory the algorithm requires to be executed. On the other hand, on mobile devices you might be more concerned about the memory requirements of a particular algorithm. In either case, we need some way to represent this these characteristics of an algorithm, this representation needs to be simple enough that just by looking at it I can tell if one algorithm will perform better than another or if it will be more memory efficient without needing to read or understand the complex mathematical analysis of each algorithm. For our purposes we will focus on the performance aspect and discuss the memory aspect later when we work with actual algorithms.&lt;/p&gt;  &lt;p&gt;Big-O notation gives us a concise notation that captures the performance characteristics of an algorithm over a collection of items. Basically we can see at a glace if the algorithm performance will degrade rapidly, linearly or gradually as the number of items in the collection increases. Of course as we saw earlier algorithms have best case scenarios as well as worst case scenarios, Big-O notation represents the average case, so looking at the Big-O for a Binary Search I can say that on average the Binary Search will out perform a Sequential Search. That does not mean it will always out perform the Sequential Search, remember, if the matching item is first in the list the Sequential Search will find it immediately, while the Binary Search will need to perform a few iterations before finding that the first item is the matching item, but on average we would expect that the Binary Search will perform better for real world searches. &lt;/p&gt;  &lt;p&gt;Using Big-O notation, the Sequential Search would be described as an &lt;strong&gt;O(n)&lt;/strong&gt; algorithm, where &lt;strong&gt;&lt;em&gt;n&lt;/em&gt;&lt;/strong&gt; represents the number of items the algorithm will be working with. If we searched a list of 10 items then &lt;strong&gt;&lt;em&gt;n=10&lt;/em&gt;&lt;/strong&gt; and if we searched a list of 1000 items then &lt;strong&gt;&lt;em&gt;n=1000.&lt;/em&gt;&lt;/strong&gt; From this we can conclude that on average the algorithm performs linearly, if we double the number of items the average search time will double, so the relationship between the number of items and the execution time is linear.&lt;/p&gt;  &lt;p&gt;How does that compare to our Binary Search algorithm, well without getting into the details now, I will tell you that a Binary Search is an&lt;strong&gt; O(log n)&lt;/strong&gt; algorithm. This means that as the number of items increase the execution time increases logarithmically. Mathematically &lt;strong&gt;log(n) &lt;/strong&gt;&amp;lt; &lt;strong&gt;n&lt;/strong&gt; were &lt;strong&gt;n &lt;/strong&gt;is a positive integer&lt;strong&gt; &lt;/strong&gt;(see the table below), therefore we can say that Binary Search is faster than a Sequential search. &lt;/p&gt;  &lt;p&gt;Lets look a quick analysis, if the item that I am searching for is the first item in a list of 1,000,000 items then the Sequential Search will clearly out perform the Binary Search which is going to jump to the middle of the list, see that the item is in the first half of the list and half that portion and so on for a total of 20 comparisons before locating the target item at the beginning of the list. However if the item being searched was the last item in the list then the Sequential Search would require 1,000,000 comparisons while the Binary Search worst case would not be more than 20 comparisons. So the worst case of the Binary Search of a collection of sorted items is 20 comparisons while the sequential search will exceed this worst case for when searching of any of the 999 980 that are after the first 20 items in the list.&lt;/p&gt;  &lt;p&gt;What we have seen here is that the Sequential Search has a best case execution of &lt;strong&gt;O(1)&lt;/strong&gt;, that is constant time regardless of the number of items in the list, of course this is the absolute best case when you are lucky enough to have the item you are looking for be the first item in the list. While the worst case if the item is the last item or the item does not exist at all will be O(n) which is also the average case. &lt;/p&gt;  &lt;p&gt;The Binary Search also has a best case scenario of O(1), that is when the item you are searching for happens to be the item in the middle of the list, in which case the item would be found on the first comparison, but the average case is O(log n).&lt;/p&gt;  &lt;table border="1" cellspacing="0" cellpadding="2" width="503"&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;td valign="top" width="80"&gt;&lt;strong&gt;n&lt;/strong&gt;&lt;/td&gt;        &lt;td valign="top" width="80"&gt;&lt;strong&gt;O(1)&lt;/strong&gt;&lt;/td&gt;        &lt;td valign="top" width="80"&gt;&lt;strong&gt;O(n)&lt;/strong&gt;&lt;/td&gt;        &lt;td valign="top" width="76"&gt;&lt;strong&gt;O(log n)&lt;/strong&gt;&lt;/td&gt;        &lt;td valign="top" width="80"&gt;&lt;strong&gt;O(n log n)&lt;/strong&gt;&lt;/td&gt;        &lt;td valign="top" width="105"&gt;&lt;strong&gt;O(n&lt;sup&gt;2&lt;/sup&gt;)&lt;/strong&gt;&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td&gt;1&lt;/td&gt;        &lt;td&gt;1&lt;/td&gt;        &lt;td&gt;1&lt;/td&gt;        &lt;td&gt;0&lt;/td&gt;        &lt;td&gt;0&lt;/td&gt;        &lt;td&gt;1&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td&gt;10&lt;/td&gt;        &lt;td&gt;1&lt;/td&gt;        &lt;td&gt;10&lt;/td&gt;        &lt;td&gt;3.32&lt;/td&gt;        &lt;td&gt;33.22&lt;/td&gt;        &lt;td&gt;100&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td&gt;100&lt;/td&gt;        &lt;td&gt;1&lt;/td&gt;        &lt;td&gt;100&lt;/td&gt;        &lt;td&gt;6.64&lt;/td&gt;        &lt;td&gt;664.39&lt;/td&gt;        &lt;td&gt;10000&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td&gt;1000&lt;/td&gt;        &lt;td&gt;1&lt;/td&gt;        &lt;td&gt;1000&lt;/td&gt;        &lt;td&gt;9.97&lt;/td&gt;        &lt;td&gt;9965.78&lt;/td&gt;        &lt;td&gt;1000000&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td&gt;10000&lt;/td&gt;        &lt;td&gt;1&lt;/td&gt;        &lt;td&gt;10000&lt;/td&gt;        &lt;td&gt;13.29&lt;/td&gt;        &lt;td&gt;132877.12&lt;/td&gt;        &lt;td&gt;100000000&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td&gt;100000&lt;/td&gt;        &lt;td&gt;1&lt;/td&gt;        &lt;td&gt;100000&lt;/td&gt;        &lt;td&gt;16.61&lt;/td&gt;        &lt;td&gt;1660964.05&lt;/td&gt;        &lt;td&gt;10000000000&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td&gt;1000000&lt;/td&gt;        &lt;td&gt;1&lt;/td&gt;        &lt;td&gt;1000000&lt;/td&gt;        &lt;td&gt;19.93&lt;/td&gt;        &lt;td&gt;19931568.57&lt;/td&gt;        &lt;td&gt;1000000000000&lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;Looking at the above table you see a comparison of some Big-O representations for various values of &lt;strong&gt;n&lt;/strong&gt;. This should give you a feel for how one algorithm would perform relative to another based on the Big-O of the algorithm. The best general purpose sorting algorithms today are &lt;strong&gt;O(n log n)&lt;/strong&gt; algorithms.&lt;/p&gt;  &lt;p&gt;Given the speed of computers today, even the worst performing algorithms will appear to perform efficiently for small values of n. That is why it is very important to understand the volume of data that your system might need to work with and make sure you test with volumes that are representative of what you expect to see in the production environment.&lt;/p&gt;  &lt;p&gt;When selecting your algorithms, make sure that you fully grasp the context in which the algorithm will be used and how that scope might change overtime as your system hopefully becomes more and more popular.&lt;/p&gt;  &lt;p&gt;If you would like to see a visual representation of the table above take a look at my &lt;a href="http://taylorza.blogspot.com/2010/12/visualizing-big-o-complexity-functions.html"&gt;Big-O Visualizer&lt;/a&gt;. Note this application requires Silverlight 4. &lt;/p&gt;  &lt;hr /&gt;  &lt;p&gt;&lt;a href="http://taylorza.blogspot.com/2011/09/practical-algorithms-and-data.html"&gt;Next: Arrays – Part 1&lt;/a&gt;&lt;/p&gt;  &lt;hr /&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-8156669110721072984?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/wDoAO_lyJxRJShsgjJG7FCrhnwM/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/wDoAO_lyJxRJShsgjJG7FCrhnwM/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/wDoAO_lyJxRJShsgjJG7FCrhnwM/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/wDoAO_lyJxRJShsgjJG7FCrhnwM/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/rQSivf0qy1k" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://taylorza.blogspot.com/feeds/8156669110721072984/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://taylorza.blogspot.com/2011/07/practical-algorithms-and-data.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/8156669110721072984?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/8156669110721072984?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/rQSivf0qy1k/practical-algorithms-and-data.html" title="Practical Algorithms and Data Structures : Introduction" /><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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2011/07/practical-algorithms-and-data.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0UERnwzfSp7ImA9WhdXEU8.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2011-08-23T20:40:07.285+03:00</app:edited><title>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="silverlightControlHost" style="height:400px"&gt;&lt;object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%"&gt;     &lt;param name="source" value="http://dotnetwarrior.com/Silverlight/BigOVisualizer/BigOVisualizer.xap"/&gt;&lt;param name="onError" value="onSilverlightError" /&gt;&lt;param name="background" value="white" /&gt;&lt;param name="minRuntimeVersion" value="4.0.50826.0" /&gt;&lt;param name="maxFrameRate" value="10" /&gt;&lt;param name="autoUpgrade" value="true" /&gt;&lt;a href="http://go.microsoft.com/fwlink/?LinkID=149156&amp;v=4.0.50826.0" style="text-decoration:none"&gt;       &lt;img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/&gt;     &lt;/a&gt;      &lt;/object&gt;&lt;iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"&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="http://www.go-mono.com/moonlight/prerelease.aspx"&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="http://en.wikipedia.org/wiki/Big_O_notation"&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;table border="1"&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="http://en.wikipedia.org/wiki/Array_data_structure"&gt;Array direct indexing&lt;/a&gt;, &lt;a href="http://en.wikipedia.org/wiki/Hash_table"&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="http://en.wikipedia.org/wiki/Sequential_search"&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="http://en.wikipedia.org/wiki/Binary_search_algorithm"&gt;Binary Search&lt;/a&gt; on sorted data, Lookup in &lt;a href="http://en.wikipedia.org/wiki/Red-black_tree"&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="http://en.wikipedia.org/wiki/Heapsort"&gt;Heap Sort&lt;/a&gt;, &lt;a href="http://en.wikipedia.org/wiki/Merge_sort"&gt;Merge Sort&lt;/a&gt;, &lt;a href="http://en.wikipedia.org/wiki/Quicksort"&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="http://en.wikipedia.org/wiki/Bubble_sort"&gt;Bubble Sort&lt;/a&gt;, &lt;a href="http://en.wikipedia.org/wiki/Insertion_sort"&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="http://en.wikipedia.org/wiki/Traveling_salesman_problem"&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;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-8892447985346793041?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/aa_wKqGJU87QnYJT5iGclwlSFBI/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/aa_wKqGJU87QnYJT5iGclwlSFBI/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/aa_wKqGJU87QnYJT5iGclwlSFBI/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/aa_wKqGJU87QnYJT5iGclwlSFBI/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/6MItpFyrU0s" height="1" width="1"/&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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/8892447985346793041?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/6MItpFyrU0s/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2010/12/visualizing-big-o-complexity-functions.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DEQHRH88fCp7ImA9Wx5WE0s.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2010-09-25T01:12:15.174+03:00</app:edited><title>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="http://stackoverflow.com/questions/3788399/find-contentplaceholders-in-master-page/3788493#3788493"&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="http://msdn.microsoft.com/en-us/library/system.web.ui.templatecontrol.aspx"&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="codeSnippetWrapper"&gt;   &lt;pre style="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" id="codeSnippet"&gt;var site1Master = LoadControl(&lt;span style="color: #006080"&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="codeSnippetWrapper"&gt;&lt;br /&gt;  &lt;pre style="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" id="codeSnippet"&gt;&lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; WebHelper&lt;br /&gt;{&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&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="color: #0000ff"&gt;where&lt;/span&gt; T : Control&lt;br /&gt;  {&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (root == &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;) &lt;span style="color: #0000ff"&gt;throw&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; ArgumentNullException(&lt;span style="color: #006080"&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="color: #0000ff"&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="color: #0000ff"&gt;return&lt;/span&gt; controls;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&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="color: #0000ff"&gt;where&lt;/span&gt; T : Control&lt;br /&gt;  {&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (Control control &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; root.Controls)&lt;br /&gt;    {&lt;br /&gt;      &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (control &lt;span style="color: #0000ff"&gt;is&lt;/span&gt; T)&lt;br /&gt;      {&lt;br /&gt;        controls.Add(control &lt;span style="color: #0000ff"&gt;as&lt;/span&gt; T);&lt;br /&gt;      }&lt;br /&gt;      &lt;span style="color: #0000ff"&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="codeSnippetWrapper"&gt;&lt;br /&gt;  &lt;pre style="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" id="codeSnippet"&gt;&lt;span style="color: #008000"&gt;// Load the Master Page&lt;/span&gt;&lt;br /&gt;var site1Master = LoadControl(&lt;span style="color: #006080"&gt;&amp;quot;Site1.Master&amp;quot;&lt;/span&gt;);&lt;br /&gt;&lt;br /&gt;&lt;span style="color: #008000"&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="color: #008000"&gt;// Do something with each control that was found&lt;/span&gt;&lt;br /&gt;&lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (var control &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; controls)&lt;br /&gt;{&lt;br /&gt;  Response.Write(control.ClientID);&lt;br /&gt;  Response.Write(&lt;span style="color: #006080"&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;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-456160839185215831?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/vNw7VVBXBRP1tcw_ZmOuFG9_dn0/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/vNw7VVBXBRP1tcw_ZmOuFG9_dn0/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/vNw7VVBXBRP1tcw_ZmOuFG9_dn0/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/vNw7VVBXBRP1tcw_ZmOuFG9_dn0/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/XUYbOTNRYbU" height="1" width="1"/&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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/456160839185215831?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/XUYbOTNRYbU/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2010/09/code-share-finding-controls-by-control.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEQAQ3Y_eip7ImA9WxFUFkg.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2010-06-27T18:25:42.842+03:00</app:edited><title>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="codeSnippetWrapper"&gt;   &lt;pre style="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" id="codeSnippet"&gt;&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System;&lt;br /&gt;&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System.Runtime.InteropServices;&lt;br /&gt;&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System.Text;&lt;br /&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; CrossProcessMemory&lt;br /&gt;{&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; LVM_GETITEM = 0x1005;&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; LVM_SETITEM = 0x1006;&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; LVIF_TEXT   = 0x0001;&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; &lt;span style="color: #0000ff"&gt;uint&lt;/span&gt; PROCESS_ALL_ACCESS = (&lt;span style="color: #0000ff"&gt;uint&lt;/span&gt;)(0x000F0000L | 0x00100000L | 0xFFF);&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; &lt;span style="color: #0000ff"&gt;uint&lt;/span&gt; MEM_COMMIT         = 0x1000;&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; &lt;span style="color: #0000ff"&gt;uint&lt;/span&gt; MEM_RELEASE        = 0x8000;&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; &lt;span style="color: #0000ff"&gt;uint&lt;/span&gt; PAGE_READWRITE     = 0x04;&lt;br /&gt;&lt;br /&gt;  [DllImport(&lt;span style="color: #006080"&gt;&amp;quot;user32.dll&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;extern&lt;/span&gt; &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; SendMessage(IntPtr hWnd, Int32 msg, Int32 wParam, IntPtr lParam);&lt;br /&gt;  &lt;br /&gt;  [DllImport(&lt;span style="color: #006080"&gt;&amp;quot;user32&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;extern&lt;/span&gt; IntPtr GetWindowThreadProcessId( IntPtr hWnd, &lt;span style="color: #0000ff"&gt;out&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; lpwdProcessID );    &lt;br /&gt;  &lt;br /&gt;  [DllImport(&lt;span style="color: #006080"&gt;&amp;quot;kernel32&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;extern&lt;/span&gt; IntPtr OpenProcess(&lt;span style="color: #0000ff"&gt;uint&lt;/span&gt; dwDesiredAccess, &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; bInheritHandle, &lt;br /&gt;    &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; dwProcessId);&lt;br /&gt;&lt;br /&gt;  [DllImport(&lt;span style="color: #006080"&gt;&amp;quot;kernel32&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;extern&lt;/span&gt; IntPtr VirtualAllocEx( IntPtr hProcess, IntPtr lpAddress, &lt;br /&gt;    &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; dwSize, &lt;span style="color: #0000ff"&gt;uint&lt;/span&gt; flAllocationType, &lt;span style="color: #0000ff"&gt;uint&lt;/span&gt; flProtect);&lt;br /&gt;&lt;br /&gt;  [DllImport(&lt;span style="color: #006080"&gt;&amp;quot;kernel32&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;extern&lt;/span&gt; &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; VirtualFreeEx( IntPtr hProcess, IntPtr lpAddress, &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; dwSize, &lt;br /&gt;    &lt;span style="color: #0000ff"&gt;uint&lt;/span&gt; dwFreeType );&lt;br /&gt;&lt;br /&gt;  [DllImport(&lt;span style="color: #006080"&gt;&amp;quot;kernel32&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;extern&lt;/span&gt; &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; WriteProcessMemory( IntPtr hProcess, IntPtr lpBaseAddress, &lt;br /&gt;    &lt;span style="color: #0000ff"&gt;ref&lt;/span&gt; LV_ITEM buffer, &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; dwSize, IntPtr lpNumberOfBytesWritten );&lt;br /&gt;&lt;br /&gt;  [DllImport(&lt;span style="color: #006080"&gt;&amp;quot;kernel32&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;extern&lt;/span&gt; &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; ReadProcessMemory( IntPtr hProcess, IntPtr lpBaseAddress, &lt;br /&gt;    IntPtr lpBuffer, &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; dwSize, IntPtr lpNumberOfBytesRead );&lt;br /&gt;&lt;br /&gt;  [DllImport(&lt;span style="color: #006080"&gt;&amp;quot;kernel32&amp;quot;&lt;/span&gt;)]&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;extern&lt;/span&gt; &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; CloseHandle( IntPtr hObject );&lt;br /&gt;&lt;br /&gt;  [StructLayout(LayoutKind.Sequential)]&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;struct&lt;/span&gt; LV_ITEM&lt;br /&gt;  {&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;uint&lt;/span&gt;   mask; &lt;br /&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt;    iItem; &lt;br /&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt;    iSubItem; &lt;br /&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;uint&lt;/span&gt;   state; &lt;br /&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;uint&lt;/span&gt;   stateMask; &lt;br /&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; IntPtr pszText; &lt;br /&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt;    cchTextMax; &lt;br /&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt;    iImage;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; ReadListViewItem( IntPtr hWnd, &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; item )&lt;br /&gt;  {&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; dwBufferSize = 1024;&lt;br /&gt;          &lt;br /&gt;    &lt;span style="color: #0000ff"&gt;int&lt;/span&gt;         dwProcessID;&lt;br /&gt;    LV_ITEM     lvItem;      &lt;br /&gt;    &lt;span style="color: #0000ff"&gt;string&lt;/span&gt;      retval;&lt;br /&gt;    &lt;span style="color: #0000ff"&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="color: #0000ff"&gt;try&lt;/span&gt;&lt;br /&gt;    {&lt;br /&gt;      lvItem = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; LV_ITEM();&lt;br /&gt;      lpLocalBuffer = Marshal.AllocHGlobal(dwBufferSize);&lt;br /&gt;      &lt;span style="color: #008000"&gt;// Get the process id owning the window&lt;/span&gt;&lt;br /&gt;      threadId = GetWindowThreadProcessId( hWnd, &lt;span style="color: #0000ff"&gt;out&lt;/span&gt; dwProcessID );&lt;br /&gt;      &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; ( (threadId == IntPtr.Zero) || (dwProcessID == 0) )&lt;br /&gt;        &lt;span style="color: #0000ff"&gt;throw&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; ArgumentException( &lt;span style="color: #006080"&gt;&amp;quot;hWnd&amp;quot;&lt;/span&gt; );&lt;br /&gt;&lt;br /&gt;      &lt;span style="color: #008000"&gt;// Open the process with all access&lt;/span&gt;&lt;br /&gt;      hProcess = OpenProcess( PROCESS_ALL_ACCESS, &lt;span style="color: #0000ff"&gt;false&lt;/span&gt;, dwProcessID );&lt;br /&gt;      &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; ( hProcess == IntPtr.Zero )&lt;br /&gt;        &lt;span style="color: #0000ff"&gt;throw&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; ApplicationException( &lt;span style="color: #006080"&gt;&amp;quot;Failed to access process&amp;quot;&lt;/span&gt; );&lt;br /&gt;&lt;br /&gt;      &lt;span style="color: #008000"&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="color: #0000ff"&gt;if&lt;/span&gt; ( lpRemoteBuffer == IntPtr.Zero )&lt;br /&gt;        &lt;span style="color: #0000ff"&gt;throw&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; SystemException( &lt;span style="color: #006080"&gt;&amp;quot;Failed to allocate memory in remote process&amp;quot;&lt;/span&gt; );&lt;br /&gt;      &lt;br /&gt;      &lt;span style="color: #008000"&gt;// Fill in the LVITEM struct, this is in your own process&lt;/span&gt;&lt;br /&gt;      &lt;span style="color: #008000"&gt;// Set the pszText member to somewhere in the remote buffer,&lt;/span&gt;&lt;br /&gt;      &lt;span style="color: #008000"&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="color: #0000ff"&gt;typeof&lt;/span&gt;(LV_ITEM)));&lt;br /&gt;      lvItem.cchTextMax = 50;&lt;br /&gt;&lt;br /&gt;      &lt;span style="color: #008000"&gt;// Copy the local LVITEM to the remote buffer&lt;/span&gt;&lt;br /&gt;      bSuccess = WriteProcessMemory( hProcess, lpRemoteBuffer, &lt;span style="color: #0000ff"&gt;ref&lt;/span&gt; lvItem, &lt;br /&gt;        Marshal.SizeOf(&lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(LV_ITEM)), IntPtr.Zero );&lt;br /&gt;      &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; ( !bSuccess )&lt;br /&gt;        &lt;span style="color: #0000ff"&gt;throw&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; SystemException( &lt;span style="color: #006080"&gt;&amp;quot;Failed to write to process memory&amp;quot;&lt;/span&gt; );&lt;br /&gt;&lt;br /&gt;      &lt;span style="color: #008000"&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="color: #008000"&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="color: #0000ff"&gt;if&lt;/span&gt; ( !bSuccess )&lt;br /&gt;        &lt;span style="color: #0000ff"&gt;throw&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; SystemException( &lt;span style="color: #006080"&gt;&amp;quot;Failed to read from process memory&amp;quot;&lt;/span&gt; );&lt;br /&gt;      &lt;br /&gt;      &lt;span style="color: #008000"&gt;// At this point the lpLocalBuffer contains the returned LV_ITEM structure&lt;/span&gt;&lt;br /&gt;      &lt;span style="color: #008000"&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="color: #0000ff"&gt;typeof&lt;/span&gt;(LV_ITEM))));&lt;br /&gt;    }&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;finally&lt;/span&gt;&lt;br /&gt;    { &lt;br /&gt;      &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; ( lpLocalBuffer != IntPtr.Zero )&lt;br /&gt;        Marshal.FreeHGlobal( lpLocalBuffer );&lt;br /&gt;      &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; ( lpRemoteBuffer != IntPtr.Zero )&lt;br /&gt;        VirtualFreeEx( hProcess, lpRemoteBuffer, 0, MEM_RELEASE ); &lt;br /&gt;      &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; ( hProcess != IntPtr.Zero )&lt;br /&gt;        CloseHandle( hProcess );&lt;br /&gt;    }&lt;br /&gt;    &lt;span style="color: #0000ff"&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;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-6902220327516819781?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/NEGag-XOlGzB44LACYq7ZINDtfY/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/NEGag-XOlGzB44LACYq7ZINDtfY/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/NEGag-XOlGzB44LACYq7ZINDtfY/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/NEGag-XOlGzB44LACYq7ZINDtfY/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/eyWwL-cXd3U" height="1" width="1"/&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="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/6902220327516819781?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/6902220327516819781?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/eyWwL-cXd3U/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>1</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2010/06/crossing-process-boundary-with-net.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0AGR3szcSp7ImA9WxFWGEw.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2010-06-06T11:08:46.589+03:00</app:edited><title>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="http://www.youtube.com/watch?v=qp2WuJ2rEE4"&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;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-7082894442411206270?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/5Vr-ljfRS3nkpMk87omXnDPwrlY/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/5Vr-ljfRS3nkpMk87omXnDPwrlY/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/5Vr-ljfRS3nkpMk87omXnDPwrlY/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/5Vr-ljfRS3nkpMk87omXnDPwrlY/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/FNo7FZweVas" height="1" width="1"/&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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/7082894442411206270?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/FNo7FZweVas/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2010/06/visual-studio-2010-box-selection.html</feedburner:origLink></entry><entry gd:etag="W/&quot;Dk4FSXs5fyp7ImA9WxFSFU0.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2010-04-17T14:48:38.527+03:00</app:edited><title>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="codeSnippetWrapper"&gt;&lt;pre id="codeSnippet" class="csharpcode"&gt;[StructLayout(LayoutKind.Sequential, Pack = 1)]
&lt;span class="kwrd"&gt;struct&lt;/span&gt; DBFHeader
{
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt; Tag;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt; Year;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt; Month;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt; Day; 
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; RecCount;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;short&lt;/span&gt; HeaderSize;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;short&lt;/span&gt; RecSize;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;short&lt;/span&gt; Reserved1;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt; Trans;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt; Encrypt;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;long&lt;/span&gt; Reserved2_1;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;short&lt;/span&gt; Reserved2_2;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt; MDX;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt; LangId;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&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="codeSnippetWrapper"&gt;&lt;pre id="codeSnippet" class="csharpcode"&gt;DBFHeader hdr = &lt;span class="kwrd"&gt;new&lt;/span&gt; DBFHeader(); 
&lt;span class="kwrd"&gt;byte&lt;/span&gt;[] data = &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt;[Marshal.SizeOf(hdr)];
&lt;span class="kwrd"&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="codeSnippetWrapper"&gt;&lt;pre id="codeSnippet" class="csharpcode"&gt;DBFHeader hdr = &lt;span class="kwrd"&gt;new&lt;/span&gt; DBFHeader(); 
&lt;span class="kwrd"&gt;byte&lt;/span&gt;[] data = &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt;[Marshal.SizeOf(hdr)];
IntPtr p = Marshal.AllocHGlobal( Marshal.SizeOf(hdr) );
Marshal.StructureToPtr( hdr, p, &lt;span class="kwrd"&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="codeSnippetWrapper"&gt;&lt;pre id="codeSnippet" class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; (BinaryWriter wr = &lt;span class="kwrd"&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;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-909388696117524541?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/nZbg36CnL8MvMx5yw_kFV6vyUlw/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/nZbg36CnL8MvMx5yw_kFV6vyUlw/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/nZbg36CnL8MvMx5yw_kFV6vyUlw/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/nZbg36CnL8MvMx5yw_kFV6vyUlw/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/U64mO6yVfD8" height="1" width="1"/&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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/909388696117524541?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/U64mO6yVfD8/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2010/04/archive-binary-data-from-structure.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DkAASXo4fCp7ImA9WxFSFU0.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2010-04-17T14:45:48.434+03:00</app:edited><title>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="codeSnippetWrapper"&gt;&lt;pre id="codeSnippet" class="csharpcode"&gt;[StructLayout(LayoutKind.Sequential, Pack = 1)]
&lt;span class="kwrd"&gt;struct&lt;/span&gt; IpHeader
{
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt; VerLen;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt; TOS;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;short&lt;/span&gt; TotalLength; 
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;short&lt;/span&gt; ID;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;short&lt;/span&gt; Offset;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt; TTL;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;byte&lt;/span&gt; Protocol;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;short&lt;/span&gt; Checksum;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; SrcAddr;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&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="codeSnippetWrapper"&gt;&lt;pre id="codeSnippet" class="csharpcode"&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="codeSnippetWrapper"&gt;&lt;pre id="codeSnippet" class="csharpcode"&gt;IpHeader iphdr;
&lt;span class="kwrd"&gt;unsafe&lt;/span&gt;
{
  &lt;span class="kwrd"&gt;fixed&lt;/span&gt; ( &lt;span class="kwrd"&gt;byte&lt;/span&gt; *pData = packet)
  {
    iphdr = *(IpHeader*)pData;
  }
}
&lt;span class="rem"&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="codeSnippetWrapper"&gt;&lt;pre id="codeSnippet" class="csharpcode"&gt;IntPtr pIP = Marshal.AllocHGlobal( len );
Marshal.Copy( packet, 0, pIP, len );
iphdr = (IpHeader)Marshal.PtrToStructure( pIP, &lt;span class="kwrd"&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="codeSnippetWrapper"&gt;&lt;pre id="codeSnippet" class="csharpcode"&gt;System.IO.MemoryStream stm = &lt;span class="kwrd"&gt;new&lt;/span&gt; System.IO.MemoryStream( packet, 0, len );
System.IO.BinaryReader rdr = &lt;span class="kwrd"&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="codeSnippetWrapper"&gt;&lt;pre id="codeSnippet" class="csharpcode"&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="codeSnippetWrapper"&gt;&lt;pre id="codeSnippet" class="csharpcode"&gt;IpHeader iphdr = IpHeader.FromPacket( packet, len );&lt;/pre&gt;Or&lt;/div&gt;&lt;div id="codeSnippetWrapper"&gt;&lt;pre id="codeSnippet" class="csharpcode"&gt;IpHeader iphdr = &lt;span class="kwrd"&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;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-2929360607743542059?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/1KcUmpiqVCrok6J5Yit6WCi2WaA/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/1KcUmpiqVCrok6J5Yit6WCi2WaA/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/1KcUmpiqVCrok6J5Yit6WCi2WaA/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/1KcUmpiqVCrok6J5Yit6WCi2WaA/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/-WGFYc5IrlQ" height="1" width="1"/&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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/2929360607743542059?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/-WGFYc5IrlQ/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2010/04/archive-structure-from-binary-data.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A0cASHg6eip7ImA9WxNUFk0.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2009-11-07T17:50:49.612+02:00</app:edited><title>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="codeSnippetWrapper" class="csharpcode-wrapper"&gt;   &lt;pre id="codeSnippet" class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] GetWindowsIdentityRoles(WindowsIdentity identity)&lt;br /&gt;{&lt;br /&gt;  &lt;span class="kwrd"&gt;if&lt;/span&gt; (identity == &lt;span class="kwrd"&gt;null&lt;/span&gt;) &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class="str"&gt;&amp;quot;identity&amp;quot;&lt;/span&gt;);&lt;br /&gt;&lt;br /&gt;  IdentityReferenceCollection groups = identity.Groups.Translate(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(NTAccount));&lt;br /&gt;  &lt;span class="kwrd"&gt;string&lt;/span&gt;[] roles = &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[groups.Count]; &lt;br /&gt;  &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&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="kwrd"&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="codeSnippetWrapper" class="csharpcode-wrapper"&gt;&lt;br /&gt;  &lt;pre id="codeSnippet" class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] GetWindowsIdentityRoles( WindowsIdentity identity )&lt;br /&gt;{&lt;br /&gt;  &lt;span class="kwrd"&gt;object&lt;/span&gt; result = &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(WindowsIdentity).InvokeMember( &lt;span class="str"&gt;&amp;quot;_GetRoles&amp;quot;&lt;/span&gt;,&lt;br /&gt;    BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.NonPublic,&lt;br /&gt;    &lt;span class="kwrd"&gt;null&lt;/span&gt;, identity, &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt;[]{identity.Token}, &lt;span class="kwrd"&gt;null&lt;/span&gt; );&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;return&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt;[])result; &lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;  &lt;br /&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-3540321462958306424?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/L9VD6dUUy4wNzrY1F1TBmBGJLkY/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/L9VD6dUUy4wNzrY1F1TBmBGJLkY/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/L9VD6dUUy4wNzrY1F1TBmBGJLkY/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/L9VD6dUUy4wNzrY1F1TBmBGJLkY/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/eNgGJeLDq6c" height="1" width="1"/&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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/3540321462958306424?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/eNgGJeLDq6c/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2009/11/archive-debugging-windowsidentity-and.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEQDRng-cCp7ImA9WxNbE0w.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2009-11-15T21:12:57.658+02:00</app:edited><title>Archive - Thread Local Storage in .NET</title><content type="html">&lt;span style="color: blue;"&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="csharpcode-wrapper"&gt;&lt;pre class="csharpcode" id="codeSnippet"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Class1
{
&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
{
System.Threading.Thread t1 = &lt;span class="kwrd"&gt;new&lt;/span&gt; System.Threading.Thread(&lt;span class="kwrd"&gt;new&lt;/span&gt; System.Threading.ThreadStart(ThreadFunction));
System.Threading.Thread t2 = &lt;span class="kwrd"&gt;new&lt;/span&gt; System.Threading.Thread(&lt;span class="kwrd"&gt;new&lt;/span&gt; System.Threading.ThreadStart(ThreadFunction));

&lt;span class="rem"&gt;// Start the threads&lt;/span&gt;
t1.Start();
t2.Start();

&lt;span class="rem"&gt;// Wait for the threads to complete&lt;/span&gt;
t1.Join();
t2.Join();

System.Console.Read();
} 

&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; PerThreadCallCounterKey = &lt;span class="str"&gt;"CallCounter"&lt;/span&gt;;
&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Random Rnd = &lt;span class="kwrd"&gt;new&lt;/span&gt; Random();

&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; ThreadFunction()
{
&lt;span class="rem"&gt;// Initialize the per-thread CallCounter&lt;/span&gt;
System.Runtime.Remoting.Messaging.CallContext.SetData(PerThreadCallCounterKey, 0);
&lt;span class="rem"&gt;// Pick a randon number of times to call the target method&lt;/span&gt;
&lt;span class="kwrd"&gt;int&lt;/span&gt; iterations = Rnd.Next(255); 
&lt;span class="rem"&gt;// Call the method iteration number of times&lt;/span&gt;
&lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0; i &amp;lt; iterations; ++i)
{
DoTheWork();
}
DisplayCounterValue();
}

&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; DoTheWork()
{
&lt;span class="rem"&gt;// Get the current threads CallCounter from the CallContext&lt;/span&gt;
&lt;span class="kwrd"&gt;int&lt;/span&gt; counter = (&lt;span class="kwrd"&gt;int&lt;/span&gt;)System.Runtime.Remoting.Messaging.CallContext.GetData(PerThreadCallCounterKey);

&lt;span class="rem"&gt;// Increment the counter and store the new value in the CallContext&lt;/span&gt;
&lt;span class="rem"&gt;// Notice the pre-increment (++counter).&lt;/span&gt;
System.Runtime.Remoting.Messaging.CallContext.SetData(PerThreadCallCounterKey, ++counter);

&lt;span class="rem"&gt;//OK, so we updated the counter now do the real work of this method&lt;/span&gt;
&lt;span class="rem"&gt;//...&lt;/span&gt;
}

&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; DisplayCounterValue()
{
&lt;span class="rem"&gt;// Get the current threads CallCounter from the CallContext&lt;/span&gt;
&lt;span class="kwrd"&gt;int&lt;/span&gt; counter = (&lt;span class="kwrd"&gt;int&lt;/span&gt;)System.Runtime.Remoting.Messaging.CallContext.GetData(PerThreadCallCounterKey);
System.Console.WriteLine(&lt;span class="str"&gt;"The method was called {0} times from this thread"&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="csharpcode-wrapper" id="codeSnippetWrapper"&gt;&lt;br /&gt;
&lt;pre class="csharpcode" id="codeSnippet"&gt;[ThreadStatic]
&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&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="csharpcode-wrapper" id="codeSnippetWrapper"&gt;&lt;pre class="csharpcode" id="codeSnippet"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Class1
{
&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
{
System.Threading.Thread t1 = &lt;span class="kwrd"&gt;new&lt;/span&gt; System.Threading.Thread(&lt;span class="kwrd"&gt;new&lt;/span&gt; System.Threading.ThreadStart(ThreadFunction));
System.Threading.Thread t2 = &lt;span class="kwrd"&gt;new&lt;/span&gt; System.Threading.Thread(&lt;span class="kwrd"&gt;new&lt;/span&gt; System.Threading.ThreadStart(ThreadFunction));

&lt;span class="rem"&gt;// Start the threads&lt;/span&gt;
t1.Start();
t2.Start();

&lt;span class="rem"&gt;// Wait for the threads to complete&lt;/span&gt;
t1.Join();
t2.Join();
System.Console.Read();
} 


[ThreadStatic]
&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; PerThreadCallCounter;

&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Random Rnd = &lt;span class="kwrd"&gt;new&lt;/span&gt; Random();

&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; ThreadFunction()
{ 
&lt;span class="rem"&gt;// Pick a randon number of times to call the target method &lt;/span&gt;
&lt;span class="kwrd"&gt;int&lt;/span&gt; iterations = Rnd.Next(255); 

&lt;span class="rem"&gt;// Call the method iteration number of times&lt;/span&gt;
&lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0; i &amp;lt; iterations; ++i)
{
DoTheWork();
}
DisplayCounterValue();
}

&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; DoTheWork()
{
&lt;span class="rem"&gt;// Increment the static member associated with the current thread&lt;/span&gt;
PerThreadCallCounter++;

&lt;span class="rem"&gt;//OK, so we updated the counter now do the real work of this method&lt;/span&gt;
&lt;span class="rem"&gt;//...&lt;/span&gt;
}

&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; DisplayCounterValue()
{
&lt;span class="rem"&gt;// Display the value of the thread static member to the user&lt;/span&gt;
System.Console.WriteLine(&lt;span class="str"&gt;"The method was called {0} times from this thread"&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.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-2997976491425137598?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/qLAMWQGQ7iXs9Nzhcs527z7B2m8/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/qLAMWQGQ7iXs9Nzhcs527z7B2m8/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/qLAMWQGQ7iXs9Nzhcs527z7B2m8/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/qLAMWQGQ7iXs9Nzhcs527z7B2m8/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/5brbh3wYaTw" height="1" width="1"/&gt;</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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/2997976491425137598?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/5brbh3wYaTw/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2009/11/archive-thread-local-storage-in-net.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0YGR3g-eip7ImA9WxNUEEU.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2009-11-01T15:12:06.652+02:00</app:edited><title>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="codeSnippetWrapper" class="csharpcode-wrapper"&gt;   &lt;pre id="codeSnippet" class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; Color Gradient(Color from, Color to, &lt;span class="kwrd"&gt;byte&lt;/span&gt; step)&lt;br /&gt;{&lt;br /&gt;   &lt;span class="kwrd"&gt;double&lt;/span&gt; stepFactor = (&lt;span class="kwrd"&gt;double&lt;/span&gt;)step / 255;&lt;br /&gt;   &lt;span class="kwrd"&gt;return&lt;/span&gt; Color.FromArgb(&lt;br /&gt;      (&lt;span class="kwrd"&gt;int&lt;/span&gt;)(from.R + ((to.R - from.R) * stepFactor)),&lt;br /&gt;      (&lt;span class="kwrd"&gt;int&lt;/span&gt;)(from.G + ((to.G - from.G) * stepFactor)),&lt;br /&gt;      (&lt;span class="kwrd"&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;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-4663778536225404720?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/7-6oRvq_eJWtlBiqqjj9Wd1leTE/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/7-6oRvq_eJWtlBiqqjj9Wd1leTE/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/7-6oRvq_eJWtlBiqqjj9Wd1leTE/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/7-6oRvq_eJWtlBiqqjj9Wd1leTE/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/csfmv52Ru98" height="1" width="1"/&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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/4663778536225404720?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/csfmv52Ru98/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2009/11/color-gradient.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0ENQ3w-fyp7ImA9WxNQGUg.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2009-09-26T12:01:32.257+03:00</app:edited><title>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="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; test1()&lt;br /&gt;{&lt;br /&gt;  &lt;span class="rem"&gt;// Throw an exception for testing purposes&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentException( &lt;span class="str"&gt;&amp;quot;test1&amp;quot;&lt;/span&gt; ); &lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;void&lt;/span&gt; test2()&lt;br /&gt;{&lt;br /&gt;  &lt;span class="kwrd"&gt;try&lt;/span&gt;&lt;br /&gt;  {  &lt;br /&gt;    MethodInfo mi = &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(Form1).GetMethod( &lt;span class="str"&gt;&amp;quot;test1&amp;quot;&lt;/span&gt; );&lt;br /&gt;    mi.Invoke( &lt;span class="kwrd"&gt;this&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt; );&lt;br /&gt;  }&lt;br /&gt;  &lt;span class="kwrd"&gt;catch&lt;/span&gt;( TargetInvocationException tiex )&lt;br /&gt;  { &lt;br /&gt;    &lt;span class="rem"&gt;// NB: Error checking etc. excluded&lt;/span&gt;&lt;br /&gt;    &lt;span class="rem"&gt;// Get the _remoteStackTraceString of the Exception class&lt;/span&gt;&lt;br /&gt;    FieldInfo remoteStackTraceString = &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(Exception).GetField(&lt;span class="str"&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="rem"&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="rem"&gt;// Throw the new exception&lt;/span&gt;&lt;br /&gt;    &lt;span class="kwrd"&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="rem"&gt;// Test the effect of the above code by calling test2() and handling &lt;/span&gt;&lt;br /&gt;&lt;span class="rem"&gt;// the exception that is thrown&lt;/span&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;try&lt;/span&gt;&lt;br /&gt;{&lt;br /&gt;  test2(); &lt;span class="rem"&gt;// Call the method that uses reflection to call another method&lt;/span&gt;&lt;br /&gt;}&lt;br /&gt;&lt;span class="kwrd"&gt;catch&lt;/span&gt; ( Exception ex )&lt;br /&gt;{&lt;br /&gt;  Console.WriteLine( ex.ToString() );&lt;br /&gt;}&lt;/pre&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-7013264991897807029?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/EiqCyIo7uBbeYB_Yxn8Ux05cPKE/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/EiqCyIo7uBbeYB_Yxn8Ux05cPKE/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/EiqCyIo7uBbeYB_Yxn8Ux05cPKE/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/EiqCyIo7uBbeYB_Yxn8Ux05cPKE/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/KEUqJi3hBJI" height="1" width="1"/&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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/7013264991897807029?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/KEUqJi3hBJI/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2009/09/re-throw-innerexception-and-preserve.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0YERH46eyp7ImA9WxNQGE8.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2009-09-24T22:38:25.013+03:00</app:edited><title>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="http://www.silverarcade.com/games/taylorza/labyrinth" target="_blank"&gt;here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.silverarcade.com/games/taylorza/labyrinth"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenshotMashoo" border="0" alt="ScreenshotMashoo" src="http://lh6.ggpht.com/_sofFKEz4lW8/SrvKr_mnv6I/AAAAAAAAAus/nK-fvm-0UA8/ScreenshotMashoo_thumb%5B7%5D.png?imgmax=800" width="244" height="186" /&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;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-5942254829326090006?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/e22ObT56brJCsH-ietYqHw-r1G4/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/e22ObT56brJCsH-ietYqHw-r1G4/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/e22ObT56brJCsH-ietYqHw-r1G4/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/e22ObT56brJCsH-ietYqHw-r1G4/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/CaQoxsimtj4" height="1" width="1"/&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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/5942254829326090006?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/CaQoxsimtj4/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh6.ggpht.com/_sofFKEz4lW8/SrvKr_mnv6I/AAAAAAAAAus/nK-fvm-0UA8/s72-c/ScreenshotMashoo_thumb%5B7%5D.png?imgmax=800" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2009/09/silverlight-ray-casting-engine.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0QDQHY5eSp7ImA9WhZaGU8.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2011-07-06T06:02:51.821+03:00</app:edited><title>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="http://www.silverarcade.com/games/taylorza/sildoku" target="_blank"&gt;Sildoku&lt;/a&gt; and &lt;a href="http://www.silverarcade.com/games/taylorza/peg-solitaire" target="_blank"&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="http://en.wikipedia.org/wiki/Sprite_sheet" target="_blank"&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="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; SpriteSheet
{
&lt;span class="kwrd"&gt;  private&lt;/span&gt; BitmapSource _spriteSheetSource;
&lt;span class="kwrd"&gt;  private&lt;/span&gt; WriteableBitmap _spriteSheetBitmap;
&lt;span class="kwrd"&gt;  private&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; _sheetWidth;
&lt;span class="kwrd"&gt;  private&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; _sheetHeight;    

&lt;span class="kwrd"&gt;  public&lt;/span&gt; SpriteSheet(BitmapSource spriteSheetSource)
  {
&lt;span class="kwrd"&gt;    if&lt;/span&gt; (spriteSheetSource == &lt;span class="kwrd"&gt;null&lt;/span&gt;) &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class="str"&gt;"spriteSheetSource"&lt;/span&gt;);

    _spriteSheetSource = spriteSheetSource;
    _spriteSheetBitmap = &lt;span class="kwrd"&gt;new&lt;/span&gt; WriteableBitmap(_spriteSheetSource);
    _sheetWidth = _spriteSheetBitmap.PixelWidth;
    _sheetHeight = _spriteSheetBitmap.PixelHeight;
  }

&lt;span class="kwrd"&gt;  public&lt;/span&gt; WriteableBitmap GetBitmap(&lt;span class="kwrd"&gt;int&lt;/span&gt; x, &lt;span class="kwrd"&gt;int&lt;/span&gt; y, &lt;span class="kwrd"&gt;int&lt;/span&gt; width, &lt;span class="kwrd"&gt;int&lt;/span&gt; height)
  {
    WriteableBitmap destination = &lt;span class="kwrd"&gt;new&lt;/span&gt; WriteableBitmap(width, height);      
    GetBitmap(destination, x, y, width, height);
&lt;span class="kwrd"&gt;    return&lt;/span&gt; destination;
  }

&lt;span class="kwrd"&gt;  public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; GetBitmap(WriteableBitmap targetBitmap, &lt;span class="kwrd"&gt;int&lt;/span&gt; x, &lt;span class="kwrd"&gt;int&lt;/span&gt; y, &lt;span class="kwrd"&gt;int&lt;/span&gt; width, &lt;span class="kwrd"&gt;int&lt;/span&gt; height)
  {
&lt;span class="rem"&gt;    // Validate incomming data&lt;/span&gt;
&lt;span class="kwrd"&gt;    if&lt;/span&gt; (targetBitmap == &lt;span class="kwrd"&gt;null&lt;/span&gt;) &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class="str"&gt;"targetBitmap"&lt;/span&gt;);
&lt;span class="kwrd"&gt;    if&lt;/span&gt; (x &amp;lt; 0 || x &amp;gt;= _sheetWidth) &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentOutOfRangeException(&lt;span class="str"&gt;"x"&lt;/span&gt;);
&lt;span class="kwrd"&gt;    if&lt;/span&gt; (y &amp;lt; 0 || y &amp;gt;= _sheetHeight) &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentOutOfRangeException(&lt;span class="str"&gt;"y"&lt;/span&gt;);
&lt;span class="kwrd"&gt;    if&lt;/span&gt; (width &amp;lt; 0 || (x + width &amp;gt; _sheetWidth)) &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentOutOfRangeException(&lt;span class="str"&gt;"width"&lt;/span&gt;);
&lt;span class="kwrd"&gt;    if&lt;/span&gt; (height &amp;lt; 0 || (y + height &amp;gt; _sheetHeight)) &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentOutOfRangeException(&lt;span class="str"&gt;"height"&lt;/span&gt;);

&lt;span class="rem"&gt;    // Get pixel buffers for the sprite sheet and the target bitmap&lt;/span&gt;
&lt;span class="kwrd"&gt;    int&lt;/span&gt;[] sourcePixels = _spriteSheetBitmap.Pixels;
&lt;span class="kwrd"&gt;    int&lt;/span&gt;[] targetPixels = targetBitmap.Pixels;

    &lt;span class="rem"&gt;// Calculate starting offsets into the pixel buffers      &lt;/span&gt;
&lt;span class="kwrd"&gt;    int&lt;/span&gt; sourceOffset = x + (y * _sheetWidth);      
&lt;span class="kwrd"&gt;    int&lt;/span&gt; targetOffset = 0;

    &lt;span class="rem"&gt;// Note that the offsets and widths are multiplied by 4, &lt;/span&gt;&lt;span class="rem"&gt;this is because Buffer.BlockCopy requires&lt;/span&gt;
&lt;span class="rem"&gt;    // byte offsets into the buffers and our buffers are integer buffers. To optimize this I have &lt;/span&gt;
&lt;span class="rem"&gt;    // premultiplied to values so that the multiplication is removed from the loop&lt;/span&gt;
&lt;span class="kwrd"&gt;    int&lt;/span&gt; sourceByteOffset = sourceOffset &amp;lt;&amp;lt; 2;
&lt;span class="kwrd"&gt;    int&lt;/span&gt; sheetByteWidth = _sheetWidth &amp;lt;&amp;lt; 2;
&lt;span class="kwrd"&gt;    int&lt;/span&gt; targetByteWidth = width &amp;lt;&amp;lt; 2;
&lt;span class="kwrd"&gt;    for&lt;/span&gt; (&lt;span class="kwrd"&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="kwrd"&gt;  public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Width
  {
    get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _sheetWidth; }
  }

&lt;span class="kwrd"&gt;  public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Height
  {
    get { &lt;span class="kwrd"&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="csharpcode"&gt;&amp;lt;UserControl x:Class=&lt;span class="str"&gt;"Vulcan.SL.TestApplication.MainPage"&lt;/span&gt;
xmlns=&lt;span class="str"&gt;"http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;/span&gt; 
xmlns:x=&lt;span class="str"&gt;"http://schemas.microsoft.com/winfx/2006/xaml"&lt;/span&gt;
xmlns:d=&lt;span class="str"&gt;"http://schemas.microsoft.com/expression/blend/2008"&lt;/span&gt; xmlns:mc=&lt;span class="str"&gt;"http://schemas.openxmlformats.org/markup-compatibility/2006"&lt;/span&gt;
mc:Ignorable=&lt;span class="str"&gt;"d"&lt;/span&gt; d:DesignWidth=&lt;span class="str"&gt;"640"&lt;/span&gt; d:DesignHeight=&lt;span class="str"&gt;"480"&lt;/span&gt;&amp;gt;
  &amp;lt;Canvas x:Name=&lt;span class="str"&gt;"LayoutRoot"&lt;/span&gt;&amp;gt;  
    &amp;lt;Image x:Name=&lt;span class="str"&gt;"mySprite1"&lt;/span&gt; Width=&lt;span class="str"&gt;"100"&lt;/span&gt; Height=&lt;span class="str"&gt;"100"&lt;/span&gt; Canvas.Left=&lt;span class="str"&gt;"0"&lt;/span&gt;/&amp;gt;
    &amp;lt;Image x:Name=&lt;span class="str"&gt;"mySprite2"&lt;/span&gt; Width=&lt;span class="str"&gt;"100"&lt;/span&gt; Height=&lt;span class="str"&gt;"100"&lt;/span&gt; Canvas.Left=&lt;span class="str"&gt;"110"&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="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; MainPage()
{
  InitializeComponent();

  BitmapImage spriteSheetBitmap = &lt;span class="kwrd"&gt;new&lt;/span&gt; BitmapImage(&lt;span class="kwrd"&gt;new&lt;/span&gt; Uri(&lt;span class="str"&gt;"/Images/WindmillLeft.png"&lt;/span&gt;, UriKind.Relative));      
  spriteSheetBitmap.CreateOptions = BitmapCreateOptions.None;
  spriteSheetBitmap.ImageOpened += &lt;span class="kwrd"&gt;new&lt;/span&gt; EventHandler&amp;lt;RoutedEventArgs&amp;gt;(image_ImageOpened);       
}

&lt;span class="kwrd"&gt;void&lt;/span&gt; image_ImageOpened(&lt;span class="kwrd"&gt;object&lt;/span&gt; sender, RoutedEventArgs e)
{
  BitmapImage spriteSheetBitmap = sender &lt;span class="kwrd"&gt;as&lt;/span&gt; BitmapImage;

  SpriteSheet spriteSheet = &lt;span class="kwrd"&gt;new&lt;/span&gt; SpriteSheet(spriteSheetBitmap);

&lt;span class="rem"&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="rem"&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.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-7467683580253890570?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/rqPbnlIklM2C1sWpMHJ87RjDL6M/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/rqPbnlIklM2C1sWpMHJ87RjDL6M/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/rqPbnlIklM2C1sWpMHJ87RjDL6M/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/rqPbnlIklM2C1sWpMHJ87RjDL6M/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/c0eodYGn_7s" height="1" width="1"/&gt;</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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/7467683580253890570?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/c0eodYGn_7s/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2009/08/silverlight-spritesheet-management-with.html</feedburner:origLink></entry><entry gd:etag="W/&quot;AkMHR3Y5eip7ImA9WxNTFk4.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2009-08-19T02:33:56.822+03:00</app:edited><title>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="http://www.silverarcade.com" target="_blank"&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="http://www.silverarcade.com/games/taylorza/sildoku" target="_blank"&gt;here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh6.ggpht.com/_sofFKEz4lW8/Sos6UmI8fDI/AAAAAAAAAuc/pQb57m3R2Wc/s1600-h/ScreenshotSmall%5B2%5D.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenshotSmall" border="0" alt="ScreenshotSmall" src="http://lh5.ggpht.com/_sofFKEz4lW8/Sos6WluXcUI/AAAAAAAAAug/W_Wd0CZly04/ScreenshotSmall_thumb.png?imgmax=800" width="164" height="164" /&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="http://www.silverarcade.com/games/taylorza/peg-solitaire" target="_blank"&gt;here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh3.ggpht.com/_sofFKEz4lW8/Sos6XlR1EuI/AAAAAAAAAuk/oFzRvVzoWCI/s1600-h/Promotional%5B2%5D.jpg"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Promotional" border="0" alt="Promotional" src="http://lh4.ggpht.com/_sofFKEz4lW8/Sos6Y5tZOTI/AAAAAAAAAuo/06y-Eeme-_U/Promotional_thumb.jpg?imgmax=800" width="162" height="162" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-2412394062858681886?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/pwrSTUphkJaazwapiXgm8fMptXo/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/pwrSTUphkJaazwapiXgm8fMptXo/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/pwrSTUphkJaazwapiXgm8fMptXo/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/pwrSTUphkJaazwapiXgm8fMptXo/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/qrXhdj1AClk" height="1" width="1"/&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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/2412394062858681886?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/qrXhdj1AClk/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh5.ggpht.com/_sofFKEz4lW8/Sos6WluXcUI/AAAAAAAAAug/W_Wd0CZly04/s72-c/ScreenshotSmall_thumb.png?imgmax=800" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2009/08/silverlight-my-first-silverlight-games.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DkMHSXgyeip7ImA9WxNXEEg.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2009-09-27T15:27:18.692+03:00</app:edited><title>Archive – Hacking my way across the process boundary</title><content type="html">&lt;p&gt;&lt;font color="#0000ff"&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="csharpcode"&gt;&lt;span class="kwrd"&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="rem"&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="rem"&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="rem"&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="rem"&gt;// Fill in the LVITEM struct, this is in your own process&lt;/span&gt;&lt;br /&gt;&lt;span class="rem"&gt;// Set the pszText member to somewhere in the remote buffer,&lt;/span&gt;&lt;br /&gt;&lt;span class="rem"&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="rem"&gt;// Point to after LVITEM in the remote buffer&lt;/span&gt;&lt;br /&gt;lvItem.pszText = (LPTSTR)(lpRemoteBuffer + &lt;span class="kwrd"&gt;sizeof&lt;/span&gt;( LVITEM )); &lt;br /&gt;&lt;br /&gt;&lt;span class="rem"&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="kwrd"&gt;sizeof&lt;/span&gt;(LVITEM), NULL );&lt;br /&gt;&lt;br /&gt;&lt;span class="rem"&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="rem"&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="rem"&gt;//Fix pszText to point to same offset in local buffer&lt;/span&gt;&lt;br /&gt;lvItem.pszText = (LPTSTR)(lpLocalBuffer + &lt;span class="kwrd"&gt;sizeof&lt;/span&gt;( LVITEM ));&lt;br /&gt;&lt;br /&gt;&lt;span class="rem"&gt;// Clean-up&lt;/span&gt;&lt;br /&gt;::VirtualFreeEx( hProcess, (LPVOID)lpRemoteBuffer, 0, MEM_RELEASE ); &lt;br /&gt;::CloseHandle( hProcess );&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-1915756186954885843?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/DBzuicf4MIbKpA1lhLGJ5yXRA2o/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/DBzuicf4MIbKpA1lhLGJ5yXRA2o/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/DBzuicf4MIbKpA1lhLGJ5yXRA2o/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/DBzuicf4MIbKpA1lhLGJ5yXRA2o/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/0PTZ7-hMjKw" height="1" width="1"/&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="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/1915756186954885843?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/1915756186954885843?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/0PTZ7-hMjKw/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>2</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2009/08/archive-hacking-my-way-across-process.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUMERHw-fCp7ImA9WxNTE0k.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2009-08-15T16:36:45.254+03:00</app:edited><title>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="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System;&lt;br /&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Windows.Media;&lt;br /&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Windows.Media.Imaging;&lt;br /&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;namespace&lt;/span&gt; ExtensionMethods&lt;br /&gt;{&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; WriteableBitmapExtensions&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SetPixel(&lt;span class="kwrd"&gt;this&lt;/span&gt; WriteableBitmap wb, &lt;span class="kwrd"&gt;int&lt;/span&gt; x, &lt;span class="kwrd"&gt;int&lt;/span&gt; y, Color color)&lt;br /&gt;    {&lt;br /&gt;      &lt;span class="rem"&gt;// Validate that the x,y coordinates are within the bounds of the bitmap&lt;/span&gt;&lt;br /&gt;      &lt;span class="kwrd"&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="kwrd"&gt;return&lt;/span&gt;;&lt;br /&gt;      &lt;br /&gt;      &lt;span class="kwrd"&gt;int&lt;/span&gt; offset = (y * wb.PixelWidth) + x; &lt;br /&gt;      &lt;span class="kwrd"&gt;int&lt;/span&gt; pixel;&lt;br /&gt;      &lt;span class="kwrd"&gt;int&lt;/span&gt;[] buffer = wb.Pixels;&lt;br /&gt;&lt;br /&gt;      &lt;span class="kwrd"&gt;if&lt;/span&gt; (color.A == 255)&lt;br /&gt;      {                &lt;br /&gt;        &lt;span class="rem"&gt;// Since no alpha blending is required we can directly use the incomming color&lt;/span&gt;&lt;br /&gt;        &lt;span class="rem"&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="kwrd"&gt;else&lt;/span&gt;&lt;br /&gt;      {&lt;br /&gt;        &lt;span class="rem"&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="rem"&gt;// calculate the alpha channel ratios used for the blend of &lt;/span&gt;&lt;br /&gt;        &lt;span class="rem"&gt;// the source and destination pixels&lt;/span&gt;&lt;br /&gt;        &lt;span class="kwrd"&gt;double&lt;/span&gt; sourceAlpha = color.A / 255.0;&lt;br /&gt;        &lt;span class="kwrd"&gt;double&lt;/span&gt; inverseSourceAlpha = 1 - sourceAlpha;&lt;br /&gt;&lt;br /&gt;        &lt;span class="rem"&gt;// Extract the color components of the current pixel in the buffer&lt;/span&gt;&lt;br /&gt;        &lt;span class="kwrd"&gt;byte&lt;/span&gt; destA = (&lt;span class="kwrd"&gt;byte&lt;/span&gt;)(pixel &amp;gt;&amp;gt; 24);&lt;br /&gt;        &lt;span class="kwrd"&gt;byte&lt;/span&gt; destR = (&lt;span class="kwrd"&gt;byte&lt;/span&gt;)(pixel &amp;gt;&amp;gt; 16);&lt;br /&gt;        &lt;span class="kwrd"&gt;byte&lt;/span&gt; destG = (&lt;span class="kwrd"&gt;byte&lt;/span&gt;)(pixel &amp;gt;&amp;gt; 8);&lt;br /&gt;        &lt;span class="kwrd"&gt;byte&lt;/span&gt; destB = (&lt;span class="kwrd"&gt;byte&lt;/span&gt;)pixel;&lt;br /&gt;        &lt;br /&gt;        &lt;span class="rem"&gt;// Calculate the color components of the new pixel. &lt;/span&gt;&lt;br /&gt;        &lt;span class="rem"&gt;// This is the blend of the destination pixel and the new source pixel&lt;/span&gt;&lt;br /&gt;        &lt;span class="kwrd"&gt;byte&lt;/span&gt; pixelA = (&lt;span class="kwrd"&gt;byte&lt;/span&gt;)((color.A * sourceAlpha) + (inverseSourceAlpha * destA));&lt;br /&gt;        &lt;span class="kwrd"&gt;byte&lt;/span&gt; pixelR = (&lt;span class="kwrd"&gt;byte&lt;/span&gt;)((color.R * sourceAlpha) + (inverseSourceAlpha * destR));&lt;br /&gt;        &lt;span class="kwrd"&gt;byte&lt;/span&gt; pixelG = (&lt;span class="kwrd"&gt;byte&lt;/span&gt;)((color.G * sourceAlpha) + (inverseSourceAlpha * destG));&lt;br /&gt;        &lt;span class="kwrd"&gt;byte&lt;/span&gt; pixelB = (&lt;span class="kwrd"&gt;byte&lt;/span&gt;)((color.B * sourceAlpha) + (inverseSourceAlpha * destB));&lt;br /&gt;&lt;br /&gt;        &lt;span class="rem"&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="rem"&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;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-4978505800018868492?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/an6BK70tiIvVlMGabscv9KTHWJ0/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/an6BK70tiIvVlMGabscv9KTHWJ0/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/an6BK70tiIvVlMGabscv9KTHWJ0/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/an6BK70tiIvVlMGabscv9KTHWJ0/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/1ET-7dNXe_E" height="1" width="1"/&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="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/4978505800018868492?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/4978505800018868492?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/1ET-7dNXe_E/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>1</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2009/08/silverlight-writeablebitmap-setpixel.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEUCSXc6fSp7ImA9WxNTEkk.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2009-08-14T12:31:08.915+03:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Silverlight" /><title>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="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;object&lt;/span&gt; &lt;strong&gt;&lt;em&gt;&lt;span class="attr"&gt;id&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;silverlightControl&amp;quot;&lt;/span&gt;&lt;/em&gt;&lt;/strong&gt; &lt;span class="attr"&gt;data&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;data:application/x-silverlight-2,&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;type&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;application/x-silverlight-2&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;width&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;100%&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;height&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;100%&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;param&lt;/span&gt; &lt;span class="attr"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;source&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;ClientBin/DragSnapDemo.xap&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;param&lt;/span&gt; &lt;span class="attr"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;onError&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;onSilverlightError&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;strong&gt;&lt;em&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;param&lt;/span&gt; &lt;span class="attr"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;onLoad&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;silverlightControlHost_Load&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;/em&gt;&lt;/strong&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;param&lt;/span&gt; &lt;span class="attr"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;background&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;white&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;param&lt;/span&gt; &lt;span class="attr"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;minRuntimeVersion&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;3.0.40624.0&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;param&lt;/span&gt; &lt;span class="attr"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;autoUpgrade&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;true&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;a&lt;/span&gt; &lt;span class="attr"&gt;href&lt;/span&gt;&lt;span class="kwrd"&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="attr"&gt;style&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;text-decoration:none&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;img&lt;/span&gt; &lt;span class="attr"&gt;src&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;http://go.microsoft.com/fwlink/?LinkId=108181&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;alt&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Get Microsoft Silverlight&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;style&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;border-style:none&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;a&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;object&lt;/span&gt;&lt;span class="kwrd"&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="csharpcode"&gt;&lt;span class="kwrd"&gt;function&lt;/span&gt; silverlightControlHost_Load(sender, args) &lt;br /&gt;{&lt;br /&gt;  &lt;span class="kwrd"&gt;var&lt;/span&gt; control = document.getElementById(&lt;span class="str"&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;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-4795304401792078989?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/N91qNPVv6XH-qfbZom5SF4EYbpM/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/N91qNPVv6XH-qfbZom5SF4EYbpM/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/N91qNPVv6XH-qfbZom5SF4EYbpM/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/N91qNPVv6XH-qfbZom5SF4EYbpM/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/bVmg3tPZfr4" height="1" width="1"/&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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/4795304401792078989?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/bVmg3tPZfr4/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2009/08/silverlight-set-focus-to-silverlight.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DEIMRn4_cSp7ImA9WxJTFEw.&quot;"><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><app:edited xmlns:app="http://www.w3.org/2007/app">2009-04-22T19:09:47.049+03:00</app:edited><title>Range&lt;&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="csharpcode"&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ParticleSystemSettings&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&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="kwrd"&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="kwrd"&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="kwrd"&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="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&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="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&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="csharpcode"&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ParticleSystemSettings&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&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="kwrd"&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="kwrd"&gt;public&lt;/span&gt; Range&amp;lt;&lt;span class="kwrd"&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="csharpcode"&gt;ParticleSystemSettings settings = &lt;span class="kwrd"&gt;new&lt;/span&gt; ParticleSystemSettings();&lt;br /&gt;&lt;br /&gt;settings.StartColorRange = &lt;span class="kwrd"&gt;new&lt;/span&gt; Range&amp;lt;Color&amp;gt;(Color.Yellow, Color.Orange);&lt;br /&gt;settings.EndColorRange = &lt;span class="kwrd"&gt;new&lt;/span&gt; Range&amp;lt;Color&amp;gt;(Color.Orange, Color.Red);&lt;br /&gt;settings.LifeSpanRange = &lt;span class="kwrd"&gt;new&lt;/span&gt; Range&amp;lt;&lt;span class="kwrd"&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="csharpcode"&gt;Particle particle = &lt;span class="kwrd"&gt;new&lt;/span&gt; Particle();&lt;br /&gt;particle.LifeSpan = settings.LifeSpanRange.Random();&lt;br /&gt;particle.ColorRange = &lt;span class="kwrd"&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="csharpcode"&gt;&lt;span class="kwrd"&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="kwrd"&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="csharpcode"&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;struct&lt;/span&gt; Range&amp;lt;T&amp;gt;&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;private&lt;/span&gt; T _start;&lt;br /&gt;    &lt;span class="kwrd"&gt;private&lt;/span&gt; T _end;&lt;br /&gt;    &lt;span class="kwrd"&gt;private&lt;/span&gt; Func&amp;lt;T, T, &lt;span class="kwrd"&gt;float&lt;/span&gt;, T&amp;gt; _lerp;&lt;br /&gt; &lt;br /&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; Range(T &lt;span class="kwrd"&gt;value&lt;/span&gt;, Func&amp;lt;T, T, &lt;span class="kwrd"&gt;float&lt;/span&gt;, T&amp;gt; lerp)&lt;br /&gt;      : &lt;span class="kwrd"&gt;this&lt;/span&gt;(&lt;span class="kwrd"&gt;value&lt;/span&gt;, &lt;span class="kwrd"&gt;value&lt;/span&gt;, lerp)&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; Range(T start, T end, Func&amp;lt;T, T, &lt;span class="kwrd"&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="kwrd"&gt;public&lt;/span&gt; T Start&lt;br /&gt;    {&lt;br /&gt;      get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _start; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; T End&lt;br /&gt;    {&lt;br /&gt;      get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _end; }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; T Lerp(&lt;span class="kwrd"&gt;float&lt;/span&gt; amount)&lt;br /&gt;    {&lt;br /&gt;      &lt;span class="kwrd"&gt;if&lt;/span&gt; (_lerp == &lt;span class="kwrd"&gt;null&lt;/span&gt;) &lt;span class="kwrd"&gt;return&lt;/span&gt; _start;&lt;br /&gt;      &lt;span class="kwrd"&gt;return&lt;/span&gt; _lerp(_start, _end, amount);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; T Random()&lt;br /&gt;    {&lt;br /&gt;      &lt;span class="kwrd"&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="csharpcode"&gt;&lt;span class="rem"&gt;// Initialize a few ranges&lt;/span&gt;&lt;br /&gt;Range&amp;lt;Vector2&amp;gt; positionRange = &lt;span class="kwrd"&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="kwrd"&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="kwrd"&gt;float&lt;/span&gt;&amp;gt; floatRange = &lt;span class="kwrd"&gt;new&lt;/span&gt; Range&amp;lt;&lt;span class="kwrd"&gt;float&lt;/span&gt;&amp;gt;(0.0f, 5.0f,&lt;br /&gt;  (start, end, amount) =&amp;gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; start + ((end - start) * amount); });&lt;br /&gt;&lt;br /&gt;&lt;span class="rem"&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="kwrd"&gt;float&lt;/span&gt; &lt;span class="kwrd"&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="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Range&lt;br /&gt;{&lt;br /&gt;  &lt;span class="rem"&gt;// Factory Functions&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&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="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&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="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&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="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&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="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Range&amp;lt;&lt;span class="kwrd"&gt;float&lt;/span&gt;&amp;gt; CreateFloat(Color start, Color end)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&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="rem"&gt;// Custom Lerp functions&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;float&lt;/span&gt; LerpFloat(&lt;span class="kwrd"&gt;float&lt;/span&gt; start, &lt;span class="kwrd"&gt;float&lt;/span&gt; end, &lt;span class="kwrd"&gt;float&lt;/span&gt; amount)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&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="csharpcode"&gt;&lt;span class="rem"&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="kwrd"&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="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;struct&lt;/span&gt; Range&amp;lt;T&amp;gt;&lt;br /&gt;{&lt;br /&gt;  &lt;span class="kwrd"&gt;private&lt;/span&gt; T _start;&lt;br /&gt;  &lt;span class="kwrd"&gt;private&lt;/span&gt; T _end;&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; Range(T &lt;span class="kwrd"&gt;value&lt;/span&gt;)&lt;br /&gt;    : &lt;span class="kwrd"&gt;this&lt;/span&gt;(&lt;span class="kwrd"&gt;value&lt;/span&gt;, &lt;span class="kwrd"&gt;value&lt;/span&gt;)&lt;br /&gt;  {&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&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="kwrd"&gt;public&lt;/span&gt; T Start&lt;br /&gt;  {&lt;br /&gt;    get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _start; }&lt;br /&gt;    set { _start = &lt;span class="kwrd"&gt;value&lt;/span&gt;; }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; T End&lt;br /&gt;  {&lt;br /&gt;    get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _end; }&lt;br /&gt;    set { _end = &lt;span class="kwrd"&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="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; XnaRangeExtensions&lt;br /&gt;{&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;float&lt;/span&gt; Lerp(&lt;span class="kwrd"&gt;this&lt;/span&gt; Range&amp;lt;&lt;span class="kwrd"&gt;float&lt;/span&gt;&amp;gt; range, &lt;span class="kwrd"&gt;float&lt;/span&gt; amount)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; range.Start + ((range.End - range.Start) * amount);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Vector2 Lerp(&lt;span class="kwrd"&gt;this&lt;/span&gt; Range&amp;lt;Vector2&amp;gt; range, &lt;span class="kwrd"&gt;float&lt;/span&gt; amount)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; Vector2.Lerp(range.Start, range.End, amount);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Vector3 Lerp(&lt;span class="kwrd"&gt;this&lt;/span&gt; Range&amp;lt;Vector3&amp;gt; range, &lt;span class="kwrd"&gt;float&lt;/span&gt; amount)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; Vector3.Lerp(range.Start, range.End, amount);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Color Lerp(&lt;span class="kwrd"&gt;this&lt;/span&gt; Range&amp;lt;Color&amp;gt; range, &lt;span class="kwrd"&gt;float&lt;/span&gt; amount)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; Color.Lerp(range.Start, range.End, amount);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;float&lt;/span&gt; Random(&lt;span class="kwrd"&gt;this&lt;/span&gt; Range&amp;lt;&lt;span class="kwrd"&gt;float&lt;/span&gt;&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; Lerp(range, Utilities.GetRandomFloat());&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Vector2 Random(&lt;span class="kwrd"&gt;this&lt;/span&gt; Range&amp;lt;Vector2&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; Lerp(range, Utilities.GetRandomFloat());&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Vector3 Random(&lt;span class="kwrd"&gt;this&lt;/span&gt; Range&amp;lt;Vector3&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; Lerp(range, Utilities.GetRandomFloat());&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Color Random(&lt;span class="kwrd"&gt;this&lt;/span&gt; Range&amp;lt;Color&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; Lerp(range, Utilities.GetRandomFloat());&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; IsEmpty(&lt;span class="kwrd"&gt;this&lt;/span&gt; Range&amp;lt;&lt;span class="kwrd"&gt;float&lt;/span&gt;&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; range.Start == range.End;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; IsEmpty(&lt;span class="kwrd"&gt;this&lt;/span&gt; Range&amp;lt;Vector2&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; range.Start == range.End;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; IsEmpty(&lt;span class="kwrd"&gt;this&lt;/span&gt; Range&amp;lt;Vector3&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; range.Start == range.End;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; IsEmpty(&lt;span class="kwrd"&gt;this&lt;/span&gt; Range&amp;lt;Color&amp;gt; range)&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&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="csharpcode"&gt;&lt;span class="rem"&gt;// Initialize a few ranges&lt;/span&gt;&lt;br /&gt;Range&amp;lt;Vector2&amp;gt; positionRange = &lt;span class="kwrd"&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="kwrd"&gt;new&lt;/span&gt; Range&amp;lt;Color&amp;gt;(Color.White, Color.Black);&lt;br /&gt;Range&amp;lt;&lt;span class="kwrd"&gt;float&lt;/span&gt;&amp;gt; floatRange = &lt;span class="kwrd"&gt;new&lt;/span&gt; Range&amp;lt;&lt;span class="kwrd"&gt;float&lt;/span&gt;&amp;gt;(0.0f, 5.0f);&lt;br /&gt;&lt;br /&gt;&lt;span class="rem"&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="kwrd"&gt;float&lt;/span&gt; &lt;span class="kwrd"&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;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-1050497164055586723?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/SFxKuvhd-l_ecsy1OwuNHjLME2c/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/SFxKuvhd-l_ecsy1OwuNHjLME2c/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/SFxKuvhd-l_ecsy1OwuNHjLME2c/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/SFxKuvhd-l_ecsy1OwuNHjLME2c/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/A05Wf7qD5P4" height="1" width="1"/&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?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/1050497164055586723?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/A05Wf7qD5P4/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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2009/04/range-utility-data-type-for-cleaner-xna.html</feedburner:origLink></entry><entry gd:etag="W/&quot;AkQAR3Y4cCp7ImA9WxVaFEs.&quot;"><id>tag:blogger.com,1999:blog-4927779461366619687.post-8741907283922875388</id><published>2009-04-11T19:04:00.001+03:00</published><updated>2009-04-11T19:45:46.838+03:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-04-11T19:45:46.838+03:00</app:edited><title>SQL Injection - Are parameterized queries safe?</title><content type="html">&lt;p&gt;This is a repost and rework of a popular blog entry from my previous blog, the original post can be found &lt;a href="http://www.dotnetjunkies.com/WebLog/chris.taylor/archive/2004/10/13/28370.aspx" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;SQL Injection is one of those vulnerabilities that crop up without even realizing it. Attackers potentially use SQL Injection to &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Bypass authentication &lt;/li&gt;    &lt;li&gt;Gain access to sensitive information &lt;/li&gt;    &lt;li&gt;Interrupt system availability by tampering with or destroying data &lt;/li&gt;    &lt;li&gt;Elevate privileges by tampering with data &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;As most developers already know, a few of the key ways to protect against SQL injection is to&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Validate user input to ensure that the input conforms to the business requirements, and ensure that suspicious input is filtered to reduce the possible attack vectors. &lt;/li&gt;    &lt;li&gt;Apply the principals of least privilege to further limit the scope of a successful hack &lt;/li&gt;    &lt;li&gt;Use parameterized SQL queries rather than building SQL statements dynamically using string concatenation &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Following the above guidelines will go along way to protect your software from a range of strategies used by potential hackers to penetrate your systems. This is not a complete guide, it is just a starting point, I am not even talking about the various web site vulnerabilities like cross site scripting etc.&lt;/p&gt;  &lt;p&gt;The goal of this post is to demonstrate a scenario where parameterized queries could still pose a potential vulnerability. Using the following code as an example, a .NET developer might feel that the code is reasonably secure, using a nice parameterized query to a stored procedure.&lt;/p&gt;&lt;pre class="csharpcode"&gt;oCmd.CommandText = &lt;span class="str"&gt;&amp;quot;VulnerableDynamicSQL&amp;quot;&lt;/span&gt;;&lt;br /&gt;oCmd.CommandType = CommandType.StoredProcedure;&lt;br /&gt;oCmd.Parameters.Add( &lt;span class="str"&gt;&amp;quot;@userName&amp;quot;&lt;/span&gt;, strUserName);&lt;br /&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; (oCon)&lt;br /&gt;{&lt;br /&gt;  oCon.Open();&lt;br /&gt;  &lt;span class="kwrd"&gt;string&lt;/span&gt; result = (&lt;span class="kwrd"&gt;string&lt;/span&gt;)oCmd.ExecuteScalar();&lt;br /&gt;}&lt;/pre&gt;&lt;p&gt;Everything seems fine, but unfortunately the code in the stored procedure could still pose a problem to the unsuspecting caller. The following rather contrived implementation of the stored procedure would leave the door wide open to SQL injection.&lt;/p&gt;&lt;pre class="csharpcode"&gt;create proc VulnerableDynamicSQL(@userName nvarchar(25)) &lt;span class="kwrd"&gt;as&lt;/span&gt;&lt;br /&gt;  declare @sql nvarchar(255)&lt;br /&gt;  set @sql = &lt;span class="str"&gt;'select TelephoneNumber from users where UserName = '&lt;/span&gt;&lt;span class="str"&gt;''&lt;/span&gt; + @userName + &lt;span class="str"&gt;''&lt;/span&gt;&lt;span class="str"&gt;''&lt;/span&gt;&lt;br /&gt;  exec sp_executesql @sql&lt;br /&gt;&lt;br /&gt;go&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;For example, the user input below, passed to the above stored procedure demonstrates a simple SQL Injection attack&lt;/p&gt;&lt;pre class="csharpcode"&gt;';drop table users --&lt;/pre&gt;&lt;br /&gt;This input would result in the procedure formulating and executing the following SQL statement; &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;select&lt;/span&gt; TelephoneNumber &lt;span class="kwrd"&gt;from&lt;/span&gt; users &lt;span class="kwrd"&gt;where&lt;/span&gt; UserName = &lt;span class="str"&gt;''&lt;/span&gt;;&lt;span class="kwrd"&gt;drop&lt;/span&gt; &lt;span class="kwrd"&gt;table&lt;/span&gt; users –-'&lt;/pre&gt;&lt;p&gt;I have chosen the above for simplicity and obviously this would require adequate permissions to be successful, however this does not make the example any less significant. Had the procedure been a procedure used to authenticate users of a system; only a slightly more complex injection would be required to bypass the authentication and gain unauthorized admin access to the system.&lt;/p&gt;&lt;p&gt;As I mentioned above, the procedure could be written without using dynamic SQL, and resulted in more secure implementation. However there are situations in which dynamic SQL is indispensible and this raises the question, Can dynamic SQL be used more securely? The answer is a definite ‘YES’. Firstly you should always consider if you require dynamic SQL normally there is an alternate solution that does not require dynamic SQL. However if you have exhausted all possibilities and the only recourse is dynamic SQL then there is a safer way to use it. Just like we are able to use parameters for our SQL statements from within .NET, so can you use parameters for your dynamic SQL. The following procedure is a reimplementation using parameterized dynamic SQL.&lt;/p&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;create&lt;/span&gt; &lt;span class="kwrd"&gt;proc&lt;/span&gt; SaferDynamicSQL(@userName nvarchar(25))  &lt;span class="kwrd"&gt;as&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;declare&lt;/span&gt; @&lt;span class="kwrd"&gt;sql&lt;/span&gt; nvarchar(255)&lt;br /&gt;  &lt;span class="kwrd"&gt;set&lt;/span&gt; @&lt;span class="kwrd"&gt;sql&lt;/span&gt; = &lt;span class="str"&gt;'select TelephoneNumber from users where UserName = @p_userName'&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;exec&lt;/span&gt; sp_executesql @&lt;span class="kwrd"&gt;sql&lt;/span&gt;, N&lt;span class="str"&gt;'@p_userName nvarchar(25)'&lt;/span&gt;, @p_userName = @userName&lt;br /&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;go&lt;/span&gt;&lt;/pre&gt;&lt;p&gt;As you can see in this case I have defined a parameter to be used in the dynamic SQL statement called @p_userName. This parameter is defined as part of the call to sp_executesql and its value set in the same call.&lt;/p&gt;&lt;p&gt;Don’t make the mistake of thinking that security alone will prevent users from performing a successful SQL injection. It might prevent the user from dropping your tables, but you will still be open to many other forms of attack. When ever you concatenate strings to build SQL statements think carefully of the potential implications. Security requires a mindset where you are always questioning the implications of your decisions and even questioning things you might not have been responsible for.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;And most importantly: Always validate user input.&lt;/b&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-8741907283922875388?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/_qKRxQxNNwzcu-iELuz3KF9v_xg/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/_qKRxQxNNwzcu-iELuz3KF9v_xg/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/_qKRxQxNNwzcu-iELuz3KF9v_xg/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/_qKRxQxNNwzcu-iELuz3KF9v_xg/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/_yK5PzpZPsg" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://taylorza.blogspot.com/feeds/8741907283922875388/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://taylorza.blogspot.com/2009/04/sql-injection-are-parameterized-queries.html#comment-form" title="6 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/8741907283922875388?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/8741907283922875388?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/_yK5PzpZPsg/sql-injection-are-parameterized-queries.html" title="SQL Injection - Are parameterized queries safe?" /><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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>6</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2009/04/sql-injection-are-parameterized-queries.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0MAQXk4fip7ImA9WxVaGUQ.&quot;"><id>tag:blogger.com,1999:blog-4927779461366619687.post-6768045081724891097</id><published>2009-04-11T00:43:00.004+03:00</published><updated>2009-04-17T21:04:00.736+03:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-04-17T21:04:00.736+03:00</app:edited><title>Extension Methods: In&lt;&gt; and Between&lt;&gt;</title><content type="html">&lt;p&gt;For my first real post I thought I would kick off with something light. I was writing some code recently and realized that the code readability would benefit from two simple extension methods, In&amp;lt;&amp;gt; and Between&amp;lt;&amp;gt;.&lt;br /&gt;&lt;br /&gt;I often find myself writing code along the lines of&lt;br /&gt;&lt;br /&gt;if (x &amp;gt;= 0 &amp;amp;&amp;amp; x &amp;lt;= 10) ...&lt;br /&gt;or&lt;br /&gt;if (new[] {1,2,3}.Contains(x)) ...&lt;br /&gt;&lt;br /&gt;So I thought I would throw two extension methods at the problem, I was looking for something that would give me the following syntax.&lt;br /&gt;&lt;br /&gt;if (x.Between(0, 10)) ...&lt;br /&gt;and&lt;br /&gt;if (x.In(1,2,3)) ...&lt;br /&gt;&lt;br /&gt;The result of my first attempt is the code below, note there are a few overloads to support various alternatives and customizing the comparison.&lt;/p&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System;&lt;br /&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Linq;&lt;br /&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Collections.Generic;&lt;br /&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;namespace&lt;/span&gt; DotNetWarrior&lt;br /&gt;{&lt;br /&gt;  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ExtensionMethods&lt;br /&gt;  {&lt;br /&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; In&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; T &lt;span class="kwrd"&gt;value&lt;/span&gt;, &lt;span class="kwrd"&gt;params&lt;/span&gt; T[] values)&lt;br /&gt;    {&lt;br /&gt;      &lt;span class="kwrd"&gt;return&lt;/span&gt; ExtensionMethods.In(&lt;span class="kwrd"&gt;value&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt;, values);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; In&amp;lt;T&amp;gt;&lt;t&gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; T &lt;span class="kwrd"&gt;value&lt;/span&gt;, IEqualityComparer&amp;lt;T&amp;gt;&lt;t&gt; comparer, &lt;span class="kwrd"&gt;params&lt;/span&gt; T[] values)&lt;br /&gt;    {   &lt;br /&gt;      &lt;span class="kwrd"&gt;return&lt;/span&gt; In(&lt;span class="kwrd"&gt;value&lt;/span&gt;, comparer, values &lt;span class="kwrd"&gt;as&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt;&lt;t&gt;);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; In&amp;lt;T&amp;gt;&lt;t&gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; T item, IEnumerable&amp;lt;T&amp;gt;&lt;t&gt; values)&lt;br /&gt;    {&lt;br /&gt;      &lt;span class="kwrd"&gt;return&lt;/span&gt; In(item, &lt;span class="kwrd"&gt;null&lt;/span&gt;, values);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; In&amp;lt;T&amp;gt;&lt;t&gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; T &lt;span class="kwrd"&gt;value&lt;/span&gt;, IEqualityComparer&amp;lt;T&amp;gt;&lt;t&gt; comparer, IEnumerable&amp;lt;T&amp;gt;&lt;t&gt; values)&lt;br /&gt;    {&lt;br /&gt;      &lt;span class="kwrd"&gt;return&lt;/span&gt; values.Contains(&lt;span class="kwrd"&gt;value&lt;/span&gt;, comparer);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; Between&amp;lt;T&amp;gt;&lt;t&gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; T item, T min, T max)&lt;br /&gt;    {&lt;br /&gt;      &lt;span class="kwrd"&gt;return&lt;/span&gt; ExtensionMethods.Between(item, &lt;span class="kwrd"&gt;null&lt;/span&gt;, min, max);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; Between&amp;lt;T&amp;gt;&lt;t&gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; T item, IComparer&amp;lt;T&amp;gt;&lt;t&gt; comparer, T min, T max)&lt;br /&gt;    {&lt;br /&gt;      &lt;span class="kwrd"&gt;if&lt;/span&gt; (comparer == &lt;span class="kwrd"&gt;null&lt;/span&gt;)&lt;br /&gt;      {&lt;br /&gt;        comparer = Comparer&amp;lt;T&amp;gt;&lt;t&gt;.Default;&lt;br /&gt;      }   &lt;br /&gt;      if (comparer.Compare(min, max) == 1) throw new ArgumentException("min must be less than or equal to max.");&lt;br /&gt;&lt;br /&gt;      &lt;span class="kwrd"&gt;return&lt;/span&gt; (comparer.Compare(item, min) &amp;gt;= 0) &amp;amp;&amp;amp; (comparer.Compare(item, max) &amp;lt;= 0);&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Well, I hope you find this useful. Till I blog again.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-6768045081724891097?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/0MvnWWA97KuDAk_gYEATDNu85kk/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/0MvnWWA97KuDAk_gYEATDNu85kk/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/0MvnWWA97KuDAk_gYEATDNu85kk/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/0MvnWWA97KuDAk_gYEATDNu85kk/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/jSxrO8AXIxY" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://taylorza.blogspot.com/feeds/6768045081724891097/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://taylorza.blogspot.com/2009/04/extension-methods-in-and-between.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/6768045081724891097?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/6768045081724891097?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/jSxrO8AXIxY/extension-methods-in-and-between.html" title="Extension Methods: In&amp;lt;&amp;gt; and Between&amp;lt;&amp;gt;" /><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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2009/04/extension-methods-in-and-between.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A0YMR3o6eyp7ImA9WxVaE0Q.&quot;"><id>tag:blogger.com,1999:blog-4927779461366619687.post-3487114560581752208</id><published>2009-04-11T00:33:00.001+03:00</published><updated>2009-04-11T00:33:06.413+03:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-04-11T00:33:06.413+03:00</app:edited><title>Welcome to my new Blog</title><content type="html">&lt;p&gt;Well it has been nearly two years since I last actively blogged. Recently I felt inspired to try and pickup on my community involvement, so I thought why not start blogging again. This is the start of that experiment.&lt;/p&gt;  &lt;p&gt;For the most part I will be blogging about .NET and some C++. Though these days my focus is probably less techie than I would like it to be I will try to blog about the hobby tasks that I do and which inspire me to continue learning more about the technologies I am involved with. Mostly it will cover the random things I toy with in my own time.&lt;/p&gt;  &lt;p&gt;I hope you will find what I share interesting and most importantly I hope to see your comments on my posts, especially if you have inputs that help me learn more about a topic.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/4927779461366619687-3487114560581752208?l=taylorza.blogspot.com' alt='' /&gt;&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/Jj9Onnt85Ofo5sZmwqN9wbA6FHY/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Jj9Onnt85Ofo5sZmwqN9wbA6FHY/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/Jj9Onnt85Ofo5sZmwqN9wbA6FHY/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Jj9Onnt85Ofo5sZmwqN9wbA6FHY/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/taylorza_blogspot/~4/ABp4FWN6ZrI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://taylorza.blogspot.com/feeds/3487114560581752208/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://taylorza.blogspot.com/2009/04/welcome-to-my-new-blog.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/3487114560581752208?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/4927779461366619687/posts/default/3487114560581752208?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/taylorza_blogspot/~3/ABp4FWN6ZrI/welcome-to-my-new-blog.html" title="Welcome to my new Blog" /><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="http://2.bp.blogspot.com/_sofFKEz4lW8/SvW9q2e_cmI/AAAAAAAAAu4/JboVpHodzHI/S220/Family.bmp" /></author><thr:total>0</thr:total><feedburner:origLink>http://taylorza.blogspot.com/2009/04/welcome-to-my-new-blog.html</feedburner:origLink></entry></feed>

