<?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>Tamir Khason - Just code &#187; source</title>
	<atom:link href="http://khason.net/tag/source/feed/" rel="self" type="application/rss+xml" />
	<link>http://khason.net</link>
	<description>Take care of the sense, and the sounds will take care of themselves.</description>
	<lastBuildDate>Mon, 02 Apr 2012 08:58:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>What the f***k code</title>
		<link>http://khason.net/blog/what-the-fk-code/</link>
		<comments>http://khason.net/blog/what-the-fk-code/#comments</comments>
		<pubDate>Mon, 02 Apr 2012 08:58:46 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[BLOG]]></category>
		<category><![CDATA[OFFTOPIC]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Work process]]></category>

		<guid isPermaLink="false">http://khason.net/?p=2204</guid>
		<description><![CDATA[Recently I had to go over some code in one of systems. There I’ve found real gems of production code snippets, worth to share with developers community. Note, that most of this code is not “dead code” and perfectly working. READER ADVISORY: Following post contains objectionable code snippets and might not suitable for all individuals. [...]<p/>]]></description>
			<content:encoded><![CDATA[<p>Recently I had to go over some code in one of systems. There I’ve found real gems of production code snippets, worth to share with developers community. Note, that most of this code is not “<a href="http://en.wikipedia.org/wiki/Dead_code" target="_blank">dead code</a>” and perfectly working.</p>
<p><strong>READER ADVISORY</strong>: Following post contains objectionable code snippets and might not suitable for all individuals.</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="My code is compiling!" border="0" alt="My code is compiling!" src="http://khason.net/images/2012/04/image.png" width="399" height="298" /></p>
<p><em>Disclaimer: I changed some snippets to prevent possible authors’ punishment. </em></p>
<p>Let’s start from small unit tests. This one is really ultimate test!</p>
<blockquote><p>// if this works for this this works for sure!     <br />topic = typeof(TestRequest).FullName + &quot;.&quot; + &quot;2.2.2.2.2.2&quot;;</p>
</blockquote>
<p>Also this one is brutal.</p>
<blockquote><p>// Prevent the code from exiting before double the timeout time     <br />bool ok = wait.WaitOne(_bus.DefaultResponseTimeout * 2 * 1000);      <br />Assert.IsTrue(ok == true);      <br />Assert.IsNull(error ?? null);</p>
</blockquote>
<p>Sometimes, people need definitive and proven way to eliminate annoying <a href="http://en.wikipedia.org/wiki/File_URI_scheme" target="_blank">file URI scheme</a>.</p>
<blockquote><p>string emptyString = string.Empty;     <br />do {      <br />&#160;&#160;&#160; if (File.Exists(asmPath)) break;      <br />}      <br />while (asmPath.Replace(&quot;file&quot;, emptyString).Replace(&quot;:&quot;, emptyString).Replace(&quot;\\&quot;, emptyString).Replace(&quot;/&quot;, emptyString).Replace(&quot;//&quot;, emptyString) != emptyString);      <br />// now assembly name is clean and we can load it</p>
</blockquote>
<p>There are also cases of mistrustful <a href="http://en.wikipedia.org/wiki/Globally_unique_identifier" target="_blank">GUID</a></p>
<blockquote><p>message.AddField(FIELD_OWNER_ID, _ownerId);     <br />while (string.Compare(_ownerId, Guid.NewGuid().ToString()) == 0) _ownerId = Guid.NewGuid().ToString();      <br />message.AddField(FIELD_OWNER_ID, _ownerId);</p>
</blockquote>
<p>In certain cases, they need threads to sleep for 1 second anyway.</p>
<blockquote><p>try {     <br />&#160;&#160; Thread.Sleep(1000);      <br />} catch {      <br />&#160;&#160; try {      <br />&#160;&#160;&#160;&#160;&#160; Thread.Sleep(1000);      <br />&#160;&#160; } catch {      <br />&#160;&#160;&#160;&#160;&#160; try {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Thread.Sleep(1000);      <br />&#160;&#160;&#160;&#160;&#160; } catch {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; try {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Thread.Sleep(1000);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; } catch {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; // Gracefully exit the thread      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; break;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }// catch      <br />&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160; }      <br />&#160;&#160; // Gracefully exit the thread      <br />&#160;&#160; break;      <br />} // catch      </p>
</blockquote>
<p>Graceful shutdown and correct memory management is the key of successful programming.</p>
<blockquote><p>~Bus() {     <br />try {       <br />&#160; try { this.dispatcher.Destroy(); } catch (Exception) { }      <br />&#160; try { this.queue.Destroy(); } catch (Exception) { }      <br />&#160; try { this.transport.Destroy(); } catch (Exception) { }      <br />&#160; try { this.transport1.Destroy(); } catch (Exception) { }      <br />&#160; try { Environment.Close(); } catch (Exception) { }      <br />} catch (Exception) {      <br />&#160;&#160;&#160;&#160;&#160; // Avoid crashing the process..      <br />&#160;&#160; } // catch      <br />}</p>
<p>public void Dispose() {     <br />&#160;&#160; Dispose(true);      <br />&#160;&#160; GC.SuppressFinalize(this);      <br />}</p>
<p>protected virtual void Dispose(bool disposing) {     <br />try {       <br />&#160;&#160; try { this.dispatcher.Destroy(); } catch (Exception) { }      <br />&#160;&#160; try { this.queue.Destroy(); } catch (Exception) { }      <br />&#160;&#160; try { this.transport.Destroy(); } catch (Exception) { }      <br />&#160;&#160; try { this.transport1.Destroy(); } catch (Exception) { }      <br />&#160;&#160; try { Environment.Close(); } catch (Exception) { }      <br />} catch (Exception) {      <br />&#160;&#160;&#160;&#160;&#160; // Need to assure the process ends      <br />&#160;&#160; } // catch      <br />}</p>
</blockquote>
<p>I am not violent psychopath and not going to ask somebody to maintain this code, but this is for sure built by a lot of brut force and thousands of slaves, like Egyptian pyramids. </p>
<p>Happy Passover to everyone.</p>
<p><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="gefilte fish hack" border="0" alt="gefilte fish hack" src="http://khason.net/images/2012/04/image1.png" width="399" height="300" /></p>
<p/>]]></content:encoded>
			<wfw:commentRss>http://khason.net/blog/what-the-fk-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Self installable and runnable service or how to make generic service and console hybrid</title>
		<link>http://khason.net/dev/self-installable-and-runnable-service-or-how-to-make-generic-service-and-console-hybrid/</link>
		<comments>http://khason.net/dev/self-installable-and-runnable-service-or-how-to-make-generic-service-and-console-hybrid/#comments</comments>
		<pubDate>Tue, 24 Jan 2012 11:08:13 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[DEV]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Tips and Tricks]]></category>

		<guid isPermaLink="false">http://khason.net/?p=2192</guid>
		<description><![CDATA[Frankly, I thought that one of basic things in windows development, such as “debagability” and “installability” of services,&#160; were changed for the last 10 years in development environments. However I was disappointed to discover, that nothing actually changed. You still cannot build easy to debug (in command line) service, which is also can be installed [...]
Related posts:<ol>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Frankly, I thought that one of basic things in windows development, such as “debagability” and “installability” of services,&#160; were changed for the last 10 years in development environments. However I was disappointed to discover, that nothing actually changed. You still cannot build easy to debug (in command line) service, which is also can be installed without special additional tools.</p>
<p><img style="background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://khason.net/images/2012/01/image.png" width="397" height="273" /></p>
<p>Even <a href="http://stackoverflow.com/questions/4144019/self-install-windows-service-in-net-c-sharp" target="_blank">ServiceName/ServiceNameInstaller trick</a>, is specific for the current assembly and cannot be used if your base class is not the one you are really using. This is not the only approach. Also, <a href="http://geekswithblogs.net/BlackRabbitCoder/archive/2011/03/01/c-toolbox-debug-able-self-installable-windows-service-template-redux.aspx" target="_blank">there are other methods</a>, which are too complicated to use in the simple project.</p>
<p>So, I decided to write quick basic service which is can be used as common base for self-installable and debugable service development. Let’s start.</p>
<p>First of all we need an abstract service base:</p>
<blockquote><p>public abstract class ServiceProvider : ServiceBase</p>
</blockquote>
<p>Then it identification for derived classes</p>
<blockquote><p>public static string Name;      <br />public static string ProviderKind;</p>
<p>public ServiceProvider(string name) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ProviderKind = name;       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Name = &quot;MagicService.&quot; + ProviderKind;       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ServiceName = Name;       <br />&#160;&#160;&#160;&#160;&#160; }</p>
</blockquote>
<p>Now method to start it from the hosting application (e.g. command prompt) or run it if installed.</p>
<blockquote><p>/// &lt;summary&gt;Starts the provider service in interactive mode.&lt;/summary&gt;      <br />public void Start(string[] args) {       <br />&#160;&#160; if (Environment.UserInteractive) {       <br />&#160;&#160;&#160;&#160;&#160; OnStart(args);       <br />&#160;&#160; } else {       <br />&#160;&#160;&#160;&#160;&#160; ServiceBase.Run(this);       <br />&#160;&#160; }       <br />}       </p>
</blockquote>
<p>But how to install it? Normally, if you’ll put class derived from <a href="http://msdn.microsoft.com/en-us/library/system.configuration.install.installer.aspx" target="_blank">Installer</a> and marked as <a href="http://msdn.microsoft.com/en-us/library/2ya9dxy9.aspx" target="_blank">RunInstaller</a>, Installutil.exe can initialize it and install or uninstall the service. </p>
<blockquote><p>public class ServiceProviderInstaller : Installer {      <br />&#160;&#160; private static readonly string ServiceName = ServiceProvider.Name;       <br />&#160;&#160; <br />&#160;&#160; public ServiceProviderInstaller() {       <br />&#160;&#160;&#160;&#160;&#160; var processInstaller = new ServiceProcessInstaller {       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Account = ServiceAccount.LocalSystem       <br />&#160;&#160;&#160;&#160;&#160; };</p>
<p>&#160;&#160;&#160;&#160;&#160; var serviceInstaller = new ServiceInstaller {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; DisplayName = &quot;Magic Server &quot; + ServiceProvider.ProviderKind + &quot; Provider&quot;,       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Description = &quot;Process the interface to the Magic service &quot; + ServiceProvider.ProviderKind + &quot; provider.&quot;,       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ServiceName = ServiceName,       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; StartType = ServiceStartMode.Automatic,       <br />&#160;&#160;&#160;&#160;&#160; };       <br />&#160;&#160;&#160; <br />&#160;&#160;&#160;&#160;&#160; this.Installers.Add(processInstaller);       <br />&#160;&#160;&#160;&#160;&#160; this.Installers.Add(serviceInstaller);       <br />&#160;&#160; }</p>
</blockquote>
<p>But it works only if installer is defined in the same assembly as service and the service itself can be run. In our case, this is not true. Service is abstract and we allow to run service from any other assembly which is referenced to the base one. So what to do? Simple! Let’s create our own installer. We will create the private instance of installer inside the actual service itself and pass it as additional installer to basic <a href="http://msdn.microsoft.com/en-us/library/system.configuration.install.transactedinstaller.aspx" target="_blank">TransactedInstaller</a>. Also we’ll use calling (the actual running) assembly as the service reference.</p>
<blockquote><p>/// &lt;summary&gt;Installs the provider service in interactive mode.&lt;/summary&gt;      <br />public void Install() {       <br />&#160;&#160; if (Environment.UserInteractive) {       <br />&#160;&#160;&#160;&#160;&#160; var ti = new TransactedInstaller();       <br />&#160;&#160;&#160;&#160;&#160; var spi = new ServiceProviderInstaller();       <br />&#160;&#160;&#160;&#160;&#160; ti.Installers.Add(spi);       <br />&#160;&#160;&#160;&#160;&#160; var path = &quot;/assemblypath=&quot; + Assembly.GetEntryAssembly().Location;       <br />&#160;&#160;&#160;&#160;&#160; var ctx = new InstallContext(&quot;&quot;, new string[] { path });       <br />&#160;&#160;&#160;&#160;&#160; ti.Context = ctx;       <br />&#160;&#160;&#160;&#160;&#160; ti.Install(new Hashtable());       <br />&#160;&#160; }       <br />}       </p>
</blockquote>
<p>The same way we’ll do uninstaller</p>
<blockquote><p>/// &lt;summary&gt;Uninstalls the provider service in interactive mode.&lt;/summary&gt;      <br />public void Uninstall() {       <br />&#160;&#160; if (Environment.UserInteractive) {       <br />&#160;&#160;&#160;&#160;&#160; var ti = new TransactedInstaller();       <br />&#160;&#160;&#160;&#160;&#160; var spi = new ServiceProviderInstaller();       <br />&#160;&#160;&#160;&#160;&#160; ti.Installers.Add(spi);       <br />&#160;&#160;&#160;&#160;&#160; var path = &quot;/assemblypath=&quot; + Assembly.GetEntryAssembly().Location;       <br />&#160;&#160;&#160;&#160;&#160; var ctx = new InstallContext(&quot;&quot;, new string[] { path });       <br />&#160;&#160;&#160;&#160;&#160; ti.Context = ctx;       <br />&#160;&#160;&#160;&#160;&#160; ti.Uninstall(null);       <br />&#160;&#160; }       <br />}       </p>
</blockquote>
<p>We almost done, the only problem is Component Designer which wants to be run when you click on any class derived from ServiceBase. I know that Visual Studio developers wanted to do our life easier, but this designer (especially one cannot initialize abstract classes) is very annoying. In in order to get rid of this thing we can override <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.designercategoryattribute.aspx" target="_blank">DesignerCategory</a> of the class and tell VS that it is not SeriviceComponent anymore. To do this all we need is one small attribute set on classes</p>
<blockquote><p>[System.ComponentModel.DesignerCategory(&quot;&quot;)]      <br />public abstract class ServiceProvider : ServiceBase {       <br />…       </p>
<p>[RunInstaller(true), System.ComponentModel.DesignerCategory(&quot;&quot;), SerializableAttribute]      <br />public class ServiceProviderInstaller : Installer {       </p>
</blockquote>
<p>&#160;</p>
<p>Take into account that it should be full reference pass in order to help Visual Studio with fast resolving of references.</p>
<p>We done, let’s put everything together and see what we have and how to use it</p>
<blockquote><p>/// &lt;summary&gt;Provides service class to respond to service control manager (all responses are defaults).&lt;/summary&gt;      <br />[System.ComponentModel.DesignerCategory(&quot;&quot;)]       <br />public abstract class ServiceProvider : ServiceBase {</p>
<p>&#160;&#160; public static string Name;      <br />&#160;&#160; public static string ProviderKind;</p>
<p>&#160;&#160; public ServiceProvider(string name) {      <br />&#160;&#160;&#160;&#160;&#160; ProviderKind = name;       <br />&#160;&#160;&#160;&#160;&#160; Name = &quot;Magic.Provider.&quot; + ProviderKind;       <br />&#160;&#160;&#160;&#160;&#160; ServiceName = Name;       <br />&#160;&#160; }</p>
<p>&#160;&#160; /// &lt;summary&gt;Starts the provider service in interactive mode.&lt;/summary&gt;       <br />&#160;&#160; public void Start(string[] args) {       <br />&#160;&#160;&#160;&#160;&#160; if (Environment.UserInteractive) {       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; OnStart(args);       <br />&#160;&#160;&#160;&#160;&#160; } else {       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ServiceBase.Run(this);       <br />&#160;&#160;&#160;&#160;&#160; }       <br />&#160;&#160; }</p>
<p>&#160;&#160; /// &lt;summary&gt;Installs the provider service in interactive mode.&lt;/summary&gt;      <br />&#160;&#160; public void Install() {       <br />&#160;&#160;&#160;&#160;&#160; if (Environment.UserInteractive) {       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var ti = new TransactedInstaller();       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var spi = new ServiceProviderInstaller();       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ti.Installers.Add(spi);       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var path = &quot;/assemblypath=&quot; + Assembly.GetEntryAssembly().Location;       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var ctx = new InstallContext(&quot;&quot;, new string[] { path });       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ti.Context = ctx;       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ti.Install(new Hashtable());       <br />&#160;&#160;&#160;&#160;&#160; }       <br />&#160;&#160; }</p>
<p>&#160;&#160; /// &lt;summary&gt;Uninstalls the provider service in interactive mode.&lt;/summary&gt;      <br />&#160;&#160; public void Uninstall() {       <br />&#160;&#160;&#160;&#160;&#160; if (Environment.UserInteractive) {       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var ti = new TransactedInstaller();       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var spi = new ServiceProviderInstaller();       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ti.Installers.Add(spi);       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var path = &quot;/assemblypath=&quot; + Assembly.GetEntryAssembly().Location;       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var ctx = new InstallContext(&quot;&quot;, new string[] { path });       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ti.Context = ctx;       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ti.Uninstall(null);       <br />&#160;&#160;&#160;&#160;&#160; }       <br />&#160;&#160; }       <br />}</p>
<p>[RunInstaller(true), System.ComponentModel.DesignerCategory(&quot;&quot;), SerializableAttribute]      <br />public class ServiceProviderInstaller : Installer {       <br />&#160;&#160; private static readonly string ServiceName = ServiceProvider.Name;       <br />&#160;&#160; <br />&#160;&#160; public ServiceProviderInstaller() {       <br />&#160;&#160;&#160;&#160;&#160; var processInstaller = new ServiceProcessInstaller {       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Account = ServiceAccount.LocalSystem       <br />&#160;&#160;&#160;&#160;&#160; };</p>
<p>&#160;&#160;&#160;&#160;&#160; var serviceInstaller = new ServiceInstaller {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; DisplayName = &quot;Magic Service &quot; + ServiceProvider.ProviderKind + &quot; Provider&quot;,       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Description = &quot;Process the interface to the Magic service &quot; + ServiceProvider.ProviderKind + &quot; provider.&quot;,       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ServiceName = ServiceName,       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; StartType = ServiceStartMode.Automatic,       <br />&#160;&#160;&#160;&#160;&#160; };       <br />&#160;&#160;&#160; <br />&#160;&#160;&#160;&#160;&#160; this.Installers.Add(processInstaller);       <br />&#160;&#160;&#160;&#160;&#160; this.Installers.Add(serviceInstaller);       <br />&#160;&#160; }</p>
<p>&#160;&#160; protected override void OnCommitted(IDictionary savedState) {      <br />&#160;&#160;&#160;&#160;&#160; base.OnCommitted(savedState);       <br />&#160;&#160;&#160;&#160;&#160; var c = new ServiceController(ServiceName);       <br />&#160;&#160;&#160;&#160;&#160; c.Start();       <br />&#160;&#160; }       <br />}       </p>
</blockquote>
<p>In order to use it, just reference to the hosting assembly and inherit this class</p>
<blockquote><p>&#160;&#160; public abstract class SampleService : ServiceProvider {</p>
<p>&#160;&#160;&#160;&#160;&#160; /// &lt;summary&gt;Creates a new &lt;see cref=&quot;SampleService&quot;/&gt; instance.&lt;/summary&gt;      <br />&#160;&#160;&#160;&#160;&#160; public SampleService()       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; : base(&quot;Sample&quot;) {       <br />&#160;&#160;&#160;&#160;&#160; }       <br />}</p>
</blockquote>
<p>And run it from command prompt:</p>
<blockquote><p>class Program {      <br />&#160;&#160; static void Main(string[] args) {       <br />&#160;&#160;&#160;&#160;&#160; var p = new SampleService();       <br />&#160;&#160;&#160;&#160;&#160; if (args.Length &gt; 0) {       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (args[0] == &quot;/i&quot;){       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; p.Install();       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return;       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (args[0] == &quot;/u&quot;) {       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; p.Uninstall();       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return;       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }       <br />&#160;&#160;&#160;&#160;&#160; }       <br />&#160;&#160;&#160;&#160;&#160; p.Start(null);       <br />&#160;&#160;&#160;&#160;&#160; Console.Read();       <br />&#160;&#160;&#160;&#160;&#160; p.Stop();       <br />&#160;&#160; }       <br />}       </p>
</blockquote>
<p>We done. The only remaining thing is how to prevent component designer appearance on derived (SampleService) class. As for now I found no way to do this and <a href="http://stackoverflow.com/questions/8984683/how-to-disable-designer-in-derived-classes-in-following-generations" target="_blank">asked collective intelligence to help me with it</a>. Once I’ll have an answer I will update it here.</p>
<p>Be good people and have a good day!</p>
<p><strong>UPD</strong> (25th Jan): The reason for this strange behavior is cached reference assemblies. If you reference your base assembly <strong>before</strong> setting <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.designercategoryattribute.aspx" target="_blank">DesignerCategory</a> attribute, you’ll have to remove it and reference again on all consuming projects after you set it. Another evidence of Visual Studio developers laziness.</p>
<p>Related posts:<ol>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/dev/self-installable-and-runnable-service-or-how-to-make-generic-service-and-console-hybrid/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>RSA private key import from PEM format in C#</title>
		<link>http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/</link>
		<comments>http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/#comments</comments>
		<pubDate>Mon, 13 Jun 2011 21:14:42 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[DEV]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[Work process]]></category>

		<guid isPermaLink="false">http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/</guid>
		<description><![CDATA[First of all, I want to apologies for not writing. From one hand, this is not a good think for me to disappeared from development community horizons, from other hand, I am investing all my time into our better feature, which is good thing. There are too much things were done during last two years. [...]
Related posts:<ol>
<li><a href='http://khason.net/dev/self-installable-and-runnable-service-or-how-to-make-generic-service-and-console-hybrid/' rel='bookmark' title='Self installable and runnable service or how to make generic service and console hybrid'>Self installable and runnable service or how to make generic service and console hybrid</a></li>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>First of all, I want to apologies for not writing. From one hand, this is not a good think for me to disappeared from development community horizons, from other hand, I am investing all my time <a href="http://www.betterplace.com/">into our better feature</a>, which is good thing. There are too much things were done during last two years. And the good news are that we already delivered whatever was promised to deliver and know for sure that we are able to deliver even more in the future. But let’s come into business. First of all I have huge pipeline of interesting articles to share with you, second, some people from my team are also decided to contribute to the community and write <a href="http://betterteamblog.com/" target="_blank">Better Place development team blog</a>. There are not too much there, but this is only a matter of time.</p>
<p>Today we’ll speak about security. About how to import <a href="http://www.openssl.org/" target="_blank">OpenSSL</a> private key into .NET application and use it aside with X509 public certificate to establish <a href="http://en.wikipedia.org/wiki/Transport_Layer_Security" target="_blank">TLS connection</a> with <a href="http://en.wikipedia.org/wiki/Public-key_cryptography" target="_blank">asymmetric encryption</a> and two phase certificates handshake. </p>
<p><img style="display: inline" title="image" alt="image" src="http://khason.net/images/2011/06/image.png" width="435" height="275" /></p>
<p>Let’s start from the very beginning. What is SSL? SSL is the secure way to communicate when transferred data is encrypted by using one time and per-session cipher. There are different implementations of such connection. The most famous one is the one all of you using when connection to https://someting… When doing this, your browser asks remote side to provide it public certificate for you in order to check it with local “authority” you trusted in. If everything is ok and the host defined on the remote certificate is the host you are speaking with, your browser allows communication after both sides decide about the one-time cipher for encryption.</p>
<p>You can implement this mode of SSL very easy by using <a href="http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx" target="_blank">SslStream</a> class in .NET as 1-2-3.    <br />1) Resolve host and open <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx" target="_blank">TcpClient</a> connection to it</p>
<blockquote><p>var host = new IPHostEntry();     <br />try {      <br />host = Dns.GetHostEntry(RemoteAddress.DnsSafeHost);      <br />} catch (SocketException soe) {      <br />if (soe.SocketErrorCode == SocketError.HostNotFound) {      <br />&#160; host.HostName = RemoteAddress.DnsSafeHost;      <br />}      <br />}      </p>
<p>Client.Connect(host.HostName, RemoteAddress.Port);</p>
</blockquote>
<p>2) Initialize SSL encrypted stream to it by providing validation callback for remote certificate</p>
<blockquote><p>var stream = new SslStream(Client.GetStream(), true, _validateCertificate);</p>
</blockquote>
<p>3) Ask for authorization</p>
<blockquote><p>stream.AuthenticateAsClient(host.HostName);</p>
</blockquote>
<p>Inside remote certificate validation callback, you should decide what to do if something bad happened during negotiation phase.</p>
<blockquote><p>private readonly RemoteCertificateValidationCallback _validateCertificate = (sender, certificate, chain, sslPolicyErrors) =&gt; {     <br />&#160; var result = sslPolicyErrors == SslPolicyErrors.None;      <br />&#160;&#160;&#160; if (!result) {      <br />&#160;&#160;&#160;&#160;&#160; var err = new StringBuilder();      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; err.AppendFormat(&quot;Unable to establish security connection due to {0}. Error chain:&quot;, sslPolicyErrors);</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160; foreach (var el in chain.ChainElements) {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; foreach (var s in el.ChainElementStatus) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; err.AppendFormat(&quot;{0} &#8211; {1}&quot;, el.Certificate.Subject, s.StatusInformation);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Log.Warn(err.ToString());      <br />&#160;&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160;&#160;&#160;&#160; return result;      <br />&#160;&#160;&#160; };</p>
</blockquote>
<p>So far, so good. Now, if everything is OK, just use SslStream as regular stream to write and read from the socket. All other complicated things will be done by .NET.</p>
<p>However this is only a part of the game. Now the real thing comes. What if you want to be more secure and want your server to be able to validate that local client is one it can trust. This scenario often used in closed networks, when server side (or any other provisioning entity) can assure that every client is well known and it able to provide certificate to each of those. For this scenario we also have solution in SslStream implementation, which takes into account this ability, defined by TLS RFC. All we need is to use other override of SslStream constructor which receives the callback for client certificate choose logic and authorization method with prepared clients certificates.</p>
<blockquote><p>var stream = new SslStream(Client.GetStream(), true, _validateCertificate, _selectCertificate);     <br />stream.AuthenticateAsClient(host.HostName, _clientCerts, SslProtocols.Ssl3, false);</p>
</blockquote>
<p>Inside local certificate selection logic you should receive the remote end choice algorithm and return the most secure client certificate you have</p>
<blockquote><p>private readonly LocalCertificateSelectionCallback _selectCertificate = (sender, target, localCerts, remoteCert, issuers) =&gt; {     <br />….      <br />return securestCert;      <br />}</p>
</blockquote>
<p>Also you should prepare the local certificates collection, provided as input to negotiation method. This one is simple too. All you need is standard X509 certificate(s). Usually, such certificates provided by uber-secure-unix-seriose-unbreakable-machine, which uses OpenSSL to export generated keys. This means, that in most cases, your public certificate will looks inside like this:</p>
<blockquote><p>Certificate:     <br />&#160;&#160;&#160; Data:      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Version: 1 (0&#215;0)      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Serial Number: 268436473 (0x100003f9)      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Signature Algorithm: md5WithRSAEncryption      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Issuer: O=UBER, OU=RD/emailAddress=ca@ubersecurity.org, L=TLV, ST=Israel, C=IL, CN=ca      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Validity      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Not Before: May 25 11:26:50 2011 GMT      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Not After : May 24 11:26:50 2012 GMT      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Subject: C=IL, ST=Israel, O=UBER, OU=SEC, CN=UberSecurity      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Subject Public Key Info:      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Public Key Algorithm: rsaEncryption      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; RSA Public Key: (1024 bit)      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Modulus (1024 bit):      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <em>… some random HEX numbers …</em>      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Exponent: 65537 (0&#215;10001)      <br />&#160;&#160;&#160; Signature Algorithm: md5WithRSAEncryption      <br /><em>&#160;&#160;&#160;&#160;&#160;&#160;&#160; … some other random HEX numbers …</em>      <br />&#8212;&#8211;BEGIN CERTIFICATE&#8212;&#8211;      <br /><em>… some BASE64 random characters here …</em>      <br />&#8212;&#8211;END CERTIFICATE&#8212;&#8211; </p>
</blockquote>
<p>This format called <a href="http://en.wikipedia.org/wiki/Privacy-enhanced_Electronic_Mail" target="_blank">PEM (Privacy Enhanced Mail)</a>. This is most common and easiest format for secure text transfer. Such file can be easily imported and used by <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate.aspx" target="_blank">X509Certificate</a> class as following:</p>
<blockquote><p>var clientCert = X509Certificate.CreateFromCertFile(&quot;myCert.pem&quot;);</p>
</blockquote>
<p>That’s all, all you need now is to add this certificate into certificate collection (<em>_clientCerts</em> in this case) and return it when _selectCertificate delegate being called.</p>
<p>Looks simple and secure? It is, but there is a small <strong>BUT</strong> in all this. Real security experts, come from OpenSSL world often do not want to put private key for client (the key will be used for outgoing traffic encryption) inside client certificate and want to provide it via other channel securely. </p>
<p>Now you are asking what I am speaking about? Let me explain:</p>
<p>When SSL uses asymmetric encryption algorithm, local side uses private key to encrypt outgoing traffic. Once it trust other side (by validating remote certificate), it send local public key to the remote side, which uses it for information decryption. So far we have three entities: public key, private key and certificate. There is a method commonly used by industry to minimize transit problems. We know to pack public certificate and wrapped public key inside the same store to send it. If we want to go even further, we can also store securely private key inside the same store. Looks not very secure? This is not quite right. First of all, in most cases private certificate is encrypted by using special keyphase only known to the side this certificate intended to, second, it uses the same public key+certificate itself hash values to encrypt it event better. In this case there is a big advantage of compact and well known package format (keypair+certificate) and high security level.</p>
<p>However people come from OpenSSL world not trust too much to this method (and called it “evil empire bought the patent”) and often provide encrypted private key separately. This key being transferred in PEM format, however this time it is not standard one, but specific and designed by OpenSSL geeks. Even if they call it <a href="http://en.wikipedia.org/wiki/RSA" target="_blank">RSA</a> format, it has almost not relation to it.</p>
<p>Such key looks as following:</p>
<blockquote><p>&#8212;&#8211;BEGIN RSA PRIVATE KEY&#8212;&#8211;     <br />Proc-Type: 4,ENCRYPTED      <br />DEK-Info: DES-EDE3-CBC,<em>…some geeky HEX here …</em></p>
<p>   <em>… some BASE64 random characters here …</em>    <br /> 
<p>&#8212;&#8211;END RSA PRIVATE KEY&#8212;&#8211;</p>
</blockquote>
<p>Looks simple? Do not hurry this much. .NET has not build in method to read this format. So we’ll have to write one, based on OpenSSL specification. Let’s start</p>
<p>First of all “well known headers”</p>
<blockquote><p>private const string _begin = &quot;&#8212;&#8211;BEGIN &quot;;     <br />private const string _end = &quot;&#8212;&#8211;END &quot;;      <br />private const string _private = &quot;PRIVATE KEY&quot;;      <br />private const string _public = &quot;PUBLIC KEY&quot;;      <br />private const string _rsaPublic = &quot;RSA PUBLIC KEY&quot;;      </p>
</blockquote>
<p>Next read the text inside the file:</p>
<blockquote><p>using (var reader = new StringReader(data)) {     <br />&#160;&#160; var line = reader.ReadLine();      <br />&#160;&#160; if (line.NotNull() &amp;&amp; line.StartsWith(_begin)) {      <br />&#160;&#160;&#160;&#160;&#160; line = line.Substring(_begin.Length);      <br />&#160;&#160;&#160;&#160;&#160; var idx = line.IndexOf(&#8216;-&#8217;);      <br />&#160;&#160;&#160;&#160;&#160; if (idx &gt; 0) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var type = line.Before(idx);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return _loadPem(reader, type, passKey);      <br />&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160; }      <br />&#160;&#160; throw new ArgumentException(&quot;This is not valid PEM format&quot;, &quot;data&quot;, new FormatException(&quot;PEM start identifier is invalid or not found.&quot;));      <br />}      </p>
</blockquote>
<p>…and read headers:</p>
<blockquote><p>var end = _end + type;     <br />var headers = new _pemHeaders();      <br />var line = string.Empty;      <br />var body = new StringBuilder();      <br />while ((line = reader.ReadLine()) != null &amp;&amp; line.IndexOf(end) == -1) {      <br />&#160;&#160; if (line == null) {      <br />&#160;&#160;&#160;&#160;&#160; throw new FormatException(&quot;PEM end identifier is invalid or not found.&quot;);      <br />&#160;&#160; }      <br />&#160;&#160; var d = line.IndexOf(&#8216;:&#8217;);      <br />&#160;&#160; if (d &gt;= 0) {      <br />&#160;&#160;&#160;&#160;&#160; // header      <br />&#160;&#160; <br />&#160;&#160;&#160;&#160;&#160; var n = line.Substring(0, d).Trim();      <br />&#160;&#160;&#160;&#160;&#160; if (n.StartsWith(&quot;X-&quot;)) n = n.Substring(2);      <br />&#160;&#160;&#160;&#160;&#160; var v = line.After(d).Trim();      <br />&#160;&#160;&#160;&#160;&#160; if (!headers.ContainsKey(n)) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; headers.Add(n, v);      <br />&#160;&#160;&#160;&#160;&#160; } else {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; throw new FormatException(&quot;Duplicate header {0} in PEM data.&quot;.Substitute(n));      <br />&#160;&#160;&#160;&#160;&#160; }</p>
</blockquote>
<p>When headers are ready, we need to read a body. This is base64 encrypted</p>
<blockquote><p>&#160;&#160; } else {      <br />&#160;&#160;&#160;&#160;&#160; // body      <br />&#160;&#160;&#160;&#160;&#160; body.Append(line);      <br />&#160;&#160; }      <br />}      <br />if (body.Length % 4 != 0 || type.EndsWith(_private)) {      <br />&#160;&#160; throw new FormatException(&quot;PEM data is invalid or truncated.&quot;);      <br />}</p>
<p>return _createPem(type, headers, Convert.FromBase64String(body.ToString()), passkey);</p>
</blockquote>
<p>and now, based on headers, we can decode body. For simplification, we’ll decode only most common encryptions for the key</p>
<blockquote><p>type = type.Before(type.Length &#8211; _private.Length).Trim();     <br />var pType = headers.TryGet(&quot;Proc-Type&quot;);      <br />if (pType == &quot;4,ENCRYPTED&quot;) {      <br />&#160;&#160; if (passkey.IsEmpty()) {      <br />&#160;&#160;&#160;&#160;&#160; throw new ArgumentException(&quot;Passkey is mandatory for encrypted PEM object&quot;);      <br />&#160;&#160; }</p>
<p>&#160;&#160; var dek = headers.TryGet(&quot;DEK-Info&quot;);     <br />&#160;&#160; var tkz = dek.Split(&#8216;,&#8217;);      <br />&#160;&#160; if (tkz.Length &gt; 1) {      <br />&#160;&#160;&#160;&#160;&#160; var alg = new _alg(tkz[0]);      <br />&#160;&#160;&#160;&#160;&#160; var saltLen = tkz[1].Length;      <br />&#160;&#160;&#160;&#160;&#160; var salt = new byte[saltLen / 2];      <br />&#160;&#160;&#160;&#160;&#160; for (var i = 0; i &lt; saltLen / 2; i++) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var pair = tkz[1].Substring(2 * i, 2);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; salt[i] = Byte.Parse(pair, NumberStyles.AllowHexSpecifier);      <br />&#160;&#160;&#160;&#160;&#160; }</p>
<p>&#160;&#160;&#160;&#160;&#160; body = _decodePem(body, passkey, alg, salt);     <br />&#160;&#160;&#160;&#160;&#160; if (body != null) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return _decodeRsaPrivateKey(body);      <br />&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160; } else {      <br />&#160;&#160;&#160;&#160;&#160; throw new FormatException(&quot;DEK information is invalid or truncated.&quot;);      <br />&#160;&#160; }      <br />}      </p>
</blockquote>
<p>For simplification, we’ll support only most common encryption algorithms (3DES with CBC mode). In general RSA private key can be encrypted by AES, Blow Fish, DES/Triple DES and RC2</p>
<blockquote><p>private static byte[] _decodePem(byte[] body, string passkey, _alg alg, byte[] salt) {     <br />&#160;&#160; if (alg.AlgBase != _alg.BaseAlg.DES_EDE3 &amp;&amp; alg.AlgMode != _alg.Mode.CBC) {      <br />&#160;&#160;&#160;&#160;&#160; throw new NotSupportedException(&quot;Only 3DES-CBC keys are supported.&quot;);      <br />&#160;&#160; }      <br />&#160;&#160; var des = _get3DesKey(salt, passkey);      <br />&#160;&#160; if (des == null) {      <br />&#160;&#160;&#160;&#160;&#160; throw new ApplicationException(&quot;Unable to calculate 3DES key for decryption.&quot;);      <br />&#160;&#160; }      <br />&#160;&#160; var rsa = _decryptRsaKey(body, des, salt);      <br />&#160;&#160; if (rsa == null) {      <br />&#160;&#160;&#160;&#160;&#160; throw new ApplicationException(&quot;Unable to decrypt RSA private key.&quot;);      <br />&#160;&#160; }      <br />&#160;&#160; return rsa;      <br />}      </p>
</blockquote>
<p>And decrypt itself</p>
<blockquote><p>private static byte[] _decryptRsaKey(byte[] body, byte[] desKey, byte[] iv) {     <br />&#160;&#160; byte[] result = null;      <br />&#160;&#160; using (var stream = new MemoryStream()) {      <br />&#160;&#160;&#160;&#160;&#160; var alg = TripleDES.Create();      <br />&#160;&#160;&#160;&#160;&#160; alg.Key = desKey;      <br />&#160;&#160;&#160;&#160;&#160; alg.IV = iv;      <br />&#160;&#160;&#160;&#160;&#160; try {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; using (var cs = new CryptoStream(stream, alg.CreateDecryptor(), CryptoStreamMode.Write)) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; cs.Write(body, 0, body.Length);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; cs.Close();      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; result = stream.ToArray();      <br />&#160;&#160;&#160;&#160;&#160; } catch (CryptographicException ce) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; // throw up      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; throw ce;      <br />&#160;&#160;&#160;&#160;&#160; } catch (Exception ex) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Log.Exception(ex, Severity.Info, &quot;Failed to write crypto stream.&quot;);      <br />&#160;&#160;&#160;&#160;&#160; };      <br />&#160;&#160; }      <br />&#160;&#160; return result;      <br />}      </p>
</blockquote>
<p>by getting 3DES key from stream</p>
<blockquote><p>private static byte[] _get3DesKey(byte[] salt, string passkey) {     <br />&#160;&#160; var HASHLENGTH = 16;      <br />&#160;&#160; var m = 2; // 2 iterations for at least 24 bytes      <br />&#160;&#160; var c = 1; // 1 hash for Open SSL      <br />&#160;&#160; var k = new byte[HASHLENGTH * m];</p>
<p>&#160;&#160; var pk = Encoding.ASCII.GetBytes(passkey);     <br />&#160;&#160; var data = new byte[salt.Length + pk.Length];      <br />&#160;&#160; Array.Copy(pk, data, pk.Length);      <br />&#160;&#160; Array.Copy(salt, 0, data, pk.Length, salt.Length);      <br />&#160;&#160; var md5 = new MD5CryptoServiceProvider();      <br />&#160;&#160; byte[] result = null;      <br />&#160;&#160; var hash = new byte[HASHLENGTH + data.Length];      <br />&#160;&#160; <br />&#160;&#160; for (int i = 0; i &lt; m; i++) {      <br />&#160;&#160;&#160;&#160;&#160; if (i == 0) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; result = data;      <br />&#160;&#160;&#160;&#160;&#160; } else {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Array.Copy(result, hash, result.Length);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Array.Copy(data, 0, hash, result.Length, data.Length);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; result = hash;      <br />&#160;&#160;&#160;&#160;&#160; }</p>
<p>&#160;&#160;&#160;&#160;&#160; for (int j = 0; j &lt; c; j++) {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; result = md5.ComputeHash(result);      <br />&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160;&#160;&#160;&#160; Array.Copy(result, 0, k, i * HASHLENGTH, result.Length);      <br />&#160;&#160; }      <br />&#160;&#160; var dk = new byte[24]; //final key      <br />&#160;&#160; Array.Copy(k, dk, dk.Length);      <br />&#160;&#160; return dk;      <br />}      </p>
</blockquote>
<p>When we decode the body, we can use create <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx" target="_blank">RSACryptoServiceProvider</a> class from it to be used by our SslStream. Oh, yeah, some crazy math here</p>
<blockquote><p>using (var ms = new MemoryStream(body)) {     <br />&#160;&#160; using (var reader = new BinaryReader(ms)) {      <br />&#160;&#160;&#160;&#160;&#160; try {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var tb = reader.ReadUInt16(); // LE: x30 x81      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (tb == 0&#215;8130) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; reader.ReadByte(); // fw 1      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; } else if (tb == 0&#215;8230) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; reader.ReadInt16(); // fw 2      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; } else {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return null;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; tb = reader.ReadUInt16(); // version     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (tb != 0&#215;0102) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return null;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (reader.ReadByte() != 0&#215;00) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return null;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var MODULUS = _readInt(reader);     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var E = _readInt(reader);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var D = _readInt(reader);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var P = _readInt(reader);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var Q = _readInt(reader);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var DP = _readInt(reader);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var DQ = _readInt(reader);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var IQ = _readInt(reader);</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var result = new RSACryptoServiceProvider();     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var param = new RSAParameters {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Modulus = MODULUS,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Exponent = E,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; D = D,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; P = P,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Q = Q,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; DP = DP,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; DQ = DQ,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; InverseQ = IQ      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; };      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; result.ImportParameters(param);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return result;</p>
<p>&#160;</p>
<p>&#160;&#160;&#160;&#160;&#160; } catch (Exception ex) {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Log.Exception(ex);      <br />&#160;&#160;&#160;&#160;&#160; } finally {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; reader.Close();      <br />&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160; }      <br />}      </p>
</blockquote>
<p>Some helper methods to read bytes and we done</p>
<blockquote><p>private static Func&lt;BinaryReader, byte[]&gt; _readInt = r =&gt; {     <br />&#160;&#160; var s = _getIntSize(r);      <br />&#160;&#160; return r.ReadBytes(s);      <br />};</p>
<p>private static Func&lt;BinaryReader, int&gt; _getIntSize = r =&gt; {     <br />&#160;&#160; byte lb = 0&#215;00;      <br />&#160;&#160; byte hb = 0&#215;00;      <br />&#160;&#160; int c = 0;      <br />&#160;&#160; var b = r.ReadByte();      <br />&#160;&#160; if (b != 0&#215;02) { //int      <br />&#160;&#160;&#160;&#160;&#160; return 0;      <br />&#160;&#160; }      <br />&#160;&#160; b = r.ReadByte();</p>
<p>&#160;&#160; if (b == 0&#215;81) {     <br />&#160;&#160;&#160;&#160;&#160; c = r.ReadByte(); //size      <br />&#160;&#160; } else      <br />&#160;&#160;&#160;&#160;&#160; if (b == 0&#215;82) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; hb = r.ReadByte(); //size      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; lb = r.ReadByte();      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; byte[] m = { lb, hb, 0&#215;00, 0&#215;00 };      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; c = BitConverter.ToInt32(m, 0);      <br />&#160;&#160;&#160;&#160;&#160; } else {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; c = b; //got size      <br />&#160;&#160;&#160;&#160;&#160; }</p>
<p>&#160;&#160; while (r.ReadByte() == 0&#215;00) { //remove high zero      <br />&#160;&#160;&#160;&#160;&#160; c -= 1;      <br />&#160;&#160; }      <br />&#160;&#160; r.BaseStream.Seek(-1, SeekOrigin.Current); // last byte is not zero, go back;      <br />&#160;&#160; return c;      <br />};      </p>
</blockquote>
<p>We done, all we have to do now is to construct our private key and pack it for SslStream use. For this purpose we have X509Certificate big brother <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.aspx" target="_blank">X509Certificate2</a>&#160;</p>
<blockquote><p>var cert = new X509Certificate2(File.ReadAllBytes(“myCert.pem”)) {     <br />&#160; PrivateKey = FromPem(Encoding.ASCII.GetString(File.ReadAllBytes(“myKey.pem”)), _sslPrivateKeyPasskey)      <br />};</p>
</blockquote>
<p>Now when you supply cert as the client certificate SslStream will use private key for outgoing stream encryption, provide public key for remote incoming stream encryption and certificate for remote side identification.</p>
<p>We done. Be good people and subscribe to <a href="http://betterteamblog.com/" target="_blank">our dev blog</a>, it promised to be one of the most interesting blogs for those who is not satisfied with the way Windows works and want to pimp it a bit.</p>
<p><a href="http://khason.net/images/2011/06/RSA.zip" target="_blank"><strong>Source code for this article (4 KB) &gt;&gt;</strong></a></p>
<p><em>P.S.</em> If, in case, you got invitation from Microsoft Israel to participate “Be what’s next” event next Wednesday 22<sup>nd</sup>. It is highly recommended to come and see me (and other large ISVs) speak about solutions we did. If you did not get an invitation, and you are MS partner, please contact local DPE guys. This is for certain ISVs and only by invitations.</p>
<p><img style="margin: 0px; display: inline" title="image" alt="image" src="http://khason.net/images/2011/06/image1.png" width="629" height="444" /></p>
<p>Related posts:<ol>
<li><a href='http://khason.net/dev/self-installable-and-runnable-service-or-how-to-make-generic-service-and-console-hybrid/' rel='bookmark' title='Self installable and runnable service or how to make generic service and console hybrid'>Self installable and runnable service or how to make generic service and console hybrid</a></li>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Real singleton approach in WPF application</title>
		<link>http://khason.net/dev/read-singleton-approach-in-wpf-application/</link>
		<comments>http://khason.net/dev/read-singleton-approach-in-wpf-application/#comments</comments>
		<pubDate>Mon, 24 Aug 2009 20:19:35 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[DEV]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://khason.net/dev/read-singleton-approach-in-wpf-application/</guid>
		<description><![CDATA[One of the most common problems in WPF is memory/processor time consumption. Yes, WPF is rather greedy framework. It become even greedier when using unmanaged resources, such as memory files or interop images. To take care on it, you can implement singleton pattern for the application and share only one unmanaged instance among different application [...]
Related posts:<ol>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>One of the most common problems in WPF is memory/processor time consumption. Yes, WPF is rather greedy framework. It become even greedier when using unmanaged resources, such as memory files or interop images. To take care on it, you can implement singleton pattern for the application and share only one unmanaged instance among different application resources. So today we’ll try to create one large in-memory dynamic bitmap and share it between different instances of WPF controls. Let’s start</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="The Singleton" border="0" alt="The Singleton" src="http://khason.net/images/2009/08/image2.png" width="206" height="520" /> </p>
<p>First of all let’s create our single instance source. The pattern is straight forward. Create a class derived from INotifyPropertyChanged, create private constructor and static member returns the single instance of the class.</p>
<blockquote><p>public class MySingleton : INotifyPropertyChanged { </p>
<p>&#160;&#160; #region Properties     <br />&#160;&#160; public BitmapSource Source { get { return _source; } }      <br />&#160;&#160; public static MySingleton Instance {      <br />&#160;&#160;&#160;&#160;&#160; get {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (_instance == default(MySingleton)) _instance = new MySingleton();      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return _instance;      <br />&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160; }      <br />&#160;&#160; #endregion </p>
<p>&#160;&#160; #region ctor     <br />&#160;&#160; private MySingleton() { _init(); }      <br />&#160;&#160; #endregion</p>
</blockquote>
<p>Now we need to create this single instance of this class inside our XAML program. To do this, we have great extension x:Static</p>
<blockquote><p>&lt;Window.DataContext&gt;     <br />&#160;&#160;&#160; &lt;x:StaticExtension Member=&quot;l:MySingleton.Instance&quot; /&gt;      <br />&lt;/Window.DataContext&gt;</p>
</blockquote>
<p>Now we need to find a way to do all dirty work inside MySingleton and keep classes using it as simple is possible. For this purpose we’ll register class handler to catch all GotFocus routed events, check the target of the event and rebind the only instance to new focused element. How to do this? Simple as 1-2-3</p>
<p>Create class handler</p>
<blockquote><p>EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.GotFocusEvent, (RoutedEventHandler)_onAnotherItemFocused);</p>
</blockquote>
<p>Check whether selected and focused item of the right type</p>
<blockquote><p>private void _onAnotherItemFocused(object sender, RoutedEventArgs e) {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; DependencyPropertyDescriptor.FromProperty(ListBoxItem.IsSelectedProperty, typeof(ListBoxItem)).AddValueChanged(sender, (s, ex) =&gt; {}</p>
</blockquote>
<p>and reset binding </p>
<blockquote><p>var item = s as ListBoxItem;     <br />var img = item.Content as Image;      <br />if (_current != null &amp;&amp; _current.Target is Image &amp;&amp; _current.Target != img) {      <br />&#160;&#160; ((Image)_current.Target).ClearValue(Image.SourceProperty);      <br />}       <br />if (img != null) {      <br />&#160;&#160; _current = new WeakReference(img);      <br />&#160;&#160; img.SetBinding(Image.SourceProperty, _binding);      <br />}</p>
</blockquote>
<p>We almost done. a bit grease to make the source bitmap shiny </p>
<blockquote><p>var count = (uint)(_w * _h * 4);     <br />var section = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0&#215;04, 0, count, null);      <br />_map = MapViewOfFile(section, 0xF001F, 0, 0, count);      <br />_source = Imaging.CreateBitmapSourceFromMemorySection(section, _w, _h, PixelFormats.Bgr32, (int)(_w * 4), 0) as InteropBitmap;      <br />_binding = new Binding {      <br />&#160;&#160; Mode = BindingMode.OneWay,      <br />&#160;&#160; Source = _source      <br />};      <br />CompositionTarget.Rendering += (s, e) =&gt; { _invalidate(); };</p>
</blockquote>
<blockquote><p>private void _invalidate() {     <br />&#160;&#160; var color = (uint)((uint)0xFF &lt;&lt; 24) | (uint)(_pixel &lt;&lt; 16) | (uint)(_pixel &lt;&lt; <img src='http://khason.net/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> | (uint)_pixel;      <br />&#160;&#160; _pixel++; </p>
<p>&#160;&#160; unsafe {     <br />&#160;&#160;&#160;&#160;&#160; uint* pBuffer = (uint*)_map;      <br />&#160;&#160;&#160;&#160;&#160; int _pxs = (_w * _h);      <br />&#160;&#160;&#160;&#160;&#160; for (var i = 0; i &lt; _pxs; i++) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; pBuffer[i] = color;      <br />&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160; }      <br />&#160;&#160; _source.Invalidate();      <br />&#160;&#160; OnPropertyChanged(&quot;Source&quot;);      <br />}</p>
</blockquote>
<p>And we done. The usage of this approach is very simple – there is no usage at all. All happens automagically inside MySingleton class, all you need is to set static data context and add images</p>
<blockquote><p>&lt;StackPanel&gt;     <br />&#160;&#160;&#160; &lt;Button Click=&quot;_addAnother&quot;&gt;Add another&#8230;&lt;/Button&gt;      <br />&#160;&#160;&#160; &lt;ListBox Name=&quot;target&quot; /&gt;      <br />&lt;/StackPanel&gt;      <br />…      <br />private void _addAnother(object sender, RoutedEventArgs e) {      <br />&#160;&#160; var img = new Image { Width=200, Height=200, Margin=new Thickness(0,5,0,5) };      <br />&#160;&#160; target.Items.Add(img);      <br />&#160;&#160; this.Height += 200;      <br />}</p>
</blockquote>
<p>To summarize: in this article we learned how to use singletons as data sources for your XAML application, how to reuse it across WPF, how to connect to routed events externally and also how to handle dependency property changed from outside of the owner class. Have a nice day and be good people. </p>
<p><a href="http://khason.net/images/2009/08/ReuseSingleton.zip" target="_blank">Source code for this article (21k) &gt;&gt;</a></p>
<p>To make it works press number of times on “Add another…” button and then start selecting images used as listbox items. Pay attention to the working set of the application. Due to the fact that only one instance is in use it is not growing.</p>
<p>Related posts:<ol>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/dev/read-singleton-approach-in-wpf-application/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>INotifyPropertyChanged auto wiring or how to get rid of redundant code</title>
		<link>http://khason.net/dev/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code/</link>
		<comments>http://khason.net/dev/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code/#comments</comments>
		<pubDate>Sun, 09 Aug 2009 19:43:41 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[DEV]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Work process]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://khason.net/dev/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code/</guid>
		<description><![CDATA[For the last week most of WPF disciples are discussing how to get rid of hardcoded property name string inside INotifyPropertyChanged implementation and how to keep using automatic properties implementation but keep WPF binding working. The thread was started by Karl Shifflett, who proposed interesting method of using StackFrame for this task. During this thread [...]
Related posts:<ol>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>For the last week most of <a title="RSS feed of all disciples" href="http://pipes.yahoo.com/pipes/pipe.run?_id=Jp_ob_fn3RGFP6DnBRNMsA&amp;_render=rss" rel="rss" target="_blank">WPF disciples</a> are discussing how to get rid of hardcoded property name string inside <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx" target="_blank">INotifyPropertyChanged</a> implementation and how to keep using automatic properties implementation but keep WPF binding working. The thread was started by Karl Shifflett, <a href="http://karlshifflett.wordpress.com/2009/08/02/inotifypropertychanged-how-to-remove-the-property-name-string-code-smell/" target="_blank">who proposed interesting method</a> of using <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe.aspx" target="_blank">StackFrame</a> for this task. During this thread other methods were proposed including code snippets, R#, <a href="http://ayende.com/Blog/archive/2009/08/08/an-easier-way-to-manage-inotifypropertychanged.aspx" target="_blank">Observer Pattern</a>, <a href="http://www.codeproject.com/KB/WPF/CinchII.aspx#Better_INPC" target="_blank">Cinch framework</a>, <a href="http://mbrownchicago.spaces.live.com/blog/cns!2221DC39E0C749A4!1285.entry" target="_blank">Static Reflection</a>, <a href="http://danielvaughan.orpius.com/post/Property-Change-Notification-using-a-Weak-Referencing-Strategy.aspx" target="_blank">Weak References</a> and others. I also proposed the method we’re using for our classes and promised to blog about it. So the topic today is how to use <a href="http://www.postsharp.org" target="_blank">PostSharp</a> to wire automatic implementation of INotifyPropertyChanged interface based on automatic setters only.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="My 5 ¢" border="0" alt="My 5 ¢" src="http://khason.net/images/2009/08/image1.png" width="483" height="337" /> </p>
<p>So, I want my code to looks like this:</p>
<blockquote><p>public class AutoWiredSource {      <br />&#160;&#160; public double MyProperty { get; set; }       <br />&#160;&#160; public double MyOtherProperty { get; set; }       <br />}</p>
</blockquote>
<p>while be fully noticeable about any change in any property and makes me able to bind to those properties.</p>
<blockquote><p>&lt;StackPanel DataContext=&quot;{Binding Source={StaticResource source}}&quot;&gt;      <br />&#160;&#160;&#160; &lt;Slider Value=&quot;{Binding Path=MyProperty}&quot; /&gt;       <br />&#160;&#160;&#160; &lt;Slider Value=&quot;{Binding Path=MyProperty}&quot; /&gt;       <br />&lt;/StackPanel&gt;</p>
</blockquote>
<p>How to achieve it? How to make compiler to replace my code with following?:</p>
<blockquote><p>private double _MyProperty;      <br />public double MyProperty {       <br />&#160;&#160; get { return _MyProperty; }       <br />&#160;&#160; set {       <br />&#160;&#160;&#160;&#160;&#160; if (value != _MyProperty) {       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; _MyProperty = value; OnPropertyChanged(&quot;MyProperty&quot;);       <br />&#160;&#160;&#160;&#160;&#160; }       <br />&#160;&#160; }       <br />}       <br />public event PropertyChangedEventHandler PropertyChanged;       <br />internal void OnPropertyChanged(string propertyName) {       <br />&#160;&#160; if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException(&quot;propertyName&quot;); </p>
<p>&#160;&#160; var handler = PropertyChanged as PropertyChangedEventHandler;      <br />&#160;&#160; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));       <br />}</p>
</blockquote>
<p>Simple: to use aspect oriented programming to inject set of instructions into pre-compiled source.</p>
<p>First of all we have to build some attribute will be used for marking classes requires change tracking. This attribute should be combined (compound) aspect to include all aspects used for change tracking. All we’re doing here is to get all set methods to add composition aspect to</p>
<blockquote><p>[Serializable, DebuggerNonUserCode, AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = false, Inherited = false),      <br />MulticastAttributeUsage(MulticastTargets.Class, AllowMultiple = false, Inheritance = MulticastInheritance.None, AllowExternalAssemblies = true)]       <br />public sealed class NotifyPropertyChangedAttribute : CompoundAspect {       <br />&#160;&#160; public int AspectPriority { get; set; } </p>
<p>&#160;&#160; public override void ProvideAspects(object element, LaosReflectionAspectCollection collection) {      <br />&#160;&#160;&#160;&#160;&#160; Type targetType = (Type)element;       <br />&#160;&#160;&#160;&#160;&#160; collection.AddAspect(targetType, new PropertyChangedAspect { AspectPriority = AspectPriority });       <br />&#160;&#160;&#160;&#160;&#160; foreach (var info in targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(pi =&gt; pi.GetSetMethod() != null)) {       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; collection.AddAspect(info.GetSetMethod(), new NotifyPropertyChangedAspect(info.Name) { AspectPriority = AspectPriority });       <br />&#160;&#160;&#160;&#160;&#160; }       <br />&#160;&#160; }       <br />}</p>
</blockquote>
<p>Next aspect is change tracking composition aspect. Which is used for marking only</p>
<blockquote><p>[Serializable]      <br />internal sealed class PropertyChangedAspect : CompositionAspect {       <br />&#160;&#160; public override object CreateImplementationObject(InstanceBoundLaosEventArgs eventArgs) {       <br />&#160;&#160;&#160;&#160;&#160; return new PropertyChangedImpl(eventArgs.Instance);       <br />&#160;&#160; } </p>
<p>&#160;&#160; public override Type GetPublicInterface(Type containerType) {      <br />&#160;&#160;&#160;&#160;&#160; return typeof(INotifyPropertyChanged);       <br />&#160;&#160; } </p>
<p>&#160;&#160; public override CompositionAspectOptions GetOptions() {      <br />&#160;&#160;&#160;&#160;&#160; return CompositionAspectOptions.GenerateImplementationAccessor;       <br />&#160;&#160; }       <br />}</p>
</blockquote>
<p>And the next which is most interesting one, we will put onto method boundary for tracking. There are some highlights here. First we do not want to fire PropertyChanged event if the actual value did not changed, thus we’ll handle the method on it entry and on it exit for check.</p>
<blockquote><p>[Serializable]      <br />internal sealed class NotifyPropertyChangedAspect : OnMethodBoundaryAspect {       <br />&#160;&#160; private readonly string _propertyName; </p>
<p>&#160;&#160; public NotifyPropertyChangedAspect(string propertyName) {      <br />&#160;&#160;&#160;&#160;&#160; if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException(&quot;propertyName&quot;);       <br />&#160;&#160;&#160;&#160;&#160; _propertyName = propertyName;       <br />&#160;&#160; } </p>
<p>&#160;&#160; public override void OnEntry(MethodExecutionEventArgs eventArgs) {      <br />&#160;&#160;&#160;&#160;&#160; var targetType = eventArgs.Instance.GetType();       <br />&#160;&#160;&#160;&#160;&#160; var setSetMethod = targetType.GetProperty(_propertyName);       <br />&#160;&#160;&#160;&#160;&#160; if (setSetMethod == null) throw new AccessViolationException();       <br />&#160;&#160;&#160;&#160;&#160; var oldValue = setSetMethod.GetValue(eventArgs.Instance,null);       <br />&#160;&#160;&#160;&#160;&#160; var newValue = eventArgs.GetReadOnlyArgumentArray()[0];       <br />&#160;&#160;&#160;&#160;&#160; if (oldValue == newValue) eventArgs.FlowBehavior = FlowBehavior.Return;       <br />&#160;&#160; } </p>
<p>&#160;&#160; public override void OnSuccess(MethodExecutionEventArgs eventArgs) {      <br />&#160;&#160;&#160;&#160;&#160; var instance = eventArgs.Instance as IComposed&lt;INotifyPropertyChanged&gt;;       <br />&#160;&#160;&#160;&#160;&#160; var imp = instance.GetImplementation(eventArgs.InstanceCredentials) as PropertyChangedImpl;       <br />&#160;&#160;&#160;&#160;&#160; imp.OnPropertyChanged(_propertyName);       <br />&#160;&#160; }       <br />}</p>
</blockquote>
<p>We almost done, all we have to do is to create class which implements INotifyPropertyChanged with internal method to useful call</p>
<blockquote><p>[Serializable]      <br />internal sealed class PropertyChangedImpl : INotifyPropertyChanged {       <br />&#160;&#160; private readonly object _instance; </p>
<p>&#160;&#160; public PropertyChangedImpl(object instance) {      <br />&#160;&#160;&#160;&#160;&#160; if (instance == null) throw new ArgumentNullException(&quot;instance&quot;);       <br />&#160;&#160;&#160;&#160;&#160; _instance = instance;       <br />&#160;&#160; } </p>
<p>&#160;&#160; public event PropertyChangedEventHandler PropertyChanged; </p>
<p>&#160;&#160; internal void OnPropertyChanged(string propertyName) {      <br />&#160;&#160;&#160;&#160;&#160; if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException(&quot;propertyName&quot;); </p>
<p>&#160;&#160;&#160;&#160;&#160; var handler = PropertyChanged as PropertyChangedEventHandler;      <br />&#160;&#160;&#160;&#160;&#160; if (handler != null) handler(_instance, new PropertyChangedEventArgs(propertyName));       <br />&#160;&#160; }       <br />}</p>
</blockquote>
<p>We done. The last thing is to reference to PostSharp Laos and Public assemblies and mark compiler to use Postsharp targets (inside your project file (*.csproj)</p>
<blockquote><p>&lt;Import Project=&quot;$(MSBuildToolsPath)\Microsoft.CSharp.targets&quot; /&gt;      <br />&lt;PropertyGroup&gt;       <br />&#160; &lt;DontImportPostSharp&gt;True&lt;/DontImportPostSharp&gt;       <br />&lt;/PropertyGroup&gt;       <br />&lt;Import Project=&quot;PostSharp\PostSharp-1.5.targets&quot; /&gt;</p>
</blockquote>
<p>Now we done. We can use clear syntax like following to make all our properties has public setter to be traceable. The only disadvantage is that you’ll have to drag two Post Sharp files with your project. But after all it much more convenience than manual notify change tracking all over your project.</p>
<blockquote><p>[NotifyPropertyChanged]      <br />public class AutoWiredSource {       <br />&#160;&#160; public double MyProperty { get; set; }       <br />}</p>
</blockquote>
<p>Have a nice day and be good people. Also try to thing what other extremely useful things can be done with PostSharp (or any other aspect oriented engine)</p>
<p><a href="http://khason.net/images/2009/08/AutoPropertyChangedWiring.zip" rel="enclosure" target="_blank">Source code for this article (1,225 KB)&gt;&gt;</a></p>
<p>Related posts:<ol>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/dev/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>How to calculate CRC in C#?</title>
		<link>http://khason.net/dev/how-to-calculate-crc-in-c/</link>
		<comments>http://khason.net/dev/how-to-calculate-crc-in-c/#comments</comments>
		<pubDate>Mon, 06 Apr 2009 19:38:15 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[DEV]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Work process]]></category>

		<guid isPermaLink="false">http://khason.net/dev/how-to-calculate-crc-in-c/</guid>
		<description><![CDATA[First of all, I want to beg your pardon about the frequency of posts last time. I’m completely understaffed and have a ton of things to do for my job. This why, today I’ll just write a quick post about checksum calculation in C#. It might be very useful for any of you, working with [...]
Related posts:<ol>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>First of all, I want to beg your pardon about the frequency of posts last time. I’m completely understaffed and have a ton of things to do for my job. This why, today I’ll just write a quick post about checksum calculation in C#. It might be very useful for any of you, working with devices or external systems.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="BIOS CRC Error for old thinkpad" src="http://khason.net/images/2009/04/image.png" border="0" alt="BIOS CRC Error for old thinkpad" width="636" height="53" /></p>
<p><a href="http://en.wikipedia.org/wiki/Cyclic_redundancy_check" target="_blank">CRC – Cyclic Redundancy Check</a> is an algorithm, which is widely used in different communication protocols, packing and packaging algorithms for assure robustness of data. The idea behind it is simple – calculate unique checksum (frame check sequence) for each data frame, based on it’s content and stick it at the end of each meaningful message. Once data received it’s possible to perform the same calculating and compare results – if results are similar, message is ok.</p>
<p>There are two kinds of CRC – 16 and 32 bit. There are also less used checksums for 8 and 64 bits. All this is about appending a string of zeros to the frame equal in number of frames and modulo two device by using generator polynomial containing one or more bits then checksum to be generated. This is very similar to performing a bit-wise XOR operation in the frame, while the reminder is actually our CRC.</p>
<p>In many industries first polynomial is in use to create CRC tables and then apply it for performance purposes. The default polynomial, defined by IEEE 802.3 which is 0xA001 for 16 bit and 0x04C11DB7 for 32 bit. We’re in C#, thus we should use it inversed version which is 0&#215;8408 for 16 bit and 0xEDB88320 for 32 bit. Those polynomials we’re going to use also in our sample.</p>
<p>So let’s start. Because CRC is HashAlgorithm after all, we can derive our classes from System.Security.Cryptography.HashAlgorithm class.</p>
<blockquote><p>public class CRC16 : HashAlgorithm {<br />
public class CRC32 : HashAlgorithm {</p>
</blockquote>
<p>Then, upon first creation we’ll generate hashtables with CRC values to enhance future performance. It’s all about values table for bytes from 0 to 255 , so we should calculate it only once and then we can use it statically.</p>
<blockquote><p>[CLSCompliant(false)]<br />
public CRC16(ushort polynomial) {<br />
HashSizeValue = 16;<br />
_crc16Table = (ushort[])_crc16TablesCache[polynomial];<br />
if (_crc16Table == null) {<br />
_crc16Table = CRC16._buildCRC16Table(polynomial);<br />
_crc16TablesCache.Add(polynomial, _crc16Table);<br />
}<br />
Initialize();<br />
}</p>
<p>[CLSCompliant(false)]<br />
public CRC32(uint polynomial) {<br />
HashSizeValue = 32;<br />
_crc32Table = (uint[])_crc32TablesCache[polynomial];<br />
if (_crc32Table == null) {<br />
_crc32Table = CRC32._buildCRC32Table(polynomial);<br />
_crc32TablesCache.Add(polynomial, _crc32Table);<br />
}<br />
Initialize();<br />
}</p>
</blockquote>
<p>Then let’s calculate it</p>
<blockquote><p>private static ushort[] _buildCRC16Table(ushort polynomial) {<br />
// 256 values representing ASCII character codes.<br />
ushort[] table = new ushort[256];<br />
for (ushort i = 0; i &lt; table.Length; i++) {<br />
ushort value = 0;<br />
ushort temp = i;<br />
for (byte j = 0; j &lt; 8; j++) {<br />
if (((value ^ temp) &amp; 0&#215;0001) != 0) {<br />
value = (ushort)((value &gt;&gt; 1) ^ polynomial);<br />
} else {<br />
value &gt;&gt;= 1;<br />
}<br />
temp &gt;&gt;= 1;<br />
}<br />
table[i] = value;<br />
}<br />
return table;<br />
}</p>
<p>private static uint[] _buildCRC32Table(uint polynomial) {<br />
uint crc;<br />
uint[] table = new uint[256];</p>
<p>// 256 values representing ASCII character codes.<br />
for (int i = 0; i &lt; 256; i++) {<br />
crc = (uint)i;<br />
for (int j = 8; j &gt; 0; j&#8211;) {<br />
if ((crc &amp; 1) == 1)<br />
crc = (crc &gt;&gt; 1) ^ polynomial;<br />
else<br />
crc &gt;&gt;= 1;<br />
}<br />
table[i] = crc;<br />
}</p>
<p>return table;<br />
}</p>
</blockquote>
<p>The result will looks like this for 32 bits</p>
<blockquote>
<pre>        0x00, 0x31, 0x62, 0x53, 0xC4, 0xF5, 0xA6, 0x97,
        0xB9, 0x88, 0xDB, 0xEA, 0x7D, 0x4C, 0x1F, 0x2E,
        0x43, 0x72, 0x21, 0x10, 0x87, 0xB6, 0xE5, 0xD4,
        0xFA, 0xCB, 0x98, 0xA9, 0x3E, 0x0F, 0x5C, 0x6D,
        0x86, 0xB7, 0xE4, 0xD5, 0x42, 0x73, 0x20, 0x11,
        0x3F, 0x0E, 0x5D, 0x6C, 0xFB, 0xCA, 0x99, 0xA8,
        0xC5, 0xF4, 0xA7, 0x96, 0x01, 0x30, 0x63, 0x52,
        0x7C, 0x4D, 0x1E, 0x2F, 0xB8, 0x89, 0xDA, 0xEB,
        0x3D, 0x0C, 0x5F, 0x6E, 0xF9, 0xC8, 0x9B, 0xAA,
        0x84, 0xB5, 0xE6, 0xD7, 0x40, 0x71, 0x22, 0x13,
        0x7E, 0x4F, 0x1C, 0x2D, 0xBA, 0x8B, 0xD8, 0xE9,
        0xC7, 0xF6, 0xA5, 0x94, 0x03, 0x32, 0x61, 0x50,
        0xBB, 0x8A, 0xD9, 0xE8, 0x7F, 0x4E, 0x1D, 0x2C,
        0x02, 0x33, 0x60, 0x51, 0xC6, 0xF7, 0xA4, 0x95,
        0xF8, 0xC9, 0x9A, 0xAB, 0x3C, 0x0D, 0x5E, 0x6F,
        0x41, 0x70, 0x23, 0x12, 0x85, 0xB4, 0xE7, 0xD6,
        0x7A, 0x4B, 0x18, 0x29, 0xBE, 0x8F, 0xDC, 0xED,
        0xC3, 0xF2, 0xA1, 0x90, 0x07, 0x36, 0x65, 0x54,
        0x39, 0x08, 0x5B, 0x6A, 0xFD, 0xCC, 0x9F, 0xAE,
        0x80, 0xB1, 0xE2, 0xD3, 0x44, 0x75, 0x26, 0x17,
        0xFC, 0xCD, 0x9E, 0xAF, 0x38, 0x09, 0x5A, 0x6B,
        0x45, 0x74, 0x27, 0x16, 0x81, 0xB0, 0xE3, 0xD2,
        0xBF, 0x8E, 0xDD, 0xEC, 0x7B, 0x4A, 0x19, 0x28,
        0x06, 0x37, 0x64, 0x55, 0xC2, 0xF3, 0xA0, 0x91,
        0x47, 0x76, 0x25, 0x14, 0x83, 0xB2, 0xE1, 0xD0,
        0xFE, 0xCF, 0x9C, 0xAD, 0x3A, 0x0B, 0x58, 0x69,
        0x04, 0x35, 0x66, 0x57, 0xC0, 0xF1, 0xA2, 0x93,
        0xBD, 0x8C, 0xDF, 0xEE, 0x79, 0x48, 0x1B, 0x2A,
        0xC1, 0xF0, 0xA3, 0x92, 0x05, 0x34, 0x67, 0x56,
        0x78, 0x49, 0x1A, 0x2B, 0xBC, 0x8D, 0xDE, 0xEF,
        0x82, 0xB3, 0xE0, 0xD1, 0x46, 0x77, 0x24, 0x15,
        0x3B, 0x0A, 0x59, 0x68, 0xFF, 0xCE, 0x9D, 0xAC</pre>
</blockquote>
<p>Now, all we have to do is to upon request to lookup into this hash table for related value and XOR it</p>
<blockquote><p>protected override void HashCore(byte[] buffer, int offset, int count) {</p>
<p>for (int i = offset; i &lt; count; i++) {</p>
<p>ulong ptr = (_crc &amp; 0xFF) ^ buffer[i];</p>
<p>_crc &gt;&gt;= 8;</p>
<p>_crc ^= _crc32Table[ptr];</p>
<p>}</p>
<p>}</p>
<p>new public byte[] ComputeHash(Stream inputStream) {</p>
<p>byte[] buffer = new byte[4096];</p>
<p>int bytesRead;</p>
<p>while ((bytesRead = inputStream.Read(buffer, 0, 4096)) &gt; 0) {</p>
<p>HashCore(buffer, 0, bytesRead);</p>
<p>}</p>
<p>return HashFinal();</p>
<p>}</p>
<p>protected override byte[] HashFinal() {</p>
<p>byte[] finalHash = new byte[4];</p>
<p>ulong finalCRC = _crc ^ _allOnes;</p>
<p>finalHash[0] = (byte)((finalCRC &gt;&gt; 0) &amp; 0xFF);</p>
<p>finalHash[1] = (byte)((finalCRC &gt;&gt; <img src='http://khason.net/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> &amp; 0xFF);</p>
<p>finalHash[2] = (byte)((finalCRC &gt;&gt; 16) &amp; 0xFF);</p>
<p>finalHash[3] = (byte)((finalCRC &gt;&gt; 24) &amp; 0xFF);</p>
<p>return finalHash;</p>
<p>}</p>
</blockquote>
<p>We done. Have a good time and be good people. Also, I want to thank Boris for helping me with this article. He promised to write here some day…</p>
<p><a href="http://khason.net/images/2009/04/crc-source.zip" target="_blank">Source code for this article</a></p>
<p>Related posts:<ol>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/dev/how-to-calculate-crc-in-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
<enclosure url="http://khason.net/images/2009/04/crc-source.zip" length="" type="" />
		</item>
		<item>
		<title>Making TFS better or what is TITS?</title>
		<link>http://khason.net/tech/making-tfs-better-or-what-is-tits/</link>
		<comments>http://khason.net/tech/making-tfs-better-or-what-is-tits/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 17:42:07 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[TECH]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DEV]]></category>
		<category><![CDATA[My tools]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[soft]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[VSTS]]></category>

		<guid isPermaLink="false">http://khason.net/tech/making-tfs-better-or-what-is-tits/</guid>
		<description><![CDATA[Those days me and my team work very hard toward new version of “The System”. This includes massive refactoring of all solutions, hard work with TFS (which not restricted to only adding files, but also deleting, moving, etc. other words, all stuff, which TFS is not really love). Because of this, we need a bunch [...]<p/>]]></description>
			<content:encoded><![CDATA[<p>Those days me and my team work very hard toward new version of “The System”. This includes massive refactoring of all solutions, hard work with TFS (which not restricted to only adding files, but also deleting, moving, etc. other words, all stuff, which TFS is not really love). Because of this, we need a bunch of handy tools to make our dreams come true and to decrease unnecessary number of clicks inside Team System Explorer and Visual Studio. You do not really think, that we have no tools to make our everyday job easier. We have. However, we never package and release it. Let me introduce “<strong>TITS” – T</strong>ools, <strong>I</strong>nvaluable for <strong>T</strong>eam <strong>S</strong>ystem. This suite I’m planning to release as another open source project within couple of months.</p>
<p><img title="TITS - Tools, Invaluable for Team System" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="498" alt="TITS - Tools, Invaluable for Team System" src="http://khason.net/images/2009/01/image19.png" width="632" border="0" /> </p>
<p>What “TITS” includes? First of all &#8211; </p>
<h3>“QOF” – Quick Open File</h3>
<p><img title="QOF - Quick Open File" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="550" alt="QOF - Quick Open File" src="http://khason.net/images/2009/01/image20.png" width="562" border="0" /> </p>
<p>This tools is absolutely invaluable if you have big solutions. While all it knows to do is to search. But, wait, what’s wrong with build-in search of Visual Studio? First of all, it does not search Solution items and files, are in solution directory, but not in project. Also it cannot fix your typos and errors. Also it does not know to move you quickly to found solution item in Solution Explorer or in Source Editor.</p>
<p>Basic set of QOF features:</p>
<ul>
<li>No mouse &#8211; open any file</li>
<li>No mouse – locate any file in solution explorer</li>
<li>Highlighting found items</li>
<li>Multiple files open</li>
<li>Filter by source files only, resources, owner or any other kind of filters</li>
<li>Search inside TFS, including history, changesets, shelves (either private and public)</li>
<li>…and much much more</li>
</ul>
<p>Next tool is:</p>
<h3>“WIBREW” – Who Is Breaking What</h3>
<p><img title="WIBREW - Who is breaking what" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="181" alt="WIBREW - Who is breaking what" src="http://khason.net/images/2009/01/image21.png" width="372" border="0" /> </p>
<p>Absolutely invaluable tool to know who actually breaking what file inside TFS. For example, I do not want to lock files, while I still want to know who holds what file. TFS provides such feature out-of-the-box, however from command prompt only. You can add it even as macro. Like this:</p>
<p><img title="WIBREW for poor people" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="451" alt="WIBREW for poor people" src="http://khason.net/images/2009/01/image22.png" width="464" border="0" /> </p>
<p>However it not user friendly and impossible for use, ‘cos it looks as following:</p>
<p><img title="WIBREW for poor people in action" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="308" alt="WIBREW for poor people in action" src="http://khason.net/images/2009/01/image23.png" width="387" border="0" /> </p>
<p>You do not know what actually developer doing, where and why. With “WIBREW”, you can know:</p>
<ul>
<li>When developer started to break files</li>
<li>What exactly he’s doing</li>
<li>Is the breaking file locked or now</li>
<li>Where the developer breaks it (workspace and computer name of the user)</li>
<li>…and much much more</li>
</ul>
<p>Another tool is:</p>
<h3>“WITCH” – What I have To Check-in</h3>
<p>If you ever worked with Team Force, you know what this tool is doing. It shows you a preview of all <strong>changed</strong> files, you’ll check-in. For some reason, TFS has no such feature. Let’s imagine, that your work method is to check out everything, change something and check-in only changed files. Until here TFS does everything, however if you want to preview changeset (for example in order to compare with “WIBREW” output), you can not. Here “WITCH” comes to help. </p>
<blockquote><p><em>[Here should be a screenshot of “WITCH”, but it looks exactly the same as “WIBREW” with shameless blurring]</em></p>
</blockquote>
<p>Another invaluable tool is:</p>
<h3>“VOCUS” – VOid CUstom Settings for check in</h3>
<p>This tool is absolutely UI-less. It allows developers to work with their own custom settings in Visual Studio, while for check-in and check-out it format all documents, according predefined custom settings (for example indentation). How many times, you tried to merge files, when all the difference is indentation it tab size? Well, this tool solves this problem.</p>
<p><img title="VOCUS – VOid CUstom Settings for check in" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="329" alt="VOCUS – VOid CUstom Settings for check in" src="http://khason.net/images/2009/01/image24.png" width="633" border="0" /> </p>
<p>It stores custom settings for each user (BTW, it also makes able for each developer to restore his settings fluently in any computer) and reformat documents on check-in action toward corporate settings, when on check-out toward custom developer’s setting.</p>
<h3>“SHMOC” – SHow MOre Code</h3>
<p>This is not actually tool, works with TFS. It rather works with your Visual Studio Development Environment. It’s UI-less as well and makes able to hide and restore all docking windows in VS. It makes you able to write in “Dark Room” mode (which is full screen, distraction free environment) and return to Visual Studio within one button press. It can also change VS color scheme, if required.</p>
<p><img title="“SHMOC” – SHow MOre Code" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="309" alt="“SHMOC” – SHow MOre Code" src="http://khason.net/images/2009/01/image25.png" width="639" border="0" /> </p>
<p>There are some other tools should be inside this suite, however, I still have no names for them <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Also, if you have something interesting, and you want to contribute it to this suite, you’re highly welcome.</p>
<p><em>PS</em>: This blog is about code, but this post is 6th in row without even one line of code, so I have to fix it as soon as possible. Thus, I’ll example how WIBREW works under the hood. Other words, small example of how to work with TFS API from Visual Studio plugin.</p>
<p>First of all, as in any VS plugin, you need to acquire DTE2 application object:</p>
<blockquote><p>_applicationObject = (DTE2)application;     <br />_addInInstance = (AddIn)addInInst;</p>
</blockquote>
<p>When you have it, you need to detect what TFS server you’re working with and what are user credentials for this session. The common problem of WIBREW for poor men, was how to work with this tool over VPN (when your connected session is only inside VS). So each time, you tried to run it, you had to enter your domain credentials – very inconvenience way of work. </p>
<p>In order to prevent it, let’s ask your environment about Team Foundation information:</p>
<blockquote><p>private TeamFoundationServerExt _tfsExt;     <br />…      <br />_tfsExt = (TeamFoundationServerExt)_applicationObject.GetObject(&quot;Microsoft.VisualStudio.TeamFoundation.TeamFoundationServerExt&quot;);</p>
</blockquote>
<p>Also, you can be notified when your work project context was changed. To do this, just subscribe to ProjectContextChanged event and handle it inside:</p>
<blockquote><p>_tfsExt.ProjectContextChanged += OnProjectContextChanged;     <br />…      <br />public void OnProjectContextChanged(object sender, EventArgs e) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (!string.IsNullOrEmpty(_tfsExt.ActiveProjectContext.ProjectName)) {</p>
</blockquote>
<p>Now when we know, that we have out active project context, all we have to do is to ask about changes</p>
<blockquote><p>private VersionControlExt _vcExt;     <br />…      <br />_vcExt = (VersionControlExt)_applicationObject.GetObject(&quot;Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExt&quot;);</p>
</blockquote>
<p>Inside VersionControlExt object you have following self-descriptive properties and methods: FindChangeSet, History, PendingChanges, SolutionWorkspace etc. however it works only with TFS solution explorer. To handle pending changes for the project without tickling TFS, we can use it internal methods. All the difference is with references. To work with Visual Studio TFS explorer methods, you should reference:   <br />Microsoft.VisualStudio.TeamFoundation.dll, Microsoft.VisualStudio.TeamFoundation.Client.dll and Microsoft.VisualStudio.TeamFoundation.VersionControl.dll, while working with TFS API directly, use Microsoft.TeamFoundation.dll, Microsoft.TeamFoundation.Client.dll and Microsoft.TeamFoundation.VersionControl.dll from [PROGRAM FILES]\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\. Just like this:</p>
<blockquote><pre>VersionControlServer _vcs…_vcs = (VersionControlServer)_server.GetService(typeof(VersionControlServer));…var _sets = _vcs.QueryPendingSets( new[] { new ItemSpec(serverPath, RecursionType.Full) }, null, null);…foreach (PendingSet set in sets) {…
//Get everything you need here</pre>
</blockquote>
<p>We done. It’s very easy to work with Team System from inside Visual Studio. Also it’s very easy to build useful tools, not built by Microsoft for some reason <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Have a nice day, be good people and wait for me to beatify sources before releasing as another <a title="Open Source licenses comparison table" href="http://khason.net/blog/open-source-licenses-comparison-table/" target="_blank" rel="dofollow">Open Source</a> application. </p>
<p/>]]></content:encoded>
			<wfw:commentRss>http://khason.net/tech/making-tfs-better-or-what-is-tits/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Nifty time savers for WPF development</title>
		<link>http://khason.net/dev/nifty-time-savers-for-wpf-development/</link>
		<comments>http://khason.net/dev/nifty-time-savers-for-wpf-development/#comments</comments>
		<pubDate>Thu, 08 Jan 2009 18:23:04 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[DEV]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[help]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[soft]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Work process]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://khason.net/dev/nifty-time-savers-for-wpf-development/</guid>
		<description><![CDATA[I just published an article on Code Project, that explains how to use my latest FM USB library for building real world software radio receiver with WPF. There I referenced to some nifty WPF time savers, I’m using for everyday development. So, today I want to share those code pieces with you. Binding time savers [...]
Related posts:<ol>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a target="_blank" href="http://www.codeproject.com/KB/WPF/fmradio.aspx">I just published an article</a> on Code Project, that explains how to use my latest <a target="_blank" href="http://www.codeplex.com/FM">FM USB library</a> for building real world software radio receiver with WPF. There I referenced to some nifty WPF time savers, I’m using for everyday development. So, today I want to share those code pieces with you.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Software radio reciever screenshot" border="0" alt="Software radio reciever screenshot" src="http://khason.net/images/2009/01/radio.jpg" width="500" height="199" /> </p>
<h3>Binding time savers</h3>
<p>Want to use following syntax for set binding in code?</p>
<blockquote><p>Presets.SetBinding(ListBox.ItemsSourceProperty, _device, &quot;Presets&quot;);</p>
</blockquote>
<p>This piece of code sets binding to Preset DependencyObject, which is Listbox and connects ListBox.ItemsSource dependency property with “Presets” property of CLR object _device. How it done? Simple, as usual</p>
<blockquote><p>[DebuggerStepThrough]     <br />public static BindingExpressionBase SetBinding(this DependencyObject target, DependencyProperty dp, object source, string path) {      <br />&#160;&#160; Binding b = new Binding(path);      <br />&#160;&#160; b.Source = source;      <br />&#160;&#160; return BindingOperations.SetBinding(target, dp, b);      <br />}</p>
</blockquote>
<p>But what to do when we need a converter? Simple:</p>
<blockquote><p>[DebuggerStepThrough]     <br />public static BindingExpressionBase SetBinding(this DependencyObject target, DependencyProperty dp, object source, string path, IValueConverter converter) {      <br />&#160;&#160; Binding b = new Binding(path);      <br />&#160;&#160; b.Source = source;      <br />&#160;&#160; b.Converter = converter;      <br />&#160;&#160; return BindingOperations.SetBinding(target, dp, b);      <br />}</p>
</blockquote>
<p>However to use this method, we need to create special object, which implements IValueConverter. Whey not to do it generically? Like this:</p>
<blockquote><p>SignalTransform.SetBinding(ScaleTransform.ScaleYProperty, _device.RDS,&quot;SignalStrength&quot;, new ValueConverter&lt;byte, double&gt;(b =&gt; { return 1-(b / 36d); }));</p>
</blockquote>
<p>But we need this special handy ValueConverter class. What’s the problem? Here come the king:</p>
<blockquote><p>public class ValueConverter&lt;TIN, TOUT&gt; : IValueConverter { </p>
<p>&#160;&#160; public ValueConverter(Func&lt;TIN, TOUT&gt; forwardConversion) {     <br />&#160;&#160;&#160;&#160;&#160; ForwardConversion = forwardConversion;      <br />&#160;&#160; } </p>
<p>&#160;&#160; public ValueConverter(Func&lt;TIN, TOUT&gt; forwardConversion, Func&lt;TOUT, TIN&gt; reverseConversion) {     <br />&#160;&#160;&#160;&#160;&#160; ForwardConversion = forwardConversion;      <br />&#160;&#160;&#160;&#160;&#160; ReverseConversion = reverseConversion;      <br />&#160;&#160; } </p>
<p>&#160;&#160; public Func&lt;TIN, TOUT&gt; ForwardConversion { get; set; } </p>
<p>&#160;&#160; public Func&lt;TOUT, TIN&gt; ReverseConversion { get; set; }     <br />&#160;&#160; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {      <br />&#160;&#160;&#160;&#160;&#160; try {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var in1 = Object.ReferenceEquals(value, DependencyProperty.UnsetValue) ? default(TIN) : (TIN)value;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return ForwardConversion(in1);      <br />&#160;&#160;&#160;&#160;&#160; } catch {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return Binding.DoNothing;      <br />&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160; } </p>
<p>&#160;&#160; public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {     <br />&#160;&#160;&#160;&#160;&#160; try {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var out1 = Object.ReferenceEquals(value, DependencyProperty.UnsetValue) ? default(TOUT) : (TOUT)value;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return ReverseConversion(out1);      <br />&#160;&#160;&#160;&#160;&#160; } catch {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return Binding.DoNothing;      <br />&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160; } </p>
<p>}</p>
</blockquote>
<p>Isn’t it really simple? But what to do with ugly App.Current.Dispatcher.BeginInvoke((SendOrPostCallback)delegate(object o)…? Use dispatcher time savers. </p>
<h3>Dispatcher time savers</h3>
<p>Don’t you ever want to do this in order to make context switching between UI thread and other application thread in WPF?</p>
<blockquote><p>this.Dispatch(() =&gt; {… DO SOMETHING IN UI THREAD …};</p>
</blockquote>
<p>Now you can (with default and preset DispatcherPriority:</p>
<blockquote><p>public static DispatcherOperation Dispatch(this DispatcherObject sender, Action callback) { return sender.Dispatch(DispatcherPriority.Normal, callback); } </p>
<p>public static DispatcherOperation Dispatch(this DispatcherObject sender,&#160; DispatcherPriority priority, Action callback) {     <br />&#160;&#160; if (sender.Dispatcher == null) return null;      <br />&#160;&#160; if (sender.Dispatcher.CheckAccess()) {      <br />&#160;&#160;&#160;&#160;&#160; callback();      <br />&#160;&#160;&#160;&#160;&#160; return null;      <br />&#160;&#160; } else {      <br />&#160;&#160;&#160;&#160;&#160; return sender.Dispatcher.BeginInvoke(priority, callback);      <br />&#160;&#160; }      <br />}</p>
</blockquote>
<p>Nice, isn’t it? But what to do if we do not want to set binding, but we do want to be notified about property change of dependency objects? </p>
<h3>Bindingless handlers time saver</h3>
<p>Let’s assume, that we have “Tune” UIelement, which has Angle property, but not exposes PropertyChanged event (like it done with <a target="_blank" href="http://blogs.msdn.com/expression/archive/2007/10/13/rotary-custom-control.aspx">Rotary custom control by Expression Blend team</a>… Designers, you know… <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>However I want to be able to add handler for Angle dependency property changed event and do something when it changed. Like this:</p>
<blockquote><p>Tune.AddValueChanged(RotaryControl.RotaryControl.AngleProperty, (s, ex) =&gt; {     <br />&#160;&#160; _device.Tune(Tune.Angle &gt; _prevTune);      <br />&#160;&#160; _prevTune = Tune.Angle;      <br />});</p>
</blockquote>
<p>Here comes our time saver for this purpose:</p>
<blockquote><p>public static void AddValueChanged(this DependencyObject sender, DependencyProperty property, EventHandler handler) {     <br />&#160;&#160; DependencyPropertyDescriptor.FromProperty(property, sender.GetType()).AddValueChanged(sender, handler);      <br />}</p>
</blockquote>
<p>But if we add handler we should be able to remove it too.</p>
<blockquote><p>public static void RemoveValueChanged(this DependencyObject sender, DependencyProperty property, EventHandler handler) {     <br />&#160;&#160; DependencyPropertyDescriptor.FromProperty(property, sender.GetType()).RemoveValueChanged(sender, handler);      <br />}</p>
</blockquote>
<p>Now we done with some of my nifty helpers. And last, but not the least: </p>
<h3>All times question: how to scale ranges</h3>
<p>Here is how <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<blockquote><p>public static double ToRange(this double value, double minSource, double maxSource, double minTarget, double maxTarget) {     <br />&#160;&#160; var sr = maxSource &#8211; minSource;      <br />&#160;&#160; var tr = maxTarget &#8211; minTarget;      <br />&#160;&#160; var ratio = sr / tr;      <br />&#160;&#160; return minTarget+(value / ratio);      <br />}</p>
</blockquote>
<p>Now we can connect them and get something like this:</p>
<blockquote><p>Volume.AddValueChanged(RotaryControl.RotaryControl.AngleProperty, (s, ex) =&gt; {     <br />&#160;&#160; DirectSoundMethods.Volume = (int)Volume.Angle.ToRange(Volume.CounterClockwiseMostAngle, Volume.ClockwiseMostAngle, -4000, 0);      <br />});</p>
</blockquote>
<p>Isn’t it brilliant? </p>
<p>Have a good day and <a target="_blank" href="http://www.codeproject.com/KB/WPF/fmradio.aspx">be sure to read and rate my last article on Code Project</a> <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Be good people.</p>
<p>Related posts:<ol>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/dev/nifty-time-savers-for-wpf-development/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Source code for Silverlight 2 controls</title>
		<link>http://khason.net/tech/source-code-for-silverlight-2-controls/</link>
		<comments>http://khason.net/tech/source-code-for-silverlight-2-controls/#comments</comments>
		<pubDate>Thu, 08 Jan 2009 07:48:07 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[TECH]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[soft]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://khason.net/tech/source-code-for-silverlight-2-controls/</guid>
		<description><![CDATA[Too much exciting news today. Shortly after announced about Windows 7 beta download, I found, that Joe Stegman, Seema Ramchandani, Andre Michaud, Jon Sheller and other guys from Silverlight team released the source code of managed Silverlight controls, included in System.Windows.dll, System.Windows.Controls.dll, and System.Windows.Controls.Data.dll. Get it, you have a lot of thing to learn from [...]<p/>]]></description>
			<content:encoded><![CDATA[<p>Too much exciting news today. Shortly after <a target="_blank" href="http://khason.net/itpro/windows-7-beta-is-available-for-download/">announced about Windows 7 beta download</a>, I found, that <a target="_blank" href="http://blogs.msdn.com/jstegman/archive/2009/01/07/source-code-for-silverlight-2-runtime-and-sdk-controls-published.aspx">Joe Stegman</a>, <a target="_blank" href="http://blogs.msdn.com/seema/archive/2009/01/07/published-the-control-source-code-for-silverlight-2-runtime-sdk.aspx">Seema Ramchandani</a>, Andre Michaud, Jon Sheller and other guys from Silverlight team <a target="_blank" href="http://www.microsoft.com/downloads/details.aspx?FamilyID=EB83ED4C-AC85-4DE9-8395-285628EE2254&amp;displaylang=en">released the source code of managed Silverlight controls</a>, included in System.Windows.dll, System.Windows.Controls.dll, and System.Windows.Controls.Data.dll. Get it, you have a lot of thing to learn from this package.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://khason.net/images/2009/01/image3.png" width="259" height="502" /> </p>
<p><a target="_blank" href="http://www.microsoft.com/downloads/details.aspx?FamilyID=EB83ED4C-AC85-4DE9-8395-285628EE2254&amp;displaylang=en"><strong>Download Silverlight 2.0 controls source code &gt;&gt;</strong></a></p>
<p/>]]></content:encoded>
			<wfw:commentRss>http://khason.net/tech/source-code-for-silverlight-2-controls/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Audio CD operation including CD-Text reading in pure C#</title>
		<link>http://khason.net/dev/audio-cd-operation-including-cd-text-reading-in-pure-c/</link>
		<comments>http://khason.net/dev/audio-cd-operation-including-cd-text-reading-in-pure-c/#comments</comments>
		<pubDate>Wed, 07 Jan 2009 18:46:26 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[DEV]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Interop]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Work process]]></category>

		<guid isPermaLink="false">http://khason.net/dev/audio-cd-operation-including-cd-text-reading-in-pure-c/</guid>
		<description><![CDATA[Recently we spoke about reading radio data in C#, however as in any vehicle we have also CD players. So what can be better, than to have an ability to play CDs while being notified about track name, gathered from CD-Text? So, let’s start. First of all, I want to express my pain with MSDN [...]
Related posts:<ol>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Recently we spoke about <a target="_blank" href="http://khason.net/dev/usb-fm-radio-library-was-published-on-codeplex/">reading radio data in C#</a>, however as in any vehicle we have also CD players. So what can be better, than to have an ability to play CDs while being notified about track name, gathered from <a target="_blank" href="http://en.wikipedia.org/wiki/CD-Text">CD-Text</a>?</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://khason.net/images/2009/01/image1.png" width="240" height="198" /> </p>
<p>So, let’s start. First of all, I want to express my pain with MSDN documentation <a target="_blank" href="http://msdn.microsoft.com/en-us/library/ms808417.aspx">about CD-ROM structure</a>. Documentation team, please, please, please update it. First of all it is no accurate, then there are a ton of things missing. However, “À la guerre comme à la guerre”, thus I invested three days in deep DDK research.</p>
<p>Before we can do anything with CD-ROM, we have to find it. I took the same approach as <a target="_blank" href="http://khason.net/blog/read-and-use-fm-radio-or-any-other-usb-hid-device-from-c/">I used for HID devices</a>. Let’s create a device</p>
<blockquote><p>[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]     <br />[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]      <br />public class CDDADevice : SafeHandleZeroOrMinusOneIsInvalid, IDisposable, INotifyPropertyChanged {</p>
</blockquote>
<p>Internal constructor for security reasons</p>
<blockquote><p>[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]     <br />internal CDDADevice(char drive) : base(true) {       <br />&#160;&#160; findDevice(drive);      <br />}</p>
</blockquote>
<p>And a find method itself</p>
<blockquote><p>[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]     <br />private void findDevice(char drive) {      <br />&#160;&#160; if (Drive == drive) return;      <br />&#160;&#160; if (Native.GetDriveType(string.Concat(drive, &quot;:\&quot;)) == Native.DRIVE.CDROM) {      <br />&#160;&#160;&#160;&#160;&#160; this.handle = Native.CreateFile(string.Concat(&quot;\\.\&quot;, drive, &#8216;:&#8217;), Native.GENERIC_READ, Native.FILE_SHARE_READ, IntPtr.Zero, Native.OPEN_EXISTING, Native.FILE_ATTRIBUTE_READONLY | Native.FILE_FLAG_SEQUENTIAL_SCAN, IntPtr.Zero);      <br />&#160;&#160;&#160;&#160;&#160; if (this.handle.ToInt32() != -1 &amp;&amp; this.handle.ToInt32() != 0) this.Drive = drive;      <br />&#160;&#160; }      <br />}</p>
</blockquote>
<p>Where GetDriveType and CreateFile are win32 methods with following signatures</p>
<blockquote><p>[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]     <br />[DllImport(&quot;kernel32.dll&quot;, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]      <br />internal static extern DRIVE GetDriveType(string drive);      <br />[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]      <br />[DllImport(&quot;kernel32.dll&quot;, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]      <br />internal static extern IntPtr CreateFile(      <br />&#160;&#160;&#160;&#160;&#160; string lpFileName,      <br />&#160;&#160;&#160;&#160;&#160; uint dwDesiredAccess,      <br />&#160;&#160;&#160;&#160;&#160; uint dwShareMode,      <br />&#160;&#160;&#160;&#160;&#160; IntPtr SecurityAttributes,      <br />&#160;&#160;&#160;&#160;&#160; uint dwCreationDisposition,      <br />&#160;&#160;&#160;&#160;&#160; uint dwFlagsAndAttributes,      <br />&#160;&#160;&#160;&#160;&#160; IntPtr hTemplateFile);      <br />[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]      <br />[DllImport(&quot;kernel32.dll&quot;, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]      <br />internal static extern bool CloseHandle(IntPtr hHandle);</p>
</blockquote>
<p>Also, we need some constants</p>
<blockquote><p>internal enum DRIVE : byte {     <br />&#160;&#160; UNKNOWN = 0,      <br />&#160;&#160; NO_ROOT_DIR,      <br />&#160;&#160; REMOVABLE,      <br />&#160;&#160; FIXED,      <br />&#160;&#160; REMOTE,      <br />&#160;&#160; CDROM,      <br />&#160;&#160; RAMDISK      <br />}</p>
<p>internal const uint GENERIC_READ = 0&#215;80000000;     <br />internal const uint FILE_SHARE_READ = 0&#215;00000001;      <br />internal const uint OPEN_EXISTING = 3;      <br />internal const uint FILE_ATTRIBUTE_READONLY = 0&#215;00000001;      <br />internal const uint FILE_FLAG_SEQUENTIAL_SCAN = 0&#215;08000000;</p>
</blockquote>
<p>Now, when we have our cdrom handle in hands, we can read it’s Table Of Content. Now, thing become harder because of the fact, that we have to use very complicated platform method:</p>
<blockquote><p>[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]     <br />[DllImport(&quot;kernel32.dll&quot;, EntryPoint = &quot;DeviceIoControl&quot;, SetLastError=true)]      <br />[return: MarshalAs(UnmanagedType.Bool)]      <br />internal static extern bool DeviceIoControl(      <br />&#160;&#160; [In] IntPtr hDevice,      <br />&#160;&#160; IOCTL dwIoControl,       <br />&#160;&#160; [In] IntPtr lpInBuffer,       <br />&#160;&#160; uint nInBufferSize,       <br />&#160;&#160; IntPtr lpOutBuffer,       <br />&#160;&#160; uint nOutBufferSize,       <br />&#160;&#160; out uint lpBytesReturned,       <br />&#160;&#160; IntPtr lpOverlapped);</p>
</blockquote>
<p>When thing are generic it’s good, however this one is, probably, most generic method in Win32 API. You can do anything with this method and you never know what to expect in lpOutBuffer <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>However, as I told earlier, I invested three days in investigations and researches (tnx to DDK documentation team) and now things become to be clearer. We need to get CDROM_TOC. It done by invoking IOCTL_CDROM_READ_TOC call</p>
<blockquote><p>uint bytesRead = 0;     <br />TOC = new Native.CDROM_TOC();      <br />TOC.Length = (ushort)Marshal.SizeOf(TOC);      <br />var hTOC = Marshal.AllocHGlobal(TOC.Length);      <br />Marshal.StructureToPtr(TOC, hTOC, true);      <br />if (Native.DeviceIoControl(this.handle, Native.IOCTL.CDROM_READ_TOC, IntPtr.Zero, 0, hTOC, TOC.Length, out bytesRead, IntPtr.Zero)) Marshal.PtrToStructure(hTOC, TOC);      <br />Marshal.FreeHGlobal(hTOC);</p>
</blockquote>
<p>But, not too fast. CDROM_TOC contains array of TRACK_DATA with unknown size.</p>
<blockquote><pre>typedef struct _CDROM_TOC {&#160; UCHAR&#160; Length[2];&#160; UCHAR&#160; FirstTrack;&#160; UCHAR&#160; LastTrack;&#160; TRACK_DATA&#160; TrackData[MAXIMUM_NUMBER_TRACKS];} CDROM_TOC, *PCDROM_TOC;</pre>
<pre>typedef struct _TRACK_DATA {&#160; UCHAR&#160; Reserved;&#160; UCHAR&#160; Control : 4;&#160; UCHAR&#160; Adr : 4;&#160; UCHAR&#160; TrackNumber;&#160; UCHAR&#160; Reserved1;&#160; UCHAR&#160; Address[4];} TRACK_DATA, *PTRACK_DATA;</pre>
</blockquote>
<p><a target="_blank" href="http://khason.net/blog/pinvoke-cheat-sheet/">P/Invoke</a> it! But how to marshal unknown array? We should create wrapper object. Also there is very fun BitVector, used in this structure! What’s the problem? Pin it with some Math!</p>
<blockquote>
<p>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]<br />
    <br />public class CDROM_TOC {</p>
<p>&#160;&#160; public ushort Length;</p>
<p>&#160;&#160; public byte FirstTrack;</p>
<p>&#160;&#160; public byte LastTrack;</p>
<p>&#160;&#160; public TRACK_DATA_ARRAY TrackData;</p>
<p>}</p>
<p>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]<br />
    <br />public struct TRACK_DATA {</p>
<p>&#160;&#160; public byte Reserved;</p>
<p>&#160;&#160; public byte bitVector;</p>
<p>&#160;&#160; public byte Control {</p>
<p>&#160;&#160;&#160;&#160;&#160; get { return ((byte)((this.bitVector &amp; 15u))); }</p>
<p>&#160;&#160;&#160;&#160;&#160; set { this.bitVector = ((byte)((value | this.bitVector))); }</p>
<p>&#160;&#160; }</p>
<p>&#160;&#160; public byte Adr {</p>
<p>&#160;&#160;&#160;&#160;&#160; get { return ((byte)(((this.bitVector &amp; 240u) / 16))); }</p>
<p>&#160;&#160;&#160;&#160;&#160; set { this.bitVector = ((byte)(((value * 16) | this.bitVector))); }</p>
<p>&#160;&#160; }</p>
<p>&#160;&#160; public byte TrackNumber;</p>
<p>&#160;&#160; public byte Reserved1;</p>
<p>&#160;&#160; public uint Address;</p>
<p>}</p>
<p>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]<br />
    <br />internal sealed class TRACK_DATA_ARRAY {</p>
<p>&#160;&#160; internal TRACK_DATA_ARRAY() { data = new byte[MAXIMUM_NUMBER_TRACKS * Marshal.SizeOf(typeof(TRACK_DATA))]; } </p>
<p>&#160;&#160; [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAXIMUM_NUMBER_TRACKS * 8)]<br />
    <br />&#160;&#160; private byte[] data;</p>
<p>&#160;&#160; public TRACK_DATA this[int idx] {</p>
<p>&#160;&#160;&#160;&#160;&#160; get {</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if ((idx &lt; 0) | (idx &gt;= MAXIMUM_NUMBER_TRACKS)) throw new IndexOutOfRangeException();</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; TRACK_DATA res;</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var hData = GCHandle.Alloc(data, GCHandleType.Pinned);</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; try {</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var buffer = hData.AddrOfPinnedObject();</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; buffer = (IntPtr)(buffer.ToInt32() + (idx * Marshal.SizeOf(typeof(TRACK_DATA))));</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; res = (TRACK_DATA)Marshal.PtrToStructure(buffer, typeof(TRACK_DATA));</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; } finally {</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; hData.Free();</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return res;</p>
<p>&#160;&#160;&#160;&#160;&#160; }</p>
<p>&#160;&#160; }</p>
<p>}</p>
</blockquote>
<p>Fuf, done. The code is rather self explaining, we just “tell” marshaler, that we have byte array, while calculating pointers to pinned object to get actual value and marshal it back. So, now we have TOC. So, we know how many tracks we have and addresses to data chunks inside the CD. </p>
<p>But it now enough to understand where our tracks. <a target="_blank" href="http://en.wikipedia.org/wiki/CD-ROM">CD-ROM</a> structure is very tricky. There we have blocks or sectors (which is the smallest chunks of data), so we have to convert bytes into sector addresses. Each block is 2352 bytes in RAW mode, while address value inside TRACK_DATA points us to layout address with is sync, sector id, error detection etc… So, in order to convert TRACK object into actual track number on disk, we have to stick to following method</p>
<blockquote>
<p>public static int SectorAddress(this TRACK_DATA data) {<br />
    <br />&#160;&#160; var addr = BitConverter.GetBytes(data.Address);</p>
<p>&#160;&#160; return (addr[1] * 60 * 75 + addr[2] * 75 + addr[3]) &#8211; 150;</p>
<p>}</p>
</blockquote>
<p>Now, when we know numbers of tracks, we also know start and end sector, disk type and other useful information we are ready to twist it a bit and read CD-Text (if there are and your CD reader supports it).</p>
<p>So, coming back to our favorite method DeviceIoControl, but this time with IOCTL_CDROM_READ_TOC_EX control. </p>
<blockquote>
<p>bytesRead = 0;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <br />TOCex = new Native.CDROM_READ_TOC_EX {</p>
<p>&#160;&#160; Format = Native.CDROM_READ_TOC_EX_FORMAT.CDTEXT</p>
<p>};</p>
<p>var sTOCex = Marshal.SizeOf(TOCex);</p>
<p>var hTOCex = Marshal.AllocHGlobal(sTOCex);</p>
<p>Marshal.StructureToPtr(TOCex, hTOCex, true); </p>
<p>var Data = new Native.CDROM_TOC_CD_TEXT_DATA();<br />
    <br />Data.Length = (ushort)Marshal.SizeOf(Data);</p>
<p>var hData = Marshal.AllocHGlobal(Data.Length);</p>
<p>Marshal.StructureToPtr(Data, hData, true);</p>
<p>if (Native.DeviceIoControl(this.handle, Native.IOCTL.CDROM_READ_TOC_EX, hTOCex, (ushort)sTOCex, hData, Data.Length, out bytesRead, IntPtr.Zero)) Marshal.PtrToStructure(hData, Data);</p>
<p>Marshal.FreeHGlobal(hData);</p>
<p>Marshal.FreeHGlobal(hTOCex);</p>
</blockquote>
<p>Looks too simple? Let’s see inside CDROM_READ_TOC_EX structure. It is very similar to _CDROM_TOC.</p>
<blockquote>
<pre>typedef struct _CDROM_READ_TOC_EX {&#160; UCHAR Format : 4;&#160; UCHAR Reserved1 : 3; &#160; UCHAR Msf : 1;&#160; UCHAR SessionTrack;&#160; UCHAR Reserved2;&#160; UCHAR Reserved3;} CDROM_READ_TOC_EX, *PCDROM_READ_TOC_EX;</pre>
</blockquote>
<p>Simple. Isn’t it?</p>
<blockquote>
<p>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]<br />
    <br />public struct CDROM_READ_TOC_EX {</p>
<p>&#160;&#160; public uint bitVector;</p>
<p>&#160;&#160; public CDROM_READ_TOC_EX_FORMAT Format {</p>
<p>&#160;&#160;&#160;&#160;&#160; get { return ((CDROM_READ_TOC_EX_FORMAT)((this.bitVector &amp; 15u))); }</p>
<p>&#160;&#160;&#160;&#160;&#160; set { this.bitVector = (uint)((byte)value | this.bitVector); }</p>
<p>&#160;&#160; } </p>
<p>&#160;&#160; public uint Reserved1 {<br />
    <br />&#160;&#160;&#160;&#160;&#160; get { return ((uint)(((this.bitVector &amp; 112u) / 16))); }</p>
<p>&#160;&#160;&#160;&#160;&#160; set { this.bitVector = ((uint)(((value * 16) | this.bitVector))); }</p>
<p>&#160;&#160; } </p>
<p>&#160;&#160; public uint Msf {<br />
    <br />&#160;&#160;&#160;&#160;&#160; get { return ((uint)(((this.bitVector &amp; 128u) / 128))); }</p>
<p>&#160;&#160;&#160;&#160;&#160; set { this.bitVector = ((uint)(((value * 128) | this.bitVector))); }</p>
<p>&#160;&#160; }</p>
<p>&#160;&#160; public byte SessionTrack;</p>
<p>&#160;&#160; public byte Reserved2;</p>
<p>&#160;&#160; public byte Reserved3;</p>
<p>}</p>
</blockquote>
<p>But what will come inside lpOutBuffer? Fellow structure, named CDROM_TOC_CD_TEXT_DATA with unknown size array of CDROM_TOC_CD_TEXT_DATA_BLOCK</p>
<blockquote>
<pre>typedef struct _CDROM_TOC_CD_TEXT_DATA {&#160; UCHAR&#160; Length[2];&#160; UCHAR&#160; Reserved1;&#160; UCHAR&#160; Reserved2;&#160; CDROM_TOC_CD_TEXT_DATA_BLOCK&#160; Descriptors[0];} CDROM_TOC_CD_TEXT_DATA, *PCDROM_TOC_CD_TEXT_DATA;</pre>
<pre>typedef struct _CDROM_TOC_CD_TEXT_DATA_BLOCK {&#160; UCHAR&#160; PackType;&#160; UCHAR&#160; TrackNumber:7;&#160; UCHAR&#160; ExtensionFlag:1;&#160; UCHAR&#160; SequenceNumber;&#160; UCHAR&#160; CharacterPosition:4;&#160; UCHAR&#160; BlockNumber:3;&#160; UCHAR&#160; Unicode:1;&#160; union {&#160;&#160;&#160; UCHAR&#160; Text[12];&#160;&#160;&#160; WCHAR&#160; WText[6];&#160; };&#160; UCHAR&#160; CRC[2];} CDROM_TOC_CD_TEXT_DATA_BLOCK, *PCDROM_TOC_CD_TEXT_DATA_BLOCK;</pre>
</blockquote>
<p>Too bad to be true. Isn’t it? Let’s try to marshal it my hands (with the trick used for TRACK_DATA</p>
<blockquote>
<p>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]<br />
    <br />public class CDROM_TOC_CD_TEXT_DATA {</p>
<p>&#160;&#160; public ushort Length;</p>
<p>&#160;&#160; public byte Reserved1;</p>
<p>&#160;&#160; public byte Reserved2;</p>
<p>&#160;&#160; public CDROM_TOC_CD_TEXT_DATA_BLOCK_ARRAY Descriptors;</p>
<p>} </p>
<p>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]<br />
    <br />internal sealed class CDROM_TOC_CD_TEXT_DATA_BLOCK_ARRAY {</p>
<p>&#160;&#160; internal CDROM_TOC_CD_TEXT_DATA_BLOCK_ARRAY() { data = new byte[MINIMUM_CDROM_READ_TOC_EX_SIZE * MAXIMUM_NUMBER_TRACKS * Marshal.SizeOf(typeof(CDROM_TOC_CD_TEXT_DATA_BLOCK))]; } </p>
<p>&#160;&#160; [MarshalAs(UnmanagedType.ByValArray, SizeConst = MINIMUM_CDROM_READ_TOC_EX_SIZE * MAXIMUM_NUMBER_TRACKS * 18)]<br />
    <br />&#160;&#160; private byte[] data;</p>
<p>&#160;&#160; public CDROM_TOC_CD_TEXT_DATA_BLOCK this[int idx] {</p>
<p>&#160;&#160;&#160;&#160;&#160; get {</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if ((idx &lt; 0) | (idx &gt;= MINIMUM_CDROM_READ_TOC_EX_SIZE * MAXIMUM_NUMBER_TRACKS)) throw new IndexOutOfRangeException();</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; CDROM_TOC_CD_TEXT_DATA_BLOCK res;</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var hData = GCHandle.Alloc(data, GCHandleType.Pinned);</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; try {</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var buffer = hData.AddrOfPinnedObject();</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; buffer = (IntPtr)(buffer.ToInt32() + (idx * Marshal.SizeOf(typeof(CDROM_TOC_CD_TEXT_DATA_BLOCK))));</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; res = (CDROM_TOC_CD_TEXT_DATA_BLOCK)Marshal.PtrToStructure(buffer, typeof(CDROM_TOC_CD_TEXT_DATA_BLOCK));</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; } finally {</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; hData.Free();</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return res;</p>
<p>&#160;&#160;&#160;&#160;&#160; }</p>
<p>&#160;&#160; }</p>
<p>} </p>
<p>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]<br />
    <br />public struct CDROM_TOC_CD_TEXT_DATA_BLOCK {</p>
<p>&#160;&#160; public CDROM_CD_TEXT_PACK PackType;</p>
<p>&#160;&#160; public byte bitVector1;</p>
<p>&#160;&#160; public byte TrackNumber {</p>
<p>&#160;&#160;&#160;&#160;&#160; get { return ((byte)((this.bitVector1 &amp; 127u))); }</p>
<p>&#160;&#160;&#160;&#160;&#160; set { this.bitVector1 = ((byte)((value | this.bitVector1))); }</p>
<p>&#160;&#160; } </p>
<p>&#160;&#160; public byte ExtensionFlag {<br />
    <br />&#160;&#160;&#160;&#160;&#160; get { return ((byte)(((this.bitVector1 &amp; 128u) / 128))); }</p>
<p>&#160;&#160;&#160;&#160;&#160; set { this.bitVector1 = ((byte)(((value * 128) | this.bitVector1))); }</p>
<p>&#160;&#160; } </p>
<p>&#160;&#160; public byte SequenceNumber;<br />
    <br />&#160;&#160; public byte bitVector2;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </p>
<p>&#160;&#160; public byte CharacterPosition {<br />
    <br />&#160;&#160;&#160;&#160;&#160; get { return ((byte)((this.bitVector2 &amp; 15u))); }</p>
<p>&#160;&#160;&#160;&#160;&#160; set { this.bitVector2 = ((byte)((value | this.bitVector2))); }</p>
<p>&#160;&#160; } </p>
<p>&#160;&#160; public byte BlockNumber {<br />
    <br />&#160;&#160;&#160;&#160;&#160; get { return ((byte)(((this.bitVector2 &amp; 112u) / 16))); }</p>
<p>&#160;&#160;&#160;&#160;&#160; set { this.bitVector2 = ((byte)(((value * 16) | this.bitVector2))); }</p>
<p>&#160;&#160; } </p>
<p>&#160;&#160; public byte Unicode {<br />
    <br />&#160;&#160;&#160;&#160;&#160; get { return ((byte)(((this.bitVector2 &amp; 128u) / 128))); }</p>
<p>&#160;&#160;&#160;&#160;&#160; set { this.bitVector2 = ((byte)(((value * 128) | this.bitVector2))); }</p>
<p>&#160;&#160; }</p>
<p>&#160;&#160; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12, ArraySubType = UnmanagedType.I1)]</p>
<p>&#160;&#160; public byte[] TextBuffer; </p>
<p>&#160;&#160; public string Text {<br />
    <br />&#160;&#160;&#160;&#160;&#160; get { return (Unicode == 1) ? ASCIIEncoding.ASCII.GetString(TextBuffer) : UTF32Encoding.UTF8.GetString(TextBuffer); }</p>
<p>&#160;&#160; } </p>
<p>&#160;&#160; public ushort CRC;<br />
    <br />}</p>
</blockquote>
<p>Can’t you see a small problem here? Yes, we do not know the actual/maximum size of CDROM_TOC_CD_TEXT_DATA_BLOCK array. Until, I’ll find a nice way to marshal smart pointers, we’ll stick to MAX_TRACKS (100) * MIN_DATA_BLOCK (2).</p>
<p>We almost finished and the worst things are behind us. Now you should enumerate thru CDROM_TOC_CD_TEXT_DATA_BLOCK and look for Text, TrackNumber and SequenceNumber (which is continuation of text reported). For example, slot for ALBUM_NAME “Satisfaction” will looks as following </p>
<table border="0" cellspacing="0" cellpadding="2" width="200">
<tbody>
<tr>
<td valign="top" width="100">BlockNumber</td>
<td valign="top" width="100">0&#215;00</td>
</tr>
<tr>
<td valign="top" width="100">CharacterPosition</td>
<td valign="top" width="100">0&#215;00</td>
</tr>
<tr>
<td valign="top" width="100">CRC</td>
<td valign="top" width="100">0x3EAB</td>
</tr>
<tr>
<td valign="top" width="100">SequenceNumber</td>
<td valign="top" width="100">0&#215;00</td>
</tr>
<tr>
<td valign="top" width="100">Text</td>
<td valign="top" width="100"> SATISFACTIO</td>
</tr>
</tbody>
</table>
<table border="0" cellspacing="0" cellpadding="2" width="219">
<tbody>
<tr>
<td valign="top" width="100">BlockNumber</td>
<td valign="top" width="117">0&#215;00</td>
</tr>
<tr>
<td valign="top" width="100">CharacterPosition</td>
<td valign="top" width="117">0x0B</td>
</tr>
<tr>
<td valign="top" width="100">CRC</td>
<td valign="top" width="117">0&#215;0564</td>
</tr>
<tr>
<td valign="top" width="100">SequenceNumber</td>
<td valign="top" width="117">0&#215;01</td>
</tr>
<tr>
<td valign="top" width="100">Text</td>
<td valign="top" width="117">N </td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<p>And so on… What to do with all other data and how to use it to enhance listening (ripping/crunching/seeking) experience we’ll speak next time. Have a good day and be good people.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:eeb67b17-3e9f-4256-8b73-87096ef1d693" class="wlWriterEditableSmartContent">
<div><object width="425" height="355"><param name="movie" value="http://www.youtube.com/v/Y7T49_LPt-8&amp;hl=en"></param><embed src="http://www.youtube.com/v/Y7T49_LPt-8&amp;hl=en" type="application/x-shockwave-flash" width="425" height="355"></embed></object></div>
</div>
<p>Related posts:<ol>
<li><a href='http://khason.net/dev/video-encoder-and-metadata-reading-by-using-windows-media-foundation/' rel='bookmark' title='Video encoder and metadata reading by using Windows Media Foundation'>Video encoder and metadata reading by using Windows Media Foundation</a></li>
<li><a href='http://khason.net/dev/rsa-private-key-import-from-pem-format-in-c/' rel='bookmark' title='RSA private key import from PEM format in C#'>RSA private key import from PEM format in C#</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/dev/audio-cd-operation-including-cd-text-reading-in-pure-c/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

