<?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</title>
	<atom:link href="http://www.lesnikowski.com/blog/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.lesnikowski.com/blog</link>
	<description>.Net</description>
	<lastBuildDate>Fri, 19 Feb 2010 15:47:38 +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>Email template engine</title>
		<link>http://www.lesnikowski.com/blog/index.php/email-template-engine/</link>
		<comments>http://www.lesnikowski.com/blog/index.php/email-template-engine/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 15:47:38 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Component]]></category>
		<category><![CDATA[email]]></category>
		<category><![CDATA[Mail.dll]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=520</guid>
		<description><![CDATA[Newest version of Mail.dll email client includes a simple template engine.
It allows you to easily create html template for your emails:

Loading and rendering such template requires one line of code:

Contact contact = ...;

 string html = Template
     .FromFile(&#34;template.txt&#34;)
     .DataFrom(contact)
     .Render();

This is how the [...]]]></description>
			<content:encoded><![CDATA[<p>Newest version of <a href="http://www.lesnikowski.com/mail/">Mail.dll email client</a> includes a simple template engine.</p>
<p>It allows you to easily create html template for your emails:<br />
<img src="http://www.lesnikowski.com/blog/wp-content/uploads/2010/02/TemplateSample.png" alt="" title="TemplateSample" width="459" height="420" class="aligncenter size-full wp-image-541" /></p>
<p>Loading and rendering such template requires one line of code:</p>
<pre class="brush: csharp;">
Contact contact = ...;

 string html = Template
     .FromFile(&quot;template.txt&quot;)
     .DataFrom(contact)
     .Render();
</pre>
<p>This is how the template looks like:</p>
<pre class="brush: xml;">
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Your order&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
	Hi {FirstName} {LastName},
	&lt;br /&gt;
	&lt;p&gt;
	Your account {if Verified}has{else}&lt;strong&gt;has not&lt;/strong&gt;{end} been verified. &lt;br/&gt;
	Your password is: {Password}.
	&lt;/p&gt;
	&lt;p&gt;
	Here are your orders:
	&lt;/p&gt;
	{foreach Orders}
		&lt;p&gt;
		Order sent to &lt;strong&gt;{Street}&lt;/strong&gt;:
		&lt;/p&gt;
		&lt;table style=&quot;width: 30%;&quot;&gt;
			{foreach Items}
				&lt;tr style=&quot;background-color: #E0ECFF;&quot;&gt;
					&lt;td&gt;{Name}&lt;/td&gt;&lt;td&gt;{Price}&lt;/td&gt;
				&lt;/tr&gt;
			{end}
		&lt;/table&gt;
	{end}
	&lt;p&gt;
		Thank you for your orders.
	&lt;p&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Here&#8217;s the sample of how to load, fill the template and send it using Mail.dll:</p>
<pre class="brush: csharp;">
Mail.Html(Template
              .FromFile(&quot;template.txt&quot;)
              .DataFrom(_contact)
              .Render())
    .Text(&quot;This is text version of the message.&quot;)
    .From(new MailBox(&quot;alice@mail.com&quot;, &quot;Alice&quot;))
    .To(new MailBox(&quot;bob@mail.com&quot;, &quot;Bob&quot;))
    .Subject(&quot;Your order&quot;)
    .UsingNewSmtp()
    .WithCredentials(&quot;alice@mail.com&quot;, &quot;password&quot;)
    .Server(&quot;mail.com&quot;)
    .WithSSL()
    .Send();
</pre>
<p>And this is how the data used by template look like:</p>
<pre class="brush: csharp;">
public class Contact
{
    public List&lt;Order&gt; Orders { get; private set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool Verified;
    private string Password { get; set; }

    public Contact()
    {
        Orders = new List&lt;Order&gt;();
    }
} ;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/email-template-engine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>INotifyPropertyChanged with lambdas</title>
		<link>http://www.lesnikowski.com/blog/index.php/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 [...]]]></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/</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>0</slash:comments>
		</item>
		<item>
		<title>Background processing in WinForms</title>
		<link>http://www.lesnikowski.com/blog/index.php/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 [...]]]></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/</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>4</slash:comments>
		</item>
		<item>
		<title>Mark emails as read using IMAP</title>
		<link>http://www.lesnikowski.com/blog/index.php/mark-emails-as-read-with-imap/</link>
		<comments>http://www.lesnikowski.com/blog/index.php/mark-emails-as-read-with-imap/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 18:31:22 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Component]]></category>
		<category><![CDATA[IMAP]]></category>
		<category><![CDATA[Mail.dll]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=389</guid>
		<description><![CDATA[First you need to download Mail.dll IMAP client.
The following code connects to IMAP server, downloads unique ids of all unseen emails and marks the first one as seen.

// C# version

using(Imap imap = new Imap())
{
	imap.Connect(&#34;server&#34;);

	imap.User = &#34;user&#34;;
	imap.Password = &#34;password&#34;;
	imap.Login();

	imap.SelectInbox();
	List&#60;long&#62; uids = client.SearchFlag(Flag.Unseen);
	if (uids.Count &#62; 0)
		client.MarkMessageSeenByUID(uids[0]);
    imap.Close(true);
}


' VB.NET version

Using imap As New Imap()
	imap.Connect(&#34;server&#34;)

	imap.User = [...]]]></description>
			<content:encoded><![CDATA[<p>First you need to download <a href="http://www.lesnikowski.com/mail/">Mail.dll IMAP client</a>.</p>
<p>The following code connects to IMAP server, <strong>downloads </strong>unique ids of all <strong>unseen emails</strong> and <strong>marks the first one as seen</strong>.</p>
<pre class="brush: csharp;">
// C# version

using(Imap imap = new Imap())
{
	imap.Connect(&quot;server&quot;);

	imap.User = &quot;user&quot;;
	imap.Password = &quot;password&quot;;
	imap.Login();

	imap.SelectInbox();
	List&lt;long&gt; uids = client.SearchFlag(Flag.Unseen);
	if (uids.Count &gt; 0)
		client.MarkMessageSeenByUID(uids[0]);
    imap.Close(true);
}
</pre>
<pre class="brush: vb;">
' VB.NET version

Using imap As New Imap()
	imap.Connect(&quot;server&quot;)

	imap.User = &quot;user&quot;
	imap.Password = &quot;password&quot;
	imap.Login()

	imap.SelectInbox()
	Dim uids As List(Of Long) = client.SearchFlag(Flag.Unseen)
	If uids.Count &gt; 0 Then
		client.MarkMessageSeenByUID(uids(0))
	End If
	imap.Close(True)
End Using
</pre>
<p>Please note that it is not possible to mark messages as read using POP3 protocol.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/mark-emails-as-read-with-imap/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cross-thread operations with PostSharp</title>
		<link>http://www.lesnikowski.com/blog/index.php/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>5</slash:comments>
		</item>
		<item>
		<title>Download email attachments in .NET</title>
		<link>http://www.lesnikowski.com/blog/index.php/download-email-attachments-net/</link>
		<comments>http://www.lesnikowski.com/blog/index.php/download-email-attachments-net/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 16:45:15 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Component]]></category>
		<category><![CDATA[IMAP]]></category>
		<category><![CDATA[Mail.dll]]></category>
		<category><![CDATA[POP3]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=258</guid>
		<description><![CDATA[First you&#8217;ll need an IMAP client or POP3 client to download emails from the server.
The email attachments are downloaded as a part of the message. Attachments are stored within the email as part of a mime tree. Usually Quoted-Printable or Base64 encoding are used. Mail.dll is going to parse such tree for you and expose [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.lesnikowski.com/blog/wp-content/uploads/2009/12/mail.png"><img src="http://www.lesnikowski.com/blog/wp-content/uploads/2009/12/mail.png" alt="" title="mail" width="157" height="149" class="alignleft size-full wp-image-360" /></a>First you&#8217;ll need an <a href="http://www.lesnikowski.com/mail/">IMAP client</a> or <a href="http://www.lesnikowski.com/mail/">POP3 client</a> to download emails from the server.</p>
<p>The email attachments are downloaded as a <strong>part of the message</strong>. Attachments are stored within the email as part of a mime tree. Usually Quoted-Printable or Base64 encoding are used. Mail.dll is going to parse such tree for you and expose all attachments as well known .NET collections.</p>
<p>ISimpleMailMessage uses 2 collections for storing attachments:</p>
<ul>
<li><strong>Attachments </strong>- contains all attached documents</li>
<li><strong>Visuals </strong>- contains files that should be &#8216;displayed&#8217; to the user (like images or music that should be played in background)</li>
</ul>
<p>Following you&#8217;ll find samples of how you can save all attachments to disk using C# and  VB.NET via POP3 and IMAP protocols.</p>
<p><strong>When you use IMAP server:</strong></p>
<pre class="brush: csharp;">
// C# version
using(Imap imap = new Imap())
{
	imap.Connect(&quot;server&quot;);

	imap.User = &quot;user&quot;;
	imap.Password = &quot;password&quot;;
	imap.Login();

	imap.SelectInbox();
	List&lt;long&gt; uids = imap.SearchFlag(Flag.All);
	foreach (long uid in uids)
	{
		string eml = imap.GetMessageByUID(uid);
		ISimpleMailMessage email = new SimpleMailMessageBuilder()
			.CreateFromEml(eml);

		Console.WriteLine(email.Subject);

		// save all attachments to disk
		email.Attachments.ForEach(mime =&gt; mime.Save(mime.FileName));
		email.Visuals.ForEach(mime =&gt; mime.Save(mime.FileName));
	}
	imap.Close(true);
}
</pre>
<p>You can also save attachment to stream: void MimeData.Save(Stream stream)<br />
Or get direct access to it: MemoryStream MimeData.GetMemoryStream() </p>
<pre class="brush: vb;">
' VB.NET version
Using imap As New Imap()
	imap.Connect(&quot;server&quot;)

	imap.User = &quot;user&quot;
	imap.Password = &quot;password&quot;
	imap.Login()

	imap.SelectInbox()
	Dim uids As List(Of Long) = imap.SearchFlag(Flag.All)
	For Each uid As Long In uids
		Dim eml As String = imap.GetMessageByUID(uid)
		Dim email As ISimpleMailMessage = New SimpleMailMessageBuilder()_
			.CreateFromEml(eml)

		Console.WriteLine(email.Subject)

		' save all attachments to disk
		email.Attachments.ForEach(Function(mime) mime.Save(mime.FileName))
		email.Visuals.ForEach(Function(mime) mime.Save(mime.FileName))
	Next
	imap.Close(True)
End Using
</pre>
<p><strong>When you use POP3 server:</strong></p>
<pre class="brush: csharp;">
// C# version
using(Pop3 pop3 = new Pop3())
{
	pop3.Connect(&quot;server&quot;);

	pop3.User = &quot;user&quot;;
	pop3.Password = &quot;password&quot;;
	pop3.Login();

	pop3.GetAccountStat();
	for (int i = 1; i &lt;= pop3.MessageCount; i++)
	{
		string eml = pop3.GetMessage(i);
		ISimpleMailMessage email = new SimpleMailMessageBuilder()
			.CreateFromEml(eml);

		Console.WriteLine(email.Subject);

		// save all attachments to disk
		email.Attachments.ForEach(mime =&gt; mime.Save(mime.FileName));
		email.Visuals.ForEach(mime =&gt; mime.Save(mime.FileName));
	}
	pop3.Close(true);
}
</pre>
<pre class="brush: vb;">
' VB.NET version
Using pop3 As New Pop3()
	pop3.Connect(&quot;server&quot;)

	pop3.User = &quot;user&quot;
	pop3.Password = &quot;password&quot;
	pop3.Login()

	pop3.GetAccountStat()
	For i As Integer = 1 To pop3.MessageCount
		Dim eml As String = pop3.GetMessage(i)
		Dim email As ISimpleMailMessage = New SimpleMailMessageBuilder()_
			.CreateFromEml(eml)

		Console.WriteLine(email.Subject)

		' save all attachments to disk
		email.Attachments.ForEach(Function(mime) mime.Save(mime.FileName))
		email.Visuals.ForEach(Function(mime) mime.Save(mime.FileName))
	End While
	pop3.Close(True)
End Using
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/download-email-attachments-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>FindAll, ConvertAll are your friends</title>
		<link>http://www.lesnikowski.com/blog/index.php/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>Uploading emails using IMAP</title>
		<link>http://www.lesnikowski.com/blog/index.php/uploading-emails-using-imap/</link>
		<comments>http://www.lesnikowski.com/blog/index.php/uploading-emails-using-imap/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 16:59:13 +0000</pubDate>
		<dc:creator>Pawel Lesnikowski</dc:creator>
				<category><![CDATA[Component]]></category>
		<category><![CDATA[GMail]]></category>
		<category><![CDATA[IMAP]]></category>
		<category><![CDATA[Mail.dll]]></category>

		<guid isPermaLink="false">http://www.lesnikowski.com/blog/?p=379</guid>
		<description><![CDATA[Uploading emails to the IMAP server is fairly easy with Mail.dll IMAP client
First we&#8217;ll use Mail.dll to upload an existing email in eml format to the IMAP server:

// C# code

using (Imap imap = new Imap())
{
    imap.Connect(&#34;server&#34;);

    imap.User = &#34;user&#34;;
    imap.Password = &#34;password&#34;;
    imap.Login();

 [...]]]></description>
			<content:encoded><![CDATA[<p>Uploading emails to the IMAP server is fairly easy with <a href="http://www.lesnikowski.com/mail/">Mail.dll IMAP client</a></p>
<p>First we&#8217;ll use Mail.dll to upload an existing email in eml format to the IMAP server:</p>
<pre class="brush: csharp;">
// C# code

using (Imap imap = new Imap())
{
    imap.Connect(&quot;server&quot;);

    imap.User = &quot;user&quot;;
    imap.Password = &quot;password&quot;;
    imap.Login();

    string eml = File.ReadAllText(&quot;email.eml&quot;);

    // The name of the folder depends on your IMAP server
    imap.UploadMessage(&quot;[Gmail]/Sent Mail&quot;, eml);

    imap.Close(true);
}
</pre>
<pre class="brush: vb;">
' VB.NET code

Using imap As New Imap()
	imap.Connect(&quot;server&quot;)

	imap.User = &quot;user&quot;
	imap.Password = &quot;password&quot;
	imap.Login()

	Dim eml As String = File.ReadAllText(&quot;email.eml&quot;)

	' The name of the folder depends on your IMAP server
	imap.UploadMessage(&quot;[Gmail]/Sent Mail&quot;, eml)

	imap.Close(True)
End Using
</pre>
<p>Second sample shows how to create <strong>new email message</strong> and upload it to IMAP server.</p>
<pre class="brush: csharp;">
// C# code

using (Imap imap = new Imap())
{
    imap.Connect(&quot;server&quot;);

    imap.User = &quot;user&quot;;
    imap.Password = &quot;password&quot;;
    imap.Login();

    // Create new mail message
    SimpleMailMessageBuilder builder = new SimpleMailMessageBuilder();
    builder.Subject = &quot;subject&quot;;
    builder.From.Add(new MailBox(&quot;alice@email.com&quot;, &quot;Alice&quot;));
    builder.To.Add(new MailBox(&quot;bob@email.com&quot;, &quot;Bob&quot;));
    builder.SetTextData(&quot;This is plain text email&quot;);

    // Upload
    // The name of the folder depends on your IMAP server
    imap.UploadMessage(&quot;[Gmail]/Sent Mail&quot;, builder.Create());

    imap.Close(true);
}
</pre>
<pre class="brush: vb;">
' VB.NET code

Using imap As New Imap()
	imap.Connect(&quot;server&quot;)

	imap.User = &quot;user&quot;
	imap.Password = &quot;password&quot;
	imap.Login()

	' Create new mail message
	Dim builder As New SimpleMailMessageBuilder()
	builder.Subject = &quot;subject&quot;
	builder.From.Add(New MailBox(&quot;alice@email.com&quot;, &quot;Alice&quot;))
	builder.[To].Add(New MailBox(&quot;bob@email.com&quot;, &quot;Bob&quot;))
	builder.SetTextData(&quot;This is plain text email&quot;)

	' Upload
	' The name of the folder depends on your IMAP server
	imap.UploadMessage(&quot;[Gmail]/Sent Mail&quot;, builder.Create())

	imap.Close(True)
End Using
</pre>
<p>Please note that only few IMAP servers are going to send the message to the actual recipients. Most servers will only upload the message without sending it.<br />
You should use SMTP protocol for this.<br />
You can <a href="http://www.lesnikowski.com/mail/">download Mail.dll IMAP client here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lesnikowski.com/blog/index.php/uploading-emails-using-imap/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
