<?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>Marius Bancila's Blog &#187; C#</title>
	<atom:link href="http://mariusbancila.ro/blog/category/it/software/net/csharp/feed/" rel="self" type="application/rss+xml" />
	<link>http://mariusbancila.ro/blog</link>
	<description>Sharing my opinions and ideas!</description>
	<lastBuildDate>Fri, 06 Apr 2012 13:45:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>WinRT and winmd Files</title>
		<link>http://mariusbancila.ro/blog/2011/10/30/winrt-and-winmd-files/</link>
		<comments>http://mariusbancila.ro/blog/2011/10/30/winrt-and-winmd-files/#comments</comments>
		<pubDate>Sun, 30 Oct 2011 19:15:40 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[CTPs & Betas]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[WinRT]]></category>
		<category><![CDATA[C++/CX]]></category>
		<category><![CDATA[ildasm]]></category>
		<category><![CDATA[managed]]></category>
		<category><![CDATA[native]]></category>
		<category><![CDATA[win8]]></category>
		<category><![CDATA[winmd]]></category>
		<category><![CDATA[winrt]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=1162</guid>
		<description><![CDATA[If you tried the Win8 Developer Preview and built WinRT components (native or managed) you noticed the .winmd files. The name stands for Windows Meta Data and the format of these files is the same used by the .NET framework for the CLI, i.e. ECMA-335. That means you can actually read these files with a [...]]]></description>
			<content:encoded><![CDATA[<p>If you tried the Win8 Developer Preview and built WinRT components (native or managed) you noticed the <strong>.winmd</strong> files. The name stands for Windows Meta Data and the format of these files is the same used by the .NET framework for the CLI, i.e. <a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm">ECMA-335</a>. That means you can actually read these files with a tool such as ILDASM or Reflector, or of course, through .NET Reflection.</p>
<p>If you look in C:\Windows\System32\WinMetadata folder you&#8217;ll find the WinMD files for the Windows Runtime. You can browse the content of these files with one of the aforementioned disassemblers.<br />
<img alt="" src="/blog/wp-content/uploads/2011/10/winmetadatafolder.png" title="WinMetadata folder" class="alignnone" width="856" height="601" /></p>
<p>Here are two dummy WinRT components, one developed in C++/CX and one in C#.</p>
<table>
<tr>
<td>Native WinRT component in C++/CX</td>
<td>Managed WinRT component in C#</td>
</tr>
<tr valign="top">
<td>
<pre class="cpp" name="code">
namespace WinRTNativeComponent
{
    public ref class MyWinRTComponent sealed
    {
        int _id;
		String^ _name;

    public:
		MyWinRTComponent () {}
		~MyWinRTComponent () {}

        property int Id
        {
            int get() { return _id; }
            void set(int value) { _id = value; }
        }

		property String^ Name
		{
			String^ get() {return _name;}
			void set(String^ value) { _name= value; }
		}

        bool Update(int id, String^ name)
		{
			{
				if(_id == id)
				{
					_name = name;
					return true;
				}

				return false;
			}
		}
    };
}
</pre>
</td>
<td>
<pre class="csharp" name="code">
namespace WinRTManagedComponent
{
    public sealed class MyWinRTComponent
    {
        public int Id { get; set; }
        public string Name { get; set; }

        bool Update(int id, string name)
        {
            if (Id == id)
            {
                Name = name;
                return true;
            }

            return false;
        }
    }
}
</pre>
</td>
</tr>
</table>
<p>In the case of the native component, the output includes a DLL and a WINMD file (and of course a PDB file). In the case of the managed component, the output is either a DLL only or a WINMD only (plus the associated PDB file), depending on the Output type as defined in the project properties. If the type is <strong>Class Library</strong> the output is a DLL; this is enough if your component is supposed to be consumed from a managed language. However, if the component should be consumed from C++/CX or Javascript, then the project type must be set to <strong>WinMD File</strong>. In this case the DLL is replaced by a WinMD file, that contains, at least in the current version, both the matadata (as implied by the name) and the implementation.</p>
<table>
<tr>
<td>Native WinRT component in C++/CX</td>
<td>Managed WinRT component in C#</td>
</tr>
<tr valign="top">
<td><img alt="" src="/blog/wp-content/uploads/2011/10/winmdnative.png" title="WinMD for native component" class="alignnone" width="419" height="600" /></td>
<td><img alt="" src="/blog/wp-content/uploads/2011/10/winmdmanaged.png" title="WinMD for managed component" class="alignnone" width="419" height="600" /></td>
</tr>
</table>
<p>It should be possible to use reflection with winmd files. However, the reflection capabilities of .NET 4.5 in this developer preview seem to be very limited. The only available Load method in the Assembly class is</p>
<pre class="csharp" name="code">
public static Assembly Load(AssemblyName assemblyRef);
</pre>
<p>Trying to load the winmd file fails with a FailLoadException with the message &#8220;Could not load file or assembly &#8216;Winmdreflection, ContentType=WindowsRuntime&#8217; or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0&#215;80131515)&#8221;.</p>
<pre class="csharp" name="code">
try
{
    var assembly = Assembly.Load(
        new AssemblyName()
        {
            Name = "WinRTManagedComponent",
            ContentType = AssemblyContentType.WindowsRuntime
        });
}
catch (Exception ex)
{
}
</pre>
<p>It is possible though to read information for the types described in an winmd file in native code using the  <a href="http://msdn.microsoft.com/en-us/library/ms230172.aspx">IMetaDataImport</a>/<a href="http://msdn.microsoft.com/en-us/library/ms232953.aspx">IMetaDataImport2</a> COM interfaces. You can find an example <a href="http://social.msdn.microsoft.com/Forums/en-AU/winappswithnativecode/thread/211ef583-db11-4e55-926b-6d9ab53dbdb4">here</a>. But this has the drawback that you have to instantiate an object first and then query for its type information.</p>
<p>To use a Windows Runtime component in a Metro application (managed or native) you have to add a reference to it. That is pretty straight forward. In the following example I&#8217;m adding a reference in a C++ Metro application to the two WinRT components, one native and one managed, shown earlier. To do this, you can go to the project&#8217;s property page and open the Common Properties > Frameworks and References page, or use the References command from the project&#8217;s context menu which opens that page directly. You can add a reference to a project from the same solution, to a Windows component or you can browse for the winmd file.<br />
<img alt="" src="/blog/wp-content/uploads/2011/10/winmdreference.png" title="Adding a references to an winmd file" class="alignnone" width="800" height="556" /></p>
<p>Having done that you can instantiate the WinRT components.</p>
<pre class="cpp" name="code">
auto obj1 = ref new WinRTManagedComponent::MyWinRTComponent();
obj1->Id = 1;
obj1->Name = L"marius";

auto obj2 = ref new WinRTNativeComponent::MyWinRTComponent();
obj2->Id = 1;
obj2->Name = L"marius";
</pre>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2011/10/30/winrt-and-winmd-files/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Accessing 64-bit Native COM Server From a Managed Client</title>
		<link>http://mariusbancila.ro/blog/2011/10/19/accessing-64-bit-native-com-server-from-a-managed-client/</link>
		<comments>http://mariusbancila.ro/blog/2011/10/19/accessing-64-bit-native-com-server-from-a-managed-client/#comments</comments>
		<pubDate>Wed, 19 Oct 2011 07:26:43 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[64bit]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[interop]]></category>
		<category><![CDATA[managed]]></category>
		<category><![CDATA[native]]></category>
		<category><![CDATA[tlbimp]]></category>
		<category><![CDATA[VisualStudio]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=1147</guid>
		<description><![CDATA[Not long ago I ran into a COM interop problem that was a bit tricky to fix. So I&#8217;m sharing the problem and the solution here in case others encounter the same problem. I had this native in-proc COM server that initially was built only for x86. It was used in a native MFC application [...]]]></description>
			<content:encoded><![CDATA[<p>Not long ago I ran into a COM interop problem that was a bit tricky to fix. So I&#8217;m sharing the problem and the solution here in case others encounter the same problem.</p>
<p>I had this native in-proc COM server that initially was built only for x86. It was used in a native MFC application as well as a C# Windows Forms application, where it was added as a COM reference. Both worked nicely. But then I needed to port the MFC app to the x64 platform, so I had to do the same with the in-proc COM server. They both worked correctly, but the managed app, which had to be available also both as 64-bit and 32-bit (even on 64-bit machines), was broken. Eventually I traced the problem to some COM method calls which were a bit atypical, because the arguments to the methods were not COM &#8220;native&#8221; types, but custom structures.</p>
<p>These structures looked like this:</p>
<pre class="cpp" name="code">
[uuid(6F13C84D-0E01-48cd-BFD4-F7071A32B49F)] struct S
{
      long a;
      BSTR b;
      long c;
      BSTR d;
      long e;
      BSTR f;
      BSTR g;
      BSTR h;
      BSTR i;
      long j;
      BSTR k;
      long l;
      BSTR m;
      long n;
};
</pre>
<p>and the COM method signature:</p>
<pre class="cpp" name="code">
[id(42)] HRESULT GetListOfStructs(SAFEARRAY(struct S)* arrRes);
</pre>
<p>When you add a COM reference to a .NET assembly, Visual Studio runs <a href="http://msdn.microsoft.com/en-us/library/tt0cf3sx.aspx">tlbimp.exe</a> to generate a .NET assembly with equivalent definitions to the type definitions found in the COM type library. This interop assembly is used to access the COM server. It contains Runtime Callable Wrappers that bridge the two worlds together. By default, the interop assembly, generated in the project&#8217;s output folder, is called <strong>Interop.&lt;comname&gt;Lib.dll</strong>. For instance if the COM server is called NativeCOMServer, the interop assembly is called Interop.NativeCOMServerLib.dll.</p>
<p>The wrapper that was generated in the interop assembly had the following signature for the aforementioned method:</p>
<pre class="cpp" name="code">
[DispId(42)]
void GetListOfStructs(ref Array arrRes);
</pre>
<p>and therefore used like this:</p>
<pre class="cpp" name="code">
System.Array result = null;
obj.GetListOfStructs(ref result);
</pre>
<p>The call was performed correctly, the native code was executing, but as soon as it was returning an access violation exception was occurring. Thanks to <a href="http://stackoverflow.com/questions/7517474/accessing-64-bit-com-server-from-managed-assembly-fails">Hans Passant</a> I figured the problem was rooted in the way Visual Studio generates the interop assembly. The generated RCW didn&#8217;t know how to handle the custom structure correctly. Probably different padding on the two sides generated the access violation. </p>
<p>The trick was to generate the interop assembly directly, as a custom build step in the COM server project, and include it as an assembly reference in the managed project. Here are the commands for the custom build (must to make sure you have the correct path to the 32-bit and the 64-bit version of tlbimp.exe):</p>
<pre>
<pathto32bittool>\TlbImp.exe $(TargetPath) /out:$(TargetDir)\NativeCOMLib.Interop.dll /primary  /keyfile:mykey.snk /machine:x86
<pathto64bittool>\TlbImp.exe $(TargetPath) /out:$(TargetDir)\NativeCOMLib.Interop.dll /primary  /keyfile:mykey.snk /machine:x64
</pre>
<p>The result was a wrapper with methods like this:</p>
<pre class="cpp" name="code">
[DispId(42)]
void GetListOfStructs(ref S[] arrRes);
</pre>
<p>which of course had to be called like this:</p>
<pre class="cpp" name="code">
S[] result = null;
obj.GetListOfStructs(ref result);
</pre>
<p>To include either one or the other in the C# project I had to manually change the project file, since Visual Studio does not know conditional references, a feature available in MSBuild. I didn&#8217;t build the managed app for Any CPU because it had to be able to run as 32-bit on 64-bit machines, so I had two configurations, one for x86 and one fore x64.</p>
<pre class="xml" name="code">
    &lt;Reference Condition=" '$(Platform)' == 'x86' " Include="NativeCOMServer.Interop,
               Version=1.0.0.0, Culture=neutral, PublicKeyToken=f5b9312191a42d52, processorArchitecture=x86">
      &lt;SpecificVersion>False&lt;/SpecificVersion>
      &lt;HintPath>..\Bin\NativeCOMServer.Interop.dll&lt;/HintPath>
    &lt;/Reference>
    &lt;Reference Condition=" '$(Platform)' == 'x64' " Include="NativeCOMServer.Interop,
               Version=1.0.0.0, Culture=neutral, PublicKeyToken=f5b9312191a42d52, processorArchitecture=x64">
      &lt;SpecificVersion>False&lt;/SpecificVersion>
      &lt;HintPath>..\Bin64\NativeCOMServer.Interop.dll&lt;/HintPath>
    &lt;/Reference>
</pre>
<p>But this time the wrappers were able to bridge the call and everything worked smoothly. </p>
<p>The lesson learned is that when you have COM custom structures you should not rely on the way Visual Studio generates the interop assembly. You should build the interop explicitly (maybe as a custom build step, like I did) and include it as an assembly reference to your managed project.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2011/10/19/accessing-64-bit-native-com-server-from-a-managed-client/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Weasel Implementation in C#</title>
		<link>http://mariusbancila.ro/blog/2010/01/11/weasel-implementation-in-csharp/</link>
		<comments>http://mariusbancila.ro/blog/2010/01/11/weasel-implementation-in-csharp/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 10:08:13 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[dawkins]]></category>
		<category><![CDATA[evolution]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[weasel]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=455</guid>
		<description><![CDATA[In the book The Blind Watchmaker, Richard Dawkins explains how evolution happens through accumulated small random variations (or mutations) filtered by the natural selection, as opposed to the mainstream misinterpretation that evolution happens in big leaps. He proposes a computer program, called weasel, to demonstrate how the accumulated small improvements (mutations that bring a benefit [...]]]></description>
			<content:encoded><![CDATA[<p>In the book <a href="http://en.wikipedia.org/wiki/The_Blind_Watchmaker" target="_blank">The Blind Watchmaker</a>, <a href="http://en.wikipedia.org/wiki/Richard_Dawkins" target="_blank">Richard Dawkins</a> explains how evolution happens through accumulated small random variations (or mutations) filtered by the natural selection, as opposed to the mainstream misinterpretation that evolution happens in big leaps. He proposes a computer program, called <a href="http://en.wikipedia.org/wiki/Weasel_program" target="_blank">weasel</a>, to demonstrate how the accumulated small improvements (mutations that bring a benefit to the individual so that it is &#8220;chosen&#8221; by the natural selection) produce faster results.</p>
<blockquote><p>
I don&#8217;t know who it was first pointed out that, given enough time, a monkey bashing away at random on a typewriter could produce all the works of Shakespeare. The operative phrase is, of course, given enough time. Let us limit the task facing our monkey somewhat. Suppose that he has to produce, not the complete works of Shakespeare but just the short sentence &#8216;Methinks it is like a weasel&#8217;, and we shall make it relatively easy by giving him a typewriter with a restricted keyboard, one with just the 26 (capital) letters, and a space bar. How long will he take to write this one little sentence?</p>
<p>[...]</p>
<p>We again use our computer monkey, but with a crucial difference in its program. It again begins by choosing a random sequence of 28 letters, just as before &#8230; it duplicates it repeatedly, but with a certain chance of random error – &#8216;mutation&#8217; – in the copying. The computer examines the mutant nonsense phrases, the &#8216;progeny&#8217; of the original phrase, and chooses the one which, however slightly, most resembles the target phrase, METHINKS IT IS LIKE A WEASEL.
</p></blockquote>
<p>The phrase &#8220;METHINKS IT IS LIKE A WEASEL&#8221; is from Hamlet:</p>
<blockquote><p>
<strong>Hamlet</strong>: Do you see yonder cloud that&#8217;s almost in shape of a camel?<br />
<strong>Polonius</strong>: By the mass, and &#8217;tis like a camel, indeed.<br />
<strong>Hamlet</strong>: Methinks it is like a weasel.
</p></blockquote>
<p>The algorithm as described on Wikipedia, is as follows: </p>
<ol>
<li>Start with a random string of 28 characters.</li>
<li>Make 100 copies of this string, with a 5% chance per character of that character being replaced with a random character.</li>
<li>Compare each new string with the target &#8220;METHINKS IT IS LIKE A WEASEL&#8221;, and give each a score (the number of letters in the string that are correct and in the correct position).</li>
<li>If any of the new strings has a perfect score (28), halt.</li>
<li>Otherwise, take the highest scoring string, and go to step 2.</li>
</ol>
<p>A character is an upper case letter or space, the number of copies per iteration could be 100 and the mutation rate 5%.  </p>
<p>The following C# code is an implementation of the algorithm.</p>
<pre name="code" class="csharp">
class Weasel1
{
   private const string ALLOWED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVXYWZ ";
   private const string TARGET = "METHINKS IT IS LIKE A WEASEL";
   Random rand = new Random();

   private int Fitness(string candidate)
   {
      int score = 0;
      for (int i = 0; i &lt; candidate.Length; ++i)
      {
         if (candidate[i] == TARGET[i])
            score++;
      }

      return score;
   }

   private string Mutate(string parent)
   {
      StringBuilder builder = new StringBuilder();
      for (int i = 0; i < parent.Length; ++i)
      {
         bool mutate = rand.Next(20) == 10;
         builder.Append(
            mutate ?
            ALLOWED_CHARS[rand.Next(ALLOWED_CHARS.Length)] : parent
            [i]);
      }
      return builder.ToString();
   }

   public void Run(int copies)
   {
      StringBuilder builder = new StringBuilder();
      for (int i = 0; i &lt; TARGET.Length; ++i)
      {
         builder.Append(ALLOWED_CHARS[rand.Next(ALLOWED_CHARS.Length)]);
      }
      string parent = builder.ToString();

      int step = 1;
      Console.WriteLine("{0:D3} {1}", step, parent);

      do
      {
         step++;

         string[] children = new string[copies];
         for (int i = 0; i &lt; copies; ++i)
         {
            children[i] = Mutate(parent);
         }

         int indexMax = 0;
         int scoreMax = 0;
         for (int i = 0; i &lt; copies; ++i)
         {
            int score = Fitness(children[i]);

            if (score &gt; scoreMax)
            {
               scoreMax = score;
               indexMax = i;
            }
         }

         parent = children[indexMax];

         Console.WriteLine("{0:D3} {1}", step, parent);

      } while (parent != TARGET);
   }
}

class Program
{
   static void Main(string[] args)
   {
      Weasel1 weasel = new Weasel1();
      weasel.Run(100);
   }
}
</pre>
<p>Function Fitness() computes how similar an offspring is to the parent, function Mutate() makes a copy of the parent with a 5% chance for each character to mutate. Function Run() runs the algorithm until the target string is reached. A possible output of the program is shown below. Different runs require different number of iterations (even more than 100).</p>
<pre name="code" class="text">
001 E PVBQVRYRNQSRBCDLOCFOGEIB J
002 E PVBQVRYRNQSRBCDLOCFOWEIB J
003 E PVIQVRYRNQSRBCDLOCFOWEIB J
004 EEPLIQVUYRNQSRBCDLOCFOWEIB J
005 EEPLIQVU RNQSRBCDLOCFOWEIB J
006 EEPHIQLU RNQSRBCDLOCFKWEIB J
007 EEPHIQLU RNQSRHCDKOCFKWEIB J
008 EEPHIQLU RNQSSHCDKOCFKWEIB J
009 EEPHIQLU RNQSS CDKOCFKWEIB J
010 EEPHIQLU RNQSS CDKOCWKWEKB L
011 EEPHIQLU RNQSS CDKOCOKWEKB L
012 EEPHIQLU RN SS CDKOGOKWEKB L
013 EEPHIQLU RN SS LDKOGOKWEKB L
014 EEPHIQLU RT SS LDKOGOKWEKB L
015 EEPHIQLU RT SS LDKOGOKWEKBEL
016 EEPHIQLU RT SS LPKOGOKWEKBEL
017 EEPHIQLU RT SS LPKOGOKWEKSEL
018 EEPHIQLU IT SS LPKOGOKWEKSEL
019 EEPHIQLU IT SS LIKOGOKWEKSEL
020 EEPHIQLU IT SS LIKOGOKWEKSEL
021 EEKHIQLS IT SS LIKOGOKWEKSEL
022 EEKHIQLS IT SS LIKOGOKWEKSEL
023 EEKHIQLS IT SS LIKO OKWEKSEL
024 EEKHIQLS IT SS LIKO OFWEKSEL
025 EEKHIQLS IT ES LIKO OFWENSEL
026 EEKHINLS IT ES LIKO OFWENSEL
027 EEKHINLS IT ES LIKO O WENSEL
028 EEKHINLS IT ES LIKO O WECSEL
029 EEKHINLS IT BS LIKO O WEHSEL
030 EEKHINLS IT QS LIKO O WEASEL
031 EETHINSS IT QS LIKO O WEASEL
032 EETHINSS IT QS LIKO O WEASEL
033 EETHINSS IT IS LIKO O WEASEL
034 EETHINSS IT IS LIKO O WEASEL
035 EETHINBS IT IS LIKO O WEASEL
036 XETHINBS IT IS LIKO O WEASEL
037 XETHINBS IT IS LIKO O WEASEL
038 XETHINBS IT IS LIKO O WEASEL
039 XETHINBS IT IS LIKO O WEASEL
040 XETHINBS IT IS LIKK O WEASEL
041 XETHINBS IT IS LIKK O WEASEL
042 XETHINBS IT IS LIKK O WEASEL
043 XETHINKS IT IS LIKK O WEASEL
044 XETHINKS IT IS LIKK   WEASEL
045 XETHINKS IT IS LIKK   WEASEL
046 XETHINKS IT IS LIKK   WEASEL
047 XETHINKS IT IS LIKE   WEASEL
048 XETHINKS IT IS LIKE   WEASEL
049 METHINKS IT IS LIKE   WEASEL
050 METHINKS IT IS LIKE   WEASEL
051 METHINKS IT IS LIKE A WEASEL
</pre>
<p>We can change this algorithm to randomize the chance of mutation. The changes to the code are small (basically function Mutate changes to take not only the parent string but only the chance for the mutation rate), but this increases the number of iterations needed to reach the target string.</p>
<pre name="code" class="csharp">
class Weasel2
{
   const string TARGET = "METHINKS IT IS LIKE A WEASEL";
   const string ALLOWED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
   Random rand = new Random();

   private double Fitness(string candidate)
   {
      int score = 0;
      for (int i = 0; i &lt; candidate.Length; ++i)
      {
         if (candidate[i] == TARGET[i])
            score++;
      }

      return score;
   }

   private string Mutate(string parent, double rate)
   {
      StringBuilder builder = new StringBuilder();
      foreach(char c in parent)
      {
         builder.Append(
            rand.NextDouble() &lt; rate ?
            c:
            ALLOWED_CHARS[rand.Next(ALLOWED_CHARS.Length)]);
      }

      return builder.ToString();
   }

   public void Run(int copies)
   {
      StringBuilder builder = new StringBuilder();
      for (int i = 0; i &lt; TARGET.Length; ++i)
      {
         builder.Append(ALLOWED_CHARS[rand.Next(ALLOWED_CHARS.Length)]);
      }
      string parent = builder.ToString();

      int step = 1;
      Console.WriteLine("{0:D4} {1}", step, parent);

      do
      {
         string[] children = new string[copies];
         for(int i = 0; i &lt; copies; ++i)
         {
            children[i] = Mutate(parent, rand.NextDouble());
         }

         int indexMax = 0;
         double scoreMax = 0;
         for (int i = 0; i &lt; copies; ++i)
         {
            double score = Fitness(children[i]);

            if (score &gt; scoreMax)
            {
               scoreMax = score;
               indexMax = i;
            }
         }

         parent = children[indexMax];

         Console.WriteLine("{0:D4} {1}", step, parent);
         step++;

      } while (parent != TARGET);
   }
}
</pre>
<p>Here is the output, but because of the bigger number of iterations, only every 20th iteration is shown:</p>
<pre name="code" class="text">
0001 BXZZBDJSZTVYFWRSGNKYEULISWRK
0020 MSTCFNBSTITVIS L KPLEDBRASEC
0040 METCINQSDITVIS LIKW A IRISEW
0060 METLINKSOITJIS LJKW A IGASEW
0080 METLINKSOITJIS LJKX A WEAUEL
0100 METLINKSTKTXIS LIKK A WEAOEL
0120 METHINKS KTXIS LIKH A WEAOEL
0140 METHINKSDKTXIS LIKA A WEASEL
0160 METHINKSEGTXIS LIKA A WEASEL
0180 METHINKSEGTEIS LIKE A WEASEL
0200 METHIMKSEGTMIS LIKE A WEASEL
0220 METHIMKSTITNIS LIKE A WEASEL
0240 METHIAKSTIT IS LIKE A WEASEL
0260 METHIPKSTIT IS LIKE A WEASEL
0280 METHJKKSTOT IS LRKE A WEASEL
0300 METHYQKSCOT IS LRKE A WEASEL
0320 METHFPKSCOT IS LRKE A WEASEL
0340 METHFPKSCGT IS LRKE A WEASES
0360 METHINKS XT IS LMOE A WEAIEL
0380 METHINKS YT IS LMZE A WEAIEL
0400 METHINKS IT IS LMHE A WEAIEL
0420 METHINKS IT IS LEDE A WEANEL
0440 METHINKS IT IS LIPE A WEANYL
0460 METHINKS IT IS LIPE A WEAOYL
0480 METHINKS IT IS LIWE A WEARWL
0500 METHINKS IT IS LIWEDA WEAFWT
0520 METVINKS IT IS LILE A WEABBG
0540 METVINKS IT IS LIJE A WEABTG
0560 METHINKS IT IS LIJE A WEAMRV
0580 METHINKS IT IS LIZE A WEAMRV
0600 METHINKS IT IS LIZE A WEA OV
0620 METHINKS IT IS LIZE A WEAHE
0640 METHINKS IT IS LIJE A WEAHEH
0660 METHINKS IT IS LIFE A WEAHEH
0680 M THINKS IT IS LINE I WXAHEL
0700 MQTHINKS IT IS LIAE I WXASEL
0720 MZTHIRKS IT IS LIKE T WXASEL
0740 METHINKR IT IS LIKE T WRASEL
0760 METOINKI IT IS LIKE T WRASEL
0780 METMINKM IT IS LIKE A WQASEL
0800 METMINKS IT IS LIKE A WQASEL
0820 METJIXKS IT IS LIKE A WQASEL
0840 METJILKS IT IS LIKE A WUASEL
0860 METJIPKS IP IS LIKE A WAASEL
0880 METJIPKS IW IS LIKE A WLASEL
0900 METIIBKS QT IS LIKE A SEASEL
0920 METIIPKS PT IS LIKE A SEASEL
0940 METKINKS PT IS LIKE A TEASEL
0960 METKINKS BT IS LIKE A QEASEL
0980 METWINKS IT IS LIKE A QEASEL
1000 METOINKS IT IS LIKE ANQEASEL
1020 METUINKS IT IS LIKE AHTEASEL
1040 METUINKS IT IS LIKE AMWEASEO
1060 METQINKS IT IS LIKE AMWEASEO
1080 MZTYINKS IT ISULIKE AKWEASEL
1100 MZTYINKS IT ISULIKE APWEADEL
1120 MJTHINKS IT ISULIKE AEWEAQEL
1140 MJTHINKS IT ISULIKE AFWEAUEL
1160 MJTHINKS IT ISCLIKP AVWEABEL
1180 MJTHINKS IT IS LIKP AVWEAGEG
1200 MNTHINKS IT IS LIKM AVWEACE
1220 MNTHINKS IT IS LIKM AQWEACEL
1240 MNTHINKS IT IS LIKMXAKWEAAEL
1260 MNTHINKS CT IS LIKMGAPWEASEL
1280 MPTHINKS IX IS EIK GA WEASEL
1300 METHINKS IX IS LIK RA WEASEL
1320 METHINKS IZ IS LIKEWA WEASEL
1340 METHINKS IZ ISILIKEWA WEASEL
1360 METHINKS IJ ISILIKE A WEASEL
1380 METHINKS IM ISELIKE A WEASEL
1400 METHINKS IM ISELIKE A WEASEL
1420 METHINKS IU ISELIKE A WEASEL
1440 METHINKS IY ISELIKE A WEASEL
1460 METHINKS IT ISVLIKE A WEASEL
1480 METHINKS IT ISCLIKE A WEASEL
1500 METHINKS IT ISCLIKF A WEASEL
1520 METHINKS IT ISTLIKF A WEASEL
1540 METXINKS IT ISOLIKF A WEASEL
1560 MZTXINKS IT ISOLIKC A WEASEL
1580 MATXINKS IT IS LIKC A WEASEL
1600 MATXINKS IT IS LIKE A WEDSEL
1620 METHINKSGITVIC LIKE A WEASEL
1640 METHINKSGITQIC LIKE A WEASEL
1660 METHINLSAITQIC LIKE A WEASEL
1680 METHINLSAITQIH LIKE A WEASEL
1700 METHINGS ITAIH LIKE A WEASEL
1720 METHINGS ITRIS LIKE W WEASEL
1740 METHINVS IT IS LIJE A WEASEL
1760 METHINVS IT IS LIGE A WEASEL
1780 METHINVS IT IS LIGE A WEASEL
1800 METHINVS IT IS LI E A WEASYL
1820 METHIN S IT IS LIKE A WTASYT
1840 METHINQS IT IS LIKE A STASYT
1860 METHINWA IT IS LIKE A IFASES
1880 METHINKA IT IS LIKE A IFASEJ
1900 METHINKA IT YS LIKE O IEAAEL
1920 METHINKU IT YS LIKE O WEAAEL
1940 METHOJKM IT JS LIKE O WEAPEL
1960 METHOJKF IT IS LIKE  RWEATEL
1980 METHFGKF IT IS LIKE ARWBATEL
2000 METHYNKG IT IS LIKE ARWEALEL
2020 METHUNKD IT IS LIKE AAWEAWEL
2040 METHIWKN IT IS LIKE AYWEADEL
2060 METHIUKN IT IS LIKE AKWEAQEL
2080 METHIUKN IT IS LIKE A WEAQEL
2100 METHIAKN IT IS LIKE N WEAQEL
2120 METHINKK IT IS LIKE N WEEQEL
2140 METHDNKQ IT IS LIKE A WEBSEL
2160 METHDNKQ IT IS LIKE A WEBSEL
2180 METHDNKQ IT IS LIKE A WEBSEL
2200 METHMNKQ IT IS LIKE A WEBSEL
2220 MEKHBNKX IT IS LIKE A WEBSEL
2240 MEBHQNKS IT IS LIKE A WEBSEL
2260 METHQNKS IT IS LIKEZA WEFSEL
2280 METHGNKS IT IS LIKEZA WESSEL
2300 METHGNKS IT IS LIKEZA WEWSEL
2320 METHLNKS IT IP BIKE A WEOSEL
2340 METHYNKS IT IB SIKE A WEQSEL
2360 METHINKS ITQIJ LIKE A WEQSEL
2380 METHINKS ITIIJ LIKE A WEYSTL
2400 METQINKS ITIIJ LIKE A WEASGL
2420 METHINKS ITIIJJLIKE A WEASGL
2440 METHINKS ITQIWJLIKE A WEAS L
2460 METHINKS ITZIWJLIKE A WEASCL
2480 METHINKS IT IDLLIZE A UEASCL
2500 METHINKS IT ID LIZE A IEASZL
2520 METHINKS IT ID LIZE A IEASZL
2540 METHINKS IT IB LIZE A XEASOL
2560 METHINKS IT IB LIAE A  EASOL
2580 METHINKS IT IBVLICE A  EASEL
2600 METHINKS IT IBVLIKE A  EASEL
2620 METHINKS IT IKDLIKE A  EASEL
2640 METHINKS IT IKNLIKE A HEASEL
2660 METHINKS IT IKNLIKE A HIASEL
2680 METHINKS IT IZNLIKE A HIASEL
2700 METHINKS IT IZNLIKE A WOASEL
2720 METHINKS IT ISNLIKE A WOASEL
2740 METHINKS IT ISNLIKE M WSASEL
2760 METHINKS IT ISVLIKE M WXASEL
2780 METHINKS IT IS LIKE S WEASEL
2785 METHINKS IT IS LIKE A WEASEL
</pre>
<p>Notice that matching letters are not immutable. A letter, even if it matches one in the target string can change at any time.</p>
<p>You can find similar implementations in several programming languages on the <a href="http://rosettacode.org/wiki/Evolutionary_algorithm" target="_blank">Rosetta Code website</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2010/01/11/weasel-implementation-in-csharp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Interface Implementation in C#</title>
		<link>http://mariusbancila.ro/blog/2009/12/08/interface-implementation-in-csharp/</link>
		<comments>http://mariusbancila.ro/blog/2009/12/08/interface-implementation-in-csharp/#comments</comments>
		<pubDate>Tue, 08 Dec 2009 09:46:07 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[interfaces]]></category>
		<category><![CDATA[OO]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=419</guid>
		<description><![CDATA[I recently found a piece of code that can be summarized by the following sample: interface I { void F1(); void F2(); } class X { public void F2() { Console.WriteLine("F2"); } } class A : X, I { public void F1() { Console.WriteLine("F1"); } } As you can see there is an interface I [...]]]></description>
			<content:encoded><![CDATA[<p>I recently found a piece of code that can be summarized by the following sample:</p>
<pre name="code" class="csharp">
interface I
{
   void F1();
   void F2();
}

class X
{
   public void F2() { Console.WriteLine("F2"); }
}

class A : X, I
{
   public void F1() { Console.WriteLine("F1"); }
}
</pre>
<p>As you can see there is an interface <i>I</i> that has two methods, F1 and F2. <i>A</i> is derived from <i>X</i>, that has a method F2, and also implements I, but only contains F1. I was puzzled at first, because I was expecting that <i>A</i> was <i>explictitly</i> implementing all the methods defined in the interface <i>I</i>. But F2 was implemented in <em>X</em>, its base class. After thinking a little bit it all become clear. This was a normal behavior of the compiler.</p>
<p>When a class <i>A</i> implements an interface <i>I</i> it guarantees that it supports (implements) the entire contract that the interface defines. But it does not assert that it will explicitly implement all the interface members within its explicit definition. I&#8217;m stressing on the <i>explicit</i> word here, because <i>A</i> extends (is derived from) <i>X</i>. That means <i>A</i> <i>is an</i> <i>X</i>. Everything that <i>X</i> exposes (i.e. what is visible to its derived classes) is part of <i>A</i> too. </p>
<p>In our case, F2, implemented in <i>X</i>, is also available to <i>A</i>, because <i>A</i> is an <i>X</i>. Since both F1 and F2 are members of <i>A</i>, then it means <i>A</i> fully implements <i>I</i>, which makes the code compile just fine.</p>
<p>How is this helpful? Suppose you have several interfaces that all define one ore several members with the same meaning. </p>
<pre name="code" class="csharp">
interface I1
{
  void F1();
  void F2();
  int ErrorCode { get; }
}

interface I2
{
  void G1();
  void G2();
  int ErrorCode { get; }
}

interface I3
{
  void H1();
  int ErrorCode { get; }
}
</pre>
<p>Instead of providing the same implementation several times, like in the following code, you can have only one implementation for the common functionality.</p>
<pre name="code" class="csharp">
class A : I1
{
  private int m_errorCode;

  public void F1() {}
  public void F2() {}
  public int ErrorCode { get {return m_errorCode;} }
}

class B : I2
{
  private int m_errorCode;

  public void G1() {}
  public void G2() {}
  public int ErrorCode { get {return m_errorCode;} }
}

class C : I3
{
  private int m_errorCode;

  public void H1() {}
  public int ErrorCode { get {return m_errorCode;} }
}
</pre>
<p>We can create one class that provides the implementation for ErrorCode and let the others extend it and implement the corresponding interface.</p>
<pre name="code" class="csharp">
class X
{
  protected int m_errorCode;

  public int ErrorCode { get {return m_errorCode;} }
}

class A : X, I1
{
  public void F1() {}
  public void F2() {}
}

class B : X, I2
{
  public void G1() {}
  public void G2() {}
}

class C : X, I3
{
  public void H1() {}
}
</pre>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2009/12/08/interface-implementation-in-csharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using ColorMatrix for Creating Negative Image</title>
		<link>http://mariusbancila.ro/blog/2009/11/13/using-colormatrix-for-creating-negative-image/</link>
		<comments>http://mariusbancila.ro/blog/2009/11/13/using-colormatrix-for-creating-negative-image/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 08:49:45 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[ColorMatrix]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[negative]]></category>
		<category><![CDATA[transformation]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=395</guid>
		<description><![CDATA[.NET provides two classes for image transformations: Matrix, used for geometric transformations, and ColorMatrix, used for color transformations. One of such color transformations is inverting or negating. This means subtracting each color component from 255. Black (0,0,0) becomes White (255, 255, 255), and Green (0, 255, 0) becomes Magenta (255, 0, 255). You can find [...]]]></description>
			<content:encoded><![CDATA[<p>.NET provides two classes for image transformations: Matrix, used for geometric transformations, and ColorMatrix, used for color transformations. </p>
<p>One of such color transformations is inverting or negating. This means subtracting each color component from 255. Black (0,0,0) becomes White (255, 255, 255), and Green (0, 255, 0) becomes Magenta (255, 0, 255). </p>
<p>You can find many examples on the web that look like this:</p>
<pre name="code" class="csharp">
public Bitmap Transform(Bitmap source)
{
    //create a blank bitmap the same size as original
    Bitmap newBitmap = new Bitmap(source.Width, source.Height);

    //get a graphics object from the new image
    Graphics g = Graphics.FromImage(newBitmap);

    // create the negative color matrix
    ColorMatrix colorMatrix = new ColorMatrix();
    colorMatrix.Matrix00 = colorMatrix.Matrix11 = colorMatrix.Matrix22 = -1f;
    colorMatrix.Matrix33 = colorMatrix.Matrix44 = 1f;

    // create some image attributes
    ImageAttributes attributes = new ImageAttributes();

    attributes.SetColorMatrix(colorMatrix);

    g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height),
                0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes);

    //dispose the Graphics object
    g.Dispose();

    return newBitmap;
}
</pre>
<p>Using this code one can get a negative image.<br />
<div class="wp-caption alignnone" style="width: 497px"><img alt="Original image" src="/blog/wp-content/uploads/2009/11/negativesample1.jpg" title="Original image" width="487" height="396" /><p class="wp-caption-text">Original image</p></div></p>
<div class="wp-caption alignnone" style="width: 497px"><img alt="Negative image" src="/blog/wp-content/uploads/2009/11/negativesample3.jpg" title="Negative image" width="487" height="396" /><p class="wp-caption-text">Negative image</p></div>
<p>This runs fine on Windows XP. But when I ran it on Windows 7, I was getting only a black image. All the pixels were ARGB(255, 0, 0, 0). This was how it looked:</p>
<div class="wp-caption alignnone" style="width: 495px"><img alt="Incorrectly transformed image" src="/blog/wp-content/uploads/2009/11/negativesample2.jpg" title="Incorrectly transformed image" width="485" height="395" /><p class="wp-caption-text">Incorrectly transformed image</p></div>
<p>I was surprised to learn that it worked on Windows XP, but not on Windows 7. I don&#8217;t have Windows Vista to test but I guess it&#8217;s the same as with Windows 7. I thought it must be something in the GDI+ library, because building with .NET 3.5 SP1 or 4.0 Beta 2 didn&#8217;t change a thing.</p>
<p>After trying different things, I figured out what the problem was: the color matrix was incorrect. It must be defined like this:</p>
<pre name="code" class="csharp">
ColorMatrix colorMatrix = new ColorMatrix(
   new float[][]
   {
      new float[] {-1, 0, 0, 0, 0},
      new float[] {0, -1, 0, 0, 0},
      new float[] {0, 0, -1, 0, 0},
      new float[] {0, 0, 0, 1, 0},
      new float[] {1, 1, 1, 0, 1}
   });
</pre>
<p>With this change the Transform function produces a correct negative image, regardless the operating system or the .NET framework version. </p>
<p>However, what I don&#8217;t know yet, is why it worked on Windows XP. The only conclusion I can draw is that the GDI+ implementation has a fault there, that was later corrected. That&#8217;s why an incorrect color matrix produced a correct transformation on Windows XP.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2009/11/13/using-colormatrix-for-creating-negative-image/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>DotNetZip Library</title>
		<link>http://mariusbancila.ro/blog/2009/10/21/dotnetzip-library/</link>
		<comments>http://mariusbancila.ro/blog/2009/10/21/dotnetzip-library/#comments</comments>
		<pubDate>Wed, 21 Oct 2009 07:53:36 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[DotNetZip]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[zip]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=370</guid>
		<description><![CDATA[.NET 3.0 provides some support for working with ZIP files. However, it has an important drawback: it only works for packages that are conformant to the Open Packaging Convention standard. Most of the ZIP files are not. Codeplex features a library called DotNetZip that provides support for packing and unpacking in C#, VB.NET or any [...]]]></description>
			<content:encoded><![CDATA[<p>.NET 3.0 provides some support for working with ZIP files. However, it has an important drawback: it only works for packages that are conformant to the Open Packaging Convention standard. Most of the ZIP files are not. Codeplex features a library called <a href="http://dotnetzip.codeplex.com/" target="_blank">DotNetZip</a> that provides support for packing and unpacking in C#, VB.NET or any other .NET language, but also any COM environment, including Javascript, VBSCript, VB6, VBA, PHP, Perl. In addition to the basic packing and unpacking operations, it supports password protection, UNICODE filenames, ZIP64 and AES encryption, comment, and others. Here are some simple samples.</p>
<p>Creating a ZIP file:</p>
<pre name="code" class="csharp">
      public static void PackZip(string source, string targetzip)
      {
         if(File.Exists(source))
         {
            PackFile(source, targetzip);
         }
         else if(Directory.Exists(source))
         {
            PackFolder(source, targetzip);
         }
         else
         {
            Console.WriteLine("Source does not exists!");
         }
      }

      public static void PackFile(string file, string targetzip)
      {
         using (ZipFile zipfile = new ZipFile())
         {
            zipfile.AddFile(file, String.Empty);
            zipfile.Save(targetzip);
         }
      }

      public static void PackFolder(string folder, string targetzip)
      {
         using (ZipFile zipfile = new ZipFile())
         {
            zipfile.AddDirectory(folder);
            zipfile.Save(targetzip);
         }
      }
</pre>
<p>Unpacking to a target folder:</p>
<pre name="code" class="csharp">
      public static void UnpackZip(string zippath, string targetdir)
      {
         if(ZipFile.IsZipFile(zippath))
         {
            using (ZipFile zipfile = ZipFile.Read(zippath))
            {
               foreach (ZipEntry zipentry in zipfile)
               {
                  try
                  {
                     zipentry.Extract(targetdir, ExtractExistingFileAction.OverwriteSilently);
                  }
                  catch (ZipException ex)
                  {
                     if (ex.InnerException == null)
                     {
                        Console.WriteLine(ex.Message);
                     }
                     else
                     {
                        Console.WriteLine("{0}: {1}", ex.Message, ex.InnerException.Message);
                     }
                  }
               }
            }
         }
         else
         {
            Console.WriteLine("Not a zip file!");
         }
      }
</pre>
<p>Display the content of a ZIP archive:</p>
<pre name="code" class="csharp">
      public static void ShowZipContent(string zippath)
      {
         if(ZipFile.IsZipFile(zippath))
         {
            using(ZipFile zipfile = ZipFile.Read(zippath))
            {
               foreach(ZipEntry zipentry in zipfile)
               {
                  Console.WriteLine("{0}", zipentry.FileName);
               }
            }
         }
         else
         {
            Console.WriteLine("Not a zip file!");
         }
      }
</pre>
<p>You can find many more examples on Codeplex: <a href="http://dotnetzip.codeplex.com/wikipage?title=Examples&#038;referringTitle=Home" target="_blank">C#</a> and <a href="http://dotnetzip.codeplex.com/wikipage?title=VB-examples&#038;referringTitle=Home" target="_blank">VB.NET</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2009/10/21/dotnetzip-library/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>STM.NET</title>
		<link>http://mariusbancila.ro/blog/2009/07/29/stm-net/</link>
		<comments>http://mariusbancila.ro/blog/2009/07/29/stm-net/#comments</comments>
		<pubDate>Wed, 29 Jul 2009 11:19:59 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CTPs & Betas]]></category>
		<category><![CDATA[Parallel Programming]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[beta]]></category>
		<category><![CDATA[STM.NET]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=334</guid>
		<description><![CDATA[Microsoft has made available a first beta version of an experimental version of .NET 4.0, called .NET Framework 4.0 Beta 1 Enabled for Software Transactional Memory v1.0. Since that is quite a long name, the short one is STM.NET. This is a special version of .NET 4.0 that enables software transactional memory for C#. It [...]]]></description>
			<content:encoded><![CDATA[<p>Microsoft has made available a first beta version of an experimental version of .NET 4.0, called .NET Framework 4.0 Beta 1 Enabled for Software Transactional Memory v1.0. Since that is quite a long name, the short one is STM.NET. This is a special version of .NET 4.0 that enables software transactional memory for C#. It allows programmers to demarcate regions of code as operating in an atomic, isolated transaction from other code running concurrently. The means to do this is a delegate called Atomic.Do, or try-catch blocks. Might be that in the future an &#8216;atomic&#8217; block will be added to the language(s).</p>
<p>This first version of the framework, also comes with additional tools:</p>
<ul>
<li>tooling (debugging, ETW tracing)</li>
<li>lock interoperability</li>
<li>interoperability with traditional transactions</li>
<li>annotations (how methods run in transactions, suppressed transactions on methods, etc.)</li>
<li>static and dynamic checking of annotations</li>
</ul>
<p>On the other hand there are some limitations:</p>
<ul>
<li>only works for C# for now</li>
<li>cannot be installed on a machine with VS 2010, nor the opposite</li>
<li>there is only a 32-bit version</li>
</ul>
<p>More information about it can be found at the <a href="http://blogs.msdn.com/stmteam/">STM team blog</a> or <a href="http://msdn.microsoft.com/en-us/devlabs/ee334183.aspx">MSDN DevLabs</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2009/07/29/stm-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>.NET out string[] to Automation SAFEARRAY**</title>
		<link>http://mariusbancila.ro/blog/2009/07/23/net-out-string-to-automation-safearray/</link>
		<comments>http://mariusbancila.ro/blog/2009/07/23/net-out-string-to-automation-safearray/#comments</comments>
		<pubDate>Thu, 23 Jul 2009 11:44:13 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[MFC]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Windows Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[SAFEARRAY]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=328</guid>
		<description><![CDATA[.NET allows you to expose components as COM and consume them from unmanaged code. There are many references on how to this (and you can only start with MSDN), and I will not talk about that part. What I want to explain here is something different. Suppose you have this interface: [Guid("2F8433FE-4771-4037-B6B2-ED5F6585ED04")] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface [...]]]></description>
			<content:encoded><![CDATA[<p>.NET allows you to expose components as COM and consume them from unmanaged code. There are many references on how to this (and you can only start with <a href="http://msdn.microsoft.com/en-us/library/zsfww439(VS.71).aspx" target="_blank">MSDN</a>), and I will not talk about that part. What I want to explain here is something different. Suppose you have this interface:</p>
<pre name="code" class="csharp">
[Guid("2F8433FE-4771-4037-B6B2-ED5F6585ED04")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IAccounts
{
      [DispId(1)]
      string[] GetUsers();
}
</pre>
<p>Method GetUsers() returns an array on string representing the user names. But what if you also wanted the user passwords or addresses? Since this is exposed as COM, you cannot return an array of User. But you can return multiple arrays of string. So, how would you deal with out string[]? This is what I want to show you in this tutorial.</p>
<p>This is a .NET interface exposed to COM. It has two methods, GetUsers() that returns an array of string representing user names, and GetUsers2() that returns an array of strings as an output parameters and a bool as return type, indicating whether any user was found.</p>
<pre name="code" class="csharp">
namespace SampleLibrary
{
   [Guid("2F8433FE-4771-4037-B6B2-ED5F6585ED04")]
   [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
   public interface IAccounts
   {
      [DispId(1)]
      string[] GetUsers();

      [DispId(2)]
      bool GetUsers2(out string [] users);
   }
}
</pre>
<p>And this is the implementation:</p>
<pre name="code" class="csharp">
namespace SampleLibrary
{
   [Guid("C4713144-5D29-4c65-BF9C-188B1B7CD2B6")]
   [ClassInterface(ClassInterfaceType.None)]
   [ProgId("SampleLibrary.DataQuery")]
   public class Accounts : IAccounts
   {
      List&lt; string &gt; m_users;

      public Accounts()
      {
         m_users = new List&lt; string &gt; {
            "marius.bancila",
            "john.doe",
            "anna.kepler"
         };
      }

      #region IDataQuery Members

      public string[] GetUsers()
      {
         return m_users.ToArray();
      }

      public bool GetUsers2(out string[] users)
      {
         users = m_users.ToArray();

         return users.Length &gt; 0;
      }

      #endregion
   }
}
</pre>
<p>Note: If you are trying this example make sure you set the ComVisible attribute to true, either for each type or per assembly (in AssemblyInfo.cs)</p>
<pre name="code" class="csharp">
[assembly: ComVisible(true)]
</pre>
<p>Second, you have to check the &#8220;Register for COM interop&#8221; setting in the Build page of the project properties.</p>
<p>The first thing to do in C++ is importing the .TLB file that was generated by regasm.exe.</p>
<pre name="code" class="cpp">
#import "SampleLibrary.tlb"
using namespace SampleLibrary;
</pre>
<p>If we look in the .TLB file, we can see how the IAccounts interface looks like:</p>
<pre name="code" class="cpp">
struct __declspec(uuid("2f8433fe-4771-4037-b6b2-ed5f6585ed04"))
IAccounts : IDispatch
{
    //
    // Wrapper methods for error-handling
    //

    // Methods:
    SAFEARRAY * GetUsers ( );
    VARIANT_BOOL GetUsers2 (
        SAFEARRAY * * users );
};
</pre>
<p>The following C++ functions, GetUsers1() retrieves the users users list using method GetUsers() from IAccounts. It puts the users in a CStringArray (notice that this container does not have an assignment operator, so the only way to return such an array is with a reference in the parameters list).</p>
<pre name="code" class="cpp">
void GetUsers1(CStringArray&amp; arrUsers)
{
   IAccountsPtr pAccounts(__uuidof(Accounts));

   SAFEARRAY* sarrUsers = pAccounts-&gt;GetUsers();

   _variant_t varUsers;
   varUsers.parray = sarrUsers;
   varUsers.vt = VT_ARRAY | VT_BSTR;

   UnpackBstrArray(varUsers, arrUsers);
   SafeArrayDestroy(sarrUsers);

   pAccounts-&gt;Release();
}
</pre>
<p>UnpackBstrArray() is a function (see below) that extracts the elements of a SAFEARRAY and adds them to a CStringArray.</p>
<p>Function GetUsers2() uses the second method, GetUsers2() from IAccounts. This needs the address of a pointer to a SAFEARRAY (i.e. SAFEARRAY**) that will hold the values returned by the COM method. This time we have to create an empty SAFEARRAY and then pass its address to the COM method. The rest is similar to the previous case.</p>
<pre name="code" class="cpp">
void GetUsers2(CStringArray&amp; arrUsers)
{
   IAccountsPtr pAccounts(__uuidof(Accounts));

   SAFEARRAYBOUND aDim[1];
   aDim[0].lLbound = 0;
   aDim[0].cElements = 0;

   SAFEARRAY* sarrUsers = SafeArrayCreate(VT_BSTR, 1, aDim);

   VARIANT_BOOL ret = pAccounts-&gt;GetUsers2(&amp;sarrUsers);
   if(ret != VARIANT_FALSE)
   {
      _variant_t varUsers;
      varUsers.parray = sarrUsers;
      varUsers.vt = VT_ARRAY | VT_BSTR;
      UnpackBstrArray(varUsers, arrUsers);
   }

   SafeArrayDestroy(sarrUsers);

   pAccounts-&gt;Release();
}
</pre>
<p>The helper method UnpackBstrArray() used previous looks like this:</p>
<pre name="code" class="cpp">
void UnpackBstrArrayHelper(VARIANT* pvarArrayIn, CStringArray* pstrarrValues)
{
   if (!pstrarrValues || !pvarArrayIn || pvarArrayIn->vt == VT_EMPTY)
      return;

   pstrarrValues-&gt;RemoveAll();

   VARIANT* pvarArray = pvarArrayIn;
   SAFEARRAY* parrValues = NULL;

   SAFEARRAYBOUND arrayBounds[1];
   arrayBounds[0].lLbound = 0;
   arrayBounds[0].cElements = 0;

   if((pvarArray-&gt;vt &#038; (VT_VARIANT|VT_BYREF|VT_ARRAY)) == (VT_VARIANT|VT_BYREF) &#038;&#038;
      NULL != pvarArray-&gt;pvarVal &#038;&#038;
      (pvarArray-&gt;pvarVal-&gt;vt &#038; VT_ARRAY))
   {
      pvarArray = pvarArray-&gt;pvarVal;
   }

   if (pvarArray-&gt;vt &#038; VT_ARRAY)
   {
      if (VT_BYREF &amp; pvarArray-&gt;vt)
         parrValues = *pvarArray-&gt;pparray;
      else
         parrValues = pvarArray-&gt;parray;
   }
   else
      return;

   if (parrValues != NULL)
   {
      HRESULT hr = SafeArrayGetLBound(parrValues, 1, &amp;arrayBounds[0].lLbound);
      hr = SafeArrayGetUBound(parrValues, 1, (long*)&amp;arrayBounds[0].cElements);
      arrayBounds[0].cElements -= arrayBounds[0].lLbound;
      arrayBounds[0].cElements += 1;
   }

   if (arrayBounds[0].cElements &gt; 0)
   {
      for (ULONG i = 0; i &lt; arrayBounds[0].cElements; i++)
      {
         LONG lIndex = (LONG)i;
         CString strValue = _T("");

         VARTYPE vType;
         BSTR bstrItem;

         ::SafeArrayGetVartype(parrValues, &amp;vType);
         HRESULT hr = ::SafeArrayGetElement(parrValues, &amp;lIndex, &amp;bstrItem);

         if(SUCCEEDED(hr))
         {
            switch(vType)
            {
            case VT_BSTR:
               strValue = (LPCTSTR)bstrItem;
               break;
            }

            ::SysFreeString(bstrItem);
         }

         pstrarrValues-&gt;Add(strValue);
      }
   }
}

void UnpackBstrArray( const _variant_t &amp;var, CStringArray &amp;strarrValues  )
{
   UnpackBstrArrayHelper( &amp;(VARIANT)const_cast&lt; _variant_t &#038; &gt;(var), &amp;strarrValues );
}
</pre>
<p>Attached you can find a demo project (C# and C++) with the complete example show in this tutorial.</p>
<a class="downloadlink" href="http://mariusbancila.ro/blog/wp-content/plugins/download-monitor/download.php?id=4" title="Version1.0 downloaded 365 times" >output SAFEARRAY** example (365)</a>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2009/07/23/net-out-string-to-automation-safearray/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More About Code Contracts</title>
		<link>http://mariusbancila.ro/blog/2009/06/09/more-about-code-contracts/</link>
		<comments>http://mariusbancila.ro/blog/2009/06/09/more-about-code-contracts/#comments</comments>
		<pubDate>Tue, 09 Jun 2009 10:16:33 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CTPs & Betas]]></category>
		<category><![CDATA[article]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[code contracts]]></category>
		<category><![CDATA[sharparena]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=306</guid>
		<description><![CDATA[In a recent post I wrote about Code Contracts in .NET. Now you can find a more detailed article on this topic at sharparena.com. In this article I&#8217;m providing more information and examples on: pre-conditions post-conditions object invariants asserts and assumptions quantifiers In additions, you should check the official user documentation, which can be found [...]]]></description>
			<content:encoded><![CDATA[<p>In a recent post I wrote about <a href="http://mariusbancila.ro/blog/?p=296">Code Contracts in .NET</a>. Now you can find a <a href="http://www.sharparena.com/index.php?option=com_content&#038;view=article&#038;id=48:dotnet-code-contracts&#038;catid=24:category-dotnet-framework&#038;Itemid=15">more detailed article</a> on this topic at <a href="http://www.sharparena.com">sharparena.com</a>. In this article I&#8217;m providing more information and examples on:</p>
<ul>
<li>pre-conditions</li>
<li>post-conditions</li>
<li>object invariants</li>
<li>asserts and assumptions</li>
<li>quantifiers</li>
</ul>
<p>In additions, you should check the official user documentation, which can be found <a href="http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf">here</a>.</p>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2009/06/09/more-about-code-contracts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Contracts in Visual Studio 2010</title>
		<link>http://mariusbancila.ro/blog/2009/05/31/code-contracts-in-visual-studio-2010/</link>
		<comments>http://mariusbancila.ro/blog/2009/05/31/code-contracts-in-visual-studio-2010/#comments</comments>
		<pubDate>Sun, 31 May 2009 16:31:42 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CTPs & Betas]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[beta]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[code contracts]]></category>
		<category><![CDATA[VS2010]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=296</guid>
		<description><![CDATA[Visual Studio 2010 has support for code contracts that allow to express pre-, post-conditions and invariants to your .NET code. Let&#8217; say you want to create a function to return a random value in a range. This could look like it: class Program { Random rng = new Random(); public int GetRandom(int min, int max) [...]]]></description>
			<content:encoded><![CDATA[<p>Visual Studio 2010 has support for code contracts that allow to express pre-, post-conditions and invariants to your .NET code.</p>
<p>Let&#8217; say you want to create a function to return a random value in a range. This could look like it:</p>
<pre class="prettyprint">
    class Program
    {
        Random rng = new Random();

        public int GetRandom(int min, int max)
        {
            return rng.Next(min, max);
        }

        static void Main(string[] args)
        {
            Program p = new Program();
            int n1 = p.GetRandom(10, 20);
            int n2 = p.GetRandom(10, 10);
        }
    }
</pre>
<p>However, at a rough analysis one can find two problems:</p>
<ul>
<li>Second call to GetRandom(), is not well formed, because the range is 0</li>
<li>Radnom.Next returns a value greater or equal to the first argument, and lower than the second.</li>
</ul>
<p>What code contracts provide is a mean to check that some statements, like:</p>
<ul>
<li>maximum value of the range should always be greater than the minimum value</li>
<li>returned value should always be in the interval, equal or greater than the minimum, and equal or less than then maximum</li>
</ul>
<p>The first is a pre-requisite, and the second is a post-requisite. We can specify those with:</p>
<pre class="prettyprint">
        public int GetRandom(int min, int max)
        {
            Contract.Requires(max > min);
            Contract.Ensures(Contract.Result<int>() >= min &#038;&#038;
                             Contract.Result<int>() <= max);

            return rng.Next(min, max);
        }
</pre>
<p>The Contract class is available in namespace System.Diagnostics.Contracts. To enable the static checking, you have to go to Project Properties > Code Contracts and select "Perform Static Contract Checking."</p>
<div class="wp-caption alignnone" style="width: 704px"><img alt="Code Contracts Property Page" src="/blog/wp-content/uploads/2009/05/vs2010_codecontractsproperties.png" title="Code Contracts Property Page" width="694" height="505" /><p class="wp-caption-text">Code Contracts Property Page</p></div>
<p>When you build, you get the following warnings:<br />
<div class="wp-caption alignnone" style="width: 746px"><img alt="Code Contracts warnings" src="/blog/wp-content/uploads/2009/05/vs2010_codecontractswarnings.png" title="Code Contracts warnings" width="736" height="184" /><p class="wp-caption-text">Code Contracts warnings</p></div></p>
<p>The first says that the call GetRandom(10, 10) does not match the pre-condition. The second warning indicates that the post-condition is not met. It isn't possible to know whether Random.Next() returns a value that hods the post-condition. But if you check the "Perform Runtime Contract Checking" it asserts at runtime, when the return value is outside the interval (not possible with this code sample).</p>
<p>You can read more about code contracts on the <a href="http://blogs.msdn.com/bclteam/archive/2008/11/11/introduction-to-code-contracts-melitta-andersen.aspx">BCL team's blog</a>. It features a list of possible constructs for pre- and post-requisites, but also object invariants.</p>
<p>Code Contracts are also available for Visual Studio 2008. For downloads and additional information check the following links:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx">Code Contracts at DevLabs</a></li>
<li><a href="http://research.microsoft.com/en-us/projects/contracts/">Code Contracts at Microsoft Research</a></li>
</ul>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2009/05/31/code-contracts-in-visual-studio-2010/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

