<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Everything in Particular &#187; Development</title>
	<atom:link href="http://www.del337ed.com/blog/index.php/category/development/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.del337ed.com/blog</link>
	<description>Mostly tech talk</description>
	<lastBuildDate>Fri, 02 Apr 2010 03:26:53 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Cherub Milestone: Create Team Feature Complete</title>
		<link>http://www.del337ed.com/blog/index.php/2010/01/14/cherub-milestone-create-team-feature-complete/</link>
		<comments>http://www.del337ed.com/blog/index.php/2010/01/14/cherub-milestone-create-team-feature-complete/#comments</comments>
		<pubDate>Thu, 14 Jan 2010 06:06:27 +0000</pubDate>
		<dc:creator>omatase</dc:creator>
				<category><![CDATA[Cherub]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Gaming]]></category>

		<guid isPermaLink="false">http://www.del337ed.com/blog/?p=218</guid>
		<description><![CDATA[Welcome
Welcome to the latest installment in my game development subset of entries. I&#8217;m officially commissioning you to help with input on the latest testable piece of my new game, yes you! Before you get all excited, there is pretty much nothing glamorous about this. I really have no artwork and the usability and visual design [...]]]></description>
			<content:encoded><![CDATA[<h2>Welcome</h2>
<p>Welcome to the latest installment in my game development subset of entries. I&#8217;m officially commissioning you to help with input on the latest testable piece of my new game, yes you! Before you get all excited, there is pretty much nothing glamorous about this. I really have no artwork and the usability and visual design are in their first draft. In the interest of keeping this as concise as possible, I&#8217;ll get right to it.</p>
<h2>Create Team</h2>
<p>The latest testable piece for which I am soliciting feedback is the &#8220;Create Team&#8221; piece. This also happens to be the first really testable piece (other than the menu) as all other development up to this point has primarily been foundational.</p>
<p>I started with the Create Team screen as the first feature since the team is really at the heart of the game. Each player can create a single team (I upped the limit to 3 for this test). Each team consists of exactly 4 team members. Each team member has a class (only 4 are available in this demo), a look (I only have stand in art here now and only 3 models to choose from. Yes that means you&#8217;ll have to give more than one player the same look) and a name. And finally each <em>team</em> also has a name.</p>
<p>To get to the Create Team screen, first visit this url: <a title="http://apps.facebook.com/battleschool" href="http://apps.facebook.com/battleschool">http://apps.facebook.com/battleschool</a>. Using the application requires a Facebook account and requires Microsoft Silverlight 3.0 which is free and a small install. This part is intended to be pretty seamless so I would appreciate it if you can report any issues you have on this step. Once the Silverlight application loads you should get a screen with 3 options: Play Game, Statistics and Exit Game. Click &#8220;Play Game&#8221;, on the subsequent menu click &#8220;Create Team&#8221;.</p>
<p>I&#8217;m intentionally not going to go into details on how to <strong>use</strong> the Create Team screen as this is intended to be a usability test as much as anything. I realize it is pretty rough around the edges right now and hope that with everyone&#8217;s help I can make it look better and make it easier to use.</p>
<p>Some specific feedback items I&#8217;m looking for:</p>
<ul>
<li>Did it take a long time for the application to load initially?</li>
<li>How easy was it to use the Create Team screen?</li>
<li>Any suggestions for different design or look of the Create Team screen?</li>
<li>Was the application sluggish at all?</li>
<li>Did you get any error messages or find any bugs?</li>
</ul>
<p>Feel free to leave any feedback in a comment here.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.del337ed.com/blog/index.php/2010/01/14/cherub-milestone-create-team-feature-complete/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>C#: Doing a modulus (mod) operation on a very large number (&gt; Int64.MaxValue)</title>
		<link>http://www.del337ed.com/blog/index.php/2009/02/04/c-doing-a-modulus-mod-operation-on-a-very-large-number-int64maxvalue/</link>
		<comments>http://www.del337ed.com/blog/index.php/2009/02/04/c-doing-a-modulus-mod-operation-on-a-very-large-number-int64maxvalue/#comments</comments>
		<pubDate>Wed, 04 Feb 2009 23:54:29 +0000</pubDate>
		<dc:creator>omatase</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://www.del337ed.com/blog/?p=89</guid>
		<description><![CDATA[[code lang="c#"]
/// 
/// calculates a modulus on any number, specifically
/// designed to work around the Int64 limits of the
/// current version of c# which cannot hold a number
/// larger than 9,223,372,036,854,775,807
/// 
///

/// 
private static int largeNumberModulus(string numberToModulus, int modulusOperand)
{
string modulusWorkingNumber = numberToModulus;
while (modulusWorkingNumber.Length > 0 &#038;&#038; !(modulusWorkingNumber.Length < 18 &#038;&#038; Int64.Parse(modulusWorkingNumber) < modulusOperand))
{
// number to [...]]]></description>
			<content:encoded><![CDATA[<p>[code lang="c#"]</p>
<p>/// <summary><br />
/// calculates a modulus on any number, specifically<br />
/// designed to work around the Int64 limits of the<br />
/// current version of c# which cannot hold a number<br />
/// larger than 9,223,372,036,854,775,807<br />
/// </summary><br />
///
<param name="iban"></param>
/// <returns></returns><br />
private static int largeNumberModulus(string numberToModulus, int modulusOperand)<br />
{<br />
string modulusWorkingNumber = numberToModulus;</p>
<p>while (modulusWorkingNumber.Length > 0 &#038;&#038; !(modulusWorkingNumber.Length < 18 &#038;&#038; Int64.Parse(modulusWorkingNumber) < modulusOperand))<br />
{<br />
// number to work with<br />
Int64 currentNumber = 0;<br />
if (modulusWorkingNumber.Length > 18)<br />
{<br />
currentNumber = Int64.Parse(modulusWorkingNumber.Substring(0, 18));</p>
<p>// remove first 18 characters<br />
modulusWorkingNumber = modulusWorkingNumber.Substring(18);<br />
}<br />
else<br />
{<br />
currentNumber = Int64.Parse(modulusWorkingNumber);</p>
<p>// remove remaining used characters<br />
modulusWorkingNumber = string.Empty;<br />
}</p>
<p>string carryOver = (currentNumber % modulusOperand).ToString();<br />
modulusWorkingNumber = carryOver + modulusWorkingNumber;<br />
}</p>
<p>return int.Parse(modulusWorkingNumber);<br />
}</p>
<p>[/code]</p>
]]></content:encoded>
			<wfw:commentRss>http://www.del337ed.com/blog/index.php/2009/02/04/c-doing-a-modulus-mod-operation-on-a-very-large-number-int64maxvalue/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Bulk / Batch Printing on a Network Attached Epson Dot Matrix Printer</title>
		<link>http://www.del337ed.com/blog/index.php/2008/06/23/bulk-batch-printing-on-a-network-attached-epson-dot-matrix-printer/</link>
		<comments>http://www.del337ed.com/blog/index.php/2008/06/23/bulk-batch-printing-on-a-network-attached-epson-dot-matrix-printer/#comments</comments>
		<pubDate>Mon, 23 Jun 2008 15:49:33 +0000</pubDate>
		<dc:creator>omatase</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://www.del337ed.com/blog/index.php/2008/06/23/bulk-batch-printing-on-a-network-attached-epson-dot-matrix-printer/</guid>
		<description><![CDATA[I recently had the &#8220;opportunity&#8221; to learn first hand how to go attack the topic of batch printing against an Epson Dot Matrix Printer. I&#8217;m posting this here to document my woes and difficulties on this very bumpy road.
Defining the Problem
Why should batch printing be any different than single printing? There are a few simple [...]]]></description>
			<content:encoded><![CDATA[<p>I recently had the &#8220;opportunity&#8221; to learn first hand how to go attack the topic of batch printing against an Epson Dot Matrix Printer. I&#8217;m posting this here to document my woes and difficulties on this very bumpy road.</p>
<p><strong>Defining the Problem</strong></p>
<p>Why should batch printing be any different than single printing? There are a few simple reasons this is different:</p>
<ol>
<li>Running out of paper</li>
<li>Paper jams</li>
<li>Printer becomes paused</li>
</ol>
<p>Basically the problem is, if you send 100 print jobs to the printer, you want some way of assuring the jobs actually completed. Imagine if you sent 100 print jobs to the printer and the printer runs out of paper at 50. If your application isn&#8217;t set up to do batch printing properly it will send the remaining 50 jobs to the printer even though the printer may have no way of receiving them. Whether it is capable of receiving these jobs is really a matter of the model and how much memory it has to queue up your jobs. The size of the print jobs is also a factor. So your application happily sends the remaining 50 jobs to the printer, how many ultimately print successfully when the paper is loaded? 20? If so what happens to the other 30 print jobs? How does the user even know that they didn&#8217;t print or which ones didn&#8217;t print?</p>
<p><strong>Finding the Answer</strong></p>
<p>Epson was exactly 0 help on this issue. There was <em>no</em> information online that even gives a hint of a clue of an inkling of where to even start looking. So, I emailed their support department. Here is the email I sent them:</p>
<p><em>I am writing an application that will print invoices to [a printer with model #LQ-2090]. One requirement of this application is for batch printing. I have a few questions about the support for batch printing with this printer:<br />
1. If it runs out of paper while jobs are being sent to it, what is its behavior? Does it queue requests? What queue limitations (memory limit etc) does it have?<br />
2. If #1 isn&#8217;t possible is there a programmatic way to query when the printer is out of paper or otherwise unable to print?<br />
This email was sent originall on 06_05_2008. Since I was actively working on the application I couldn&#8217;t wait for their response. The chances it would take too long or that it wouldn&#8217;t be helpful were too great. So I did some researching of my own as well. Ultimately the answer came through my own research. I think Epson sent some response about how much memory was available on the printer and then said there was &#8220;no way&#8221; to ask the printer for a status. So just as I anticipated the response didn&#8217;t yield any information that would be helpful, in fact it was wrong about not being able to query the printer for a response. Their email also came several days after I wrapped up the project. I can&#8217;t find their response so I can&#8217;t say the date exactly but I want to say it took them something like 2 weeks to respond.</em></p>
<p><strong>The Solution</strong></p>
<p>Ultimately, as I said, I found the answer myself. I was coding along happily one day when one of my colleagues mentioned there was a web server built in to the network card we installed in the printer. Curious, I decided to check it out. It was from that web site that I got my first glimmer of hope. The printer supported SNMP and there were configuration items for setting up SNMP and SNMP traps Sweet! My first instinct was to do it all through traps. Surely the printer would send me a message saying &#8220;Please Load Paper&#8221; or something like that whenever there was an alert. So I pulled out my Trap Receiver application (iReasoning) and told the printer to send all traps to my desktop. With that all set up I simulated a few scenarios by forcing an out of paper situation, a paused situation and a jam situation. From across the room I could see my trap receiver filling up with traps. Excited I ran over to my computer to see what information the printer was sending me. My elation was premature and short lived. For a few minutes I compared the different traps I had received trying to notice differences. If I was sent the number 12398521 for instance whenever the printer was out of paper, I could just put those values in a config file and be done with it. What I found though over the course of a few minutes was that every trap was the same! What? It didn&#8217;t even matter if the trap was sent for a different reason, the data I recieved was exactly the same! Well, the same save for the fact that it was including in the trap an incrementing number. So the first trap sent 0, the second sent 1, the third 2 and so on. Well this is completely useless! If I want to know how many traps I have received I can count them myself! <img src='http://www.del337ed.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . I have a little experience with SNMP traps but if this is a standard thing to do with traps this is a new one for me. Whenever I send a trap I include a human readable message letting someone (or some program) know what is going on. Ultimately I did figure out (I think) what these incrementing numbers were supposed to be telling me. More on that later though. Well, it was apparant that the SNMP traps weren&#8217;t going to be of any use. I could treat them like a toggle I guess, but how would I know to have the toggle on or off to begin with? How would I know if I got a message even if the printer was capable of continuing to print? This is not a solution I would except, so I decided to keep looking. The next place I began looking was google. I decided to do a search for something less specific, a search that didn&#8217;t include Epson or LQ2090. Doing that got me a hit that ultimately led to the answer. The hit I got was of someone asking how to use SNMP messages to get printer status information. While the article I found was for a different printer and didn&#8217;t have any information in it that was, in the end, directly usable getting the hint that SNMP messaging is a possible route I could go was invaluable.</p>
<p>From there it was more and more google searches that led me to this real gem (extreme sarcasm applied here): <a rel="nofollow" href="ftp://ftp.pwg.org/pub/pwg/pmp/mibs/rfc1759.txt">ftp://ftp.pwg.org/pub/pwg/pmp/mibs/rfc1759.txt</a>. This my friends is rfc 1759. I recommend you look away, look away! Everytime I try to get any useful information from an RFC it always leaves me asking &#8220;WHY!?!&#8221;. Why on earth would someone write this, and how is it supposed to be useful? After a lot of searching I was finally able to find a guide that explains the RFC. <a title="This guide" rel="nofollow" href="http://www.mibsearch.com/objview/Printer-MIB" target="_blank">This guide</a> broke down the RFC terminology and explained what it meant, then gave the SNMP OID for each item. This guide, IMO should be the RFC. In any case, guide useful, RFC useLESS! *sigh* ok I feel better now.</p>
<p>As much as I have talked up the guide, it was also ultimately of no help <img src='http://www.del337ed.com/blog/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> . Although it did contain what I was searching for, I couldn&#8217;t find what I was looking for as a consequence of just not expecting what I was looking for to be called what it was called.</p>
<p>So how <em>did</em> I find the answer? Good old trial and error / brute force. I opened up my MIB browser app (also by iReasoning) and told it to hit the printer with every SNMP message possible by doing a walk on OID 0. This yielded hundreds of results, with after a little doing I was able to copy into a text file and save it. I did this 3 times: once when the printer had paper and was good to go, once when the printer was in an out-of-paper error state, and once when the printer was paused. I then took those 3 files and did a diff on them using KDiff (a very nice diffing tool). What I found is below (you will want to click to enlarge):</p>
<p><a rel="nofollow" href="http://www.del337ed.com/images/printerDiff.png" target="_blank"><img title="printer diff" src="http://www.del337ed.com/images/printerDiff.png" alt="printer diff" align="middle" /></a></p>
<p>The OID that is shown in this diff is the &#8220;printmib.prtAlert.prtAlertTable.prtAlertEntry.prtAlertDescription.1&#8243; OID. While this seems like a very reasonable thing to call it I was still unable to find it through my searches either in google or in the above-mentioned guide. I was always searching for things like &#8220;printer status&#8221; or &#8220;out of paper&#8221;. In any case, this brute force method <em>did</em> give me all I needed to begin querying the printer for its current state and so I was basically done with my discovery session. I don&#8217;t know all of the unique alert descriptions that can be retrieved from this printer on this OID (I couldn&#8217;t find a list anywhere from epson even after I knew some items on the list) but here are those I have found: <em>supply the paper</em>, <em>remove the paper</em>, <em>paused</em>. Of course it is not unlikely for this to be different between printer manufacturers and models so you may have to do a bit of trial and error.</p>
<p><strong>One Final Small Problem</strong></p>
<p>One minor final thing I ran into was that the OID would change slightly upon each new alert. The first alert would show up under OID printmib.prtAlert.prtAlertTable.prtAlertEntry.prtAlertDescription.1<strong>.0</strong>, the second printmib.prtAlert.prtAlertTable.prtAlertEntry.prtAlertDescription.1<strong>.1</strong> and so on up the number scale until the printer was power cycled. This gave me another &#8220;A-HA!&#8221; moment when I suddenly realized what those stupid traps I mentioned before were all about. The aforementioned printer RFC had some information in it indicating the printer could have multiple rows of alerts in a table in its MIB and that there needs to be some method by which one can return things like total number of alerts and current alert index via SNMP. I never figured out how to send an SNMP message to the printer to retrieve the current alert index (although the RFC seems to indicate it is possible), but I now realized the incrementing number in the traps was the alert index. I could then use that number to construct the correct OID for my SNMP message querying the printer for its alert status description! Pretty cool!</p>
<p>Now, For those of you who aren&#8217;t receiving or cannot programmatically receive traps from your printer another solution to this problem (and the one I ended up implementing) is to attempt to get the alert description at OID .0. If that fails (or returns an empty value), tell your SNMP client to do a GetNext(). If the GetNext returns a non-empty value that belongs to an OID that begins with &#8220;<span style="font-size: small; color: #000000;">printmib.prtAlert.prtAlertTable.prtAlertEntry.prtAlertDescription.1&#8243;, then you are good to go. Here is some sample code that does that for your reference:</span></p>
<p>[code lang='csharp']</p>
<p>while (manager.LastError == 0 &amp;&amp;  returnedValue.OID.StartsWith(oid))</p>
<p>{</p>
<p>value = returnedValue.Value;<br />
returnedValue = SnmpObject.manager.GetNext();</p>
<p>}[/code]</p>
<p>When this loop completes &#8220;value&#8221; will have the &#8220;next&#8221;-most value for the OID we are targeting.</p>
<p><strong>All Done</strong></p>
<p>This marks the end of the material I set out to cover. Hopefully this will be useful to anyone trying to get a batch printing application off the ground. SNMP is universal so as long as your printer is network attached, even with vastly different features, the solution could likely be similar.</p>
<p>Comments and questions welcome, thanks!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.del337ed.com/blog/index.php/2008/06/23/bulk-batch-printing-on-a-network-attached-epson-dot-matrix-printer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Use of the Find, FindIndex or FindAll Methods With Generic Lists in C#</title>
		<link>http://www.del337ed.com/blog/index.php/2008/01/24/making-use-of-the-find-findindex-or-findall-methods-with-generic-lists-in-c/</link>
		<comments>http://www.del337ed.com/blog/index.php/2008/01/24/making-use-of-the-find-findindex-or-findall-methods-with-generic-lists-in-c/#comments</comments>
		<pubDate>Thu, 24 Jan 2008 18:59:38 +0000</pubDate>
		<dc:creator>omatase</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.del337ed.com/blog/index.php/2008/01/24/making-use-of-the-find-findindex-or-findall-methods-with-generic-lists-in-c/</guid>
		<description><![CDATA[I often find myself in a position where I have a collection of objects and I need to determine if a particular element exists in the list. In the past (versions of C# prior to 2.0) whenever I had a list I knew I was going to have to search through I would make use [...]]]></description>
			<content:encoded><![CDATA[<p>I often find myself in a position where I have a collection of objects and I need to determine if a particular element exists in the list. In the past (versions of C# prior to 2.0) whenever I had a list I knew I was going to have to search through I would make use of a Dictionary object. The Dictionary object provides built-in very fast searching. In my pre-.Net life I was a VB6 developer and was always forced to write my own quick sort and binary search routine for such a task. Fortunately for us Microsoft has seen the value and need of making this available in the framework.</p>
<p><strong>Aren&#8217;t Dictionaries Overkill? </strong></p>
<p>The difference between a generic List however, and a Dictionary are that the Dictionary requires a name and a value for each item in your collection. What if you only want a list of values? I have to admit I have made up some &#8220;names&#8221; just to appease the requirements of the Dictionary object so I can add my values and take advantage of the great searching capabilities already provided by the dictionary object. Whenever I do this though it never quite sits right with me. No, I&#8217;m not worried about memory overhead. I haven&#8217;t even checked memory usage but that&#8217;s because there really wouldn&#8217;t be any point with the amount of memory available on even relatively older machines compared to the amount of memory a few thousand integers would take. No, the nagging feeling has always been that it&#8217;s a work around. I&#8217;m using a screw driver to do the job of a hammer in some ways and it doesn&#8217;t sit right with me.</p>
<p><strong>Let&#8217;s do it right</strong></p>
<p>One day I decided enough was enough. I was going to figure out a way to use built-in framework methods to do searching on a generic list. Looking at the intellisense for an instantiated List&lt;string&gt; showed there were a few methods that might do exactly what I needed. (In retrospect I do believe these are methods I had seen and tried to use before but without any luck. You may see here shortly why I gave up the first time I tried, it is certainly not implemented in an intuitive way). Those methods are Find, FindIndex, and FindAll. That might not be a complete list but these three all work the same and so any others may very well as well. I&#8217;m also not going to show how to do this on all three methods since, as stated earlier, they work the same.</p>
<p><strong>Searching for the answer</strong></p>
<p>My quest to begin using these methods started with the intellisense. I looked at the parameters for all of the overloads on the Find method. I noticed a recurring parameter it expected was a &#8220;predicate&#8221; which excuse my ignorance but I had no idea what that was. Since each of the overloads required a predicate, and I didn&#8217;t know what one was, I knew my searching through the intellisense quest was over. I needed an example of how to use this. So I did a Google search, something like [Generic List Find] (without the brackets). The first result was to this MSDN article <a title="http://msdn2.microsoft.com/en-us/library/x0b5b5bc.aspx" rel="nofollow" href="http://msdn2.microsoft.com/en-us/library/x0b5b5bc.aspx">http://msdn2.microsoft.com/en-us/library/x0b5b5bc.aspx</a> . Below is the relevant code excerpt from the article.</p>
<p>[code lang="c#"]<br />
using System;<br />
using System.Collections.Generic;</p>
<p>public class Example<br />
{<br />
public static void Main()<br />
{<br />
List dinosaurs = new List();</p>
<p>dinosaurs.Add("Compsognathus");<br />
dinosaurs.Add("Amargasaurus");<br />
dinosaurs.Add("Oviraptor");<br />
dinosaurs.Add("Velociraptor");<br />
dinosaurs.Add("Deinonychus");<br />
dinosaurs.Add("Dilophosaurus");<br />
dinosaurs.Add("Gallimimus");<br />
dinosaurs.Add("Triceratops");</p>
<p>Console.WriteLine();<br />
foreach(string dinosaur in dinosaurs)<br />
{<br />
Console.WriteLine(dinosaur);<br />
}</p>
<p>Console.WriteLine("nTrueForAll(EndsWithSaurus): {0}",<br />
dinosaurs.TrueForAll(EndsWithSaurus));</p>
<p>Console.WriteLine("nFind(EndsWithSaurus): {0}",<br />
dinosaurs.Find(EndsWithSaurus));</p>
<p>Console.WriteLine("nFindLast(EndsWithSaurus): {0}",<br />
dinosaurs.FindLast(EndsWithSaurus));</p>
<p>Console.WriteLine("nFindAll(EndsWithSaurus):");<br />
List sublist = dinosaurs.FindAll(EndsWithSaurus);</p>
<p>foreach(string dinosaur in sublist)<br />
{<br />
Console.WriteLine(dinosaur);<br />
}</p>
<p>Console.WriteLine(<br />
"n{0} elements removed by RemoveAll(EndsWithSaurus).",<br />
dinosaurs.RemoveAll(EndsWithSaurus));</p>
<p>Console.WriteLine("nList now contains:");<br />
foreach(string dinosaur in dinosaurs)<br />
{<br />
Console.WriteLine(dinosaur);<br />
}</p>
<p>Console.WriteLine("nExists(EndsWithSaurus): {0}",<br />
dinosaurs.Exists(EndsWithSaurus));<br />
}</p>
<p>// Search predicate returns true if a string ends in "saurus".<br />
private static bool EndsWithSaurus(String s)<br />
{<br />
if ((s.Length &amp;amp;gt; 5) &amp;amp;amp;&amp;amp;amp;<br />
(s.Substring(s.Length - 6).ToLower() == "saurus"))<br />
{<br />
return true;<br />
}<br />
else<br />
{<br />
return false;<br />
}<br />
}<br />
}</p>
<p>[/code]</p>
<p>I won&#8217;t go into detail on how this code works. Please visit the article directly for that. But I will point out one big problem with this example. The method that tells Find how to determine if it has &#8216;found&#8217; what it is looking for has a hard-coded string in it. It is searching for a hard-coded value. This method is the &#8220;EndsWithSaurus&#8221; method. Notice how it is doing a string comparison on &#8220;saurus&#8221;.</p>
<p>This doesn&#8217;t help me at all! Unless I know at design time what I would be searching for. But what if I have two lists. One list is a master list of countries in Asia and the other list is a supposed subset of that list. Let&#8217;s say it is a list provided from user input. I want to validate the list the user has provided contains only countries that exist in Asia. So I need to iterate through each item in the user-provided list and for each iteration of the loop determine if the current item exists in the Asia master list. Something like this:</p>
<p>[code lang='csharp']</p>
<p>private void validateUserInput(List listWithValuesEnteredByUser)<br />
{<br />
List asiaList = MethodThatReturnsAllCountriesInAsia();</p>
<p>foreach (string current in listWithValuesEnteredByUser)<br />
{<br />
// determine here if the value exists<br />
}<br />
}</p>
<p>[/code]</p>
<p>Now I&#8217;m suddenly in a sport where I can&#8217;t hardcode the search routine that Find, FindIndex or FindAll might use. We all know that hard coding is a bad idea anyway so we shouldn&#8217;t get away with it even if we can but you see my point. And since we all know hard coding is bad, we all also know making use of a wider scoped variable in this case would be bad as well right? We shouldn&#8217;t even look twice at that temptation. It&#8217;s a hack and a work around as seen here:</p>
<p>[code lang='csharp']</p>
<p>// ugly work around hack<br />
string _widelyScopedVariable = string.Empty;</p>
<p>private void validateUserInput(List listWithValuesEnteredByUser)<br />
{<br />
List asiaList = MethodThatReturnsAllCountriesInAsia();</p>
<p>foreach (string current in listWithValuesEnteredByUser)<br />
{<br />
// ugly work around hack<br />
_widelyScopedVariable = current;</p>
<p>if (string.IsNullOrEmpty(asiaList.Find(findCountry)))<br />
{<br />
// country not found. user input found to be invalid<br />
}<br />
}<br />
}</p>
<p>private bool findCountry(string input)<br />
{<br />
// ugly work around hack<br />
return _widelyScopedVariable == input;<br />
}</p>
<p>[/code]</p>
<p><strong>The Answer</strong></p>
<p>So what is the correct way of doing the above? Anonymous delegates. With anonymous delegates we can embed a method that will share the scope of our loop. This means it <em>will</em> have access to &#8220;current&#8221; which is what we are searching for. Here is some sample code:</p>
<p>[code lang='csharp']</p>
<p>private void validateUserInput(List listWithValuesEnteredByUser)<br />
{<br />
List asiaList = MethodThatReturnsAllCountriesInAsia();</p>
<p>foreach (string current in listWithValuesEnteredByUser)<br />
{<br />
if (string.IsNullOrEmpty(asiaList.Find(delegate(string input)<br />
{<br />
return (input == current);<br />
})))<br />
{<br />
// country not found. user input found to be invalid<br />
}<br />
}<br />
}</p>
<p>[/code]</p>
<p><strong>Wrapup</strong></p>
<p>Not only does this significantly shorten the code we have to write (a definite plus) but we also don&#8217;t have to use any ugly hacks.</p>
<p>It is important to note that &#8220;input&#8221; is defined as a string because the list I am searching through is a list of strings (List). If for instance you have a generic list defined like: List&lt;Animal&gt; then the parameter changes from &#8220;string input&#8221; to &#8220;Animal input&#8221;.</p>
<p>It is also important to say that since it cannot be assumed that your generic list is sorted and in some cases can&#8217;t be sorted it is not possible for this built-in routine to search your list using a binary search and therefore is likely to be less efficient than the dictionary search.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.del337ed.com/blog/index.php/2008/01/24/making-use-of-the-find-findindex-or-findall-methods-with-generic-lists-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Clearing the read-only flag on a file in C#</title>
		<link>http://www.del337ed.com/blog/index.php/2007/09/05/clearing-the-read-only-flag-on-a-file-in-c/</link>
		<comments>http://www.del337ed.com/blog/index.php/2007/09/05/clearing-the-read-only-flag-on-a-file-in-c/#comments</comments>
		<pubDate>Wed, 05 Sep 2007 22:58:45 +0000</pubDate>
		<dc:creator>omatase</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.del337ed.com/blog/index.php/2007/09/05/clearing-the-read-only-flag-on-a-file-in-c/</guid>
		<description><![CDATA[[code lang="c#"]
FileInfo myFile = new FileInfo("c:\\myfile.txt");
if ((myFile &#038; FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// remove the read only attribute
myFile.Attributes = (FileAttributes)(Convert.ToInt32(myFile.Attributes) - Convert.ToInt32(FileAttributes.ReadOnly));
}
[/code]
]]></description>
			<content:encoded><![CDATA[<p>[code lang="c#"]<br />
FileInfo myFile = new FileInfo("c:\\myfile.txt");</p>
<p>if ((myFile &#038; FileAttributes.ReadOnly) == FileAttributes.ReadOnly)<br />
{<br />
// remove the read only attribute<br />
myFile.Attributes = (FileAttributes)(Convert.ToInt32(myFile.Attributes) - Convert.ToInt32(FileAttributes.ReadOnly));<br />
}<br />
[/code]</p>
]]></content:encoded>
			<wfw:commentRss>http://www.del337ed.com/blog/index.php/2007/09/05/clearing-the-read-only-flag-on-a-file-in-c/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
