<?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>Blog &#124; Limilabs &#187; Presentation</title>
	<atom:link href="http://www.limilabs.com/blog/category/presentation/feed" rel="self" type="application/rss+xml" />
	<link>http://www.limilabs.com/blog</link>
	<description></description>
	<lastBuildDate>Mon, 21 May 2012 09:49:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>INotifyPropertyChanged with custom targets</title>
		<link>http://www.limilabs.com/blog/inotifypropertychanged-with-custom-targets?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=inotifypropertychanged-with-custom-targets</link>
		<comments>http://www.limilabs.com/blog/inotifypropertychanged-with-custom-targets#comments</comments>
		<pubDate>Tue, 24 May 2011 08:47:57 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=1822</guid>
		<description><![CDATA[Wouldn&#8217;t it be nice to have a simple attribute instead of backing field madness in Silverlight/WPF? Just like this: public class MainViewModel : ViewModelBase { [NotifyPropertyChanged] public string Title { get; set; } } You can use PostSharp for that, you should at least use lambda expressions instead of strings. Here&#8217;s how to do it [...]]]></description>
			<content:encoded><![CDATA[<p>Wouldn&#8217;t it be nice to have a simple attribute instead of backing field madness in Silverlight/WPF? Just like this:</p>
<pre class="brush: csharp;">
public class MainViewModel : ViewModelBase
{
    [NotifyPropertyChanged]
    public string Title { get; set; }
}
</pre>
<p>You can use <a href="http://www.limilabs.com/blog/inotifypropertychanged-with-postsharp"> PostSharp for that</a>, you should at least <a href="http://www.limilabs.com/blog/inotifypropertychanged-with-lambdas">use lambda expressions instead of strings</a>.</p>
<p>Here&#8217;s how to do it without 3rd party software:</p>
<p>1.<br />
In your project <strong>declare base view model</strong>:</p>
<pre class="brush: csharp;">
public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged
        = delegate { };

    protected void OnPropertyChanged(string propertyName)
    {
        this.PropertyChanged(
            this,
            new PropertyChangedEventArgs(propertyName));
    }
};
</pre>
<p>2.<br />
<strong>Declare the attribute</strong></p>
<p>It will be used to mark properties that should raise the PropertyChanged event.</p>
<pre class="brush: csharp;">
[AttributeUsage(AttributeTargets.Property)]
public class NotifyPropertyChangedAttribute : Attribute
{
}
</pre>
<p>3.<br />
Create <strong>new MSBuildTasks library project</strong> (it can be in different solution)</p>
<p>Add references to:</p>
<ul>
<li>Mono.Cecil.dll</li>
<li>Mono.Cecil.Pdb.dll (this needed so Cecil can updated pdb file, which is need for debugging the modified assembly)</li>
<li>MSBuild assemblies</li>
</ul>
<p>4.<br />
<strong>Create new MSBuild task</strong></p>
<p>It will inject PropertyChanged event invocation on properties marked with NotifyPropertyChanged attribute.</p>
<pre class="brush: csharp;">
using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.Cecil;
using Mono.Cecil.Cil;

namespace MSBuildTasks
{
    public class NotifyPropertyChangedTask : Task
    {
        public override bool Execute()
        {
            InjectMsil();
            return true;
        }

        private void InjectMsil()
        {
            var assemblyDefinition = AssemblyDefinition.ReadAssembly(
                AssemblyPath,
                new ReaderParameters { ReadSymbols = true });

            var module = assemblyDefinition.MainModule;

            foreach (var type in module.Types)
            {
                foreach (var prop in type.Properties)
                {
                    foreach (var attribute in prop.CustomAttributes)
                    {
                        string fullName = attribute.Constructor.DeclaringType.FullName;
                        if (fullName.Contains(&quot;NotifyPropertyChanged&quot;))
                        {
                            InjectMsilInner(module, type, prop);
                        }
                    }
                }
            }
            assemblyDefinition.Write(
                this.AssemblyPath,
                new WriterParameters { WriteSymbols = true });
        }

        private static void InjectMsilInner(
            ModuleDefinition module,
            TypeDefinition type,
            PropertyDefinition prop)
        {
            var msilWorker = prop.SetMethod.Body.GetILProcessor();
            var ldarg0 = msilWorker.Create(OpCodes.Ldarg_0);

            MethodDefinition raisePropertyChangedMethod =
                FindRaisePropertyChangedMethod(type);
            if (raisePropertyChangedMethod == null)
                throw new Exception(
                    &quot;RaisePropertyChanged method was not found in type &quot;
                    + type.FullName);

            var raisePropertyChanged = module.Import(
                raisePropertyChangedMethod);
            var propertyName = msilWorker.Create(
                OpCodes.Ldstr,
                prop.Name);
            var callRaisePropertyChanged = msilWorker.Create(
                OpCodes.Callvirt,
                raisePropertyChanged);

            msilWorker.InsertBefore(
                prop.SetMethod.Body.Instructions[
                    prop.SetMethod.Body.Instructions.Count - 1],
                ldarg0);

            msilWorker.InsertAfter(ldarg0, propertyName);
            msilWorker.InsertAfter(
                propertyName,
                callRaisePropertyChanged);
        }

        private static MethodDefinition FindRaisePropertyChangedMethod(
            TypeDefinition type)
        {
            foreach (var method in type.Methods)
            {
                if (method.Name == &quot;RaisePropertyChanged&quot;
                    &amp;&amp;  method.Parameters.Count == 1
                    &amp;&amp;  method.Parameters[0].ParameterType.FullName
                        == &quot;System.String&quot;)
                {
                    return method;
                }
            }
            if (type.BaseType.FullName == &quot;System.Object&quot;)
                return null;
            return FindRaisePropertyChangedMethod(
                type.BaseType.Resolve());
        }

        [Required]
        public string AssemblyPath { get; set; }
    }
}
</pre>
<p>5.<br />
<strong>Compile the task assembly</strong>,</p>
<p>and copy it to &#8220;$(SolutionDir)..libMSBuildMSBuildTasks.dll&#8221; folder along with Mono.Cecil.dll and Mono.Cecil.Pdb.dll assemblies.</p>
<p>4.<br />
Finally <strong>modify your Silverlight/WPF project (.csproj file)</strong>:</p>
<pre class="brush: xml;">
&lt;project&gt;
  ...
  &lt;usingTask TaskName=&quot;MSBuildTasks.NotifyPropertyChangedTask&quot; AssemblyFile=&quot;$(SolutionDir)..libMSBuildMSBuildTasks.dll&quot; /&gt;
  &lt;target Name=&quot;AfterCompile&quot;&gt;
    &lt;msbuildTasks.NotifyPropertyChangedTask AssemblyPath=&quot;$(ProjectDir)obj$(Configuration)$(TargetFileName)&quot; /&gt;
  &lt;/target&gt;
&lt;/project&gt;
</pre>
<p>Voila! Enjoy!</p>
<p>Here&#8217;s the source code of the MSBuildTasks project:<br />
<a href='http://www.limilabs.com/blog/wp-content/uploads/2011/05/MSBuildTasks.zip'>MSBuildTasks</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/inotifypropertychanged-with-custom-targets/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Update NuSpec version from MsBuild</title>
		<link>http://www.limilabs.com/blog/update-nuspec-version-from-msbuild?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=update-nuspec-version-from-msbuild</link>
		<comments>http://www.limilabs.com/blog/update-nuspec-version-from-msbuild#comments</comments>
		<pubDate>Fri, 08 Oct 2010 13:08:28 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Presentation]]></category>
		<category><![CDATA[MsBuild]]></category>
		<category><![CDATA[NuGet]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=1185</guid>
		<description><![CDATA[Here&#8217;s the sample script that updates NuGet version node in NuSpec file: &#60;target Name=&#34;UpdateNuspec&#34;&#62; &#60;getAssemblyIdentity AssemblyFiles=&#34;$(ReleaseFolder)/Redistributables/YourAssembly.dll&#34;&#62; &#60;output TaskParameter=&#34;Assemblies&#34; ItemName=&#34;YourAssemblyInfo&#34;/&#62; &#60;/getAssemblyIdentity&#62; &#60;xmlUpdate Prefix=&#34;nu&#34; Namespace=&#34;http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd&#34; XmlFileName=&#34;YourAssembly.nuspec&#34; XPath=&#34;package/nu:metadata/nu:version&#34; Value=&#34;%(YourAssemblyInfo.Version)&#34;/&#62; &#60;/target&#62;]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s the sample script that updates NuGet version node in NuSpec file:</p>
<pre class="brush: xml;">
&lt;target Name=&quot;UpdateNuspec&quot;&gt;
    &lt;getAssemblyIdentity AssemblyFiles=&quot;$(ReleaseFolder)/Redistributables/YourAssembly.dll&quot;&gt;
      &lt;output TaskParameter=&quot;Assemblies&quot; ItemName=&quot;YourAssemblyInfo&quot;/&gt;
    &lt;/getAssemblyIdentity&gt;
    &lt;xmlUpdate
        Prefix=&quot;nu&quot;
        Namespace=&quot;http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd&quot;
        XmlFileName=&quot;YourAssembly.nuspec&quot;
        XPath=&quot;package/nu:metadata/nu:version&quot;
        Value=&quot;%(YourAssemblyInfo.Version)&quot;/&gt;
&lt;/target&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/update-nuspec-version-from-msbuild/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>INotifyPropertyChanged with lambdas</title>
		<link>http://www.limilabs.com/blog/inotifypropertychanged-with-lambdas?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=inotifypropertychanged-with-lambdas</link>
		<comments>http://www.limilabs.com/blog/inotifypropertychanged-with-lambdas#comments</comments>
		<pubDate>Tue, 16 Feb 2010 21:48:22 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=475</guid>
		<description><![CDATA[There are several ways of implementing INotifyPropertyChanged in WPF applications. One that I particularly like is by using PostSharp to implement INotifyPropertyChanged. If you are not comfortable with PostSharp you can at least get rid of those nasty strings in standard implementation: public class Model : ViewModeBase { private string _status; public string Status { [...]]]></description>
			<content:encoded><![CDATA[<p>There are several ways of implementing <em>INotifyPropertyChanged</em> in WPF applications.</p>
<p>One that I particularly like is by using <a href="http://www.limilabs.com/blog/inotifypropertychanged-with-postsharp">PostSharp to implement INotifyPropertyChanged</a>.</p>
<p>If you are not comfortable with PostSharp you can at least get rid of those nasty strings in standard implementation:</p>
<pre class="brush: csharp;">
public class Model : ViewModeBase
{
    private string _status;
    public string Status
    {
        get { return _status; }
        set
        {
            _status = value;
            OnPropertyChanged(&quot;Status&quot;);
        }
    }
};
</pre>
<p>Labda expressions look nicer and are easier to refactor:</p>
<pre class="brush: csharp;">
public class MyModel : ViewModeBase
{
    private string _status;
    public string Status
    {
        get { return _status; }
        set
        {
            _status = value;
            OnPropertyChanged(() =&gt; Status);
        }
    }
};
</pre>
<p>First thing we need to do is to create base class for all our ViewModels:</p>
<pre class="brush: csharp;">
public class ViewModelBase
{
    public event PropertyChangedEventHandler PropertyChanged
        = delegate { };

    protected void OnPropertyChanged(
        Expression&lt;func&lt;object&gt;&gt; expression)
    {
        string propertyName = PropertyName.For(expression);
        this.PropertyChanged(
            this,
            new PropertyChangedEventArgs(propertyName));
    }
};
</pre>
<p>The implementation of PropertyName.For is very straightforward: <a href="http://www.limilabs.com/blog/property-name-from-lambda">How to get property name from lambda</a>.</p>
<p>That&#8217;s it!<br />
Nice, easy to refactor, compile-time checked <em>INotifyPropertyChanged</em> implementation.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/inotifypropertychanged-with-lambdas/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Background processing in WinForms</title>
		<link>http://www.limilabs.com/blog/background-processing-in-winforms?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=background-processing-in-winforms</link>
		<comments>http://www.limilabs.com/blog/background-processing-in-winforms#comments</comments>
		<pubDate>Wed, 03 Feb 2010 16:00:59 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WinForms]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=406</guid>
		<description><![CDATA[Many times developing windows applications, you&#8217;ll need to perform some operations in background. The problem you&#8217;ll face sooner or later is that those operations need to inform User Interface (UI) about their progress and completion. UI doesn&#8217;t like to be informed about anything from a different thread: you&#8217;ll get nasty &#8220;Cross-thread operation not valid&#8221; exception [...]]]></description>
			<content:encoded><![CDATA[<p>Many times developing windows applications, you&#8217;ll need to perform some operations in <strong>background</strong>.</p>
<p>The problem you&#8217;ll face sooner or later is that those operations need to<strong> inform User Interface</strong> (UI) about their <strong>progress </strong>and <strong>completion</strong>.</p>
<p>UI doesn&#8217;t like to be informed about anything from a different thread: you&#8217;ll get nasty &#8220;<strong>Cross-thread operation not valid</strong>&#8221; exception from WinForms controls, if you try.</p>
<p>Let&#8217;s take a look at the sample Presenter code:</p>
<pre class="brush: csharp;">
public void Start()
{
        TaskStatus taskStatus = this._backupService.CreateTask();
        taskStatus.Completed += BackupFinished;
        this._backupService.Start(taskStatus);
}
</pre>
<p><strong>TaskStatus</strong> contains single event Completed.<br />
What&#8217;ll do is that we&#8217;ll subscribe to this event to display some information on the View:</p>
<pre class="brush: csharp;">
public void BackupFinished(object sender, EventArgs e)
{
        // If the operation is done on different thread,
        // you'll get &quot;Cross-thread operation not valid&quot;
        // exception from WinForms controls here.
        this.View.ShowMessage(&quot;Finished!&quot;);
}
</pre>
<p>So, what are the options:</p>
<ul>
<li>Use <em>Control.BeginInvoke</em> in View &#8211; makes your code unreadable</li>
<li><a href="http://www.limilabs.com/blog/cross-thread-operations-with-postsharp">Use Control.BeginInvoke with PostSharp</a> &#8211; you need PostSharp</li>
<li><strong>SynchronizationContext</strong></li>
</ul>
<p>Lets examine the last concept as SynchronizationContext is not a well-know-class in the .NET world.<br />
Generally speaking this class is useful for synchronizing calls from worker thread to UI thread.</p>
<p>It has a static <em>Current</em> property that gets the synchronization context for the current thread or null if there is no UI thread (e.g. in Console application)</p>
<p>This is the <em>TaskStatus</em> class that utilizes <em>SynchronizationContext.Current</em> if it is not null:</p>
<pre class="brush: csharp;">
public class TaskStatus
{
    private readonly SynchronizationContext _context;

    public event EventHandler Completed = delegate { };

    public TaskStatus()
    {
        _context = SynchronizationContext.Current;
    }

    internal void OnCompleted()
    {
        Synchronize(x =&gt; this.Completed(this, EventArgs.Empty));
    }

    private void Synchronize(SendOrPostCallback callback)
    {
        if (_context != null)
            _context.Post(callback, null);
        else
            callback(null);
    }
};
</pre>
<p>Now lets see some tests.</p>
<p>First we&#8217;ll check if the event is executed:</p>
<pre class="brush: csharp;">
[Test]
public void Completed_RaisesCompleted()
{
    using(SyncContextHelper.No())
    {
        bool wasFired = false;
        TaskStatus status = new TaskStatus();
        status.Completed += (sender, args) =&gt; { wasFired = true; };
        status.OnCompleted();
        Assert.IsTrue(wasFired);
    }
}
</pre>
<p>The following test shows that in <strong>WindowsForms application</strong>, although operation is executed on different thread, Completed<strong> event is routed</strong> back (using windows message queue) <strong>to the UI thread</strong>:</p>
<pre class="brush: csharp;">
[Test]
public void Completed_WithSyncContext_IsExecutedOnSameThread()
{
    using (SyncContextHelper.WinForms())
    {
         int completedOnThread = -1;
         int thisThread = Thread.CurrentThread.GetHashCode();

         TaskStatus status = new TaskStatus();
         status.Completed += (sender, args) =&gt;
             {
                 completedOnThread =
                    Thread.CurrentThread.GetHashCode();
             };

         Scenario.ExecuteOnSeparateThread(status.OnCompleted);

         // process messages send from background thread
         // (like Completed event)
         Application.DoEvents();

         Assert.AreEqual(thisThread, completedOnThread);
    }
}
</pre>
<p>When there is no SynchronizationContext (<em>SynchronizationContext.Current</em> == <em>null</em>) <em>Completed</em> event is executed on the different thread:</p>
<pre class="brush: csharp;">
[Test]
public void Completed_InMultiThreadedScenario_IsExecuedOnDifferentThread()
{
    using(SyncContextHelper.No())
    {
        int completedOnThread = -1;
        int thisThread = Thread.CurrentThread.GetHashCode();

        TaskStatus status = new TaskStatus();
        status.Completed += (sender, args) =&gt;
            {
                completedOnThread =
                    Thread.CurrentThread.GetHashCode();
            };

        Scenario.ExecuteOnSeparateThread(status.OnCompleted);

        Assert.AreNotEqual(thisThread, completedOnThread);
    }
}
</pre>
<p>Finally unit test helper classes:</p>
<pre class="brush: csharp;">
public class SyncContextHelper : IDisposable
{
    private readonly SynchronizationContext _previous;

    private SyncContextHelper(SynchronizationContext context)
    {
        _previous = SynchronizationContext.Current;
        SynchronizationContext.SetSynchronizationContext(context);
    }

    public static SyncContextHelper WinForms()
    {
        return new SyncContextHelper(
            new WindowsFormsSynchronizationContext());
    }

    public static SyncContextHelper No()
    {
        return new SyncContextHelper(null);
    }

    public void Dispose()
    {
        SynchronizationContext.SetSynchronizationContext(_previous);
    }
};
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/background-processing-in-winforms/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Cross-thread operations with PostSharp</title>
		<link>http://www.limilabs.com/blog/cross-thread-operations-with-postsharp?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=cross-thread-operations-with-postsharp</link>
		<comments>http://www.limilabs.com/blog/cross-thread-operations-with-postsharp#comments</comments>
		<pubDate>Tue, 26 Jan 2010 15:00:43 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[PostSharp]]></category>
		<category><![CDATA[WinForms]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=101</guid>
		<description><![CDATA[When you try to inform User Interface (UI) about the background operation progress or completion, you can not do it from the background thread. UI doesn&#8217;t like to be informed about anything from a different thread: you&#8217;ll get &#8220;System.InvalidOperationException: Cross-thread operation not valid: Control &#8216;xxx&#8217; accessed from a thread other than the thread it was [...]]]></description>
			<content:encoded><![CDATA[<p>When you try to <strong> inform User Interface</strong> (UI) about the <strong>background operation progress</strong> or <strong>completion</strong>, you can not do it from the background thread.</p>
<p>UI doesn&#8217;t like to be informed about anything from a different thread: you&#8217;ll get <strong>&#8220;System.InvalidOperationException: Cross-thread operation not valid: Control &#8216;xxx&#8217; accessed from a thread other than the thread it was created on.&#8221;</strong> exception from WinForms control, if you try:</p>
<pre class="brush: csharp;">
public void ShowStatus(ApplicationStatus status)
{
    this._lblServiceAddress.Text = &quot;Connected to: &quot;
        + status.WebServiceAddress;
    this._lblUserId.Text = &quot;Working as: &quot;
        + status.UserId;
}
</pre>
<p>The easiest sollution is to use <em>BeginInvoke </em>method on the control <em>Control</em> or <em>Form</em>:</p>
<pre class="brush: csharp;">
public void ShowStatus(ApplicationStatus status)
{
    this.BeginInvoke((MethodInvoker)(() =&gt;
        {
            this._lblServiceAddress.Text = &quot;Connected to: &quot;
                + status.WebServiceAddress;
            this._lblUserId.Text = &quot;Working as: &quot;
                + status.UserId;
        }));
}
</pre>
<p>Well, it&#8217;s fun to write this once, but if you have many operations done in background sooner or later you&#8217;d like to have something nicer. Like an <strong>attribute</strong> for example:</p>
<pre class="brush: csharp;">
[ThreadAccessibleUI]
public void ShowStatus(ApplicationStatus status)
{
    this._lblServiceAddress.Text = &quot;Connected to: &quot; + status.WebServiceAddress;
    this._lblUserId.Text = &quot;Working as: &quot; + status.UserId;
}
</pre>
<p>Here&#8217;s the attribute implementation of such attribute using PostSharp 1.5:</p>
<pre class="brush: csharp;">
/// &lt;summary&gt;
/// PostSharp attribute.
/// Use it to mark Control's methods that
/// are invoked from background thread.
/// &lt;/summary&gt;
/// &lt;remarks&gt;
/// Be careful as BeginInvoke uses the message queue.
/// This means that the interface will be refreshed
/// when application has a chance to process its messages.
/// &lt;/remarks&gt;
[AttributeUsage(AttributeTargets.Method)]
[Serializable] // required by PostSharp
public class ThreadAccessibleUIAttribute : OnMethodInvocationAspect
{
    public override void OnInvocation(
        MethodInvocationEventArgs eventArgs)
    {
        Control control = eventArgs.Instance as Control;
        if (control == null)
            throw new ApplicationException(
                &quot;ThreadAccessibleUIAttribute&quot; +
                &quot;can be applied only to methods on Control class&quot;);

        // The form may be closed before
        // this method is called from another thread.
        if (control.Created == false)
            return;

        control.BeginInvoke((MethodInvoker)eventArgs.Proceed);
    }
};
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/cross-thread-operations-with-postsharp/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>M-V-VM talk</title>
		<link>http://www.limilabs.com/blog/m-v-vm-talk?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=m-v-vm-talk</link>
		<comments>http://www.limilabs.com/blog/m-v-vm-talk#comments</comments>
		<pubDate>Tue, 13 Oct 2009 08:49:58 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Presentation]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=184</guid>
		<description><![CDATA[Here are the slide-show and code from my recent M-V-VM talk on the Warsaw .NET group. I was talking about different flavors of MVVM, blendability, unit testing and separation of concerns. All in all, I think it was a good talk with great audience participation. MVVM_Presentation MyMVVMSample]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.limilabs.com/blog/wp-content/uploads/2009/10/thumbnail.jpeg" alt="thumbnail" title="thumbnail" width="256" height="192" class="alignleft size-full wp-image-185" /><br />
Here are the slide-show and code from my recent M-V-VM talk on the Warsaw .NET group. I was talking about different flavors of MVVM, blendability, unit testing and separation of concerns. All in all, I think it was a good talk with great audience participation.</p>
<p><a href='http://www.limilabs.com/blog/wp-content/uploads/2009/10/MVVM_Presentation.pptx'>MVVM_Presentation</a><br />
<a href='http://www.limilabs.com/blog/wp-content/uploads/2009/10/MyMVVMSample.zip'>MyMVVMSample</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/m-v-vm-talk/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Printing in WebBrowser control (custom header and footer)</title>
		<link>http://www.limilabs.com/blog/printing-in-webbrowser-control-custom-header-and-footer?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=printing-in-webbrowser-control-custom-header-and-footer</link>
		<comments>http://www.limilabs.com/blog/printing-in-webbrowser-control-custom-header-and-footer#comments</comments>
		<pubDate>Tue, 29 Sep 2009 08:00:50 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=103</guid>
		<description><![CDATA[This is going to be a complicated one. Whole code/working sample is near the end of the article. The Task: Enable HTML printing using WebBrowser content but modify standard header and footer. Unfortunately, when we print, nasty footer and header appear, and there is no way to get rid of them: ShowPrintDialog method comment explicitly [...]]]></description>
			<content:encoded><![CDATA[<p>This is going to be a complicated one. Whole code/working sample is near the end of the article.</p>
<p><strong>The Task:</strong><br />
Enable HTML printing using WebBrowser content <strong>but modify standard header and footer</strong>.</p>
<p><a href="http://www.limilabs.com/blog/wp-content/uploads/2009/09/SampleApp.png"><img src="http://www.limilabs.com/blog/wp-content/uploads/2009/09/SampleApp.png" alt="SampleApp" title="SampleApp" width="532" height="325" class="alignnone size-full wp-image-111" /></a></p>
<p>Unfortunately, when we print, <strong>nasty footer and header appear</strong>, and there is no way to get rid of them:<br />
<a href="http://www.limilabs.com/blog/wp-content/uploads/2009/09/NastyFooter.png"><img src="http://www.limilabs.com/blog/wp-content/uploads/2009/09/NastyFooter.png" alt="NastyFooter" title="NastyFooter" width="542" height="87" class="alignnone size-full wp-image-109" /></a></p>
<p>ShowPrintDialog method comment explicitly says that header and footer can not be modified:<br />
<a href="http://www.limilabs.com/blog/wp-content/uploads/2009/09/ShowPrintDialog.png"><img src="http://www.limilabs.com/blog/wp-content/uploads/2009/09/ShowPrintDialog.png" alt="ShowPrintDialog" title="ShowPrintDialog" width="479" height="58" class="alignnone size-full wp-image-112" /></a></p>
<p><strong>The Big Plan:</strong><br />
1. First we create IEPrinting.dll written in c++ and managed c++, it exposes one extremely simple helper class: <em>PrintHelper</em>:</p>
<pre class="brush: cpp;">
// PrintHelper.h
#pragma once
using namespace System;
namespace IEPrinting
{
	public ref class PrintHelper
	{
		public:
			static void Print(IntPtr^ ptrIWebBrowser2, String^ header, String^ footer);
	};
}
</pre>
<p>2.<br />
From now on things get complicated:</p>
<pre class="brush: cpp;">
// This is the main DLL file.
#include &quot;stdafx.h&quot;
#include &quot;PrintHelper.h&quot;

namespace IEPrinting
{
#pragma unmanaged

int UnmanagedPrint(IWebBrowser2* webOC, BSTR header, BSTR footer)
{
	SAFEARRAYBOUND psabBounds[1];
	SAFEARRAY *psaHeadFoot;
	HRESULT hr = S_OK;

	// Variables needed to send IStream header to print operation.
	HGLOBAL hG = 0;
	IStream *pStream= NULL;
	IUnknown *pUnk = NULL;
	ULONG lWrote = 0;
	LPSTR sMem = NULL;

	// Initialize header and footer parameters to send to ExecWB().
	psabBounds[0].lLbound = 0;
	psabBounds[0].cElements = 3;
	psaHeadFoot = SafeArrayCreate(VT_VARIANT, 1, psabBounds);
	if (NULL == psaHeadFoot) {
		// Error handling goes here.
		goto cleanup;
	}
	VARIANT vHeadStr, vFootStr, vHeadTxtStream;
	long rgIndices;
	VariantInit(&amp;vHeadStr);
	VariantInit(&amp;vFootStr);
	VariantInit(&amp;vHeadTxtStream);

	// Argument 1: Header
	vHeadStr.vt = VT_BSTR;
	vHeadStr.bstrVal = header;
	if (vHeadStr.bstrVal == NULL) {
		goto cleanup;
	}

	// Argument 2: Footer
	vFootStr.vt = VT_BSTR;
	vFootStr.bstrVal = footer;
	if (vFootStr.bstrVal == NULL) {
		goto cleanup;
	}

	// Argument 3: IStream containing header text. Outlook and Outlook
         // Express use this to print out the mail header.
	if ((sMem = (LPSTR)CoTaskMemAlloc(512)) == NULL) {
		goto cleanup;
	}
	// We must pass in a full HTML file here, otherwise this
         // becomes corrupted when we print.
	sprintf_s(sMem, 512, &quot;&lt;html&gt;&lt;body&gt;&lt;strong&gt;Printed By:&lt;/strong&gt;
	 Custom WebBrowser Host 1.0&lt;p&gt;&lt;/body&gt;&lt;/html&gt;&quot;);

	// Allocate an IStream for the LPSTR that we just created.
	hG = GlobalAlloc(GMEM_FIXED | GMEM_ZEROINIT, strlen(sMem));
	if (hG == NULL) {
		goto cleanup;
	}
	hr = CreateStreamOnHGlobal(hG, TRUE, &amp;pStream);
	if (FAILED(hr)) {
		//ATLTRACE(_T(&quot;OnPrint::Failed to create stream from HGlobal: %lXn&quot;), hr);
		goto cleanup;
	}
	hr = pStream-&gt;Write(sMem, strlen(sMem), &amp;lWrote);
	if (SUCCEEDED(hr)) {
	    // Set the stream back to its starting position.
		LARGE_INTEGER pos;
		pos.QuadPart = 0;
		pStream-&gt;Seek((LARGE_INTEGER)pos, STREAM_SEEK_SET, NULL);
		hr = pStream-&gt;QueryInterface(IID_IUnknown, reinterpret_cast&lt;void **&gt;(&amp;pUnk));
		vHeadTxtStream.vt = VT_UNKNOWN;
		vHeadTxtStream.punkVal = pUnk;
	}

	rgIndices = 0;
	SafeArrayPutElement(psaHeadFoot, &amp;rgIndices, static_cast&lt;void *&gt;(vHeadStr));
	rgIndices = 1;
	SafeArrayPutElement(psaHeadFoot, &amp;rgIndices, static_cast&lt;void *&gt;(&amp;vFootStr));
	rgIndices = 2;
	SafeArrayPutElement(psaHeadFoot, &amp;rgIndices, static_cast&lt;void *&gt;(&amp;vHeadTxtStream));

	//NOTE: Currently, the SAFEARRAY variant must be passed by using
	// the VT_BYREF vartype when you call the ExecWeb method.
	VARIANT vArg;
	VariantInit(&amp;vArg);
	vArg.vt = VT_ARRAY | VT_BYREF;
	vArg.parray = psaHeadFoot;

	//OLECMDEXECOPT_PROMPTUSER
	hr = webOC-&gt;ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_PROMPTUSER, &amp;vArg, NULL);

	if (FAILED(hr)) {
		//ATLTRACE(_T(&quot;DoPrint: Call to WebBrowser's ExecWB failed: %lXn&quot;), hr);
		goto cleanup;
	}
	return 1;
	//WebBrowser control will clean up the SAFEARRAY after printing.
	cleanup:
	VariantClear(&amp;vHeadStr);
	VariantClear(&amp;vFootStr);
	VariantClear(&amp;vHeadTxtStream);
	if (psaHeadFoot) {
		SafeArrayDestroy(psaHeadFoot);
	}
	if (sMem) {
		CoTaskMemFree(sMem);
	}
	if (hG != NULL) {
		GlobalFree(hG);
	}
	if (pStream != NULL) {
		pStream-&gt;Release();
		pStream = NULL;
	}
	//bHandled = TRUE;
	return 0;
}
#pragma managed

	void PrintHelper::Print(IntPtr^ ptrIWebBrowser2, String^ header,  String^ footer)
	{
		IWebBrowser2* pBrowser = (IWebBrowser2 *)ptrIWebBrowser2-&gt;ToPointer();

		IDispatch *pDisp;
		pBrowser-&gt;get_Document(&amp;pDisp);

		IHTMLDocument2 *pDoc;
		pDisp-&gt;QueryInterface&lt;ihtmldocument2&gt;(&amp;pDoc);

		IHTMLElement *body;
		pDoc-&gt;get_body(&amp;body);

		BSTR p;
		body-&gt;get_innerHTML(&amp;p);

		IntPtr pHeader = Runtime::InteropServices::Marshal::StringToBSTR(header);
		IntPtr pFooter = Runtime::InteropServices::Marshal::StringToBSTR(footer);

		UnmanagedPrint(pBrowser, (BSTR)pHeader.ToPointer(), (BSTR)pFooter.ToPointer());
	}
}
</pre>
<p>3.<br />
Now we need to generate C# version of the <em>IWebBrowser2 </em>COM interface:<br />
It can be generated from idl -> tlb -> dll and the referenced from the WindowsForms app.</p>
<pre class="brush: plain;">
midl ExDisp.Idl /tlb ExDisp.tlb
pause
tlbimp ExDisp.tlb /out:ExDisp.dll
pause
</pre>
<p>4.<br />
Then we create WindowsForms project, and create custom control inheriting<br />
from <em>WebBrowser </em> control.<br />
We need this to access IWebBrowser2 interface (defined in ExDisp.dll):</p>
<pre class="brush: csharp;">
using ExDisp;
using WebBrowser = System.Windows.Forms.WebBrowser;

namespace WindowsFormsApplication1.MyBrowser
{
    public class MyWebBrowser : WebBrowser
    {
        public IWebBrowser2 axIWebBrowser2;

        protected override void AttachInterfaces(object nativeActiveXObject)
        {
            base.AttachInterfaces(nativeActiveXObject);
            this.axIWebBrowser2 = (IWebBrowser2) nativeActiveXObject;
        }

        protected override void DetachInterfaces()
        {
            base.DetachInterfaces();
            this.axIWebBrowser2 = null;
        }
    };
}
</pre>
<p>5.<br />
Finally we create a Form and add the printing code there:</p>
<pre class="brush: cpp;">
private void _btnPrint_Click(object sender, EventArgs e)
{
    IntPtr ptr = Marshal.GetComInterfaceForObject(
        webBrowser1.axIWebBrowser2,
        typeof(IWebBrowser2));
    PrintHelper.Print(ptr, &quot;this is my header&quot;, &quot;this is my footer&quot;);
}
</pre>
<p>Modified the header and footer:<br />
<a href="http://www.limilabs.com/blog/wp-content/uploads/2009/09/NiceFooter.png"><img src="http://www.limilabs.com/blog/wp-content/uploads/2009/09/NiceFooter.png" alt="NiceFooter" title="NiceFooter" width="498" height="39" class="alignnone size-full wp-image-110" /></a></p>
<p><strong>The Zip:</strong><br />
<a href='http://www.limilabs.com/blog/wp-content/uploads/2009/09/IEPrinting.zip'>IEPrinting</a></p>
<p><strong>References:</strong><br />
<a href="http://support.microsoft.com/kb/267240" rel="nofollow">http://support.microsoft.com/kb/267240</a><br />
<a href="http://thedotnet.com/nntp/97691/showpost.aspx" rel="nofollow">http://thedotnet.com/nntp/97691/showpost.aspx</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/printing-in-webbrowser-control-custom-header-and-footer/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Assemblers with ConvertAll</title>
		<link>http://www.limilabs.com/blog/assemblers-with-convertall?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=assemblers-with-convertall</link>
		<comments>http://www.limilabs.com/blog/assemblers-with-convertall#comments</comments>
		<pubDate>Fri, 18 Sep 2009 12:44:03 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=42</guid>
		<description><![CDATA[In most applications we have some kind of assembler classes, that create models used in the presentation layer: public class EntityComboModelAssembler { public List&#60;comboBoxModel&#62; CreateComboBoxModels(IList&#60;entity&#62; entities) { List&#60;comboBoxModel&#62; list = new List&#60;comboBoxModel&#62;(); foreach (Entityentity in entities) { list.Add(new ComboBoxModel(entity, entity.Name)); } return list; } } It is possible to write this code in 1 (one) [...]]]></description>
			<content:encoded><![CDATA[<p>In most applications we have some kind of <strong>assembler classes</strong>, that create models <strong>used in the presentation layer</strong>:</p>
<pre class="brush: csharp;">
public class EntityComboModelAssembler
{
   public List&lt;comboBoxModel&gt; CreateComboBoxModels(IList&lt;entity&gt; entities)
   {
      List&lt;comboBoxModel&gt; list = new List&lt;comboBoxModel&gt;();
      foreach (Entityentity in entities)
      {
         list.Add(new ComboBoxModel(entity, entity.Name));
      }
      return list;
   }
}
</pre>
<p>It is possible to write this code in 1 (one) line of code:</p>
<pre class="brush: csharp;">
public class EntityComboModelAssembler
{
   public List&lt;comboBoxModel&gt; CreateComboBoxModels(IList&lt;entity&gt; entities)
   {
      return entities.AsList().ConvertAll(x =&gt; new ComboBoxModel(x, x.Name));
   }
}
</pre>
<p>We can also remove <em>AsList</em> method by using extension method that adds <em>ConvertAll </em>method to <em>IList </em>interface:</p>
<pre class="brush: csharp;">
public static class IListExtensions
{
   public static List&lt;tout&gt; ConvertAll&lt;tin, TOut&gt;(this IList&lt;tin&gt; source, Converter&lt;tin, TOut&gt; converter)
   {
      return source.ToList().ConvertAll(converter);
   }
}
</pre>
<p>And the final code:</p>
<pre class="brush: csharp;">
public class EntityComboModelAssembler
{
   public List&lt;comboBoxModel&gt; CreateComboBoxModels(IList&lt;entity&gt; entities)
   {
      return entities.ConvertAll(x =&gt; new ComboBoxModel(x, x.Name));
   }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/assemblers-with-convertall/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>INotifyPropertyChanged with PostSharp 1.5</title>
		<link>http://www.limilabs.com/blog/inotifypropertychanged-with-postsharp?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=inotifypropertychanged-with-postsharp</link>
		<comments>http://www.limilabs.com/blog/inotifypropertychanged-with-postsharp#comments</comments>
		<pubDate>Tue, 15 Sep 2009 12:03:01 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[AOP]]></category>
		<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[PostSharp]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=14</guid>
		<description><![CDATA[If you are doing WPF development, most likely you are tired of writing property implementations that raise PropertyChanged event manually: public class MainWindowViewModel : ViewModel { private string _message; public string Message { get { return _message; } set { _message = value; OnPropertyChanged(&#34;Message&#34;); } } // ... } PostSharp is a great tool to [...]]]></description>
			<content:encoded><![CDATA[<p>If you are doing WPF development, most likely you are tired of writing property implementations that raise <em>PropertyChanged</em> event manually:</p>
<pre class="brush: csharp;">
public class MainWindowViewModel : ViewModel
{
    private string _message;

    public string Message
    {
        get
        {
            return _message;
        }
        set
        {
            _message = value;
            OnPropertyChanged(&quot;Message&quot;);
        }
    }

    // ...
}
</pre>
<p><a href="http://www.postsharp.org">PostSharp</a> is a great tool to make such things simplier.</p>
<p>Let&#8217;s look at the specific ViewModel class that has a <em>Message</em> property that is <strong>bound to some UI element</strong> using XAML:</p>
<pre class="brush: csharp;">
public class MainWindowViewModel : ViewModel
{
    [RaisePropertyChanged]
    public string Message { get; set; }

    // ...
}
</pre>
<p> Notice the <em>RaisePropertyChanged</em> attribute, which we&#8217;ll implement later.</p>
<p>Here&#8217;s our <strong>base ViewModel</strong> class that provides <strong>actual implementation</strong> of the <em>INotifyPropertyChanged</em> interface:</p>
<pre class="brush: csharp;">
public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged
        = delegate { };

    public void OnPropertyChanged(string propertyName)
    {
        PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
    }
};
</pre>
<p>Finally the PostSharp attribute:</p>
<pre class="brush: csharp;">
[Serializable]  // required by PostSharp
public class RaisePropertyChangedAttribute : OnMethodBoundaryAspect
{
    private string _propertyName;

    /// &lt;summary&gt;
    /// Executed at runtime, after the method.
    /// &lt;/summary&gt;
    public override void OnExit(MethodExecutionEventArgs eventArgs)
    {
        ViewModel viewModel = (ViewModel)eventArgs.Instance;
        viewModel.OnPropertyChanged(_propertyName);
    }

    public override bool CompileTimeValidate(MethodBase method)
    {
        if (IsPropertySetter(method))
        {
            _propertyName = GetPropertyName(method);
            return true;
        }
        return false;
    }

    private static string GetPropertyName(MethodBase method)
    {
        return method.Name.Replace&quot;set_&quot;, &quot;&quot;);
    }

    private static bool IsPropertySetter(MethodBase method)
    {
        return method.Name.StartsWith(&quot;set_&quot;);
    }
};
</pre>
<p>Note that we are validating if the method is in fact a property only during <strong>compilation time</strong> using <em>CompileTimeValidate</em> method.</p>
<p>During compile time appropriate invocations of <em>OnPropertyChanged</em> method will be <strong>injected after every set operation</strong> applied to the <em>Message</em> property.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/inotifypropertychanged-with-postsharp/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

