<?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; CodeProject</title>
	<atom:link href="http://khason.net/tag/codeproject/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>Visual Studio debugger related attributes cheat sheet</title>
		<link>http://khason.net/dev/visual-studio-debugger-related-attributes-cheat-sheet/</link>
		<comments>http://khason.net/dev/visual-studio-debugger-related-attributes-cheat-sheet/#comments</comments>
		<pubDate>Tue, 07 Apr 2009 16:20:54 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[DEV]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[soft]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[VSTS]]></category>
		<category><![CDATA[Work process]]></category>

		<guid isPermaLink="false">http://khason.net/dev/visual-studio-debugger-related-attributes-cheat-sheet/</guid>
		<description><![CDATA[There are some debugger-oriented attributes in .Net, however 70% of developers not even know that they exist and 95% of them has no idea what they doing and how to use it. Today we’ll try to lid light on what those attributes doing and how to achieve the best of using it.
First of all let’s [...]


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>There are some debugger-oriented attributes in .Net, however 70% of developers not even know that they exist and 95% of them has no idea what they doing and how to use it. Today we’ll try to lid light on what those attributes doing and how to achieve the best of using it.</p>
<p>First of all let’s define what we want to get from debugger in VS</p>
<table border="1" cellspacing="1" cellpadding="2" width="600">
<tbody>
<tr>
<td valign="top" width="116">Term</td>
<td valign="top" width="484">What it actually does</td>
</tr>
<tr>
<td valign="top" width="116">Step Into</td>
<td valign="top" width="484">Steps into immediate child (that is what F11 does for standard VS layout)         <br /><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/04/image1.png" width="240" height="17" /> </td>
</tr>
<tr>
<td valign="top" width="116">Step Over</td>
<td valign="top" width="484">Skips to any depth (that is what F10 does)         <br /><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/04/image2.png" width="238" height="19" /> </td>
</tr>
<tr>
<td valign="top" width="116">Step Deeper</td>
<td valign="top" width="484">Steps into bypassing code, using certain attribute</td>
</tr>
<tr>
<td valign="top" width="116">Run Through</td>
<td valign="top" width="484">Steps into, but only one level. All lower lavels will be Stepped Over</td>
</tr>
</tbody>
</table>
<p>Now, when we have our set of terms, we can learn what JMC means. It is not famous whisky brand or another car company. It Just My Code option, checked in or out in “Option” dialog inside Visual Studio</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/04/image3.png" width="749" height="437" /> </p>
<p> Next turn is for attributes, there are four (I know about) attributes, related to debugger and used by me for efficient programming: <a title="Read more in MSDN about this" href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerhiddenattribute.aspx" target="_blank">DebuggerHidden</a>, <a title="Read more in MSDN about this attribute" href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggernonusercodeattribute.aspx" target="_blank">DebuggerNonUserCode</a>, <a title="Read more in MSDN about this attribute" href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx" target="_blank">DebuggerStepThrough</a> and <a title="Read more in MSDN about this attribute" href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepperboundaryattribute.aspx" target="_blank">DebuggerStepperBoundary</a>. We will use only three first. DebuggerStepperBoundary is the most secret attribute, which is related to debugging only in multithreaded environment. It used to avoid delusive effect, might appears when a context switch is made on a <a title="Read MSDN documentation about System.Threading.Thread class" href="http://msdn.microsoft.com/en-us/library/system.threading.thread.aspx" rel="tag" target="_blank">thread</a> within DebuggerNonUserCode applied. Other words, when you need to Step Through in Thread A and keep running at the same time in Thread B.</p>
<p>So let’s see the effects occurred when using those debugger attributes in case, you are trying to Step Into place, this attribute applied or set a Breakpoint there. When Just My Code (JMC) is checked all those attributes behaviors the same – they Step Deeper. However, when JMC is turned off (as in my picture) they begin to behavior differently.</p>
<table border="1" cellspacing="1" cellpadding="2" width="600">
<tbody>
<tr>
<td valign="top" width="200">Attribute</td>
<td valign="top" width="200">Step Into</td>
<td valign="top" width="200">Breakpoint</td>
</tr>
<tr>
<td valign="top" width="200">DebuggerHidden</td>
<td valign="top" width="200">Step Deeper</td>
<td valign="top" width="200">Step Deeper</td>
</tr>
<tr>
<td valign="top" width="200">DebuggerNonUserCode</td>
<td valign="top" width="200">Step Into</td>
<td valign="top" width="200">Step Into</td>
</tr>
<tr>
<td valign="top" width="200">DebuggerStepThrough</td>
<td valign="top" width="200">Step Deeper</td>
<td valign="top" width="200">Step Into</td>
</tr>
</tbody>
</table>
<p>As you can see, in this case </p>
<ul>
<li>DebuggerNonUserCode respects both for F11 (Step Into) and Breakpoints</li>
<li>DebuggerStepThrough respects only for Breakpoints</li>
<li>DebuggerHidden does not respects at all – just like when JMC is checked.</li>
</ul>
<p><strong>Bottom line</strong>: if you want people to manage whether to enter or not into your hidden methods – use DebuggerNonUserCode attribute. If you prefer them not to even know that those methods exists, use DebuggerHidden. If you want them to be able to put Breakpoints and stop on them, but keep running without explicit action – use&#160; DebuggerStepThrough</p>
<p>Have a nice day and be good people.&#160; Happy other developers friendly debugging.</p>
<p><em>Small bonus</em>: To visualize your struct, class, delegate, enum, field, property or even assembly for user debugger, you can use <a title="Read more on MSDN about this attribute" href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerdisplayattribute.aspx" target="_blank">DebuggerDisplay</a> attribute (you need to put executable code into {} for example (“Value = {X}:{Y}”)]</p>
<p><em>Thanks to <a title="Boris unleashed with huge passover gift" href="http://twitpic.com/2yivn" target="_blank">Boris</a> for deep investigation</em></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/visual-studio-debugger-related-attributes-cheat-sheet/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>Quick how to: Reduce number of colors programmatically</title>
		<link>http://khason.net/dev/quick-how-to-reduce-number-of-colors-programmatically/</link>
		<comments>http://khason.net/dev/quick-how-to-reduce-number-of-colors-programmatically/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 18:46:50 +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[DirectX]]></category>
		<category><![CDATA[Interop]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Work process]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[WPF crossbow]]></category>

		<guid isPermaLink="false">http://khason.net/dev/quick-how-to-reduce-number-of-colors-programmatically/</guid>
		<description><![CDATA[My colleague just asked me about how to reduce a number of colors in image programmatically. This is very simple task and contains of 43   steps:

First of all, you have to read a source image
using (var img = Image.FromFile(name)) {
var bmpEncoder = ImageCodecInfo.GetImageDecoders().FirstOrDefault(e =&#62; e.FormatID == ImageFormat.Bmp.Guid);
Then create your own encoder with certain [...]


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>My colleague just asked me about how to reduce a number of colors in image programmatically. This is very simple task and contains of 43 <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  steps:</p>
<p><img style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" title="Simple color matrix" src="http://khason.net/images/2009/02/image2.png" border="0" alt="Simple color matrix" width="383" height="366" /></p>
<p>First of all, you have to read a source image</p>
<blockquote><p>using (var img = Image.FromFile(name)) {<br />
var bmpEncoder = ImageCodecInfo.GetImageDecoders().FirstOrDefault(e =&gt; e.FormatID == ImageFormat.Bmp.Guid);</p></blockquote>
<p>Then create your own encoder with certain color depth (32 bits in this case)</p>
<blockquote><p>var myEncoder = System.Drawing.Imaging.Encoder.ColorDepth;<br />
var myEncoderParameter = new EncoderParameter(myEncoder, 32L);<br />
var myEncoderParameters = new EncoderParameters(1) { Param = new EncoderParameter[] { myEncoderParameter } };</p></blockquote>
<p>Then save it</p>
<blockquote><p>img.Save(name.Replace(&#8220;.png&#8221;, &#8220;.bmp&#8221;), bmpEncoder, myEncoderParameters);</p></blockquote>
<p>It it enough? Not really, because if you’re going to loose colors (by reducing color depth), it makes sense to avoid letting default WIX decoder to do this, thus you have to find nearest base colors manually. How to do this? By using simple math</p>
<blockquote><p>Color GetNearestBaseColor(Color exactColor) {<br />
Color nearestColor = Colors.Black;<br />
int cnt = baseColors.Count;<br />
for (int i = 0; i &lt; cnt; i++) {<br />
int rRed = baseColors[i].R &#8211; exactColor.R;<br />
int rGreen = baseColors[i].G &#8211; exactColor.G;<br />
int rBlue = baseColors[i].B &#8211; exactColor.B;</p>
<p>int rDistance =<br />
(rRed * rRed) +<br />
(rGreen * rGreen) +<br />
(rBlue * rBlue);<br />
if (rDistance == 0.0) {<br />
return baseColors[i];<br />
} else if (rDistance &lt; maxDistance) {<br />
maxDistance = rDistance;<br />
nearestColor = baseColors[i];<br />
}<br />
}<br />
return nearestColor;<br />
}</p></blockquote>
<p>Now, you can either change colors on base image directly</p>
<blockquote><p>unsafe {<br />
uint* pBuffer = (uint*)hMap;<br />
for (int iy = 0; iy &lt; (int)ColorMapSource.PixelHeight; ++iy)<br />
{<br />
for (int ix = 0; ix &lt; nWidth; ++ix)<br />
{<br />
Color nc = GetNearestBaseColor(pBuffer[0].FromOle());</p>
<p>pBuffer[0] &amp;= (uint)((uint)nc.A &lt;&lt; 24) | //A<br />
(uint)(nc.R &lt;&lt; 16 ) | //R<br />
(uint)(nc.G &lt;&lt; 8 ) | //G<br />
(uint)(nc.B ); //B<br />
++pBuffer;<br />
}<br />
pBuffer += nOffset;<br />
}<br />
}</p></blockquote>
<p>Or, if you’re in WPF and .NET 3.5 <a title="HLSL (Pixel shader) effects tutorial" href="http://khason.net/blog/hlsl-pixel-shader-effects-tutorial/" target="_blank">create simple pixel shader effect</a> to do it for you in hardware. Now, my colleague can do it himself in about 5 minutes <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  . Have a nice day and 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/quick-how-to-reduce-number-of-colors-programmatically/feed/</wfw:commentRss>
		<slash:comments>2</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>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>Capturing and streaming sound by using DirectSound with C#</title>
		<link>http://khason.net/blog/capturing-and-streaming-sound-by-using-directsound-with-c/</link>
		<comments>http://khason.net/blog/capturing-and-streaming-sound-by-using-directsound-with-c/#comments</comments>
		<pubDate>Thu, 25 Dec 2008 10:48:20 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[BLOG]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[DEV]]></category>
		<category><![CDATA[DirectX]]></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>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://khason.net/blog/capturing-and-streaming-sound-by-using-directsound-with-c/</guid>
		<description><![CDATA[I already wrote a little about managed way to use DirectX DirectSound. Today we’ll speak about how to get sound from your microphone or any other DirectSound capturing device (such as FM receiver) and stream it out to your PC speakers and any other DirectSound Output device. So, let’s start creating our first echo service [...]


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>I already wrote a little about <a href="http://khason.net/blog/sound-tone-and-dtmf-generation-by-using-managed-directsound-and-c-and-sine-tone-detection-with-pure-managed-goertzel-algorithm-implementation/">managed way to use DirectX DirectSound</a>. Today we’ll speak about how to get sound from your microphone or any other DirectSound capturing device (such as <a href="http://khason.net/blog/reading-and-decoding-rds-radio-data-system-in-c/">FM receiver</a>) and stream it out to your PC speakers and any other DirectSound Output device. So, let’s start creating our first echo service by using managed DirectX.</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/2008/12/image-13541f81.png" width="225" height="229" /> </p>
<p>First of all we should decide what Wave format we want to use for capturing and recording. So, let’s choose anything reasonable <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<blockquote><p>var format = new WaveFormat {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; SamplesPerSecond = 96000,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; BitsPerSample = 16,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Channels = 2,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; FormatTag = WaveFormatTag.Pcm      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; };</p>
</blockquote>
<p>Now, we should calculate block align and average byte per second value for this format. I’m wondering why it cannot be done automatically…</p>
<blockquote><p>format.BlockAlign = (short)(format.Channels * (format.BitsPerSample / 8));     <br />format.AverageBytesPerSecond = format.SamplesPerSecond * format.BlockAlign;</p>
</blockquote>
<p>Next step is to set the size of two buffers – one for input and other for output. Generally those buffers are circular, and capturing one should be twice bigger, then output. Why? Because we choose two channels to use. Also, we should decide about chunk size of the buffer, we want to signal when filled.</p>
<blockquote><p>_dwNotifySize = Math.Max(4096, format.AverageBytesPerSecond / 8);     <br />_dwNotifySize -= _dwNotifySize % format.BlockAlign;      <br />_dwCaptureBufferSize = NUM_BUFFERS * _dwNotifySize;      <br />_dwOutputBufferSize = NUM_BUFFERS * _dwNotifySize / 2;</p>
</blockquote>
<p>Next step is to create CaptureBufferDescriptor and actual capturing buffer. We’ll enumerate all devices and choose one, satisfies given string (captureDescriptor) – for example “Mic” <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<blockquote><p>var cap = default(Capture);     <br />var cdc = new CaptureDevicesCollection();      <br />for (int i = 0; i &lt; cdc.Count; i++) {      <br />&#160;&#160; if (cdc[i].Description.ToLower().Contains(captureDescriptor.ToLower())) {      <br />&#160;&#160;&#160;&#160;&#160; cap = new Capture(cdc[i].DriverGuid);      <br />&#160;&#160;&#160;&#160;&#160; break;      <br />&#160;&#160; }      <br />}      <br />var capDesc = new CaptureBufferDescription {      <br />&#160;&#160; Format = format,      <br />&#160;&#160; BufferBytes = _dwCaptureBufferSize      <br />};      <br />_dwCapBuffer = new CaptureBuffer(capDesc, cap);</p>
</blockquote>
<p>Then we’ll create output device and buffer. To simplify program, we will use default speakers to output, however, you can choose output device the same way we did for capturing. Also, because DirectSound uses any window as it’s message pump, we have to use SetCooperativeLevel method. In my case (windowless application), I’ll use desktop window as message broker. This why you will have to add Windows.Forms as reference for your project, even if it console application. Also, do not forget to set GlobalFocus value to True, if you want to play echo, even if desktop window is not focused.</p>
<blockquote><p>var dev = new Device();     <br />dev.SetCooperativeLevel(Native.GetDesktopWindow(), CooperativeLevel.Priority); </p>
<p>var devDesc = new BufferDescription {     <br />&#160;&#160; BufferBytes = _dwOutputBufferSize,      <br />&#160;&#160; Format = format,      <br />&#160;&#160; DeferLocation = true,      <br />&#160;&#160; GlobalFocus = true      <br />};      <br />_dwDevBuffer = new SecondaryBuffer(devDesc, dev);</p>
</blockquote>
<p>Now, we will subscribe to buffer notifications and set autoResetEvent to be fired when it filled up.</p>
<blockquote><p>var _resetEvent = new AutoResetEvent(false);     <br />var _notify = new Notify(_dwCapBuffer);      <br />//half&amp;half      <br />var bpn1 = new BufferPositionNotify();      <br />bpn1.Offset = _dwCapBuffer.Caps.BufferBytes / 2 &#8211; 1;      <br />bpn1.EventNotifyHandle = _resetEvent.SafeWaitHandle.DangerousGetHandle();      <br />var bpn2 = new BufferPositionNotify();      <br />bpn2.Offset = _dwCapBuffer.Caps.BufferBytes &#8211; 1;      <br />bpn2.EventNotifyHandle = _resetEvent.SafeWaitHandle.DangerousGetHandle(); </p>
<p>_notify.SetNotificationPositions(new BufferPositionNotify[] { bpn1, bpn2 });</p>
</blockquote>
<p>Almost done, the only thing we should do is to fire worker thread to take care on messages</p>
<blockquote><p>int offset = 0;     <br />_dwCaptureThread = new Thread((ThreadStart)delegate {      <br />&#160;&#160; _dwCapBuffer.Start(true); </p>
<p>&#160;&#160; while (IsReady) {     <br />&#160;&#160;&#160;&#160;&#160; _resetEvent.WaitOne();      <br />&#160;&#160;&#160;&#160;&#160; var read = _dwCapBuffer.Read(offset, typeof(byte), LockFlag.None, _dwOutputBufferSize);      <br />&#160;&#160;&#160;&#160;&#160; _dwDevBuffer.Write(0, read, LockFlag.EntireBuffer);      <br />&#160;&#160;&#160;&#160;&#160; offset = (offset + _dwOutputBufferSize) % _dwCaptureBufferSize;      <br />&#160;&#160;&#160;&#160;&#160; _dwDevBuffer.SetCurrentPosition(0);      <br />&#160;&#160;&#160;&#160;&#160; _dwDevBuffer.Play(0, BufferPlayFlags.Default);      <br />&#160;&#160; }      <br />&#160;&#160; _dwCapBuffer.Stop();      <br />});      <br />_dwCaptureThread.Start();</p>
</blockquote>
<p>That’s it. Compile and run. Now if you’ll speak, you can hear your echo from PC speakers. </p>
<p>Merry Christmas for whom concerns and be good people – do not scare your co-workers with strange sounds – be polite and make the volume lower <img src='http://khason.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </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/blog/capturing-and-streaming-sound-by-using-directsound-with-c/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>Creating transparent buttons, panels and other control with Compact Framework and putting one into other</title>
		<link>http://khason.net/blog/creating-transparent-buttons-panels-and-other-control-with-compact-framework-and-putting-one-into-other/</link>
		<comments>http://khason.net/blog/creating-transparent-buttons-panels-and-other-control-with-compact-framework-and-putting-one-into-other/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 05:09:29 +0000</pubDate>
		<dc:creator>Tamir</dc:creator>
				<category><![CDATA[BLOG]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[DEV]]></category>
		<category><![CDATA[Interop]]></category>
		<category><![CDATA[Mobile]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://khason.net/blog/creating-transparent-buttons-panels-and-other-control-with-compact-framework-and-putting-one-into-other/</guid>
		<description><![CDATA[In WPF/Silverlight world it&#8217;s very simple to make transparent controls and put anything inside anything. However, that&#8217;s not the situation in WinForms, and even worth in the world of compact devices with CF. Within this worlds, there is only one way to make controls transparent &#8211; to use color masks. Today, we&#8217;ll create transparent controls [...]


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>In <a href="http://blogs.microsoft.co.il/blogs/tamir/archive/tags/WPF/default.aspx">WPF</a>/<a href="http://blogs.microsoft.co.il/blogs/tamir/archive/tags/Silverlight/default.aspx">Silverlight</a> world it&#8217;s very simple to make transparent controls and put anything inside anything. However, that&#8217;s not the situation in WinForms, and even worth in the world of compact devices with CF. Within this worlds, there is only one way to make controls transparent &#8211; to use color masks. Today, we&#8217;ll create transparent controls with Compact Framework and put it into panel, which has image background.</p>
<p><img border="0" alt="image" src="http://khason.net/images/2008/12/image-679149a5-fff2-40ab-8966-6c6ffa40b692.png" width="259" height="397"/> </p>
<p>So let&#8217;s start. First of all, we need create our own control. For this purpose, we have to inherit from Control and override couple of things. More precise: OnPaint and OnPaintBackground. We do not want to paint background for transparent control, so let&#8217;s prevent it.</p>
<blockquote><p>public class TransparentImageButton : Control</p>
<p>protected override void OnPaintBackground(PaintEventArgs e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //prevent<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }  </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; protected override void OnPaint(PaintEventArgs e) {</p>
</blockquote>
<p>Next, we have to get graphics, delivered by OnPain event argument and draw our image over it. However, BitBlt (which is used by core graphics system) is not very fast method, so it&#8217;s better for us to draw everything first and then copy final image to the device.</p>
<blockquote><p>Graphics gxOff; <br />Rectangle imgRect;<br />var image = (_isPressed &amp;&amp; PressedImage != null) ? PressedImage : Image;  </p>
<p>if (_imgOffscreen == null) {<br /> _imgOffscreen = new Bitmap(ClientSize.Width, ClientSize.Height);<br />}  </p>
<p>gxOff = Graphics.FromImage(_imgOffscreen); <br />gxOff.Clear(this.BackColor);&nbsp; <br />&#8230;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </p>
<p>if (image != null) {<br />var imageLeft = (this.Width &#8211; image.Width) / 2;<br />var imageTop = (this.Height &#8211; image.Height) / 2;  </p>
<p>if (!_isPressed) imgRect = new Rectangle(imageLeft, imageTop, image.Width, image.Height);<br />else imgRect = new Rectangle(imageLeft + 1, imageTop + 1, image.Width, image.Height);<br />var imageAttr = new ImageAttributes();</p>
</blockquote>
<p>To make images transparent, we have to use (as mentioned earlier) transparency color key (to tell windows what color it should not draw. We can code or provide this value to detect it by hitting any pixel on the image. Just like this: </p>
<blockquote><p>public static Color BackgroundImageColor(this Bitmap bmp) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return bmp.GetPixel(0, 0);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
</blockquote>
<p>Now we can keep working.</p>
<blockquote><p>imageAttr.SetColorKey(image.BackgroundImageColor(), image.BackgroundImageColor());<br />gxOff.DrawImage(image, imgRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttr);<br />} if (_isPressed) {<br /> var rc = this.ClientRectangle;<br />&nbsp; rc.Width&#8211;;<br />&nbsp; rc.Height&#8211;;<br />&nbsp; gxOff.DrawRectangle(new Pen(Color.Black), rc);<br /> }<br />e.Graphics.DrawImage(_imgOffscreen, 0, 0);</p>
</blockquote>
<p>Also, we have to provide others with possibility to handle this even too, thus we will not forget to add base.OnPaint(e); at&nbsp; the end.</p>
<p>Next step is to detect whether our button is clicked or not. We&#8217;ll override keyboard and mouse events to detect this.</p>
<blockquote><p>protected override void OnKeyDown(KeyEventArgs e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _isPressed = this.Focused; this.Invalidate();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; base.OnKeyDown(e);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }  </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; protected override void OnKeyUp(KeyEventArgs e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _isPressed = false; this.Invalidate();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; base.OnKeyUp(e);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }  </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; protected override void OnMouseDown(MouseEventArgs e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _isPressed = this.Focused; this.Invalidate();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; base.OnMouseDown(e);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }  </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; protected override void OnMouseUp(MouseEventArgs e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _isPressed = false; this.Invalidate();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; base.OnMouseUp(e);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
</blockquote>
<p>Compile and run to see no problem, when our transparent button lies on solid color control, however, we want to put it into panel with background &#8211; just like this one. In this case, you can use real transparent PNG and GIF images, also you can replace transparent color with well known Magenta (or any other color).</p>
<blockquote><p>public class ImagePanel : Panel {  </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public Bitmap Image { get; set; }  </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; protected override void OnPaintBackground(PaintEventArgs e) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; e.Graphics.DrawImage(Image, 0, 0);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; }</p>
</blockquote>
<p>When we&#8217;ll put it onto anything, that has no background color, we&#8217;ll see that our &#8220;fake transparency&#8221; disappears. Why this happen? To provide transparency Windows uses color masks, also while confederating facts, clipping algorithm within GDI is not very trustful, thus the only thing can be taken into account is color. But what to do if we have an image? We should clip it manually. We cannot just get the handle to parent device surface (see above about trustful GDI), so the only way to do it is by providing something, that we know for sure. For example interface, telling us, that parent has image, which drawn on the screen.</p>
<blockquote><p>internal interface IHaveImage {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Bitmap Image { get; set; }<br />&nbsp;&nbsp;&nbsp; }</p>
</blockquote>
<p>When we know it, all we have to do is to clip the region of this image (not device context) and draw it as part of our really transparent control.</p>
<blockquote><p>if (this.Parent is IHaveImage) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var par = this.Parent as IHaveImage;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; gxOff.DrawImage(par.Image.Clip(this.Bounds), 0, 0);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
</blockquote>
<p>The implementation of Image.Clip is very straight forward.</p>
<blockquote><p>public static Bitmap GetSS(this Graphics grx, Rectangle bounds) {<br />&nbsp;&nbsp;&nbsp; var res = new Bitmap(bounds.Width, bounds.Height);<br />&nbsp;&nbsp;&nbsp; var gxc = Graphics.FromImage(res);<br />&nbsp;&nbsp;&nbsp; IntPtr hdc = grx.GetHdc();<br />&nbsp;&nbsp;&nbsp; PlatformAPI.BitBlt(gxc.GetHdc(), 0, 0, bounds.Width, bounds.Height, hdc, bounds.Left, bounds.Top, PlatformAPI.SRCCOPY);<br />&nbsp;&nbsp;&nbsp; grx.ReleaseHdc(hdc);<br />&nbsp;&nbsp;&nbsp; return res;<br />}  </p>
<p>public static Bitmap Clip(this Bitmap source, Rectangle bounds) {<br />&nbsp;&nbsp;&nbsp; var grx = Graphics.FromImage(source);<br />&nbsp;&nbsp;&nbsp; return grx.GetSS(bounds);<br />}</p>
</blockquote>
<p>We done. Compiling all together will fake transparency for controls, even when it&#8217;s parents background is not pained with&nbsp; solid color brush.</p>
<p><a href="http://cid-4e39ecd492e4eec1.skydrive.live.com/self.aspx/Public/TransButton.zip">Source code for this article</a></p>
<p>P.S. Do not even try to inherit your custom Button control from framework Button class, dev team &#8220;forgot&#8221; to expose it&#8217;s event for override. So, OnPaint, OnPaintBackground, OnKeyUp, OnKeydown, OnMouseUp and OnMouseDown aside with most of other base events will not work for you, also BaseButton class has no default constructor, so the only class you can inherit from is Control.</p>
<p>Have a nice day and 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/blog/creating-transparent-buttons-panels-and-other-control-with-compact-framework-and-putting-one-into-other/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
