<?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>Lesnikowski Blog &#187; Programming</title>
	<atom:link href="http://www.lesnikowski.com/blog/index.php/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.lesnikowski.com/blog</link>
	<description>.Net</description>
	<lastBuildDate>Wed, 28 Jul 2010 10:10:07 +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>A non-blocking socket operation could not be completed</title>
		<link>http://www.lesnikowski.com/blog/index.php/a-non-blocking-socket-operation/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=a-non-blocking-socket-operation</link>
		<comments>http://www.lesnikowski.com/blog/index.php/a-non-blocking-socket-operation/#comments</comments>
		<pubDate>Mon, 12 Apr 2010 16:03:29 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[mono]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=809</guid>
		<description><![CDATA[There is a bug in .NET 2.0 regarding timeout handling by Socket class.
Here&#8217;s the code that reproduces this behavior. 

using(TcpClient client = new TcpClient())
{
    // Set timeout
    client.ReceiveTimeout =
        (int)TimeSpan.FromSeconds(1).TotalMilliseconds;

    // Connect to perfectly working imap server
   [...]]]></description>
			<content:encoded><![CDATA[<p>There is a bug in .NET 2.0 regarding timeout handling by Socket class.<br />
Here&#8217;s the code that reproduces this behavior. </p>
<pre class="brush: csharp;">
using(TcpClient client = new TcpClient())
{
    // Set timeout
    client.ReceiveTimeout =
        (int)TimeSpan.FromSeconds(1).TotalMilliseconds;

    // Connect to perfectly working imap server
    client.Connect(&quot;mail.lesnikowski.com&quot;, 143);

    // Create reader &amp; writer
    NetworkStream stream = client.GetStream();
    StreamReader reader = new StreamReader(stream);
    StreamWriter writer = new StreamWriter(stream);

    // Read hello line
    Console.WriteLine(reader.ReadLine());

    // this works with no problems
    writer.WriteLine(&quot;a NOOP&quot;);             // No operation command
    writer.Flush();
    Console.WriteLine(reader.ReadLine());   // No operation response

    try
    {
        reader.ReadLine();                  // Nothing to read
    }
    catch (Exception ex)                    // Timeout
    {
        Console.WriteLine(&quot;timeout&quot;);       // This is expected
    }

    writer.WriteLine(&quot;b NOOP&quot;);             // No operation command
    writer.Flush();

    // SocketException: A non-blocking socket operation
    // could not be completed immediately
    Console.WriteLine(reader.ReadLine());   

    client.Close();
}
</pre>
<p>The above code runs as expected on Mono and on .NET 4.0.</p>
<p>The problem is in UpdateStatusAfterSocketError internal Socket method that executes SetToDisconnected method when any exception is thrown, including timeout exception.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/a-non-blocking-socket-operation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ISession.Load returns object with zero ID</title>
		<link>http://www.lesnikowski.com/blog/index.php/isession-load-returns-object-with-zero-id/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=isession-load-returns-object-with-zero-id</link>
		<comments>http://www.lesnikowski.com/blog/index.php/isession-load-returns-object-with-zero-id/#comments</comments>
		<pubDate>Fri, 02 Apr 2010 09:09:32 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=789</guid>
		<description><![CDATA[
Recently we had a following problem with NHibernate, and although I love NHiberante, it does not always behave as expected.
We have a Person class correctly mapped in NHibernate:

public class Person
{
	public int Id { get; set; }
	public int Name { get; set; }
}

We saw that sometimes we were getting a Person with Id equal to zero, [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.lesnikowski.com/blog/wp-content/uploads/2009/12/nhibernate.gif" alt="" title="nhibernate" width="204" height="125" class="alignleft size-full wp-image-365" /><br />
Recently we had a following problem with <strong>NHibernate</strong>, and although I love NHiberante, it does not always behave as expected.</p>
<p>We have a Person class correctly mapped in NHibernate:</p>
<pre class="brush: csharp;">
public class Person
{
	public int Id { get; set; }
	public int Name { get; set; }
}
</pre>
<p>We saw that sometimes we were getting a Person with Id equal to zero, from our repository:</p>
<pre class="brush: csharp;">
public class PersonRepository
{
	private ISession _session;

	//...

	public Person LoadById(int id)
	{
		return _session.Load&lt;Person&gt;(id);
	}
}
</pre>
<p>We narrowed the problem down and wrote this little test:</p>
<pre class="brush: csharp;">
[Test]
public void LoadById_Loads_IdIsSet()
{
    _context.ExecuteInTransaction(() =&gt;
		{
			Person person = _context.PersonRepository.LoadById(7);
			Assert.AreEqual(7, person.Id);
		}
	);
}
</pre>
<p>&#8230;which of course failed.</p>
<p>After initial surprise, we took a second look at the Person class and we saw that we are missing <strong>virtual </strong> keyword on properties. NHibernate is not able to create a correct Proxy object.</p>
<pre class="brush: csharp;">
public class Person
{
	public virtual int Id { get; set; }
	public virtual int Name { get; set; }
}
</pre>
<p>This fixed the issue.<br />
Strange thing is that we expect that NHibernate would throw an exception is such case.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/isession-load-returns-object-with-zero-id/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>INotifyPropertyChanged with lambdas</title>
		<link>http://www.lesnikowski.com/blog/index.php/inotifypropertychanged-with-lambdas/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=inotifypropertychanged-with-lambdas</link>
		<comments>http://www.lesnikowski.com/blog/index.php/inotifypropertychanged-with-lambdas/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 21:48:22 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.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 [...]]]></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.lesnikowski.com/blog/index.php/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.lesnikowski.com/blog/index.php/property-name-from-lambda/">How to get property name from lambda</a>.</p>
<p>That&#8217;s it!<br />
Nice, easy to refactor, compilaile-time checked <em>INotifyPropertyChanged</em> implementation.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/inotifypropertychanged-with-lambdas/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to get property name from lambda</title>
		<link>http://www.lesnikowski.com/blog/index.php/property-name-from-lambda/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=property-name-from-lambda</link>
		<comments>http://www.lesnikowski.com/blog/index.php/property-name-from-lambda/#comments</comments>
		<pubDate>Tue, 09 Feb 2010 16:00:50 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=472</guid>
		<description><![CDATA[The whole idea is simple, we want this test to pass:

[Test]
void CanGetPropertyName_UsingLambda()
{
  Assert.AreEqual(&#34;Name&#34;, PropertyName.For&#60;Person&#62;(x =&#62; x.Name));
}

It seams nice and convenient way of getting property name.
Whole test fixture looks as follows:

[TestFixture]
public class PropertyNameTests
{
    public string NameForTest { get; set; }

    [Test]
    public void CanGetPropertyName_SameType_UsingLambda()
   [...]]]></description>
			<content:encoded><![CDATA[<p>The whole idea is simple, we want this test to pass:</p>
<pre class="brush: csharp;">
[Test]
void CanGetPropertyName_UsingLambda()
{
  Assert.AreEqual(&quot;Name&quot;, PropertyName.For&lt;Person&gt;(x =&gt; x.Name));
}
</pre>
<p>It seams nice and convenient way of getting property name.<br />
Whole test fixture looks as follows:</p>
<pre class="brush: csharp;">
[TestFixture]
public class PropertyNameTests
{
    public string NameForTest { get; set; }

    [Test]
    public void CanGetPropertyName_SameType_UsingLambda()
    {
        Assert.AreEqual(&quot;NameForTest&quot;,
            PropertyName.For(() =&gt; NameForTest));
    }

    [Test]
    public void CanGetPropertyName_UsingLambda()
    {
        Assert.AreEqual(&quot;Name&quot;,
            PropertyName.For&lt;Person&gt;(x =&gt; x.Name));
        Assert.AreEqual(&quot;Age&quot;,
            PropertyName.For&lt;Person&gt;(x =&gt; x.Age));
    }

    [Test]
    public void CanGetPropertyName_Composite_UsingLambda()
    {
        Assert.AreEqual(&quot;Home.City&quot;,
            PropertyName.For&lt;Person&gt;(x =&gt; x.Home.City));
        Assert.AreEqual(&quot;Home.FlatNumber&quot;,
            PropertyName.For&lt;Person&gt;(x =&gt; x.Home.FlatNumber));
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Home Home { get; set; }
}

public class Home
{
    public string City { get; set; }
    public string FlatNumber { get; set; }
}
</pre>
<p>Implementation uses .NET 3.5 feature called expression trees. Expression trees represent language-level code in the form of data. The data is stored in a tree-shaped structure.</p>
<pre class="brush: csharp;">
/// &lt;summary&gt;
/// Gets property name using lambda expressions.
/// &lt;/summary&gt;
internal class PropertyName
{
    public static string For&lt;T&gt;(
        Expression&lt;Func&lt;T, object&gt;&gt; expression)
    {
        Expression body = expression.Body;
        return GetMemberName(body);
    }

    public static string For(
        Expression&lt;Func&lt;object&gt;&gt; expression)
    {
        Expression body = expression.Body;
        return GetMemberName(body);
    }

    public static string GetMemberName(
        Expression expression)
    {
        if (expression is MemberExpression)
        {
            var memberExpression = (MemberExpression)expression;

            if (memberExpression.Expression.NodeType ==
                ExpressionType.MemberAccess)
            {
                return GetMemberName(memberExpression.Expression)
                    + &quot;.&quot;
                    + memberExpression.Member.Name;
            }
            return memberExpression.Member.Name;
        }

        if (expression is UnaryExpression)
        {
            var unaryExpression = (UnaryExpression)expression;

            if (unaryExpression.NodeType != ExpressionType.Convert)
                throw new Exception(string.Format(
                    &quot;Cannot interpret member from {0}&quot;,
                    expression));

            return GetMemberName(unaryExpression.Operand);
        }

        throw new Exception(string.Format(
            &quot;Could not determine member from {0}&quot;,
            expression));
    }
}
</pre>
<p><em>UnaryExpression</em> part is needed for value types to work.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/property-name-from-lambda/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Background processing in WinForms</title>
		<link>http://www.lesnikowski.com/blog/index.php/background-processing-in-winforms/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=background-processing-in-winforms</link>
		<comments>http://www.lesnikowski.com/blog/index.php/background-processing-in-winforms/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 16:00:59 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WinForms]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.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 from WinForms [...]]]></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.lesnikowski.com/blog/index.php/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.lesnikowski.com/blog/index.php/background-processing-in-winforms/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Testing DateTime.Now</title>
		<link>http://www.lesnikowski.com/blog/index.php/testing-datetime-now/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=testing-datetime-now</link>
		<comments>http://www.lesnikowski.com/blog/index.php/testing-datetime-now/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 16:07:18 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[UnitTesting]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=480</guid>
		<description><![CDATA[
When you are doing Test Driven Development (TDD) many time during the testing phase you&#8217;ll find yourself with a code that depends on current time.
It&#8217;s not possible write tests for this code as DateTime.Now changes constantly.
Let&#8217;s take a look at following method:

public string CreateName(...)
{
   return &#34;name &#34; + DateTime.Now;
}

The solution to this problem [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-486" title="clock" src="http://www.lesnikowski.com/blog/wp-content/uploads/2010/01/clock.jpg" alt="" width="211" height="142" /></p>
<p>When you are doing Test Driven Development (TDD) many time during the testing phase you&#8217;ll find yourself with a code that depends on current time.</p>
<p>It&#8217;s not possible write tests for this code as <strong>DateTime.Now changes constantly</strong>.</p>
<p>Let&#8217;s take a look at following method:</p>
<pre class="brush: csharp;">
public string CreateName(...)
{
   return &quot;name &quot; + DateTime.Now;
}
</pre>
<p>The solution to this problem is simple. We&#8217;ll introduce <em>Clock</em> class with the same interface as <em>DateTime</em>:</p>
<pre class="brush: csharp;">
public string CreateName(...)
{
   return &quot;name &quot; + Clock.Now;
}
</pre>
<p>We&#8217;d like the test to look something like this:</p>
<pre class="brush: csharp;">
[Test]
public void CreateName_AddsCurrentTimeAtEnd()
{
    using (Clock.NowIs(new DateTime(2010, 12, 31, 23, 59, 00)))
    {
        string name = new ReportNameService().CreateName(...);
        Assert.AreEqual(&quot;name 2010-12-31 23:59:00&quot;, name);
    }
}
</pre>
<p><strong>Tests should not leave any side effects</strong>. This is why we are using IDisposable pattern. After text execution <em>Clock.Now</em> is reverted and again returns current time.</p>
<p>Finally this is how <em>Clock</em> class looks like:</p>
<pre class="brush: csharp;">
public class Clock : IDisposable
{
    private static DateTime? _nowForTest;

    public static DateTime Now
    {
        get { return _nowForTest ?? DateTime.Now; }
    }

    public static IDisposable NowIs(DateTime dateTime)
    {
        _nowForTest = dateTime;
        return new Clock();
    }

    public void Dispose()
    {
        _nowForTest = null;
    }
};
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/testing-datetime-now/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Cross-thread operations with PostSharp</title>
		<link>http://www.lesnikowski.com/blog/index.php/cross-thread-operations-with-postsharp/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=cross-thread-operations-with-postsharp</link>
		<comments>http://www.lesnikowski.com/blog/index.php/cross-thread-operations-with-postsharp/#comments</comments>
		<pubDate>Tue, 26 Jan 2010 15:00:43 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[PostSharp]]></category>
		<category><![CDATA[WindowsForms]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.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.lesnikowski.com/blog/index.php/cross-thread-operations-with-postsharp/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>FindAll, ConvertAll are your friends</title>
		<link>http://www.lesnikowski.com/blog/index.php/findall-convertall-are-your-friends/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=findall-convertall-are-your-friends</link>
		<comments>http://www.lesnikowski.com/blog/index.php/findall-convertall-are-your-friends/#comments</comments>
		<pubDate>Wed, 06 Jan 2010 07:40:55 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=118</guid>
		<description><![CDATA[Let&#8217;s take a look at following code:

public List&#60;string&#62; GetDeleteWarnings_ForEach()
{
    List&#60;string&#62; messages = new List&#60;string&#62;();
    foreach (ItemReference reference in _itemReferences)
    {
        if (!reference.CanBeDeleted)
        {
          [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s take a look at following code:</p>
<pre class="brush: csharp;">
public List&lt;string&gt; GetDeleteWarnings_ForEach()
{
    List&lt;string&gt; messages = new List&lt;string&gt;();
    foreach (ItemReference reference in _itemReferences)
    {
        if (!reference.CanBeDeleted)
        {
            messages.Add(reference.DeleteMessage);
        }
    }
    return messages;
}
</pre>
<p>Using <em>FindAll </em>and <em>ConvertAll</em> you can do it in one, very obvious, line:</p>
<pre class="brush: csharp;">
public List&lt;string&gt; GetDeleteWarnings_Fluently()
{
    return _itemReferences
        .FindAll(x =&gt; !x.CanBeDeleted)
        .ConvertAll(x =&gt; x.DeleteMessage);
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/findall-convertall-are-your-friends/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dictionary: SerializationException</title>
		<link>http://www.lesnikowski.com/blog/index.php/dictionary-serializationexception/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=dictionary-serializationexception</link>
		<comments>http://www.lesnikowski.com/blog/index.php/dictionary-serializationexception/#comments</comments>
		<pubDate>Wed, 30 Dec 2009 15:43:20 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=392</guid>
		<description><![CDATA[When you to inherit your custom dictionary from Dictionary class you&#8217;ll get nasty exception during deserialization:
System.Runtime.Serialization.SerializationException : The constructor to deserialize an object of type &#8216;SafeDictionary`2[System.String,System.String]&#8216; was not found.

[Serializable]
internal class SafeDictionary&#60;K, V&#62; : Dictionary&#60;K, V&#62;
{
    public new V this[K key]
    {
         [...]]]></description>
			<content:encoded><![CDATA[<p>When you to inherit your custom dictionary from <em>Dictionary<k,V></em> class you&#8217;ll get nasty exception during deserialization:</p>
<p><strong>System.Runtime.Serialization.SerializationException : The constructor to deserialize an object of type &#8216;SafeDictionary`2[System.String,System.String]&#8216; was not found.</strong></p>
<pre class="brush: csharp;">
[Serializable]
internal class SafeDictionary&lt;K, V&gt; : Dictionary&lt;K, V&gt;
{
    public new V this[K key]
    {
            get
            {
                V value;
                if (this.TryGetValue(key, out value) == true)
                    return value;
                return default(V);
            }
            set
            {
                base[key] = value;
            }
    }

     public SafeDictionary()
    {
    }
};
</pre>
<p>Here&#8217;s the test:</p>
<pre class="brush: csharp;">
[Test]
public void IsSerializable()
{
    SafeDictionary&lt;string,string&gt; dictionary =
        new SafeDictionary&lt;string, string&gt;();
    dictionary[&quot;key&quot;] = &quot;value&quot;;
    dictionary =
        SerializationHelper.SerializeAndDeserialize(dictionary);
    Assert.AreEqual(&quot;value&quot;, dictionary[&quot;key&quot;]);
}
</pre>
<p>And serialization utility class:</p>
<pre class="brush: csharp;">
class SerializationHelper
{
    public static T SerializeAndDeserialize&lt;T&gt;(T sm)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        using (MemoryStream stream = new MemoryStream())
        {
            formatter.Serialize(stream, sm);
            stream.Position = 0;
            return (T)formatter.Deserialize(stream);
        }
    }
}
</pre>
<p><em>Dictionary</em> class implements <em>ISerializable </em>interface.</p>
<p>The ISerializable interface implies a constructor with the signature constructor (SerializationInfo information, StreamingContext context).</p>
<p>At deserialization time, the current constructor is called only after the data in the SerializationInfo has been deserialized by the formatter. In general, this constructor should be protected if the class is not sealed.</p>
<p>So what you need to do is to <strong>add the following constructor</strong>:</p>
<pre class="brush: csharp;">
    //Needed for deserialization.
    protected SafeDictionary(SerializationInfo information, StreamingContext context)
            : base(information,context)
    {
    }
</pre>
<p>Now the test will pass.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/dictionary-serializationexception/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NHibernate ignores SetMaxResults in SQL</title>
		<link>http://www.lesnikowski.com/blog/index.php/nhibernate-ignores-setmaxresults-in-sql/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=nhibernate-ignores-setmaxresults-in-sql</link>
		<comments>http://www.lesnikowski.com/blog/index.php/nhibernate-ignores-setmaxresults-in-sql/#comments</comments>
		<pubDate>Tue, 08 Dec 2009 16:34:08 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=264</guid>
		<description><![CDATA[Recently me and my team realized that several our queries, that include maximum limit on the recordset, are limited in the web application and not on the Oracle side.
First thought was that somebody simply forgot to add an invocation of SetMaxResults method, but our repository code was very obvious about it:

IQuery query = session.CreateQuery(hqlQuery);
query.SetMaxResults(100);

After some [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.lesnikowski.com/blog/wp-content/uploads/2009/12/nhibernate.gif" alt="nhibernate" title="nhibernate" width="204" height="125" class="alignleft size-full wp-image-365" />Recently me and my team realized that several our queries, that include maximum limit on the recordset, are limited in the web application and <strong>not</strong> on the Oracle side.</p>
<p>First thought was that somebody simply forgot to add an invocation of SetMaxResults method, but our repository code was very obvious about it:</p>
<pre class="brush: csharp;">
IQuery query = session.CreateQuery(hqlQuery);
query.SetMaxResults(100);
</pre>
<p>After some investigation it turned out that NHiberante is not able to use ROWNUM on the SQL side, when there is a fetch join on the collection.</p>
<p><img src="http://www.lesnikowski.com/blog/wp-content/uploads/2009/12/EmployeeDatas.png" alt="EmployeeDatas" title="EmployeeDatas" width="360" height="69" class="aligncenter size-full wp-image-364" /></p>
<p>This is HQL query we use:</p>
<pre class="brush: sql;">
select
    user
from
    User user
    /* next line causes no rownum check */
    inner join fetch user.EmployeeDatas EmployeeData
    left join fetch EmployeeData.Country country
</pre>
<p>And some NHibernate code:</p>
<pre class="brush: csharp;">
public IList List(ISessionImplementor session, QueryParameters queryParameters)
{
	// ...
	if ( hasLimit &amp;&amp; ContainsCollectionFetches )
	{
		log.Warn( &quot;firstResult/maxResults specified with collection fetch; applying in memory!&quot; );
</pre>
<p>NHibernate simply ignores the limit when executing the query and applies it on the result.</p>
<p>At some point I thought that it is not possible to even create such SQL query, but I was proven to be wrong. The query would look similar to this proof-of-concept:</p>
<pre class="brush: sql;">
SELECT
	   *
FROM
(
 	SELECT
		   *
    FROM
		 TUSER u
	WHERE
		  /* Add conditions here: */
		  EXISTS(...)
		  /* Here is DB-side limit: */
 		  AND ROWNUM &lt;= 14
) AS u
/* And now fetch all collections needed */
INNER JOIN TEMPLOYEEDATA d ON u.ID = d.USERID
</pre>
<p>So it&#8217;s clear that it is possible to improve this in NHibernate.</p>
<p>In our case change was simple:<br />
We changed <em>one-to-many</em> mapping to <em>one-to-one</em>.</p>
<p>But if you are not able to do this because of your requirements I would use custom SQL view and mapped it in NHibernate. The second idea would be to use NHibernate detached criteria and sub-queries.</p>
<p>Finally the unit test that we used to check if the limit is done on SQL database side:</p>
<pre class="brush: csharp;">
[Test]
public void FindUsersBy_QueryWithLimit_LimitsOnSQLSide()
{
    using (LogChecker logChecker = new LogChecker(&quot;NHibernate&quot;, Level.Warn))
    {
        IList&lt;User&gt; users = this._context.ExecuteInTransaction(() =&gt;
        {
            UserQuery q = new UserQuery();
            q.UserId = &quot;ILMT&quot;;
            q.MaxNumberOfRecords = 14;
            return this._context.UserRepository.FindUsersBy(q);
        });
        Assert.IsEmpty(logChecker.Messages);
        Assert.AreEqual(14, users.Count);
    }
}
</pre>
<p>Here you can see the implementation of the <a="http://www.lesnikowski.com/blog/index.php/programmatically-check-log4net/">LogChecker log4net log reader</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/nhibernate-ignores-setmaxresults-in-sql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
