<?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; .NET</title>
	<atom:link href="http://mariusbancila.ro/blog/tag/net/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>Windows Runtime</title>
		<link>http://mariusbancila.ro/blog/2011/09/15/windows-runtime/</link>
		<comments>http://mariusbancila.ro/blog/2011/09/15/windows-runtime/#comments</comments>
		<pubDate>Thu, 15 Sep 2011 20:54:16 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[64bit]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[CTPs & Betas]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[Windows Programming]]></category>
		<category><![CDATA[WinRT]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[metro]]></category>
		<category><![CDATA[MSDN]]></category>
		<category><![CDATA[runtime]]></category>
		<category><![CDATA[win32]]></category>
		<category><![CDATA[winrt]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=1116</guid>
		<description><![CDATA[Windows Runtime, or shortly WinRT, is a new runtime (siting on top of the Windows kernel) that allows developers to write Metro style applications for Windows 8, using a variety of languages including C/C++, C#, VB.NET or JavaScript/HTML5. Microsoft has started rolling out information about Windows 8 and the new runtime at BUILD. WinRT is [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211377%28v=VS.85%29.aspx">Windows Runtime</a>, or shortly WinRT, is a new runtime (siting on top of the Windows kernel) that allows developers to write Metro style applications for Windows 8, using a variety of languages including C/C++, C#, VB.NET or JavaScript/HTML5. Microsoft has started rolling out information about Windows 8 and the new runtime at <a href="http://www.buildwindows.com/">BUILD</a>.</p>
<div class="wp-caption alignnone" style="width: 643px"><img alt="" src="http://i.zdnet.com/blogs/archslide.png" title="Windows 8" width="633" height="427" /><p class="wp-caption-text">(source www.zdnet.com)</p></div>
<p>WinRT is a native layer (written in C++ and being COM-based) that is intended as a replacement, or alternative, to Win32, and enables development of &#8220;immersive&#8221; applications, using the Metro style. Its API is object oriented and can be consumed both from native or managed languages, as well as JavaScript. At the same time the old Win32 applications will continue to run just as before and you can still (and most certainly will) develop Win32 applications.</p>
<p>Microsoft has created a new language called C++ Component Extension, or simply C++/CX. While the syntax is very similar to C++/CLI, the language is not managed, it&#8217;s still native. WinRT components built in C++/CX do not compile to managed code, but to 100% native code. A good news for C++ developers is that they can use XAML now to build the UI for immersive applications. However, this is not available for classical, Win32 applications.</p>
<p>You can get a glimpse of the new system and the tools by downloading and installing the <a href="http://msdn.microsoft.com/en-us/windows/apps/br229516">Windows Developer Preview with tools</a>, that includes the following:</p>
<ul>
<li>64-bit Windows Developer Preview</li>
<li>Windows SDK for Metro style apps</li>
<li>Microsoft Visual Studio 11 Express for Windows Developer Preview</li>
<li>Microsoft Expression Blend 5 Developer Preview</li>
<li>28 Metro style apps including the BUILD Conference app</li>
</ul>
<p>Notice this is a pre-beta release and you might encounter various problems.</p>
<p>Before you start here are several additional articles that you might want to read:</p>
<ul>
<li><a href="http://www.infoq.com/news/2011/09/WinRT-API">WinRT: An Object Orientated Replacement for Win32</a></li>
<li><a href="http://www.infoq.com/news/2011/09/C-Component-Extensions">C++ Component Extensions: The New Face of COM</a></li>
<li><a href="http://www.infoq.com/news/2011/09/DotNet-On-WinRT">C# and Visual Basic on the WinRT API</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh441569%28v=VS.85%29.aspx">Creating Windows Runtime Components in C++</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh441589%28v=VS.85%29.aspx">Tutorial: Creating and using extension SDKs</a></li>
<li><a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-532T">Using the Windows Runtime from C++</a></li>
</ul>
<p>There are also several <a href="http://social.msdn.microsoft.com/Forums/en-US/category/windowsapps">new forums</a> available on MSDN forums for developing Metro style applications, which you can use for addressing technical questions. Hopefully thee will be answers from Microsoft people working in this area.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2011/09/15/windows-runtime/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How To Determine the Platform Architecture for a .NET Assembly</title>
		<link>http://mariusbancila.ro/blog/2010/10/29/how-to-determine-the-platform-architecture-for-a-net-assembly/</link>
		<comments>http://mariusbancila.ro/blog/2010/10/29/how-to-determine-the-platform-architecture-for-a-net-assembly/#comments</comments>
		<pubDate>Fri, 29 Oct 2010 07:15:40 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[reflector]]></category>
		<category><![CDATA[x64]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=770</guid>
		<description><![CDATA[I&#8217;m using Red Gate&#8217;s .NET Reflector for decompiling .NET assemblies. It&#8217;s a great tool but it lacks, at least in the free version I&#8217;m using, information about the platform architecture of an assembly. Sometimes I want to know whether an assembly was built for Any CPU, x86 or x64. The tool that help you find [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m using <a href="http://www.red-gate.com/products/reflector/">Red Gate&#8217;s .NET Reflector</a> for decompiling .NET assemblies. It&#8217;s a great tool but it lacks, at least in the free version I&#8217;m using, information about the platform architecture of an assembly. Sometimes I want to know whether an assembly was built for Any CPU, x86 or x64. </p>
<p>The tool that help you find this information is <a href="http://msdn.microsoft.com/en-us/library/ms164699%28VS.80%29.aspx">CorFlags.exe</a> from Windows SDK. It displays or configures the corflags section of a PE image. Here is an example of the output of corflags.exe:</p>
<pre class="prettyprint">
Version   : v2.0.50727
CLR Header: 2.5
PE        : PE32
CorFlags  : 1
ILONLY    : 1
32BIT     : 0
Signed    : 0
</pre>
<p>The platform architecture is encoded in a combination of the PE and 32BIT flags:</p>
<ul>
<li><strong>Any CPU</strong>: PE=PE32 and 32BIT=0</li>
<li><strong>x86</strong>: PE=PE32 and 32BIT=1</li>
<li><strong>64-bit</strong>: PE=PE32+ and 32BIT=0</li>
</ul>
<p>So for the example above, PE is PE32 and 32BIT is 0, thus the platform architecture is Any CPU.</p>
<p>You can read more about this tool on <a href="http://blogs.msdn.com/b/gauravseth/archive/2006/03/07/545104.aspx">Gaurav Seth&#8217;s blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2010/10/29/how-to-determine-the-platform-architecture-for-a-net-assembly/feed/</wfw:commentRss>
		<slash:comments>0</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>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>Reference a XAML From Another Project</title>
		<link>http://mariusbancila.ro/blog/2009/08/26/reference-a-xaml-from-another-project/</link>
		<comments>http://mariusbancila.ro/blog/2009/08/26/reference-a-xaml-from-another-project/#comments</comments>
		<pubDate>Wed, 26 Aug 2009 08:20:21 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[XAML]]></category>
		<category><![CDATA[assembly]]></category>
		<category><![CDATA[URI]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=363</guid>
		<description><![CDATA[When you create a WPF application, the start-up window is by default one from the same project (by default called Window1.xaml). < Application x:Class="WpfApplication1.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="Window1.xaml" > < Application.Resources > < /Application.Resources > < /Application > But what if you want to use a window from another project (class library)? The pack URI scheme, [...]]]></description>
			<content:encoded><![CDATA[<p>When you create a WPF application, the start-up window is by default one from the same project (by default called Window1.xaml). </p>
<pre class="prettyprint">
< Application x:Class="WpfApplication1.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="Window1.xaml" >
    < Application.Resources >

    < /Application.Resources >
< /Application >
</pre>
<p>But what if you want to use a window from another project (class library)? The pack URI scheme, used by WPF, allows you to identify and load files from:</p>
<ul>
<li>the current assembly</li>
<li>a referenced assembly</li>
<li>a location relative to an assembly</li>
<li>the site of origin for the application</li>
</ul>
<p>The format of the pack URI is <strong><em>pack://authority/path</em></strong>. The authority identifies the type of package and the path the location of a part inside a package. There are two authorities supported by WPF:</p>
<ul>
<li>application:/// identifies application data files (known at compile time)</li>
<li>siteoforigin:/// identifies site of origin files</li>
</ul>
<p>To use resource files from a referenced assembly you need to use the application:/// authority, and the path must have the form <strong><em>AssemblyShortName[;Version][;PublicKey];</em>component/<em>Path</em></strong>. Version and PublicKey are optional.</p>
<p>Let&#8217;s say you want to use a XAML called SampleWindow.xaml from a referenced assembly called WpfDemoLib. The App.xaml file should look like this:</p>
<pre class="prettyprint">
< Application x:Class="WpfApplication1.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="pack://application:,,,/WpfDemoLib;component/SampleWindow.xaml" >
    < Application.Resources >

    < /Application.Resources >
< /Application >
</pre>
<p>You can learn more about pack URIs in WPF from <a href="http://msdn.microsoft.com/en-us/library/aa970069.aspx" target="_blank">MSDN</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2009/08/26/reference-a-xaml-from-another-project/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>
		<item>
		<title>Axum, A Language for Building Parallel Applications</title>
		<link>http://mariusbancila.ro/blog/2009/05/13/axum-a-language-for-building-parallel-applications/</link>
		<comments>http://mariusbancila.ro/blog/2009/05/13/axum-a-language-for-building-parallel-applications/#comments</comments>
		<pubDate>Wed, 13 May 2009 06:26:09 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CTPs & Betas]]></category>
		<category><![CDATA[Parallel Programming]]></category>
		<category><![CDATA[agents]]></category>
		<category><![CDATA[axum]]></category>
		<category><![CDATA[isolation]]></category>
		<category><![CDATA[parallel]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=268</guid>
		<description><![CDATA[Last week Microsoft published on DevLabs a .NET language for building parallel applications, called Axum, and earlier known as Maestro. This new language is build on the architecture of the web, on the principles of isolation, message-passing, fault-tolerance, loose-coupling. It is said to have a more succinct syntax than Erlang, and have the isolation advantage [...]]]></description>
			<content:encoded><![CDATA[<p>Last week Microsoft published on <a href="http://msdn.microsoft.com/en-us/devlabs/dd795202.aspx">DevLabs</a> a .NET language for building parallel applications, called Axum, and earlier known as Maestro. This new language is build on the architecture of the web, on the principles of isolation, message-passing, fault-tolerance, loose-coupling. It is said to have a more succinct syntax than Erlang, and have the isolation advantage over MPI, CCR and Asynchronous Agents.</p>
<p>Isolation is key in this architecture and is achieved with:</p>
<ul>
<li>domains, that limits the runtime scope of data to its compile-time scope (objects don&#8217;t escape domains)</li>
<li>agents, active components that provide access to domains, and live in a thread of their own, different that the callers; their methods are not accessible outside;</li>
<li>channels, are the mean to communicate with agents; they are established by the runtime, when agents are created. The most important parts of the channels are the ports (input or output), that can be viewed as queues in which data is placed.</li>
</ul>
<p>Here are more readings about these topics here:</p>
<ul>
<li><a href="http://blogs.msdn.com/maestroteam/archive/2009/02/27/we-haven-t-forgotten-about-other-models-honest.aspx">Axum core architecture principles</a></li>
<li><a href="http://blogs.msdn.com/maestroteam/archive/2009/02/27/isolation-in-maestro.aspx">Isolation in Axum</a></li>
<li><a href="http://blogs.msdn.com/maestroteam/archive/2009/03/02/channels.aspx">Channels</a></li>
</ul>
<p>You can find more about Axum at:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/devlabs/dd795202.aspx">Home page at Microsoft DevLabs</a></li>
<li><a href="http://blogs.msdn.com/maestroteam/">Axum Team Blog</a></li>
<li><a href="http://social.msdn.microsoft.com/Forums/en-US/axum/threads">Axum Forum</a></li>
</ul>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2009/05/13/axum-a-language-for-building-parallel-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

