<?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>Sun, 08 Nov 2009 18:24:29 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>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/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code/' rel='bookmark' title='Permanent Link: INotifyPropertyChanged auto wiring or how to get rid of redundant code'>INotifyPropertyChanged auto wiring or how to get rid of redundant code</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/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code/' rel='bookmark' title='Permanent Link: INotifyPropertyChanged auto wiring or how to get rid of redundant code'>INotifyPropertyChanged auto wiring or how to get rid of redundant code</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/dev/read-singleton-approach-in-wpf-application/feed/</wfw:commentRss>
		<slash:comments>4</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/read-singleton-approach-in-wpf-application/' rel='bookmark' title='Permanent Link: Real singleton approach in WPF application'>Real singleton approach in WPF application</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/read-singleton-approach-in-wpf-application/' rel='bookmark' title='Permanent Link: Real singleton approach in WPF application'>Real singleton approach in WPF application</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/read-singleton-approach-in-wpf-application/' rel='bookmark' title='Permanent Link: Real singleton approach in WPF application'>Real singleton approach in WPF application</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 0&#215;04C11DB7 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/read-singleton-approach-in-wpf-application/' rel='bookmark' title='Permanent Link: Real singleton approach in WPF application'>Real singleton approach in WPF application</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/dev/how-to-calculate-crc-in-c/feed/</wfw:commentRss>
		<slash:comments>1</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 [...]


Related posts:<ol><li><a href='http://khason.net/itpro/tfs-licensing-model-demystification-or-what-should-i-buy-for-my-company-in-order-not-to-step-on-the-licensing-mine/' rel='bookmark' title='Permanent Link: TFS licensing model demystification or what should I buy for my company in order not to step on the licensing mine?'>TFS licensing model demystification or what should I buy for my company in order not to step on the licensing mine?</a></li>
<li><a href='http://khason.net/tech/zone-of-pain-vs-zone-of-uselessness-or-code-analysis-with-ndepend/' rel='bookmark' title='Permanent Link: &ldquo;Zone of Pain vs. Zone of Uselessness&rdquo; or code analysis with NDepend'>&ldquo;Zone of Pain vs. Zone of Uselessness&rdquo; or code analysis with NDepend</a></li>
</ol>]]></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>Related posts:<ol><li><a href='http://khason.net/itpro/tfs-licensing-model-demystification-or-what-should-i-buy-for-my-company-in-order-not-to-step-on-the-licensing-mine/' rel='bookmark' title='Permanent Link: TFS licensing model demystification or what should I buy for my company in order not to step on the licensing mine?'>TFS licensing model demystification or what should I buy for my company in order not to step on the licensing mine?</a></li>
<li><a href='http://khason.net/tech/zone-of-pain-vs-zone-of-uselessness-or-code-analysis-with-ndepend/' rel='bookmark' title='Permanent Link: &ldquo;Zone of Pain vs. Zone of Uselessness&rdquo; or code analysis with NDepend'>&ldquo;Zone of Pain vs. Zone of Uselessness&rdquo; or code analysis with NDepend</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/tech/making-tfs-better-or-what-is-tits/feed/</wfw:commentRss>
		<slash:comments>9</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
Want [...]


Related posts:<ol><li><a href='http://khason.net/dev/read-singleton-approach-in-wpf-application/' rel='bookmark' title='Permanent Link: Real singleton approach in WPF application'>Real singleton approach in WPF application</a></li>
<li><a href='http://khason.net/dev/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code/' rel='bookmark' title='Permanent Link: INotifyPropertyChanged auto wiring or how to get rid of redundant code'>INotifyPropertyChanged auto wiring or how to get rid of redundant code</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/read-singleton-approach-in-wpf-application/' rel='bookmark' title='Permanent Link: Real singleton approach in WPF application'>Real singleton approach in WPF application</a></li>
<li><a href='http://khason.net/dev/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code/' rel='bookmark' title='Permanent Link: INotifyPropertyChanged auto wiring or how to get rid of redundant code'>INotifyPropertyChanged auto wiring or how to get rid of redundant code</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 [...]


Related posts:<ol><li><a href='http://khason.net/tech/some-new-in-mix-downloads/' rel='bookmark' title='Permanent Link: Some new in-mix downloads'>Some new in-mix downloads</a></li>
</ol>]]></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>Related posts:<ol><li><a href='http://khason.net/tech/some-new-in-mix-downloads/' rel='bookmark' title='Permanent Link: Some new in-mix downloads'>Some new in-mix downloads</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/tech/source-code-for-silverlight-2-controls/feed/</wfw:commentRss>
		<slash:comments>2</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/how-to-calculate-crc-in-c/' rel='bookmark' title='Permanent Link: How to calculate CRC in C#?'>How to calculate CRC in C#?</a></li>
<li><a href='http://khason.net/dev/read-singleton-approach-in-wpf-application/' rel='bookmark' title='Permanent Link: Real singleton approach in WPF application'>Real singleton approach in WPF application</a></li>
<li><a href='http://khason.net/dev/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code/' rel='bookmark' title='Permanent Link: INotifyPropertyChanged auto wiring or how to get rid of redundant code'>INotifyPropertyChanged auto wiring or how to get rid of redundant code</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">0&#215;3EAB</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">0&#215;0B</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/how-to-calculate-crc-in-c/' rel='bookmark' title='Permanent Link: How to calculate CRC in C#?'>How to calculate CRC in C#?</a></li>
<li><a href='http://khason.net/dev/read-singleton-approach-in-wpf-application/' rel='bookmark' title='Permanent Link: Real singleton approach in WPF application'>Real singleton approach in WPF application</a></li>
<li><a href='http://khason.net/dev/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code/' rel='bookmark' title='Permanent Link: INotifyPropertyChanged auto wiring or how to get rid of redundant code'>INotifyPropertyChanged auto wiring or how to get rid of redundant code</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>1</slash:comments>
		</item>
		<item>
		<title>New version of Hebrew and Arabic support for Silverlight was released</title>
		<link>http://khason.net/dev/new-version-of-hebrew-and-arabic-support-for-silverlight-was-released/</link>
		<comments>http://khason.net/dev/new-version-of-hebrew-and-arabic-support-for-silverlight-was-released/#comments</comments>
		<pubDate>Sun, 04 Jan 2009 16:21:06 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[DEV]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[promo]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[soft]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://khason.net/dev/new-version-of-hebrew-and-arabic-support-for-silverlight-was-released/</guid>
		<description><![CDATA[Please notice, that new version (RC1) of Bidi support for Silverlight was released. What’s new in this release?

Initial version of bidi DataGrid
Listbox, CheckBox, RadioButton, DatePicker, Tab and TabItem controls were added (tnx to Yasser Makram and Emad from Santeon)
There are some changes in nBidi algorithm by Itai Bar-Haim
Button and ToggleButton base fixes + valid default [...]


Related posts:<ol><li><a href='http://khason.net/tech/some-new-in-mix-downloads/' rel='bookmark' title='Permanent Link: Some new in-mix downloads'>Some new in-mix downloads</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Please notice, that new version (RC1) of <a target="_blank" href="http://www.codeplex.com/SilverlightRTL/">Bidi support for Silverlight</a> was released. What’s new in this release?</p>
<ul>
<li>Initial version of bidi DataGrid</li>
<li>Listbox, CheckBox, RadioButton, DatePicker, Tab and TabItem controls were added (tnx to <a target="_blank" href="http://www.silverlightrecipes.com/">Yasser Makram</a> and Emad from <a target="_blank" href="http://santeon.com/">Santeon</a>)</li>
<li>There are some changes in nBidi algorithm by <a target="_blank" href="http://itaibh.googlepages.com/">Itai Bar-Haim</a></li>
<li>Button and ToggleButton base fixes + valid default templates for all controls</li>
<li>Some performance and stability issues.</li>
</ul>
<p>So, be sure, that you have <a target="_blank" href="http://www.codeplex.com/SilverlightRTL/Release/ProjectReleases.aspx">the latest release</a> and take a part of <a target="_blank" href="http://khason.net/blog/arabic-and-hebrew-languages-bidirectional-support-for-silverlight-20-beta-2/">tests</a>, which were also updated to new version.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="silverpeace" border="0" alt="silverpeace" src="http://khason.net/images/2009/01/silverpeace.png" width="240" height="178" /> </p>
<p>Great thank to all contributors for huge united work done. If you want to take a part in development <a target="_blank" href="https://www.codeplex.com/site/users/contact/tamirk">drop me a note</a>.</p>
<p><a target="_blank" href="http://www.codeplex.com/SilverlightRTL/"><strong>Download latest release (RC1) of bidirectional text support for Microsoft Silverlight &gt;&gt;</strong></a></p>


<p>Related posts:<ol><li><a href='http://khason.net/tech/some-new-in-mix-downloads/' rel='bookmark' title='Permanent Link: Some new in-mix downloads'>Some new in-mix downloads</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/dev/new-version-of-hebrew-and-arabic-support-for-silverlight-was-released/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>USB FM radio library was published on CodePlex</title>
		<link>http://khason.net/dev/usb-fm-radio-library-was-published-on-codeplex/</link>
		<comments>http://khason.net/dev/usb-fm-radio-library-was-published-on-codeplex/#comments</comments>
		<pubDate>Fri, 02 Jan 2009 20:48:30 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[DEV]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Interop]]></category>
		<category><![CDATA[My tools]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[promo]]></category>
		<category><![CDATA[soft]]></category>
		<category><![CDATA[source]]></category>

		<guid isPermaLink="false">http://khason.net/dev/usb-fm-radio-library-was-published-on-codeplex/</guid>
		<description><![CDATA[I just published a part of my latest project – dynamic library to work with FM receivers on CodePlex under MS-PL. So, feel free do download, test and use it. 
Note, that this release is preliminary and has a lot of bugs. Also, RDS is not fully implements as well as recording capabilities with Direct [...]


Related posts:<ol><li><a href='http://khason.net/itpro/quick-it-tip-how-to-build-bootable-usb-stick/' rel='bookmark' title='Permanent Link: Quick IT tip: How to build bootable USB stick'>Quick IT tip: How to build bootable USB stick</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a target="_blank" href="http://www.codeplex.com/FM">I just published</a> a part of my latest project – dynamic library to work with <a target="_blank" href="http://www.codeplex.com/FM">FM receivers on CodePlex</a> under MS-PL. So, feel free do download, test and use it. </p>
<p>Note, that this release is preliminary and has a lot of bugs. Also, RDS is not fully implements as well as recording capabilities with Direct Sound. </p>
<p>I’m keep working to provide WPF UI for this library to “productize” it.</p>
<p>So, what are you waiting for? <a target="_blank" href="http://www.codeplex.com/FM/Release/ProjectReleases.aspx">Download</a> and Spear the word with this news! This is the first and only fully managed library (as far as I know) to work with RDS, TMC and FM data. Also, there are not a lot of information about HID usage as FM receiver in managed code.</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/image.png" width="405" height="405" /> </p>
<p><a target="_blank" href="http://www.codeplex.com/FM/Release/ProjectReleases.aspx"><strong>Download latest release of USBFM.DLL &gt;&gt;</strong></a></p>


<p>Related posts:<ol><li><a href='http://khason.net/itpro/quick-it-tip-how-to-build-bootable-usb-stick/' rel='bookmark' title='Permanent Link: Quick IT tip: How to build bootable USB stick'>Quick IT tip: How to build bootable USB stick</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/dev/usb-fm-radio-library-was-published-on-codeplex/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>How to migrate from CS2007 to WordPress, Movable Type  (or any other blog engine, supports XML-RPC) with C#</title>
		<link>http://khason.net/dev/how-to-migrate-from-cs2007-to-wordpress-movable-type-or-any-other-blog-engine-supports-xml-rpc-with-c/</link>
		<comments>http://khason.net/dev/how-to-migrate-from-cs2007-to-wordpress-movable-type-or-any-other-blog-engine-supports-xml-rpc-with-c/#comments</comments>
		<pubDate>Thu, 01 Jan 2009 19:31:51 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[DEV]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[blogging tools]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Interop]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://khason.net/dev/how-to-migrate-from-cs2007-to-wordpress-movable-type-or-any-other-blog-engine-supports-xml-rpc-with-c/</guid>
		<description><![CDATA[Today we’ll speak about migration from community server 2007 to another blog engine, when you have no access to CS and/or other database. 
Let’s set targets first:

You want to migrate all posts
You want to migrate all comments
You want to transfer all hosted images and media files
You should update all internal links 

Looks complicated? not really. [...]


Related posts:<ol><li><a href='http://khason.net/dev/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code/' rel='bookmark' title='Permanent Link: INotifyPropertyChanged auto wiring or how to get rid of redundant code'>INotifyPropertyChanged auto wiring or how to get rid of redundant code</a></li>
<li><a href='http://khason.net/dev/how-to-calculate-crc-in-c/' rel='bookmark' title='Permanent Link: How to calculate CRC in C#?'>How to calculate CRC in C#?</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Today we’ll speak about migration from community server 2007 to another blog engine, when you have no access to CS and/or other database. </p>
<p>Let’s set targets first:</p>
<ul>
<li>You want to migrate all posts</li>
<li>You want to migrate all comments</li>
<li>You want to transfer all hosted images and media files</li>
<li>You should update all internal links </li>
</ul>
<p>Looks complicated? not really. First of all, grab any <a target="_blank" href="http://www.xmlrpc.com/">XML-RPC</a> framework (for example <a target="_blank" href="http://www.xml-rpc.net/">xml-rcp.net</a>). Then create a proxy to CS2007 – it uses Metablog API. You can see all defined methods by accessing /blogs/metablog.ashx</p>
<blockquote><p>[XmlRpcUrl(&quot;<a href="http://blogs.microsoft.co.il/blogs/metablog.ashx&quot;)]&#8220;>http://blogs.microsoft.co.il/blogs/metablog.ashx&quot;)]</a>      <br />public interface ICommunityServer {      <br />&#160;&#160; [XmlRpcMethod(&quot;blogger.deletePost&quot;)]      <br />&#160;&#160; bool deletePost(string appKey, string postid, string username, string password, bool publish); </p>
<p>&#160;&#160;&#160; [XmlRpcMethod(&quot;blogger.getUsersBlogs&quot;)]     <br />&#160;&#160; BlogInfo[] getUsersBlogs(string appKey, string username, string password); </p>
<p>&#160;&#160; [XmlRpcMethod(&quot;metaWeblog.editPost&quot;)]     <br />&#160;&#160; bool editPost(string postid, string username, string password, Post post, bool publish); </p>
<p>&#160;&#160; [XmlRpcMethod(&quot;metaWeblog.getCategories&quot;)]     <br />&#160;&#160; CategoryInfo[] getCategories(string blogid, string username, string password); </p>
<p>&#160;&#160; [XmlRpcMethod(&quot;metaWeblog.getPost&quot;)]     <br />&#160;&#160; Post getPost(string postid, string username, string password); </p>
<p>&#160;&#160; [XmlRpcMethod(&quot;metaWeblog.getRecentPosts&quot;)]     <br />&#160;&#160; Post[] getRecentPosts(string blogid, string username, string password, int numberOfPosts); </p>
<p>&#160;&#160; [XmlRpcMethod(&quot;metaWeblog.newPost&quot;)]     <br />&#160;&#160; string newPost(string blogid, string username, string password, Post post, Boolean publish);      <br />}</p>
</blockquote>
<p>As you can see, you can read and update posts, but there is no methods for comments. What to do? Community Server supports comments rss syndication. So why not to use it? Also, if you want to fix links later, save all retrieved urls</p>
<blockquote><p>posts = csblog.getRecentPosts(csBlogid, csUsername, csPassword, toFetch);     <br />for (int i = 0; i &lt; posts.Length; i++) {      <br />if (!_postsIndex.ContainsKey(posts[i].link)) _postsIndex.Add(posts[i].link, string.Empty);      <br />…      <br />var commentsRSSURL = string.Concat(&quot;<a href="http://blogs.microsoft.co.il/blogs/tamir/rsscomments.aspx?PostID=&quot;">http://blogs.microsoft.co.il/blogs/tamir/rsscomments.aspx?PostID=&quot;</a>, posts[i].postid);      <br />_rssReader = new XmlTextReader(commentsRSSURL);      </p>
<p>while (_rssReader.Read()) {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; _rssReader.MoveToContent();      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (_rssReader.NodeType == XmlNodeType.Element) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (_rssReader.Name == &quot;pubDate&quot;) { date = DateTime.Parse(_rssReader.ReadElementContentAsString()); }      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (_rssReader.Name == &quot;dc:creator&quot;) { author = _rssReader.ReadElementContentAsString(); }      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (_rssReader.Name == &quot;description&quot;) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (!shouldSkip) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; content = _rssReader.ReadElementContentAsString();      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; comments.Add(new Comment {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; author = author,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; date_created_gmt = date,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; status = true</p>
</blockquote>
<p>As you can see, now you have all comments. Next step is to detect and reupload all images to the new host.</p>
<blockquote><p>private const string imgRX = &quot;&lt;img[^&gt;]*src=\&quot;?([^\&quot;]*)\&quot;?([^&gt;]*alt=\&quot;?([^\&quot;]*)\&quot;?)?[^&gt;]*&gt;&quot;;     <br />var matches = Regex.Matches(posts[i].description, imgRX);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Console.WriteLine(&quot;Fixing {0} images&#8230;&quot;, matches.Count);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; for (int j = 0; j &lt; matches.Count; j++) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Console.WriteLine(&quot;Retriving image #{0}&quot;, j);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var url = matches[j].Groups[1].Value;      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (url.Contains(baseURL)) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; try {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var data = wc.DownloadData(url);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Console.WriteLine(&quot;Uploading image #{0}&quot;, j);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var uf = newblog.uploadFile(newblogid, newUsername, newPassword, new MediaObject {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; bits = data,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; name = matches[j].Groups[1].Value.Substring(matches[j].Groups[1].Value.LastIndexOf(&#8216;/&#8217;) + 1)      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; });      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; posts[i].description = posts[i].description.Replace(url, uf.url);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; } catch { }      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</blockquote>
<p>Now all images are stored in the new location and all image links are updated within stored posts. Next step is to upload all posts to the new location. CS stores tags as categories, which is wrong. Why? Because categories can be hierarchical, while tags cannot. So we have to convert all categories within retrieved posts into real tags. After it we can post everything</p>
<blockquote><p>for (int i = posts.Length &#8211; 1; i &gt;= 0; i&#8211;) {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; posts[i].mt_keywords = string.Join(&quot;,&quot;, posts[i].categories);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var pid = newblog.newPost(newblogid, newUsername, newPassword, posts[i], true);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; foreach (var comment in posts[i].comments) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; try {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var cid = newblog.newComment(newblogid, newUsername, newPassword, pid, comment);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; } catch { }      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</blockquote>
<p>Now we have to update all internal links within new locations. For this we should grab all posts back to learn new URLs.</p>
<blockquote><p>var newPosts = newblog.getRecentPosts(newblogid, newUsername, newPassword, toFetch);     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; for (int i = 0; i &lt; newPosts.Length; i++) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; foreach (var pi in _postsIndex) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (newPosts[i].description.Contains(pi.Key)) newPosts[i].description = newPosts[i].description.Replace(string.Concat(baseURL,pi.Key), pi.Value);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; wpblog.editPost((string)newPosts[i].postid, newUsername, newPassword, newPosts[i], true);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (!refereces.ContainsKey(newPosts[i].link)) refereces.Add(newPosts[i].link, posts[i].link); </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</blockquote>
<p>We done. Last, but not the least, is to update old posts with new URL to make visitors able to forward into new location.</p>
<blockquote><p>csposts = csblog.getRecentPosts(csBlogid, csUsername, csPassword, toFetch);     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; for(int i=0;i&lt; csposts.Length;i++) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (_postsIndex.ContainsKey(csposts[i].link)) {      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; string write = string.Format(&quot;&lt;h3&gt;[This blog was migrated. You will not be able to comment here.&lt;br/&gt;The new URL of this post is &lt;a href=\&quot;{0}\&quot;&gt;{0}&lt;/a&gt;]&lt;/h3&gt;&lt;hr/&gt;&quot;, _postsIndex[csposts[i].link]);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; csposts[i].description = string.Concat(write, csposts[i].description);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; csblog.editPost((string)csposts[i].postid, csUsername, csPassword, csposts[i], true);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Console.WriteLine(&quot;Post {0} was updated&quot;,i);      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
</blockquote>
<p>Have a nice day and be good people!</p>


<p>Related posts:<ol><li><a href='http://khason.net/dev/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code/' rel='bookmark' title='Permanent Link: INotifyPropertyChanged auto wiring or how to get rid of redundant code'>INotifyPropertyChanged auto wiring or how to get rid of redundant code</a></li>
<li><a href='http://khason.net/dev/how-to-calculate-crc-in-c/' rel='bookmark' title='Permanent Link: How to calculate CRC in C#?'>How to calculate CRC in C#?</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://khason.net/dev/how-to-migrate-from-cs2007-to-wordpress-movable-type-or-any-other-blog-engine-supports-xml-rpc-with-c/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>
