<?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; Programming</title>
	<atom:link href="http://www.limilabs.com/blog/category/programming/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>Enable POP3 in Gmail</title>
		<link>http://www.limilabs.com/blog/enable-pop3-in-gmail?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=enable-pop3-in-gmail</link>
		<comments>http://www.limilabs.com/blog/enable-pop3-in-gmail#comments</comments>
		<pubDate>Fri, 06 Jan 2012 10:33:17 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Gmail]]></category>
		<category><![CDATA[POP3]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=2231</guid>
		<description><![CDATA[To enable POP3 in Gmail: Sign in to Gmail. Click the gear icon in the upper-right and select Mail settings . Click Forwarding and POP/IMAP. Select Enable POP for all mail or Enable POP for mail that arrives from now on. Now you are able to connect to your Gmail account with Mail.dll POP3 library. [...]]]></description>
			<content:encoded><![CDATA[<p>To enable POP3 in Gmail:</p>
<ol>
<li>Sign in to Gmail.</li>
<li>Click the <strong>gear icon</strong> in the upper-right and select <strong>Mail settings </strong>.</li>
<li>Click <strong>Forwarding and POP/IMAP</strong>.</li>
<li>Select<strong> Enable POP for all mail</strong> or <strong>Enable POP for mail that arrives from now on</strong>.</li>
<li>Now you are able to connect to your Gmail account with <a href="http://www.limilabs.com/mail">Mail.dll POP3 library</a>.</li>
</ol>
<p>Remember that Gmail only allows <strong>secure SSL connections</strong> so you need to use <strong>ConnectSSL </strong>method.</p>
<p>Now you can  <a href="http://www.limilabs.com/blog/download-emails-gmail-pop3">download emails from Gmail using POP3 protocol</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/enable-pop3-in-gmail/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Enable IMAP in Gmail</title>
		<link>http://www.limilabs.com/blog/enable-imap-in-gmail?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=enable-imap-in-gmail</link>
		<comments>http://www.limilabs.com/blog/enable-imap-in-gmail#comments</comments>
		<pubDate>Fri, 06 Jan 2012 10:26:31 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Gmail]]></category>
		<category><![CDATA[IMAP]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=2224</guid>
		<description><![CDATA[To enable IMAP in Gmail: Sign in to Gmail. Click the gear icon in the upper-right and select Mail settings . Click Forwarding and POP/IMAP. Select Enable IMAP. Now you are able to connect to your Gmail account with Mail.dll IMAP library. Remember that Gmail only allows secure SSL connections so you need to use [...]]]></description>
			<content:encoded><![CDATA[<p>To enable IMAP in Gmail:</p>
<ol>
<li>Sign in to Gmail.</li>
<li>Click the <strong>gear icon</strong> in the upper-right and select <strong>Mail settings </strong>.</li>
<li>Click <strong>Forwarding and POP/IMAP</strong>.</li>
<li>Select <strong>Enable IMAP</strong>.</li>
<li>Now you are able to connect to your Gmail account with <a href="http://www.limilabs.com/mail">Mail.dll IMAP library</a>.</li>
</ol>
<p>Remember that Gmail only allows <strong>secure SSL connections</strong> so you need to use <strong>ConnectSSL </strong>method.</p>
<p>Now you can <a href="http://www.limilabs.com/blog/download-emails-from-gmail">download emails from Gmail using IMAP protocol</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/enable-imap-in-gmail/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<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 the bound property as the user types</title>
		<link>http://www.limilabs.com/blog/update-the-bound-property-as-the-user-types?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=update-the-bound-property-as-the-user-types</link>
		<comments>http://www.limilabs.com/blog/update-the-bound-property-as-the-user-types#comments</comments>
		<pubDate>Fri, 15 Apr 2011 10:49:27 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=1777</guid>
		<description><![CDATA[In Silverlight there is no way for 2-way-bound TextBox to update it&#8217;s bound property every time user hits a key on the keyboard. In WPF you could use UpdateSourceTrigger=PropertyChanged, which is not available in Silverlight. Anyway here&#8217;s the nice Silverlight behavior to add this feature to Silverlight: // Please note that Behavior class is from [...]]]></description>
			<content:encoded><![CDATA[<p>In Silverlight there is no way for 2-way-bound TextBox to update it&#8217;s bound property every time user hits a key on the keyboard.</p>
<p>In WPF you could use UpdateSourceTrigger=PropertyChanged, which is not available in Silverlight.</p>
<p>Anyway here&#8217;s the nice Silverlight behavior to add this feature to Silverlight:</p>
<pre class="brush: csharp;">
// Please note that Behavior class is from
// System.Windows.Interactivity assembly that is available
// after you have installed Expression Blend.
// (C:Program FilesMicrosoft SDKsExpressionBlendSilverlightv4.0
//  LibrariesSystem.Windows.Interactivity.dll)

public class UpdateOnTextChangedBehavior : Behavior&lt;textBox&gt;
{
    protected override void OnAttached()
    {
        base.OnAttached();

        this.AssociatedObject.TextChanged +=
                AssociatedObject_TextChanged;
    }

    void AssociatedObject_TextChanged(
        object sender,
        TextChangedEventArgs e)
    {
        BindingExpression binding =
            this.AssociatedObject.GetBindingExpression(
                TextBox.TextProperty);

        if (binding != null)
        {
            binding.UpdateSource();
        }
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        this.AssociatedObject.TextChanged -=
                AssociatedObject_TextChanged;
    }
}
</pre>
<p>And usage:</p>
<pre class="brush: xml;">
&lt;textBox Text=&quot;{Binding Title, Mode=TwoWay}&quot;&gt;
   &lt;i:Interaction.Behaviors&gt;
      &lt;local:UpdateOnTextChangedBehavior/&gt;
   &lt;/i:Interaction.Behaviors&gt;
&lt;/textBox&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/update-the-bound-property-as-the-user-types/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Received an unexpected EOF or 0 bytes from the transport stream</title>
		<link>http://www.limilabs.com/blog/received-unexpected-eof-0-bytes-from-transport-stream?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=received-unexpected-eof-0-bytes-from-transport-stream</link>
		<comments>http://www.limilabs.com/blog/received-unexpected-eof-0-bytes-from-transport-stream#comments</comments>
		<pubDate>Mon, 17 Jan 2011 13:04:32 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Component]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Mail.dll]]></category>
		<category><![CDATA[SSL]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=1675</guid>
		<description><![CDATA[When you are getting the following error: Received an unexpected EOF or 0 bytes from the transport stream. while using ConnectSSL() most likely your server incorrectly advertises TLS support. You might be required to use SSL2 or SSL3. This article describes how to force SSL3 or SSL2 in Mail.dll or in regular .NET SslStream class. [...]]]></description>
			<content:encoded><![CDATA[<p>When you are getting the following error:<br />
<strong>Received an unexpected EOF or 0 bytes from the transport stream.</strong><br />
while using ConnectSSL() most likely your server incorrectly advertises TLS support. You might be required to use  SSL2 or SSL3.</p>
<p>This article describes <strong>how to force SSL3 or SSL2 in Mail.dll</strong> or in <strong>regular .NET SslStream class</strong>.</p>
<p>Here&#8217;s the code for Mail.dll</p>
<pre class="brush: csharp;">
// C# version
using (Imap client = new Imap())
{
   // Force to use SSL3
   client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Ssl3;
   // Ignore certificate errors
   client.ServerCertificateValidate += (sender, e) =&gt; { e.IsValid = true; };
   client.ConnectSSL(&quot;imap.gmail.com&quot;);
   client.Login(&quot;user@gmail.com&quot;, &quot;password&quot;);

   client.SelectInbox();
   foreach(long uid in client.SearchFlag(Flag.Unseen))
   {
       string eml = client.GetMessageByUID(uid);
       IMail email = new MailBuilder().CreateFromEml(eml);
       Console.WriteLine(email.Subject);
   }
   client.Close();
}
</pre>
<pre class="brush: vb;">
' VB.NET version

Using client As New Imap()
	' Force to use SSL3
	client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Ssl3
	' Ignore certificate errors
	AddHandler client.ServerCertificateValidate, AddressOf Validate
	client.ConnectSSL(&quot;imap.gmail.com&quot;)
	client.Login(&quot;user@gmail.com&quot;, &quot;password&quot;)

	client.SelectInbox()
	For Each uid As Long In client.SearchFlag(Flag.Unseen)
		Dim eml As String = client.GetMessageByUID(uid)
		Dim email As IMail = New MailBuilder().CreateFromEml(eml)
		Console.WriteLine(email.Subject)
	Next
	client.Close()
End Using

Private Sub ValidateCerificate( _
    ByVal sender As Object, _
    ByVal e As ServerCertificateValidateEventArgs)

    Const ignoredErrors As SslPolicyErrors = _
        SslPolicyErrors.RemoteCertificateChainErrors Or _
        SslPolicyErrors.RemoteCertificateNameMismatch

    If (e.SslPolicyErrors And Not ignoredErrors) = SslPolicyErrors.None Then
        e.IsValid = True
        Return
    End If
    e.IsValid = False
End Sub
</pre>
<p>Here&#8217;s the code for <strong>SslStream</strong>:</p>
<pre class="brush: csharp;">
// C# version
const string host = &quot;imap.gmail.com&quot;;

Socket socket = new Socket(
   AddressFamily.InterNetwork,
   SocketType.Stream,
   ProtocolType.Tcp);
socket.Connect(host, 993);
using(SslStream ssl = new SslStream(new NetworkStream(socket), true))
{
   ssl.AuthenticateAsClient(
      host,
      new X509CertificateCollection(),
      SslProtocols.Ssl3,
      true);
   using(StreamReader reader = new StreamReader(ssl))
   {
       Console.WriteLine(reader.ReadLine());
   }
}
socket.Close();
</pre>
<pre class="brush: vb;">
' VB.NET version

Const  host As String = &quot;imap.gmail.com&quot;

Dim socket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
socket.Connect(host, 993)
Using ssl As New SslStream(New NetworkStream(socket), True)
	ssl.AuthenticateAsClient(host, New X509CertificateCollection(), SslProtocols.Ssl3, True)
	Using reader As New StreamReader(ssl)
		Console.WriteLine(reader.ReadLine())
	End Using
End Using
socket.Close()
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/received-unexpected-eof-0-bytes-from-transport-stream/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Better public API: GetAccountStat</title>
		<link>http://www.limilabs.com/blog/better-public-api-getaccountstat?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=better-public-api-getaccountstat</link>
		<comments>http://www.limilabs.com/blog/better-public-api-getaccountstat#comments</comments>
		<pubDate>Sat, 21 Aug 2010 09:56:13 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[CleanCode]]></category>
		<category><![CDATA[Refactor]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=1081</guid>
		<description><![CDATA[Here&#8217;s some code I recently found in Mail.dll and decided to refactor. // Before: using(Pop3 client = new Pop3()) { client.GetAccountStat(); Console.WriteLine( &#34;Inbox has {0} emails.&#34;, client.MessageCount); } There are several things wrong with this code. The method is called Get&#8230; but it does not get anything, it changes the internal state of the object. [...]]]></description>
			<content:encoded><![CDATA[<p>  Here&#8217;s some code I recently found in <a href="http://www.limilabs.com/mail">Mail.dll</a> and decided to refactor.</p>
<pre class="brush: csharp;">
// Before:

using(Pop3 client = new Pop3())
{
    client.GetAccountStat();
    Console.WriteLine(
        &quot;Inbox has {0} emails.&quot;,
        client.MessageCount);
}
</pre>
<p>There are several things <strong>wrong</strong> with this code.</p>
<ul>
<li>The method is called <strong>Get&#8230;</strong> but it does not get anything, <strong>it changes the internal state</strong> of the object.</li>
<li>Message count is stored in Pop3 object:
<ul>
<li>If the user of your API connects later to a different server you need to remember to reset this variable.</li>
<li>If the user of your API forgets to call GetAccountStat, message count is undefined (Should it be null?)</li>
</ul>
</li>
</ul>
<p>It&#8217;s really hard to say that this is a friendly API, as it requires the user to <strong>perform actions in specific order</strong> (call GetAccountStat before accessing message count).</p>
<p>Another problem is that GetAccountStat method is <strong>responsible for parsing the server response</strong>. It&#8217;s not necessary a bad thing, but if you have hundreds such methods then Pop3 class gets bloated with hard-to-test parsing logic.</p>
<p>Now lets take a look at the <strong>After</strong> code:</p>
<pre class="brush: csharp;">
// After:

using(Pop3 client = new Pop3())
{
    AccountStats stats = client.GetAccountStat();
    Console.WriteLine(
        &quot;Inbox has {0} emails.&quot;,
        stats.MessageCount);

}
</pre>
<p>Here we can see a <strong>good API</strong>:</p>
<ul>
<li>Method is called Get&#8230;. and it actually gets something.</li>
<li><strong>No specific call order is required</strong>, you simply call one method and act on the result.</li>
<li><strong>Parsing logic was moved</strong> to the AccountStats class.</li>
</ul>
<p>This is not seen here but AccountStats method has a static Parse method&#8230;and look how easy is to write unit test for it&#8217;s behavior:</p>
<pre class="brush: csharp;">
[Test]
public void Parse_MessageCountAndMailboxSize_AreFilled()
{
    AccountStats stats = AccountStats.Parse(&quot;2 373766&quot;);
    Assert.AreEqual(2, stats.MessageCount);
    Assert.AreEqual(373766, stats.MailboxSize);
}
</pre>
<p>Note also that actually <strong>we have NOT introduced a breaking change</strong> to our public API. Following code still works:</p>
<pre class="brush: csharp;">
using(Pop3 client = new Pop3())
{
    client.GetAccountStat();
    Console.WriteLine(
        &quot;Inbox has {0} emails.&quot;,
        client.MessageCount);
}
</pre>
<p>You&#8217;ll get 2 obsolete warnings:</p>
<p><code>warning CS0618: 'Limilabs.Client.POP3.Pop3.MessageCount' is obsolete: 'Please use the return value of GetAccountStat method instead.'</code></p>
<p><code>warning CS0618: 'Limilabs.Client.POP3.Pop3.MailboxSize' is obsolete: 'Please use the return value of GetAccountStat method instead.'</code></p>
<p>As we marked MessageCount and MailboxSize with <strong>[obsolete]</strong> attribute, but that&#8217;s it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/better-public-api-getaccountstat/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Simple JSON .NET formatter</title>
		<link>http://www.limilabs.com/blog/json-net-formatter?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=json-net-formatter</link>
		<comments>http://www.limilabs.com/blog/json-net-formatter#comments</comments>
		<pubDate>Tue, 22 Jun 2010 07:22:41 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://www.limilabs.com/blog/?p=938</guid>
		<description><![CDATA[StringWalker class: public class StringWalker { string _s; public int Index { get; set; } public StringWalker(string s) { _s = s; Index = -1; } public bool MoveNext() { if (Index == _s.Length - 1) return false; Index++; return true; } public char CharAtIndex() { return _s[Index]; } }; IndentWriter class: public class IndentWriter [...]]]></description>
			<content:encoded><![CDATA[<p>StringWalker class:</p>
<pre class="brush: csharp;">
public class StringWalker
{
	string _s;
	public int Index { get; set; }

	public StringWalker(string s)
	{
		_s = s;
		Index = -1;
	}

	public bool MoveNext()
	{
		if (Index == _s.Length - 1)
			return false;
		Index++;
		return true;
	}

	public char CharAtIndex()
	{
		return _s[Index];
	}
};
</pre>
<p>IndentWriter class:</p>
<pre class="brush: csharp;">
public class IndentWriter
{
	StringBuilder _sb = new StringBuilder();
	int _indent;

	public void Indent()
	{
		_indent++;
	}

	public void UnIndent()
	{
		if (_indent &gt; 0)
			_indent--;
	}

	public void WriteLine(string line)
	{
		_sb.AppendLine(CreateIndent() + line);
	}

	private string CreateIndent()
	{
		StringBuilder indentString = new StringBuilder();
		for(int i = 0; i&lt; _indent; i++)
			indentString.Append(&quot;    &quot;);
		return indentString.ToString();
	}

	public override string ToString()
	{
		return _sb.ToString();
	}
};
</pre>
<p>JSON formatter class:</p>
<pre class="brush: csharp;">
public class JsonFormatter
{
	StringWalker _walker;
	IndentWriter _writer = new IndentWriter();
	StringBuilder _currentLine = new StringBuilder();
	bool _quoted;

	public JsonFormatter(string json)
	{
		_walker = new StringWalker(json);
		ResetLine();
	}

	public void ResetLine()
	{
		_currentLine.Length = 0;
	}

	public string Format()
	{
		while(MoveNextChar())
		{
			if (this._quoted == false &amp;&amp; this.IsOpenBracket())
			{
				this.WriteCurrentLine();
				this.AddCharToLine();
				this.WriteCurrentLine();
				_writer.Indent();
			}
			else if (this._quoted == false &amp;&amp; this.IsCloseBracket())
			{
				this.WriteCurrentLine();
				_writer.UnIndent();
				this.AddCharToLine();
			}
			else if (this._quoted == false &amp;&amp; this.IsColon())
			{
				this.AddCharToLine();
				this.WriteCurrentLine();
			}
			else
			{
				AddCharToLine();
			}
		}
		this.WriteCurrentLine();
		return _writer.ToString();
	}

	private bool MoveNextChar()
	{
		bool success = _walker.MoveNext();
		if (this.IsApostrophe())
		{
			this._quoted = !_quoted;
		}
		return success;
	}

	public bool IsApostrophe()
	{
		return this._walker.CharAtIndex() == '&quot;';
	}

	public bool IsOpenBracket()
	{
		return this._walker.CharAtIndex() == '{'
			|| this._walker.CharAtIndex() == '[';
	}

	public bool IsCloseBracket()
	{
		return this._walker.CharAtIndex() == '}'
			|| this._walker.CharAtIndex() == ']';
	}

	public bool IsColon()
	{
		return this._walker.CharAtIndex() == ',';
	}

	private void AddCharToLine()
	{
		this._currentLine.Append(_walker.CharAtIndex());
	}

	private void WriteCurrentLine()
	{
		string line = this._currentLine.ToString().Trim();
		if (line.Length &gt; 0)
		{
			_writer.WriteLine(line);
		}
		this.ResetLine();
	}
};
</pre>
<p>Few samples:</p>
<pre class="brush: csharp;">
Console.WriteLine(new JsonFormatter(
	@&quot;{&quot;&quot;parameter&quot;&quot; : &quot;&quot;value&quot;&quot; , { &quot;&quot;parameter2&quot;&quot; : &quot;&quot;value2&quot;&quot; },{ &quot;&quot;parameter3&quot;&quot; : &quot;&quot;value3&quot;&quot; } }&quot;).Format());
Console.WriteLine(new JsonFormatter(
	@&quot;{&quot;&quot;parameter&quot;&quot;:[&quot;&quot;value1&quot;&quot;,&quot;&quot;value2&quot;&quot;,&quot;&quot;value3&quot;&quot;] }&quot;).Format());
Console.WriteLine(new JsonFormatter(
	@&quot;{&quot;&quot;parameter&quot;&quot;: &quot;&quot;value with {brackets}&quot;&quot; }&quot;).Format());
</pre>
<p>&#8230;and results:</p>
<pre class="brush: plain;">
{
    &quot;parameter&quot; : &quot;value&quot; ,
    {
        &quot;parameter2&quot; : &quot;value2&quot;
    },
    {
        &quot;parameter3&quot; : &quot;value3&quot;
    }
}

{
    &quot;parameter&quot;:
    [
        &quot;value1&quot;,
        &quot;value2&quot;,
        &quot;value3&quot;
    ]
}

{
    &quot;parameter&quot;: &quot;value with {brackets}&quot;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.limilabs.com/blog/json-net-formatter/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>A non-blocking socket operation could not be completed</title>
		<link>http://www.limilabs.com/blog/a-non-blocking-socket-operation?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=a-non-blocking-socket-operation</link>
		<comments>http://www.limilabs.com/blog/a-non-blocking-socket-operation#comments</comments>
		<pubDate>Mon, 12 Apr 2010 16:03:29 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[mono]]></category>

		<guid isPermaLink="false">http://www.limilabs.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 client.Connect(&#34;mail.limilabs.com&#34;, 143); // Create reader and writer NetworkStream stream = client.GetStream(); StreamReader reader = new StreamReader(stream); [...]]]></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.limilabs.com&quot;, 143);

    // Create reader and 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.limilabs.com/blog/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.limilabs.com/blog/isession-load-returns-object-with-zero-id?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=isession-load-returns-object-with-zero-id</link>
		<comments>http://www.limilabs.com/blog/isession-load-returns-object-with-zero-id#comments</comments>
		<pubDate>Fri, 02 Apr 2010 09:09:32 +0000</pubDate>
		<dc:creator>Limilabs support</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://www.limilabs.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 [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.limilabs.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.limilabs.com/blog/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.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>
	</channel>
</rss>

