<?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>On technology and development &#187; code</title>
	<atom:link href="http://blog.codewrench.net/tag/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.codewrench.net</link>
	<description>My thoughs on stuff</description>
	<lastBuildDate>Thu, 09 Sep 2010 06:53:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Sorting a generic list on arbitrary property (C#)</title>
		<link>http://blog.codewrench.net/2009/04/14/sorting-a-generic-list-on-arbitrary-property/</link>
		<comments>http://blog.codewrench.net/2009/04/14/sorting-a-generic-list-on-arbitrary-property/#comments</comments>
		<pubDate>Tue, 14 Apr 2009 16:20:58 +0000</pubDate>
		<dc:creator>Pål</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[reflection]]></category>
		<category><![CDATA[Source]]></category>

		<guid isPermaLink="false">http://blog.paks.no/?p=259</guid>
		<description><![CDATA[I often need to sort a generic list on some arbitrary property. After writing the code a couple of times I decided to make it more generic using generics and some reflection. Oh, I know that reflection if costly and &#8230; <a href="http://blog.codewrench.net/2009/04/14/sorting-a-generic-list-on-arbitrary-property/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I often need to sort a generic list on some arbitrary property. After writing the code a couple of times I decided to make it more generic using generics and some reflection. Oh, I know that reflection if costly and this is not a good way to sort large lists, but I typically work with small lists.<br />
<span id="more-259"></span></p>
<pre lang="csharp">
public enum SortDirection
{
   Ascending, Descending
}

public class ListSorter where T : class
{
  public static List Sort
(
              List<T> listToSort,
              string propertyName,
              SortDirection direction) where P : IComparable
  {
    Type propertyType = typeof (P);
    Type comparableInterface = propertyType.GetInterface("IComparable");

    if (comparableInterface == null)
        throw new Exception("Properties to sort by must be IComparable");

    listToSort.Sort(
        delegate(T x, T y)
            {
              PropertyInfo p1 = x.GetType().GetProperty(propertyName, propertyType);
              PropertyInfo p2 = y.GetType().GetProperty(propertyName, propertyType);

              object p1objvalue = p1.GetValue(x, null);
              object p2objvalue = p2.GetValue(y, null);

              P p1value = (P)p1objvalue;
              P p2value = (P)p2objvalue;

              if (direction == SortDirection.Ascending)
                  return p1value.CompareTo(p2value);
              else
                  return p2value.CompareTo(p1value);
          });

    return listToSort;
  }
}
</pre>
<p>To sort a list of Person objects by the string property FirstName do the following:</p>
<pre lang="csharp">
List<Person> myUnsortedList = GetPersonsInRandomOrder();
List<Person> sortedList =  ListSorter
                                     .Sort(
                                     myUnsortedList,
                                     "FirstName",
                                     SortDirection.Ascending);
</pre>
<p>To sort a list of Person objects by the int property Age do the following:</p>
<pre lang="csharp">
List<Person> myUnsortedList = GetPersonsInRandomOrder();
List<Person> sortedList =  ListSorter
                                     .Sort(
                                     myUnsortedList,
                                     "Age",
                                     SortDirection.Ascending);
</pre>
<p>If you have the luxury of using .NET Framework 3.0 or 3.5 you can use Linq to solve the problem really quick:</p>
<pre lang="csharp">

var sortedPersonList = from p in unsortedPersonList
                               orderby p.FirstName
                               select p;

foreach (var person in sortedPersonList)
{
    Console.WriteLine(person.FirstName + " " + person.LastName);
}
</pre>
<p>Leave a comment to this post if you have any thoughts.</p>
<style>
 #sidebars {    visibility: hidden;    display: none; }
 #content { width: 860px; }
</style>
]]></content:encoded>
			<wfw:commentRss>http://blog.codewrench.net/2009/04/14/sorting-a-generic-list-on-arbitrary-property/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Silverlight 3</title>
		<link>http://blog.codewrench.net/2009/03/26/silverlight-3/</link>
		<comments>http://blog.codewrench.net/2009/03/26/silverlight-3/#comments</comments>
		<pubDate>Thu, 26 Mar 2009 13:59:20 +0000</pubDate>
		<dc:creator>Pål</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://blog.paks.no/?p=123</guid>
		<description><![CDATA[Microsoft has just released the first beta of Silverlight 3. I encourage you to check out  Tim Heuer&#8217;s great guide to the new features.]]></description>
			<content:encoded><![CDATA[<p>Microsoft has just released the first beta of Silverlight 3. I encourage you to check out  Tim Heuer&#8217;s great <a href="http://timheuer.com/blog/archive/2009/03/18/silverlight-3-whats-new-a-guide.aspx">guide to the new features</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.codewrench.net/2009/03/26/silverlight-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PI day</title>
		<link>http://blog.codewrench.net/2009/03/14/pi-day/</link>
		<comments>http://blog.codewrench.net/2009/03/14/pi-day/#comments</comments>
		<pubDate>Sat, 14 Mar 2009 07:55:48 +0000</pubDate>
		<dc:creator>Pål</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[PI]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://blog.paks.no/?p=101</guid>
		<description><![CDATA[Today is PI day (3.14) at least in the part of the world that writes the month before the day. To celebrate I wrote this little silverlight application that calculates the first 1000 digits of PI. Update: Added the every &#8230; <a href="http://blog.codewrench.net/2009/03/14/pi-day/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Today is PI day (3.14) at least in the part of the world that writes the month before the day. To celebrate I wrote this little silverlight application that calculates the first 1000 digits of PI. Update: Added the every so catchy PI song to the post.</p>
<p><span id="more-101"></span></p>
<p><object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="870" height="300"><param name="source" value="/ClientBin/SilverlightPI.xap.zip"/><param name="background" value="white" /><param name="minRuntimeVersion" value="2.0.31005.0" /><param name="autoUpgrade" value="true" /><a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;"><br />
     			<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/><br />
			</a><br />
		</object><br />
<object width="165" height="38" data="/niftyplayer.swf?file=/wp-content/uploads/2009/03/pi.mp3&amp;as=1" type="application/x-shockwave-flash"><param name="id" value="niftyPlayer1" /><param name="quality" value="high" /><param name="bgcolor" value="#FFFFFF" /><param name="src" value="/niftyplayer.swf?file=/wp-content/uploads/2009/03/pi.mp3&amp;as=1" /><param name="name" value="niftyPlayer1" /></object></p>
<style>
 #sidebars {    visibility: hidden;    display: none; }
</style>
]]></content:encoded>
			<wfw:commentRss>http://blog.codewrench.net/2009/03/14/pi-day/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler and Linq</title>
		<link>http://blog.codewrench.net/2009/03/12/project-euler-and-linq/</link>
		<comments>http://blog.codewrench.net/2009/03/12/project-euler-and-linq/#comments</comments>
		<pubDate>Thu, 12 Mar 2009 19:22:44 +0000</pubDate>
		<dc:creator>Pål</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Euler]]></category>
		<category><![CDATA[Iterators]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Source]]></category>

		<guid isPermaLink="false">http://blog.paks.no/?p=69</guid>
		<description><![CDATA[First I&#8217;d like to thank Stefaan for introducing me to Project Euler. Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant &#8230; <a href="http://blog.codewrench.net/2009/03/12/project-euler-and-linq/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>First I&#8217;d like to thank <a href="http://stefaan.wordpress.com/">Stefaan</a> for introducing me to <a href="http://projecteuler.net/">Project Euler</a>. Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.</p>
<p>Most of the problems you can brute force in resonable time, but the challenge is more of a personal level in trying to solve them elegant or in as few lines as possible.</p>
<p>I quickly found that the magic of yield return and Linq was well suited to solve several of the problems I&#8217;ve encountered yet. So I decided to write a blog post about them and share my new-found knowlege of Linq.</p>
<p><strong>Problem 1: <span style="text-decoration: none;">Add all the natural numbers below one thousand that are multiples of 3 or 5</span></strong></p>
<p>The Enumerable pattern is quite extraordinary when used in Linq like this. So I decided to use the same pattern on other problems as well.</p>
<pre>[code lang="csharp"]
return Enumerable.Range(1, 999)
.Where(x => x % 5 == 0 || x % 3 == 0)
.Sum();
[/code]</pre>
<p><strong>Problem 2: Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million</strong></p>
<p>First I made a sequence generator for Fibonacci numbers:</p>
<pre>[code lang="csharp"]
internal static IEnumerable<long>FibonacciSequence()
{
  long last1 = 1;
  yield return 1;

  long last2 = 2;
  yield return 2;

  while (true)
  {
    long next = last1 + last2;
    last1 = last2;
    last2 = next;
    yield return next;
  }
}
[/code]</pre>
<p><strong>Problem 3: What is the largest prime factor of the number 600851475143 ?</strong></p>
<p>Again I start with creating a sequence generator. This one returns the sequence of factors for any number.</p>
<pre>[code lang="csharp"]
internal static IEnumerable<long> GetFactors(long x)
{
    for (long factor = 1; factor * factor <= x; factor++)
    {
        if (x % factor == 0)
        {
            yield return factor;
            if (factor * factor != x)
                yield return x / factor;
        }
    }
}
[/code]</pre>
<p>We also need a small helper function to check if a number if a prime number:</p>
<pre>[code lang="csharp"]
private static bool IsPrime(long num)
{
  long limit = (long)Math.Sqrt(num);

  for (long d = 2; d <= limit; d++)
  {
      if (num % d == 0)
          return false;
  }

  return true;
}
[/code]</pre>
<p>Finally the actual Linq query to find the largest prime factor of the number 600851475143 :</p>
<pre>[code lang="csharp"]
var primeFactors = from factor in GetFactors(600851475143)
                          where IsPrime(factor)
                          select factor;

return primeFactors.Max();
[/code]</pre>
<p>I also have use the same pattern on several of the other problems like nr 10: <strong>Find the sum of all prime numbers below 2 000 000:</strong></p>
<pre>[code lang="csharp"]
return PrimeNumbers()
         .TakeWhile(x => x < 2000000)
         .Sum();
[/code]</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.codewrench.net/2009/03/12/project-euler-and-linq/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Find the oldest file</title>
		<link>http://blog.codewrench.net/2009/03/04/find-the-oldest-file/</link>
		<comments>http://blog.codewrench.net/2009/03/04/find-the-oldest-file/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 21:56:00 +0000</pubDate>
		<dc:creator>Pål</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[dos]]></category>

		<guid isPermaLink="false">http://importdump.wordpress.com/2009/03/04/find-the-oldest-file/</guid>
		<description><![CDATA[I had a problem at work the other day. In a project we have a service that needs to handle files on a first come, first served basis. In effect it scans a folder for files and find the file &#8230; <a href="http://blog.codewrench.net/2009/03/04/find-the-oldest-file/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I had a problem at work the other day. In a project we have a service that needs to handle files on a first come, first served basis. In effect it scans a folder for files and find the file with the oldest last modified stamp, then it processes the file.</p>
<p>This seems a simple enough task, but once when the service was down for a long time the number of files waiting to be processed was huge (in the several hundred thousand range). Scanning a folder with that many files in C# and then determining the oldest one takes quite a long time.</p>
<p>So I took a look at three different methods for solving this simple task.</p>
<p>1. Using the DirectoryInfo.GetFiles function<br />
2. Using the Directoty.GetFiles and then Directory.GetLastWriteTime on each file<br />
3. Using plain old DOS dir command</p>
<p>For 50.000 files the first two options takes about 7 seconds each on my development machine. While using dir takes only 0.7 seconds. Thats 10 times the performance difference.</p>
<p>This is how I managed to tweak dir to do the work:</p>
<pre>static string ScanFilesUsingDir(string filePath)
{
   string cmd = @"c:\Windows\System32\cmd.exe";
   string args = @"/C \"dir " + filePath + " /B /O:D /T:W\"";

   Process proc = new System.Diagnostics.Process();
   proc.EnableRaisingEvents = false;
   proc.StartInfo.CreateNoWindow = false;
   proc.StartInfo.FileName = cmd;
   proc.StartInfo.Arguments = args;
   proc.StartInfo.RedirectStandardOutput = true;
   proc.StartInfo.UseShellExecute = false;
   proc.Start();

   // Display returned console information if any
   StreamReader dirOutput = proc.StandardOutput;
   string oldestFile = dirOutput.ReadLine();
   dirOutput.Close();</pre>
<pre>   proc.Kill();
   return oldestFile;
}</pre>
<p>Oldest file found: f9e41b18-efa8-49ee-9a51-a89f7ef514ee.tmp<br />
Activity &#8216;Using DirectgoryInfo&#8217; took 00:00:07.0810000</p>
<p>Oldest file found: f9e41b18-efa8-49ee-9a51-a89f7ef514ee.tmp<br />
Activity &#8216;Using FileInfo&#8217; took 00:00:07.2710000</p>
<p>Oldest file found: f9e41b18-efa8-49ee-9a51-a89f7ef514ee.tmp<br />
Activity &#8216;Using Shell Dir&#8217; took 00:00:00.7030000</p>
<p>Just goes to show that POD (Plain Old Dos) still is good for something <img src='http://blog.codewrench.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Complete source code: <a href="http://www.fileqube.com/file/EhaModI177391">FileGenerator.rar</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.codewrench.net/2009/03/04/find-the-oldest-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
