<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title type="html">SeeSharp - SeeSharp</title>
  <icon>http://www.hightech.ir/favicon.ico</icon>
  <logo>http://www.hightech.ir/favicon.png</logo>
  <updated>2010-03-07T18:00:00</updated>
  <subtitle type="html">A C# development blog</subtitle>
  <id>http://www.hightech.ir/seesharp/atom</id>
  <link rel="alternate" type="text/html" hreflang="en" href="/seesharp/atom"/>
  <link rel="self" type="application/atom+xml" href="http://www.hightech.ir/SeeSharp/ATOM"/>
  <generator uri="http://oxite.net" version="1.0">Oxite</generator>
  <entry>
    <title type="html">Deserting SVN for good: Using Git</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/deserting-svn-for-good-using-git"/>
    <id>http://www.hightech.ir/SeeSharp/deserting-svn-for-good-using-git</id>
    <updated>2010-03-08T08:32:16.043</updated>
    <published>2010-03-07T18:00:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="svn" />
    <category term="git" />
    <content type="html" xml:lang="en">
      &lt;p&gt;
	I&amp;#39;ve been having tremendous amount of problems lately using &lt;a href=&quot;http://tortoisesvn.tigris.org/&quot;&gt;TortoiseSVN&lt;/a&gt;. Although server seemed to work fine, my SVN client had lots of problems, so I decided it was time to switch to &lt;a href=&quot;http://en.wikipedia.org/wiki/Git_(software)&quot;&gt;Git&lt;/a&gt;. I was using the free service available at &lt;a href=&quot;http://xp-dev.com&quot;&gt;xp-dev&lt;/a&gt; but the free service only includes SVN repositories, so I tried the next best thing: GIT-SVN. Let&amp;#39;s see how it worked out for me.&lt;/p&gt;
&lt;p&gt;
	Git is not (yet) natively supported on windows. The only way to run it on Windows was to use &lt;a href=&quot;http://www.cygwin.com&quot;&gt;Cygwin&lt;/a&gt;, a linux like environment for Windows, but the new project called &lt;a href=&quot;http://www.google.com/url?q=http://code.google.com/p/msysgit/w/list&amp;amp;ei=CemTS9SaC5K2lAfshbWcBw&amp;amp;sa=X&amp;amp;oi=smap&amp;amp;resnum=1&amp;amp;ct=result&amp;amp;cd=3&amp;amp;ved=0CAoQqwMoAjAA&amp;amp;usg=AFQjCNHXK6mIm-wFQ-ITmoQVFild9JDYug&quot;&gt;msysgit&lt;/a&gt; is trying to make a native Windows client. To get started &lt;a href=&quot;http://www.google.com/url?q=http://code.google.com/p/msysgit/downloads/list&amp;amp;ei=CemTS9SaC5K2lAfshbWcBw&amp;amp;sa=X&amp;amp;oi=smap&amp;amp;resnum=1&amp;amp;ct=result&amp;amp;cd=1&amp;amp;ved=0CAgQqwMoADAA&amp;amp;usg=AFQjCNFyPtxDGdLMDJmffOhizc_XsDDHNA&quot;&gt;download&lt;/a&gt; and install msysgit from google code. I&amp;#39;m using version 1.6.5.1 preview 20091022 at the time of this post, but it is updated regularly.&lt;/p&gt;
&lt;p&gt;
	To connect to SVN repository, open a Git Bash window on your destination folder and enter the following command:&lt;/p&gt;
&lt;pre&gt;
&lt;strong&gt;git svn -s clone http://your-svn-address
&lt;/strong&gt;&lt;/pre&gt;
&lt;p&gt;
	If your SVN repository has no standard folders such as &amp;quot;trunk&amp;quot;, &amp;quot;tag&amp;quot; and &amp;quot;branch&amp;quot; you should remove &amp;quot;-s&amp;quot; parameter. This command would get all the sources, except empty folders in your existing SVN repository because Git does not track folders but file content.&amp;nbsp; It would take some time for git to get all the revisions but when it finishes, you&amp;#39;re all set.&lt;/p&gt;
&lt;p&gt;
	From this point on, you can use &lt;a href=&quot;http://www.kernel.org/pub/software/scm/git/docs/everyday.html&quot;&gt;git commands&lt;/a&gt; but before committing changes back into your SVN repository, you should update your working folder by the following commands:&lt;/p&gt;
&lt;pre&gt;
&lt;strong&gt;git svn fetch
git svn rebase
&lt;/strong&gt;&lt;/pre&gt;
&lt;p&gt;
	This will update your local git working copy by getting all the changes made by other people and then applies your local changes over that.&lt;/p&gt;
&lt;p&gt;
	The last command to send your changeset to the SVN repository is the following:&lt;/p&gt;
&lt;pre&gt;
&lt;strong&gt;git svn dcommit
&lt;/strong&gt;&lt;/pre&gt;
&lt;p&gt;
	To find out more about git commands, try &lt;a href=&quot;http://git.wiki.kernel.org/index.php/GitCheatSheet&quot;&gt;this&lt;/a&gt; cheat sheet that comes handy.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Silverlight Applications with J2EE Backend - Part Two</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/Silverlight-J2EE-Backend-Part-Two"/>
    <id>http://www.hightech.ir/SeeSharp/Silverlight-J2EE-Backend-Part-Two</id>
    <updated>2010-03-07T06:43:16.933</updated>
    <published>2010-03-07T08:00:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="RIA" />
    <category term="Silverlight" />
    <category term="J2EE" />
    <content type="html" xml:lang="en">
      &lt;p&gt;
	In &lt;a href=&quot;http://www.hightech.ir/SeeSharp/Silverlight-J2EE-Backend-Part-One&quot;&gt;previous&lt;/a&gt; post, we saw how easy it is to use J2EE as a rich backend. Let&amp;#39;s continue with our example and show how to fetch and send some data from our J2EE backend to a Silverlight rich client application. Let&amp;#39;s continue our work using a simple Blog domain model.&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;&quot; src=&quot;http://www.hightech.ir/Images/BlogPics/J2EE_P2_BlogDomainModel.png&quot; style=&quot;width: 556px; height: 293px;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	&amp;nbsp;&lt;/p&gt;
&lt;p&gt;
	To create our simple domain model, let&amp;#39;s create the domain classes in java and let &lt;a href=&quot;http://en.wikipedia.org/wiki/Java_Persistence_API&quot;&gt;JPA&lt;/a&gt; create the database for us. For .NET developers familiar with NHibernate and &lt;a href=&quot;https://www.hibernate.org/hib_docs/nhibernate/html/mapping-attributes.html&quot;&gt;NHibernate Mapping Attributes&lt;/a&gt; project, when comparing this to .NET coding style, there should be nothing new here. Here&amp;#39;s a piece of code:&lt;br /&gt;
	&amp;nbsp;&lt;/p&gt;
&lt;pre class=&quot;brush:java&quot;&gt;
package ir.hightech.silverbox.domain;

import javax.persistence.*;
import java.util.List;

@Table(name = &amp;quot;sl_Post&amp;quot;)
@Entity
public class Post {

    private int postId;
    private String title;
    private Blog blog;
    private List&amp;lt;Comment&amp;gt; comments;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = &amp;quot;PostId&amp;quot;, nullable = false)
    public int getPostId() {
        return postId;
    }

    public void setPostId(int postId) {
        this.postId = postId;
    }

    @ManyToOne
    public Blog getBlog() {
        return blog;
    }

    public void setBlog(Blog blog) {
        this.blog = blog;
    }

    @Column(name = &amp;quot;Title&amp;quot;, nullable = false)
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @OneToMany(mappedBy = &amp;quot;post&amp;quot;)
    public List&amp;lt;Comment&amp;gt; getComments() {
        return comments;
    }

    public void setComments(List&amp;lt;Comment&amp;gt; comments) {
        this.comments = comments;
    }
}

package ir.hightech.silverbox.domain;

import javax.persistence.*;

@Table(name = &amp;quot;sl_Comment&amp;quot;)
@Entity
public class Comment {

    private int commentId;
    private Post post;
    private String text;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = &amp;quot;CommentId&amp;quot;, nullable = false)
    public int getCommentId() {
        return commentId;
    }

    public void setCommentId(int commentId) {
        this.commentId = commentId;
    }

    @ManyToOne()
    public Post getPost() {
        return post;
    }

    public void setPost(Post post) {
        this.post = post;
    }

    @Column(name = &amp;quot;CommentText&amp;quot;, nullable = false)
    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}
&lt;/pre&gt;
&lt;p&gt;
	Let&amp;#39;s create a service to return a list of all available Posts and display them on our Silverlight client. Continuing from previous post, you&amp;#39;ve already learned how to create services (or &lt;a href=&quot;http://en.wikipedia.org/wiki/Session_Beans&quot;&gt;SessionBeans&lt;/a&gt; as called in EJB context) but when you actually have an entity model and want to expose it through service, you&amp;#39;d better think twice. There are a lot of things that can go wrong if you do so:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;
		Your change in domain model will ripple to your clients because of changes in service contract and will probably break all your clients.&lt;br /&gt;
		&amp;nbsp;&lt;/li&gt;
	&lt;li&gt;
		Your domain model might contain sensitive information which is best kept on your service tier.&lt;br /&gt;
		&amp;nbsp;&lt;/li&gt;
	&lt;li&gt;
		Other technical stuff such as your entities beiing lazy and having problems with serialization process.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
	&lt;br /&gt;
	So before continuing, let&amp;#39;s create some &lt;a href=&quot;http://en.wikipedia.org/wiki/Data_transfer_object&quot;&gt;DTO&lt;/a&gt; objects which will be sent across the service boundary. For this sample, a &lt;a href=&quot;http://en.wikipedia.org/wiki/Plain_Old_Java_Object&quot;&gt;POJO&lt;/a&gt; class resembling your existing Post entity would suffice. To map between Entities and DTOs, you can roll your own mapper classes.&lt;/p&gt;
&lt;pre class=&quot;brush:java&quot;&gt;
package ir.hightech.silverbox.common;

import ir.hightech.silverbox.domain.Post;
import javax.ejb.Remote;
import java.util.List;

@Remote
public interface BlogService {
    List&amp;lt;PostDto&amp;gt; getAllPosts();
}


package ir.hightech.silverbox.services;

import ir.hightech.silverbox.common.BlogService;
import ir.hightech.silverbox.domain.Post;
import javax.ejb.*;
import javax.jws.*;
import javax.persistence.*;
import java.util.*;

@Stateless(name = &amp;quot;BlogService&amp;quot;)
@Remote(BlogService.class)
@WebService
public class BlogServiceImpl implements BlogService {

    @PersistenceContext
    protected EntityManager em;

    public List&amp;lt;PostDto&amp;gt; getAllPosts() {
        Query query = em.createQuery(&amp;quot;FROM Post&amp;quot;);
        List&amp;lt;Post&amp;gt; result = query.setMaxResults(10)
                                 .getResultList();

        return new PostMapper().MapMany(result);
    }
}
&lt;/pre&gt;
&lt;p&gt;
	Did you notice the EntityManager? It is injected automatically by EJB container and the good thing is you can inject other services, even your other EJB session beans too. EntityManager provides &lt;a href=&quot;http://technology-related.com/javaee/5/docs/api/javax/persistence/EntityManager.html&quot;&gt;functionalities&lt;/a&gt; similar to ISession in N/Hiberante such as CreateQuery, Find, Attach/Detach, Flush, etc.&lt;br /&gt;
	&lt;br /&gt;
	Now let&amp;#39;s create a new Silverlight application and add a new &amp;quot;Service Reference&amp;quot; to your project which points to our new service at:&lt;/p&gt;
&lt;pre&gt;
http://localhost:9090/Silverbox/BlogService?WSDL
&lt;/pre&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;&quot; src=&quot;http://www.hightech.ir/Images/BlogPics/J2EE_P2_AddingServiceReference.png&quot; style=&quot;width: 475px; height: 383px;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	Note: Use IP / Port of your JBoss server, port is usually 8080. Mind the small / caps characters.&lt;/p&gt;
&lt;p&gt;
	If you open the proxy sources which is automatically generated, you&amp;#39;ll notice our DTO objects are all here in our Silverlight application now! There&amp;#39;s a slight modification though: All the classes and properties are named according to &lt;a href=&quot;http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html&quot;&gt;java naming conventions&lt;/a&gt; so our PostDto class is now named &amp;quot;postDto&amp;quot; on the Silverlight client. This is happened to all the properties of the proxy classes too so if you&amp;#39;re binding generated classes directly to your UI keep in mind that Xaml binding are case sensitive. What is good is that INotifyPropertyChange is already implemented. The rest is just regular Silverlight application calling a remote service:&lt;/p&gt;
&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;Grid x:Name=&amp;quot;LayoutRoot&amp;quot;&amp;gt;
    &amp;lt;ListBox x:Name=&amp;quot;RecentPosts&amp;quot;&amp;gt;
        &amp;lt;ListBox.ItemTemplate&amp;gt;
            &amp;lt;DataTemplate&amp;gt;
                &amp;lt;StackPanel Orientation=&amp;quot;Horizontal&amp;quot;&amp;gt;
                    &amp;lt;TextBlock Text=&amp;quot;{Binding Path=postDate}&amp;quot; /&amp;gt;
                    &amp;lt;TextBlock Text=&amp;quot;{Binding Path=title}&amp;quot; /&amp;gt;
                &amp;lt;/StackPanel&amp;gt;
            &amp;lt;/DataTemplate&amp;gt;
        &amp;lt;/ListBox.ItemTemplate&amp;gt;
    &amp;lt;/ListBox&amp;gt;
&amp;lt;/Grid&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
	and to call the service:&lt;/p&gt;
&lt;pre class=&quot;brush:csharp&quot;&gt;
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    var service = new BlogServiceImplClient();
    service.GetAllPostsCompleted += (snd, arg) =&amp;gt; 
    {
        if(arg.Error == null)
        {
            RecentPosts.ItemsSource = arg.Result;
        }
    };
    service.GetAllPostsAsync();
}
&lt;/pre&gt;
&lt;p&gt;
	You should have a rich application that is bound to your database using your service layer on J2EE. Pretty easy so far, don&amp;#39;t you think?&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;&quot; src=&quot;http://www.hightech.ir/Images/BlogPics/J2EE_P2_RunningApplication.png&quot; style=&quot;width: 455px; height: 440px;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	Next post in this serie will show you how to handle business validation using SoapFaults, how to serialize Java exceptions into Silverlight client and how to actually deploy the whole application. Get the sources of this part from &lt;a href=&quot;http://cid-4962b6ceabc2cbd7.skydrive.live.com/self.aspx/BlogFiles/SilverBox%20-%20PartTwo.zip&quot;&gt;here&lt;/a&gt;.&lt;br /&gt;
	&amp;nbsp;&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">PersianCalendar support for DevExpress</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/PersianCalendar-Support-For-DevExpress"/>
    <id>http://www.hightech.ir/SeeSharp/PersianCalendar-Support-For-DevExpress</id>
    <updated>2010-02-27T07:43:28.787</updated>
    <published>2010-02-26T08:57:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="FarsiLibrary" />
    <category term="WPF" />
    <category term="DevExpress" />
    <content type="html" xml:lang="en">
      &lt;p&gt;
	Creating Line of Business applications using &lt;a href=&quot;http://www.devexpress.com/Products/NET/Controls/WPF/Grid/&quot;&gt;DevExpress WPF controls&lt;/a&gt; is just a breeze. The actual application is nice looking too! Since there are a couple of skins available and the good thing is the skin also changes the look and feel of standard WPF controls!&lt;/p&gt;
&lt;p&gt;
	I&amp;#39;ve used &lt;a href=&quot;http://github.com/HEskandari/FarsiLibrary&quot;&gt;my calendar library&lt;/a&gt; to develop a fully localizable solution. These controls support &lt;a href=&quot;http://en.wikipedia.org/wiki/Gregorian_calendar&quot;&gt;Gregorian&lt;/a&gt;, &lt;a href=&quot;http://en.wikipedia.org/wiki/Islamic_calendar&quot;&gt;Hijri&lt;/a&gt; and &lt;a href=&quot;http://en.wikipedia.org/wiki/Iranian_calendar&quot;&gt;Persian&lt;/a&gt; calendars so multicultural application development would be seamless, but the look and feel of my controls were a lot different than the ones provided by DevExpress. On the other hand, DevExpress only supports Gregorian calendar! So I needed to apply look and feel of DevExpress to my controls. It goes without saying that you can open the controls in Expression Blend and give it a style that mimics DevExpress look and feel, but that is not easy to do.&lt;/p&gt;
&lt;p&gt;
	DevExpress provides a PopupEditBase control that can be used to display any control as a Popup. That seemed to be a good choice and it was easy to create a new control all in xaml markup:&lt;/p&gt;
&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;Window x:Class=&amp;quot;DXCustomEditor.MainWindow&amp;quot;
        xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;
        xmlns:x=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml&amp;quot; 
        xmlns:dxe=&amp;quot;http://schemas.devexpress.com/winfx/2008/xaml/editors&amp;quot; 
        xmlns:fx=&amp;quot;http://schemas.hightech.ir/wpf/2008/FarsiLibrary&amp;quot;
        Title=&amp;quot;DX Editors&amp;quot; Height=&amp;quot;350&amp;quot; Width=&amp;quot;525&amp;quot;
        xmlns:loc=&amp;quot;clr-namespace:DXCustomEditor&amp;quot;&amp;gt;
    &amp;lt;Window.Resources&amp;gt;
        &amp;lt;loc:DateConverter x:Key=&amp;quot;DateConverter&amp;quot;/&amp;gt;
        &amp;lt;ControlTemplate x:Key=&amp;quot;DatePickerTemplate&amp;quot;&amp;gt;
            &amp;lt;fx:FXMonthView SelectedDateTime=&amp;quot;{Binding Path=(dxe:BaseEdit.OwnerEdit).EditValue, Mode=TwoWay, RelativeSource={RelativeSource Mode=TemplatedParent}, Converter={StaticResource DateConverter}}&amp;quot;/&amp;gt;
        &amp;lt;/ControlTemplate&amp;gt;
    &amp;lt;/Window.Resources&amp;gt;
    &amp;lt;StackPanel Margin=&amp;quot;10&amp;quot;&amp;gt;
        &amp;lt;dxe:PopupBaseEdit IsTextEditable=&amp;quot;False&amp;quot; PopupContentTemplate=&amp;quot;{StaticResource ResourceKey=DatePickerTemplate}&amp;quot; /&amp;gt;
    &amp;lt;/StackPanel&amp;gt;
&amp;lt;/Window&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
	The outcome is pretty good: seamless calendar support and look and feel.&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;&quot; src=&quot;http://www.hightech.ir/Images/BlogPics/ePub-Screenshot-s.png&quot; /&gt;&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Silverlight Binding: Lesson Learned</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/Silverlight-Binding-Lesson-Learned"/>
    <id>http://www.hightech.ir/SeeSharp/Silverlight-Binding-Lesson-Learned</id>
    <updated>2010-02-17T14:10:19.227</updated>
    <published>2010-02-17T10:00:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Silverlight" />
    <category term="CodeAnalysis" />
    <content type="html" xml:lang="en">
      &lt;p&gt;
	When working on a Silverlight application that recieved data from a WebService I notice that loading of an array of 1500 items takes a lot of time. With this problem, application launch that has 3 separate webservice lookups, took almost 5 minutes to complete.&lt;/p&gt;
&lt;p&gt;
	The problem became more interesting when my colleague actually ran get the same data bound UI in WinForms in 2 seconds, so there were something fishy going on in out Silverlight application. Let&amp;#39;s see the original code that loaded the data from the webservice:&lt;/p&gt;
&lt;pre class=&quot;brush:csharp&quot;&gt;
public virtual void Load()
{
    var client = new ServiceClient();
    client.GetAllFirstLookupCompleted += (s, e) =&amp;gt; Lookup.AddRange(e.Result.MapMany&amp;lt;LookupResult, LookupResultDTO&amp;gt;());
    client.GetAllFirstLookupAsync();
}

public virtual ObservableCollection&amp;lt;LookupResultDTO&amp;gt; Lookup
{
    get; private set;
}
&lt;/pre&gt;
&lt;p&gt;
	WebService call returned a &amp;quot;LookupResult&amp;quot; but we used LookupResultDTO object bound to UI so the first thing we needed to do was to convert between these types. Then our bound collection was a ObservableCollection. Unlike the same type in WPF, ObservableCollction in Silverlight has no construct that accepts an IList so you have to add individual items one by one! To make things &amp;quot;look&amp;quot; niceer, we&amp;#39;ve created an AddRange extension method that add items of an IList to an ObservableCollection.&lt;/p&gt;
&lt;p&gt;
	So, why would the above code take this long?&lt;/p&gt;
&lt;p&gt;
	&lt;span class=&quot;subtitle&quot;&gt;First Mistake&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;
	First mistake was to use &lt;a href=&quot;http://www.codeplex.com/AutoMapper&quot;&gt;AutoMapper&lt;/a&gt;! Yes, it makes life easier by automagically map two unconvertable types by using reflection and flatting structure. It even works great if your collections are relatively small but avoid using it if you have a large collection (I don&amp;#39;t even consider a collection of 1000 items large!).&lt;/p&gt;
&lt;p&gt;
	You can always roll your own mappers and it is easy to create and use. Our mapper looked like this:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class LookupResultMapper
{
    public LookupResultDTO MapOne(LookupResult result)
    {
        return new LookupResultDTO(result.PrimaryKey, result.Name, result.Number);
    }

    public IList&amp;lt;LookupResultDTO&amp;gt; MapMany(LookupResult[] results)
    {
        var list = new List&amp;lt;LookupResultDTO&amp;gt;();

        foreach (var result in results)
        {
            list.Add(MapOne(result));
        }

        return list;
    }
}
&lt;/pre&gt;
&lt;p&gt;
	The reason is obvious! Using reflection is a lot slower and when you&amp;#39;re doing it for 1000 times, you&amp;#39;ll get 1000 times slower! This small change improved the performance more than 50%.&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public virtual void Load()
{
    var client = new ServiceClient();
    client.GetAllFirstLookupCompleted += (s, e) =&amp;gt; Lookup.AddRange(new LookupResultMapper().MapMany(e.Result));
    client.GetAllFirstLookupAsync();
}
&lt;/pre&gt;
&lt;p&gt;
	&lt;span class=&quot;subtitle&quot;&gt;Second Mistake&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;
	When a UI element is bound to an observable collection, every addition and removal of an Item probably lead to some calculation in the element for things such as draing and layout calculation. Second problem was to add the collection one by one to the observable collection.&lt;/p&gt;
&lt;p&gt;
	Unfortunately, as mentioned, ObservableCollection unlike WPF version has no construct that accepts an IList. You have some options though:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;
		Make your UI element Invisible (Visibility=Collapsed or Hidden) then add the items to the bound collection. This will prevent exhaustive calculation.&lt;br /&gt;
		&amp;nbsp;&lt;/li&gt;
	&lt;li&gt;
		Change the collection type from ObservableCollection to IList, if possible.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
	&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
	Depending on your scenarios, one of the above mentioned solutions may work for you. In our case, we didn&amp;#39;t need to add / remove items from the collection at a later time so switching to IList did the trick.&lt;/div&gt;
&lt;div&gt;
	&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
	After refactoring, application that took almost 5 minutes to launch now runs in seconds!&lt;/div&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Silverlight Applications with J2EE Backend - Part One</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/Silverlight-J2EE-Backend-Part-One"/>
    <id>http://www.hightech.ir/SeeSharp/Silverlight-J2EE-Backend-Part-One</id>
    <updated>2010-02-13T16:21:09.76</updated>
    <published>2010-02-13T16:21:09.57</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Silverlight" />
    <category term="J2EE" />
    <category term="Java" />
    <content type="html" xml:lang="en">
      &lt;p&gt;
	If you have not heard, &lt;a href=&quot;http://www.microsoft.com/SILVERLIGHT/&quot;&gt;Silverlight&lt;/a&gt; is the latest rich client technology from &lt;a href=&quot;http://www.microsoft.com&quot;&gt;Microsoft&lt;/a&gt;. The good thing about it is that it works almost on all browsers and operating systems and you can host your application on non-microsoft stack too, but there are things such as database connectivity that you can&amp;#39;t benefit from when creating Silverlight applications. The only way to create data-driven applications would be to use a service backend. Here I&amp;#39;ll show you how to create a J2EE backend for your Silverlight application and host it on a &lt;a href=&quot;http://www.jboss.org/&quot;&gt;JBoss&lt;/a&gt; application server.&lt;br /&gt;
	&lt;br /&gt;
	To create the backend for the Silverlight application, I&amp;#39;ll show you how you can use &lt;a href=&quot;http://java.sun.com/javaee/&quot;&gt;J2EE&lt;/a&gt; technology which provides rich infrastructure for your backend. I&amp;#39;ll be using &lt;a href=&quot;http://sourceforge.net/projects/jboss/files/JBoss/JBoss-4.2.3.GA/&quot;&gt;JBoss 4.2.3 GA&lt;/a&gt; application server to run this sample, and &lt;a href=&quot;http://www.jetbrains.com/idea/&quot;&gt;IntelliJ IDEA 9.0 Enterprise&lt;/a&gt; to develop the backend.&amp;nbsp; IntelliJ IDEA Enterprise is not a free IDE (there&amp;#39;s a &lt;a href=&quot;http://www.jetbrains.com/idea/free_java_ide.html&quot;&gt;free Community version&lt;/a&gt;), but using it is natural for .NET developers having experience with &lt;a href=&quot;http://www.jetbrains.com/resharper&quot;&gt;Resharper&lt;/a&gt; addin tool for Visual Studio .NET. Of course, both tools are from the &lt;a href=&quot;http://www.jetbrains.com/&quot;&gt;same company&lt;/a&gt;, but if you use Resharper with IntelliJ shortcuts most of them work in IntelliJ IDEA too. You can get a trial version from &lt;a href=&quot;http://www.jetbrains.com/resharper/download&quot;&gt;here&lt;/a&gt; for this experiment if you&amp;#39;re an experienced java developer, you can still use your favorite IDE.&lt;/p&gt;
&lt;p&gt;
	This post is intented for .NET developers with (almost) no experience with Java language. If you&amp;#39;re familiar with NHiberanate, theorethically you should be able to use &lt;a href=&quot;http://en.wikipedia.org/wiki/Java_Persistence_API&quot;&gt;JPA&lt;/a&gt; in no time because of a lot API similarities: JPA provides APIs that are very familiar with (N)Hiberante.&lt;br /&gt;
	&lt;br /&gt;
	&lt;span class=&quot;subtitle&quot;&gt;Project Structure&lt;/span&gt;&lt;br /&gt;
	For our backend we&amp;#39;ll use a standard J2EE project, with support for JPA, &lt;a href=&quot;http://en.wikipedia.org/wiki/Java_API_for_XML_Web_Services&quot;&gt;JAXWS&lt;/a&gt; WebServices and other J2EE services. Fire up your IntellliJ IDEA and create a new project. In the project wizard, select &amp;quot;Java Module&amp;quot; and set path for your project sources. From the technologies page in the wizard, select &amp;quot;JavaEE Persistence&amp;quot;, &amp;quot;Enterprise JavaBeans&amp;quot;, &amp;quot;JavaEE Application&amp;quot; and &amp;quot;WebServices&amp;quot;. The wizard will download the &lt;a href=&quot;http://en.wikipedia.org/wiki/JAR_(file_format)&quot;&gt;JAR&lt;/a&gt; filles and libraries that are necessary from JetBrain&amp;#39;s website and set the project structure for you. Before we&amp;#39;re done with the project structure, we need to do some modifications.&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;&quot; src=&quot;/Images/BlogPics/J2EEBackend_NewProject.png&quot; style=&quot;width: 642px; height: 462px;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	Thanks to &lt;a href=&quot;http://en.wikipedia.org/wiki/Enterprise_JavaBean&quot;&gt;EJB 3.0&lt;/a&gt; and its &lt;a href=&quot;http://en.wikipedia.org/wiki/Java_annotation&quot;&gt;annotation&lt;/a&gt;-based EJBs no xml configuration would be necessary, so open &amp;quot;ejb-jar.xml&amp;quot; file and remove its content (enterprise-beans tag and its content). This file is in META-INF folder in the root of the project. Then open the &amp;quot;persistence.xml&amp;quot; from META-INF folder under the &amp;quot;src&amp;quot; folder and setup the persistence API.&lt;br /&gt;
	&lt;br /&gt;
	&lt;em&gt;Note: If you have hard time finding any class or file use the same shortcut as in Resharper (CTRL+SHIFT+N for files and CTRL+N for classes and interfaces).&lt;br /&gt;
	&lt;/em&gt;&lt;br /&gt;
	This file is almost like hibernate configuration file so most of the content should be self explanatory:&lt;/p&gt;
&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot;?&amp;gt;
&amp;lt;persistence xmlns=&amp;quot;http://java.sun.com/xml/ns/persistence&amp;quot; version=&amp;quot;2.0&amp;quot;&amp;gt;
    &amp;lt;persistence-unit name=&amp;quot;NewPersistenceUnit&amp;quot;&amp;gt;
        &amp;lt;provider&amp;gt;org.hibernate.ejb.HibernatePersistence&amp;lt;/provider&amp;gt;
        &amp;lt;jta-data-source&amp;gt;java:/silverbox-ds&amp;lt;/jta-data-source&amp;gt;
        &amp;lt;properties&amp;gt;
            &amp;lt;property name=&amp;quot;hibernate.connection.url&amp;quot; value=&amp;quot;jdbc:sqlserver://127.0.0.1;databaseName=silverboxdb&amp;quot;/&amp;gt;
            &amp;lt;property name=&amp;quot;hibernate.connection.driver_class&amp;quot; value=&amp;quot;com.microsoft.sqlserver.jdbc.SQLServerDriver&amp;quot;/&amp;gt;
            &amp;lt;property name=&amp;quot;hibernate.connection.username&amp;quot; value=&amp;quot;sa&amp;quot;/&amp;gt;
            &amp;lt;property name=&amp;quot;hibernate.connection.password&amp;quot; value=&amp;quot;12345&amp;quot;/&amp;gt;
            &amp;lt;property name=&amp;quot;hibernate.archive.autodetection&amp;quot; value=&amp;quot;class&amp;quot;/&amp;gt;
            &amp;lt;property name=&amp;quot;hibernate.show_sql&amp;quot; value=&amp;quot;true&amp;quot;/&amp;gt;
            &amp;lt;property name=&amp;quot;hibernate.format_sql&amp;quot; value=&amp;quot;true&amp;quot;/&amp;gt;
            &amp;lt;property name=&amp;quot;hbm2ddl.auto&amp;quot; value=&amp;quot;update&amp;quot;/&amp;gt;
        &amp;lt;/properties&amp;gt;
    &amp;lt;/persistence-unit&amp;gt;
&amp;lt;/persistence&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
	Other than database configuration, notice the &amp;quot;jta-data-source&amp;quot; tag which points to a specified datasource name. We&amp;#39;ll learn about this in a bit.&lt;br /&gt;
	&lt;br /&gt;
	IntelliJ Enterprise integrates with most of the application servers, including JBoss. First make sure you have a working version of JBoss application server which you can download from &lt;a href=&quot;http://sourceforge.net/projects/jboss/files/JBoss/JBoss-4.2.3.GA/&quot;&gt;here&lt;/a&gt;. Open the Settings menu (CTRL+ALT+S) and from the Application Servers add a new JBoss Server and select the folder where you unzipped the JBoss package. Then in IntelliJ open the &amp;quot;Edit Configurations&amp;quot; submenu from &amp;quot;Run&amp;quot; menu and add a local JBoss Server. The already added JBoss server will be added. Select the default &amp;quot;Server Instance&amp;quot;. Notice the warning message in the dialog that says &amp;quot;Warning: No artifacts marked for deployment&amp;quot;.&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;&quot; src=&quot;/Images/BlogPics/J2EEBackend_Artifact.png&quot; style=&quot;width: 556px; height: 278px;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	&lt;em&gt;Note: Your applications may contain libraries, compiled binaries, services, etc. all will be packaged in a deployable unit. The standard deployment unit in Java is JAR (java archive) but other packages exists, namingly WAR (web archive) and SAR (service archive). All the mentioned packages can be packed and deployed in a single deployment unit named EAR (enterprise archive) file.&lt;br /&gt;
	&lt;/em&gt;&lt;br /&gt;
	To specify what should be contained in the deployable package, we need to specify the deployment artifacts. To do this, go to &amp;quot;Project Structure&amp;quot; dialog (CTRL+ALT+SHIFT+S) and select the &amp;quot;Artifact&amp;quot; from the side list. Add a new artifact by pressing &amp;quot;+&amp;quot; button. Enter a name for your artifact and select the &amp;quot;JavaEE Application: Exploded&amp;quot; as the type. From the &amp;quot;Output Layout&amp;quot; add the &amp;quot;Module Output&amp;quot; and a &amp;quot;JPA Descriptors&amp;quot;. From the bottom of the page, click &amp;quot;Create Manifest&amp;quot; button to create an empty manifest in your &amp;quot;src\META-INF&amp;quot; folder.&lt;br /&gt;
	&lt;br /&gt;
	Open up the &amp;quot;Project Structure&amp;quot; dialog again and check the &amp;quot;Build Artifacts...&amp;quot; check mark and from the dialog select the artifact name you&amp;#39;ve just created.&lt;br /&gt;
	&lt;br /&gt;
	The project structure is almost ready. Now let&amp;#39;s add some code.&lt;br /&gt;
	&lt;br /&gt;
	&lt;span class=&quot;subtitle&quot;&gt;Create Enterprise Beans&lt;/span&gt;&lt;br /&gt;
	Under the &amp;quot;src&amp;quot; folder create two &lt;a href=&quot;http://en.wikipedia.org/wiki/Java_package&quot;&gt;packages&lt;/a&gt; (a.k.a namespaces). I&amp;#39;ve named the packages as &amp;quot;ir.hightech.silverbox.common&amp;quot; and &amp;quot;ir.hightech.silverbox.services&amp;quot;. I will separate the service interfaces and implementation in separate folders. To create a basic loopback service create the following interface in the &amp;quot;common&amp;quot; package:&lt;/p&gt;
&lt;pre class=&quot;brush:java&quot;&gt;
package ir.hightech.silverbox.common;

import javax.ejb.Remote;

@Remote
public interface LoopbackService {
    void echo();
}
&lt;/pre&gt;
&lt;p&gt;
	...and create the implementation in the &amp;quot;services&amp;quot; folder:&lt;/p&gt;
&lt;pre class=&quot;brush:java&quot;&gt;
package ir.hightech.silverbox.services;

import ir.hightech.silverbox.common.LoopbackService;
import javax.ejb.Remote;
import javax.ejb.Stateless;

@Stateless(name = &amp;quot;LoopbackService&amp;quot;)
@Remote(LoopbackService.class)
public class LoopbackServiceImpl implements LoopbackService{
    public void echo() {
        System.out.println(&amp;quot;Hello, world!&amp;quot;);
    }
}
&lt;/pre&gt;
&lt;p&gt;
	&lt;em&gt;Note: Each EJB can be used locally or remotely so different annotations are required based on usage context. Since we need to only expose the EJBs as a service, we&amp;#39;ve only specified it to be a &amp;quot;Remote&amp;quot; service / interface.&lt;br /&gt;
	&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;
	Final step would be to expose the EJB as a Webservice. That is as easy as adding an annotation to our service implementation:&lt;/p&gt;
&lt;pre class=&quot;brush:java&quot;&gt;
@Stateless(name = &amp;quot;LoopbackService&amp;quot;)
@Remote(LoopbackService.class)
@WebService
public class LoopbackServiceImpl implements LoopbackService{
   ...
}
&lt;/pre&gt;
&lt;p&gt;
	&lt;br /&gt;
	&lt;span class=&quot;subtitle&quot;&gt;Data Sources&lt;/span&gt;&lt;br /&gt;
	Before we deploy and run the application, we need to setup the datasource specified as &amp;quot;jta-data-source&amp;quot; in our &amp;quot;persistence.xml&amp;quot; file. JBoss when ran searches the deploy folder for the specified datasource. Datasource file names are ended with &amp;quot;ds&amp;quot; suffix by convention. The datasource file contains connection information that will be used in our application. Here the &amp;quot;jndi-name&amp;quot; is important and it should be the same thing as what we&amp;#39;ve specified in persistence.xml file. To use MS-SQL 2005 database create the following file and copy the file in the &amp;quot;deploy&amp;quot; folder of the JBoss. You can create an &lt;a href=&quot;http://ant.apache.org/&quot;&gt;ANT script&lt;/a&gt; and automatically copy this file into the destination folder, if you prefer.&lt;/p&gt;
&lt;pre class=&quot;brush:java&quot;&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; standalone=&amp;quot;no&amp;quot;?&amp;gt;
&amp;lt;datasources&amp;gt;
    &amp;lt;local-tx-datasource&amp;gt;
        &amp;lt;jndi-name&amp;gt;silverbox-ds&amp;lt;/jndi-name&amp;gt;
        &amp;lt;connection-url&amp;gt;jdbc:sqlserver://127.0.0.1;databaseName=silverboxdb&amp;lt;/connection-url&amp;gt;
        &amp;lt;driver-class&amp;gt;com.microsoft.sqlserver.jdbc.SQLServerDriver&amp;lt;/driver-class&amp;gt;
        &amp;lt;user-name&amp;gt;sa&amp;lt;/user-name&amp;gt;
        &amp;lt;password&amp;gt;12345&amp;lt;/password&amp;gt;
        &amp;lt;metadata&amp;gt;
            &amp;lt;type-mapping&amp;gt;MS SQLSERVER2000&amp;lt;/type-mapping&amp;gt;
        &amp;lt;/metadata&amp;gt;
    &amp;lt;/local-tx-datasource&amp;gt;
&amp;lt;/datasources&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
	&lt;span class=&quot;subtitle&quot;&gt;Deployment&lt;/span&gt;&lt;br /&gt;
	We&amp;#39;re almost there now. From the main toolbar, click the &amp;quot;Run&amp;quot; button to fire up the JBoss server. Notice the logs that appear in Output window of the IntelliJ IDEA. If you see that artifact is deployed successfully, you&amp;#39;re good. Fire up your browser and enter the services url to see the automatically generated WSDL. The deployed URL would be http://localhost:8080/Silverbox/LoopbackService?WSDL but if you&amp;#39;ve named your artifact and service something different it is in the format of http://jbossmachine:port/artifactname/Servicename (you can also see the registered Endpoint in the output window).&lt;/p&gt;
&lt;p&gt;
	Next we&amp;#39;ll see how to extend the service and create a Silverlight client that accesses our backend. Get the source files for this part from &lt;a href=&quot;http://cid-4962b6ceabc2cbd7.skydrive.live.com/self.aspx/BlogFiles/SilverBox-PartOne.zip&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Must Read Books For Programmers</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/Must-Read-Books-For-Programmers"/>
    <id>http://www.hightech.ir/SeeSharp/Must-Read-Books-For-Programmers</id>
    <updated>2010-01-25T10:22:25.323</updated>
    <published>2010-01-21T08:00:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Books" />
    <category term="Programming" />
    <content type="html" xml:lang="en">
      &lt;p&gt;
	It&amp;#39;s been a while that I wanted to prepare a list of books that, in my opinion, every programmer should read. These are the most influential books I&amp;#39;ve read so far in my career. It is not supposed to be a complete list of any kind and this is just my idea of a must read. Books mentioned here may or may not be specific to a programming language, so check it before you buy the book.&lt;/p&gt;
&lt;p&gt;
	With the fact (or is it a fiction?) that &lt;a href=&quot;http://www.codinghorror.com/blog/archives/001108.html&quot;&gt;programmers don&amp;#39;t like to read books&lt;/a&gt; in mind, I limited the list to only ten books, but there are certainly other great books out there that either I&amp;#39;m not aware of or may be have not read yet. I was already a programmer when I read most of these books, but these really helped me open my mind towards how professionals are doing it and why.&lt;/p&gt;
&lt;p&gt;
	Enough said, here&amp;#39;s the list:&lt;/p&gt;
&lt;p&gt;
	&lt;a href=&quot;http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;&quot; src=&quot;../../../Images/url_icon.gif&quot; style=&quot;width: 13px; height: 13px;&quot; /&gt;&lt;/a&gt; 10- &lt;strong&gt;Design Patterns: Elements of Reusable Object-Oriented Software&lt;/strong&gt; by &lt;em&gt;Gang of Four&lt;/em&gt;&lt;br /&gt;
	&lt;a href=&quot;http://www.amazon.com/gp/aw/d.html?a=0132350882&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;&quot; src=&quot;../../../Images/url_icon.gif&quot; style=&quot;width: 13px; height: 13px;&quot; /&gt;&lt;/a&gt; 9- &lt;strong&gt;Clean Code A Handbook of Agile Software Craftsmanship&lt;/strong&gt; by &lt;em&gt;Robert C. Martin&lt;/em&gt;&lt;br /&gt;
	&lt;a href=&quot;http://www.amazon.com/Agile-Project-Management-Microsoft-Professional/dp/073561993X&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;&quot; src=&quot;../../../Images/url_icon.gif&quot; style=&quot;width: 13px; height: 13px;&quot; /&gt;&lt;/a&gt; 8- &lt;strong&gt;Agile Project Management with Scrum&lt;/strong&gt; by &lt;em&gt;Ken Schwaber&lt;/em&gt;&lt;br /&gt;
	&lt;a href=&quot;http://www.amazon.com/Applying-Domain-Driven-Design-Patterns-Examples/dp/0321268202&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;&quot; src=&quot;../../../Images/url_icon.gif&quot; style=&quot;width: 13px; height: 13px;&quot; /&gt;&lt;/a&gt; 7- &lt;strong&gt;Applying Domain-Driven Design and Patterns&lt;/strong&gt; by &lt;em&gt;Jimmy Nilsson&lt;/em&gt;&lt;br /&gt;
	&lt;a href=&quot;http://www.amazon.com/gp/aw/d.html?a=0131177052&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;&quot; src=&quot;../../../Images/url_icon.gif&quot; style=&quot;width: 13px; height: 13px;&quot; /&gt;&lt;/a&gt; 6- &lt;strong&gt;Working Effectively with Legacy Code&lt;/strong&gt; by &lt;em&gt;Michael Feathers&lt;/em&gt;&lt;br /&gt;
	&lt;a href=&quot;http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;&quot; src=&quot;../../../Images/url_icon.gif&quot; style=&quot;width: 13px; height: 13px;&quot; /&gt;&lt;/a&gt; 5- &lt;strong&gt;Patterns of Enterprise Application Architecture&lt;/strong&gt; by &lt;em&gt;Martin Fowler&lt;/em&gt;&lt;br /&gt;
	&lt;a href=&quot;http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;&quot; src=&quot;../../../Images/url_icon.gif&quot; style=&quot;width: 13px; height: 13px;&quot; /&gt;&lt;/a&gt; 4- &lt;strong&gt;Refactoring: Improving the Design of Existing Code&lt;/strong&gt; by &lt;em&gt;Martin Fowler&lt;/em&gt;&lt;em&gt;&lt;br /&gt;
	&lt;/em&gt;&lt;a href=&quot;http://www.amazon.com/gp/aw/d.html?a=0321146530&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;&quot; src=&quot;../../../Images/url_icon.gif&quot; style=&quot;width: 13px; height: 13px;&quot; /&gt;&lt;/a&gt; 3- &lt;strong&gt;Test Driven Development By Example&lt;/strong&gt; by &lt;em&gt;Kent Beck&lt;/em&gt;&lt;br /&gt;
	&lt;a href=&quot;http://www.amazon.com/Agile-Principles-Patterns-Practices-C/dp/0131857258&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;&quot; src=&quot;../../../Images/url_icon.gif&quot; style=&quot;width: 13px; height: 13px;&quot; /&gt;&lt;/a&gt; 2- &lt;strong&gt;Agile Principles Patterns and Practices&lt;/strong&gt; by &lt;em&gt;Robert C. Martin&lt;/em&gt;&lt;br /&gt;
	&lt;a href=&quot;http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;&quot; src=&quot;../../../Images/url_icon.gif&quot; style=&quot;width: 13px; height: 13px;&quot; /&gt;&lt;/a&gt; 1- &lt;strong&gt;Domain-Driven Design: Tackling Complexity in the Heart of Software&lt;/strong&gt; by &lt;em&gt;Eric Evans&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;
	Thoughts?&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Java and .NET Interoperability</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/Java-Interop-With-NET"/>
    <id>http://www.hightech.ir/SeeSharp/Java-Interop-With-NET</id>
    <updated>2010-01-18T10:53:46.093</updated>
    <published>2010-01-18T00:00:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="NET" />
    <category term="Java" />
    <category term="Interop" />
    <content type="html" xml:lang="en">
      &lt;p&gt;
	We&amp;#39;ve been doing a lot of Java / .NET &lt;a href=&quot;http://en.wikipedia.org/wiki/Interoperability&quot;&gt;interop&lt;/a&gt; for last couple of years in our enterprise applications. On one hand, our customers used their existing expertise and infrastructure that worked better with Java based technologies like their existing Unix based servers, Sybase database (on Unix) and the knowledge of their DBA team, and we using our existing Java developers and expertise. But what Java based technology provides that we don&amp;#39;t have on .NET world? Is it important at all?&lt;br /&gt;
	&lt;br /&gt;
	With rise of Silverlight presentation framework working the interop becomes more important. You can now create a sophisticated user interface and make it work with your existing EJBs on your JBoss backend and you have best of both worlds. As a .NET developer you might not be familiar what this provides, so here&amp;#39;s a few things you&amp;#39;ll get right out of the box:&lt;br /&gt;
	&lt;br /&gt;
	&lt;span class=&quot;subtitle&quot;&gt;Standard JPA (Java Persistance API)&lt;/span&gt;&lt;br /&gt;
	When you create applications on top of &lt;a href=&quot;http://java.sun.com/javaee/reference/faq/ejb.jsp&quot;&gt;EJB 3.0&lt;/a&gt; using any EJB compliant application server, one thing you get is a standard, pluggable persistence API. The idea behind &lt;a href=&quot;http://en.wikipedia.org/wiki/Java_Persistence_API&quot;&gt;JPA&lt;/a&gt; was to provide a standard set of interfaces to application developers and let the application server provide different implementations of these interfaces using various persistence frameworks. Great idea, right? This means you don&amp;#39;t need to learn how to use another persistence framework, because now they all support an standard interface.&lt;/p&gt;
&lt;p&gt;
	&lt;a href=&quot;http://www.jboss.org/&quot;&gt;JBoss&lt;/a&gt; actually uses &lt;a href=&quot;https://www.hibernate.org/&quot;&gt;Hiberante&lt;/a&gt; under the hood to implement this API but other application servers may have different engines. If you&amp;#39;re familiar with NHibernate, you&amp;#39;ll feel right at home!&lt;br /&gt;
	&lt;br /&gt;
	&lt;span class=&quot;subtitle&quot;&gt;JAX-WS WebServices&lt;/span&gt;&lt;br /&gt;
	Should you need to expose your business logic through WebServices, all you need to do is to decorate your existing services with an &lt;a href=&quot;http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html&quot;&gt;Annotation&lt;/a&gt; to signify the application service that the class provides a WebService endpoint. An &lt;em&gt;Annotation&lt;/em&gt; is actually a Java term for almost the same thing we call an &lt;em&gt;Attribute&lt;/em&gt; in .NET world.&lt;br /&gt;
	&lt;br /&gt;
	&lt;span class=&quot;subtitle&quot;&gt;Infrastructural Services&lt;/span&gt;&lt;br /&gt;
	There are a lot of cross cutting concerns your application server provides. Things such as standard logging framework, inversion of control container, queues, scheduling, &lt;a href=&quot;http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/EJBConcepts5.html&quot;&gt;Message Driven Bean&lt;/a&gt; (which is a very simple &lt;a href=&quot;http://en.wikipedia.org/wiki/Enterprise_service_bus&quot;&gt;ESB&lt;/a&gt;) , hot deployment of applications, etc.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;
	&lt;span class=&quot;subtitle&quot;&gt;Price Tag&lt;/span&gt;&lt;br /&gt;
	Yes, the best part of it is that all of this comes as free (as in free food). You don&amp;#39;t have to pay for licenses for your application server, you don&amp;#39;t have to pay for IDEs because there are a lot of great IDEs available, you don&amp;#39;t have to buy license for your Linux based Server and there&amp;#39;s a large community out there that can help you freely, if you&amp;#39;re stuck. Of course there are paid services too, mostly for services such as support, but you hardly need it. If you&amp;#39;re pairing Silverlight frontend with Java backend, you can use &lt;a href=&quot;http://www.eclipse4sl.org&quot;&gt;Eclipse&lt;/a&gt; to handle both in one place!&lt;/p&gt;
&lt;p&gt;
	This is just a scratch on the surface. I&amp;#39;ll shed more light on the subject on upcoming posts.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">WPF Application with Caliburn - Part Two</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/WPF-Application-With-Caliburn-Part-Two"/>
    <id>http://www.hightech.ir/SeeSharp/WPF-Application-With-Caliburn-Part-Two</id>
    <updated>2010-01-15T12:04:49.06</updated>
    <published>2010-01-15T00:00:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="MVVM" />
    <category term="WPF" />
    <category term="Caliburn" />
    <content type="html" xml:lang="en">
      &lt;p&gt;
	In this part of the tutorial, we&amp;#39;ll enhance our shell view to display other presenters and add Save and Print support for presenters supporting it. You can use generalize this example and learn how to implement generic features in your shell.&lt;/p&gt;
&lt;p&gt;
	Caliburn has several existing classes that can be used as a base class for our presenters. Let&amp;#39;s explain some of them and see where do they fit:&lt;/p&gt;
&lt;p&gt;
	&lt;span style=&quot;color: rgb(255, 140, 0);&quot;&gt;&lt;em&gt;&lt;strong&gt;Presenter&lt;/strong&gt;&lt;/em&gt;&lt;/span&gt;&lt;br /&gt;
	This class implements IPresenter interface and provides life time methods such as Initialize, Shutdown, Active and Deactive. You can use this class for other views that are going to be displayed in the Shell View.&lt;/p&gt;
&lt;p&gt;
	&lt;span style=&quot;color: rgb(255, 140, 0);&quot;&gt;&lt;em&gt;&lt;strong&gt;Presenter Manager&lt;/strong&gt;&lt;/em&gt;&lt;/span&gt;&lt;br /&gt;
	Using a presenter manager, as the name implies, you can host and display a single instance of a Presenter. It only allows displaying of one Presenter only so you have only one view displayed to the user when using it.&lt;/p&gt;
&lt;p&gt;
	&lt;span style=&quot;color: rgb(255, 140, 0);&quot;&gt;&lt;em&gt;&lt;strong&gt;MultiPresenterManager&lt;/strong&gt;&lt;/em&gt;&lt;/span&gt;&lt;br /&gt;
	Same as PresenterManager but can host multiple Presenters at the same time, but only one of them is Active at a time.&lt;/p&gt;
&lt;p&gt;
	When we display a Presenter, the PresenterManager will call the lifetime methods on the Presenter instance. The following diagram shows this flow:&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;&quot; src=&quot;/Images/BlogPics/Caliburn_PartTwo_Presenter.png&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	For now, it is obvious that we need to change the base class of our &lt;em&gt;ShellViewModel&lt;/em&gt; to &lt;em&gt;PresenterManager&lt;/em&gt; (too keep it simple for the time being), but how should we change the xaml code to host the views (other Presenters)? Your first guess would be to bind &lt;em&gt;CurrentPresenter&lt;/em&gt; property of the &lt;em&gt;PresenterManager&lt;/em&gt; to a &lt;em&gt;ContentControl&lt;/em&gt; in the Shell.xaml, but you don&amp;#39;t need to do that as Caliburn will do the plumbing for us, just add a &lt;em&gt;ContentControl&lt;/em&gt; to the Shell view where you want the views to be displayed and name it as &amp;quot;CurrentPresenter&amp;quot;.&lt;/p&gt;
&lt;p&gt;
	To make Caliburn bind Views to the content control, you need to enable additional &lt;em&gt;Conventions&lt;/em&gt; that are not enabled by default. Placing the following snippet in Caliburn configuration will do the trick:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
var binder = (DefaultBinder)Container.GetInstance&amp;lt;IBinder&amp;gt;();
binder.EnableBindingConventions();
&lt;/pre&gt;
&lt;p&gt;
	The bare bone of the shell view that displays a single presenter is this:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;Window x:Class=&amp;quot;PayRoll.Views.ShellView&amp;quot;
    xmlns=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&amp;quot;
    xmlns:x=&amp;quot;http://schemas.microsoft.com/winfx/2006/xaml&amp;quot; Width=&amp;quot;640&amp;quot; Height=&amp;quot;400&amp;quot;&amp;gt;
    &amp;lt;DockPanel LastChildFill=&amp;quot;True&amp;quot;&amp;gt;

        &amp;lt;ScrollViewer&amp;gt;
            &amp;lt;ContentControl x:Name=&amp;quot;CurrentPresenter&amp;quot; /&amp;gt;
        &amp;lt;/ScrollViewer&amp;gt;

    &amp;lt;/DockPanel&amp;gt;
&amp;lt;/Window&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
	&lt;span class=&quot;subtitle&quot;&gt;&lt;br /&gt;
	Adding Custom Controls&lt;/span&gt;&lt;br /&gt;
	Now to handle user interaction with the shell and the open presenter, we need some kind of a Toolbar / Menu control. WPF comes with a very basic menu and toolbar control, but to show how to use custom controls and see how Caliburn facilitates this, let&amp;#39;s use DevExpress BarManager control in this example.&lt;/p&gt;
&lt;p&gt;
	DevExpress, among other nice things, provides presentation layer controls for WPF such as Editors, Bars (MenuBar, ToolBar and soon Ribbon), Grid and Printing. One other thing they&amp;#39;ve also done is that they also have skinned native WPF controls so if used together with DevExpress controls, you&amp;#39;ll have a seemless look and feel.&lt;/p&gt;
&lt;p&gt;
	To add the BarManager control to our ShellView, you need to download DevExpress WPF controls (trial version here) and install it. The add the necessary reference to devexpress WPF assemblies and import the xml namespaces. Here&amp;#39;s the snippet that creates the BarButtonItems which is equivalent of a ToolbarItem. (Get the accompanied zip for complete source code):&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;dxb:BarManager.Items&amp;gt;
	&amp;lt;!--General Actions--&amp;gt;
	&amp;lt;dxb:BarButtonItem Name=&amp;quot;bSave&amp;quot;  CategoryName=&amp;quot;File&amp;quot; Content=&amp;quot;Save&amp;quot; Glyph=&amp;quot;/Images/Save.png&amp;quot;  KeyGesture=&amp;quot;Ctrl+S&amp;quot; /&amp;gt;
	&amp;lt;dxb:BarButtonItem Name=&amp;quot;bPrint&amp;quot; CategoryName=&amp;quot;File&amp;quot; Content=&amp;quot;Print&amp;quot; Glyph=&amp;quot;/Images/Print.png&amp;quot; KeyGesture=&amp;quot;Ctrl+P&amp;quot; /&amp;gt;
	&amp;lt;dxb:BarButtonItem Name=&amp;quot;bExit&amp;quot;  CategoryName=&amp;quot;File&amp;quot; Content=&amp;quot;Exit&amp;quot; Glyph=&amp;quot;/Images/Exit.png&amp;quot; KeyGesture=&amp;quot;Ctrl+X&amp;quot; /&amp;gt;
	
	&amp;lt;!--Status Bar--&amp;gt;
	&amp;lt;dxb:BarStaticItem Name=&amp;quot;bStatus&amp;quot; CategoryName=&amp;quot;Status&amp;quot; MinWidth=&amp;quot;300&amp;quot; Content=&amp;quot;Read&amp;quot; AutoSizeMode=&amp;quot;Fill&amp;quot;/&amp;gt;
&amp;lt;/dxb:BarManager.Items&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
	Same as Button object, BarButtonItems provide a Command property which you can bind to an ICommand instance on your ViewModel, but this is rather limited, don&amp;#39;t you think? What if you want to bind another event (other then Click) to your ViewModel?&lt;/p&gt;
&lt;p&gt;
	Caliburn provides Actions and Messages with which you can bind a regular Event on your View and Controls to a method on your ViewModel, without using ICommand. You can even run the event handler (on your VM) asynchronously! There are a few ways to do this but the best way, in my opinion, is to this format:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
cal:Message.Attach=&amp;quot;[Event EventNameOnControl] = [Action ActionNameOnViewModel()]&amp;quot;
&lt;/pre&gt;
&lt;p&gt;
	Note that you can actually bind two actions to one event, just like you can have two methods listening to a regular event. Let&amp;#39;s change the snippet above and add the messaging support:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;dxb:BarButtonItem Name=&amp;quot;bSave&amp;quot; cal:Message.Attach=&amp;quot;[Event ItemClick] = [Action SavePresenter()]&amp;quot;/&amp;gt;
	&amp;lt;dxb:BarButtonItem Name=&amp;quot;bPrint&amp;quot; cal:Message.Attach=&amp;quot;[Event ItemClick] = [Action PrintPresenter()]&amp;quot;/&amp;gt;
	&amp;lt;dxb:BarButtonItem Name=&amp;quot;bExit&amp;quot; cal:Message.Attach=&amp;quot;[Event ItemClick] = [Action Exit()]&amp;quot; /&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
	Note: Unlike a regular Button, BarButtonItem has no &amp;quot;Click&amp;quot; event and provides an &amp;quot;ItemClick&amp;quot; event instead. Clearly, we need the specified methods on our ViewModel, so let&amp;#39;s add them too:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class ShellViewModel : PresenterManager, IShellViewModel
{
    public virtual void SavePresenter()
    {
    }

    public virtual void PrintPresenter()
    {
    }

    public virtual void Exit()
    {
    }
}
&lt;/pre&gt;
&lt;p&gt;
	At this point, you can run the shell and click the tool bar items, which will call the specified method on the view model. Now the question is, what if a presenter is not in a suitable state to be saved (dirty checking, already saved, etc.). What if a presenter does not even support printing? How can we disable the BarButtonItem responsible for an action, if the presenter does not support it?&lt;/p&gt;
&lt;p&gt;
	With Conventions already enabled, you can have additional &amp;quot;Can*&amp;quot; methods acting as a Filter for your actions. These filters will be checked on runtime for returning false value indicating the action can not be performed, or true value for allowed actions. Caliburn will try to disable the piece of UI through an &amp;quot;IAvailabilityEffect&amp;quot; interface. Let&amp;#39;s see this in more dept.&lt;br /&gt;
	&amp;nbsp;&lt;/p&gt;
&lt;p&gt;
	&lt;span class=&quot;subtitle&quot;&gt;Working with Actions&lt;/span&gt;&lt;br /&gt;
	As mentioned, Caliburn checks for availability of an action automagically if it finds a pairing &amp;quot;Can*&amp;quot; filter method on the presenter. So let&amp;#39;s add those and see how it works:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public virtual bool CanExit()
{
    return base.CanShutdown();
}

public virtual bool CanPrintPresenter()
{
    var presenter = CurrentPresenter as IPrintablePresenter;
    return presenter != null &amp;amp;&amp;amp;
           presenter.CanPrint;
}

public virtual bool CanSavePresenter()
{
    var presenter = CurrentPresenter as ISaveablePresenter;
    return presenter != null &amp;amp;&amp;amp;
           presenter.CanSave;
}
&lt;/pre&gt;
&lt;p&gt;
	When you run the application and set a break point on CanSave and Save methods, you&amp;#39;ll notice two things:&lt;/p&gt;
&lt;p&gt;
	&lt;em&gt;A. While CanPrint method returns False value, UI element (BarButtonItem) is not disabled!&lt;br /&gt;
	&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;
	&lt;em&gt;B. By clicking the BarButtonItem, the Save method will not be called.&lt;br /&gt;
	&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;
	So there seems to be a problem...Why isn&amp;#39;t BarButtonItem disabled? Wasn&amp;#39;t Caliburn supposed to do that for us? Well...The default &lt;em&gt;&lt;strong&gt;&amp;quot;Disable&amp;quot;&lt;/strong&gt;&lt;/em&gt; effect, only works for &lt;em&gt;UIElements&lt;/em&gt;, but &lt;em&gt;BarButtonItem&lt;/em&gt; is actually a &lt;em&gt;FrameworkContentElement&lt;/em&gt;. Those are two different beasts and Caliburn can not handle our UI control. The solution is easy though. You can create your own &lt;strong&gt;&lt;em&gt;IAvailabilityEffect&lt;/em&gt;&lt;/strong&gt; that works with &lt;em&gt;FrameworkContentElements&lt;/em&gt;.&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class DisableMenuEffect : IAvailabilityEffect
{
    public void ApplyTo(DependencyObject target, bool isAvailable)
    {
        var element = target as FrameworkContentElement;
        if(element == null)
            return;

        element.IsEnabled = isAvailable;
    }
}
&lt;/pre&gt;
&lt;p&gt;
	...and set it along with the action on the View:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;dxb:BarButtonItem cal:Message.Attach=&amp;quot;[Event ItemClick] = [Action SavePresenter()]&amp;quot; cal:Message.AvailabilityEffect=&amp;quot;DisableMenuEffect&amp;quot; /&amp;gt;
    &amp;lt;dxb:BarButtonItem cal:Message.Attach=&amp;quot;[Event ItemClick] = [Action PrintPresenter()]&amp;quot; cal:Message.AvailabilityEffect=&amp;quot;DisableMenuEffect&amp;quot; /&amp;gt;
    &amp;lt;dxb:BarButtonItem cal:Message.Attach=&amp;quot;[Event ItemClick] = [Action Exit()]&amp;quot; cal:Message.AvailabilityEffect=&amp;quot;DisableMenuEffect&amp;quot; /&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
	There&amp;#39;s one last trick to make this work. Caliburn has no way to convert the specified string to an IAvailabilityEffect instance! The existing ValueCovertor, asks our Container for any object named &amp;quot;DisableMenuEffect&amp;quot;. The final piece of code would be to register all instances of IAvailabilityEffects you might want to use on the container:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
_container.Register(Component.For&amp;lt;DisableMenuEffect&amp;gt;()
                             .Named(&amp;quot;DisableMenuEffect&amp;quot;)
                             .LifeStyle.Singleton);
&lt;/pre&gt;
&lt;p&gt;
	When running the application, and there&amp;#39;s no open view, the toolbar items are disabled.&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;&quot; src=&quot;/Images/BlogPics/Caliburn_PartTwo_DisabledToolbar.png&quot; style=&quot;width: 400px; height: 280px;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	To show how it works, let&amp;#39;s add a new View and ViewModel to our application, and also add a button to the shell that allows us to open this view. As mentioned before, to do this, you need to create a UserControl for you View and a class deriving from Presenter base class for your ViewModel.&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class PersonViewModel : Presenter
{
    private Person _person;
    private ObservableCollection&amp;lt;Person&amp;gt; _personnelList;
    private ObservableCollection&amp;lt;Job&amp;gt; _jobs;
    private readonly IPersonDataService _service;

    public PersonViewModel(IPersonDataService service)
    {
        _service = service;
    }

    public override void Initialize()
    {
        _jobs = new ObservableCollection&amp;lt;Job&amp;gt;(_service.GetJobs());
        _personnelList = new ObservableCollection&amp;lt;Person&amp;gt;(_service.GetPersonnel());
    }

    public Person CurrentPerson
    {
        get { return _person; }
        set
        {
            _person = value;
            base.NotifyOfPropertyChange(&amp;quot;CurrentPerson&amp;quot;);
        }
    }

    public ObservableCollection&amp;lt;Person&amp;gt; Personnel
    {
        get { return _personnelList; }
    }

    public ObservableCollection&amp;lt;Job&amp;gt; Jobs
    {
        get { return _jobs; }
    }
}
&lt;/pre&gt;
&lt;p&gt;
	Now create a UserControl for PersonView using DevExpress editors looking like this:&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;&quot; src=&quot;/Images/BlogPics/Caliburn_PartTwo_PersonView.png&quot; style=&quot;width: 533px; height: 272px;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	To support saving, let&amp;#39;s add ISaveablePresenter interface to our ViewModel and check if DateOfBirth property of the current person is valid before saving:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public bool CanSave
{
    get 
    {
        return CurrentPerson != null &amp;amp;&amp;amp;
               CurrentPerson.DateOfBirth.Year &amp;gt; 1900;
    }
}

public void Save()
{
    MessageBox.Show(&amp;quot;Saved&amp;quot;);
}
&lt;/pre&gt;
&lt;p&gt;
	You can observe that CanSave property will never get executed! The reason is that when application starts, Caliburn checks if any of the Action methods are available by checking their respective Filters (here CanSavePresenter and CanPrintPresenter), but it never checks them again. In other words, by default action filters (Can* methods) are only called once. How can we change this behavior?&lt;/p&gt;
&lt;p&gt;
	There&amp;#39;s an attribute called &lt;em&gt;&lt;strong&gt;&amp;quot;AutoCheckAvailability&amp;quot;&lt;/strong&gt;&lt;/em&gt; that you can place on your action methods. This will tell WPF Command Manager to look out for availability of the bound action. Doing this will call the action filters periodically, so make sure if you really need it before actually using it. So apply this to our ViewModel, let&amp;#39;s get back to our ShellViewModel class and place the attribute on our actions:&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[AutoCheckAvailability]
public virtual void SavePresenter()
{
    var presenter = (ISaveablePresenter)CurrentPresenter;
    presenter.Save();
}

[AutoCheckAvailability]
public virtual void PrintPresenter()
{
    var presenter = (IPrintablePresenter)CurrentPresenter;
    presenter.Print();
}
&lt;/pre&gt;
&lt;p&gt;
	&lt;em&gt;&lt;strong&gt;Note: You need to place this on your actions, not on filters.&lt;br /&gt;
	&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;
	...et voila!&lt;/p&gt;
&lt;p style=&quot;text-align: center;&quot;&gt;
	&lt;img alt=&quot;&quot; src=&quot;/Images/BlogPics/Caliburn_PartTwo_Application_View.png&quot; /&gt;&lt;/p&gt;
&lt;p&gt;
	Our shell now can host other views and has generic actions that is automagically enabled / disabled for views supporting it.&lt;/p&gt;
&lt;p&gt;
	In the next post, I&amp;#39;ll show you how to change our existing shell to display a Tabbed interface and display multiple views at the same time. The &lt;a href=&quot;http://cid-4962b6ceabc2cbd7.skydrive.live.com/self.aspx/BlogFiles/PayRoll%20-%20Caliburn%20Part%20Two.zip&quot;&gt;attached zip file&lt;/a&gt; contains the complete source code.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">WPF Application with Caliburn - Part One</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/WPF-Application-With-Caliburn-Part-One"/>
    <id>http://www.hightech.ir/SeeSharp/WPF-Application-With-Caliburn-Part-One</id>
    <updated>2009-12-30T13:31:53.05</updated>
    <published>2009-12-30T00:00:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="MVVM" />
    <category term="WPF" />
    <category term="Caliburn" />
    <content type="html" xml:lang="en">
      &lt;p&gt;Back in May 2008, I did &lt;a href=&quot;http://www.hightech.ir/SeeSharp/wpf-composite-application-with-caliburn-part-one&quot;&gt;two posts&lt;/a&gt; on how to implement a composite application using &lt;a href=&quot;http://caliburn.codeplex.com/&quot;&gt;Caliburn&lt;/a&gt; framework. By that time, Caliburn was still in pre-alpha stage. With lots of the changes along the way to reach &lt;a href=&quot;http://caliburn.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=32809&quot;&gt;Release Candidate&lt;/a&gt;, those content are not valid anymore, so I thought a new post to show how you can use Caliburn to build a WPF application is in order.&lt;br/&gt;&lt;br/&gt;

In fact, a while ago I started porting my old .NET 1.1 pay roll application to WPF and .NET 3.5 so I naturally chose to use Caliburn and it did facilitate things a lot, but to keep things simple, I'm not going to discuss my own application here. I'll show how you how can create your own application using Caliburn framework and how it will help you out.&lt;/p&gt;

&lt;span class=&quot;subtitle&quot;&gt;Framework Setup&lt;/span&gt;
&lt;p&gt;
First thing you need to do, is to setup a new WPF application. Let's call it PayRoll application. After doing so, add reference to &lt;a href=&quot;http://caliburn.codeplex.com&quot;&gt;Caliburn&lt;/a&gt; and &lt;a href=&quot;http://www.castleproject.org/container/index.html&quot;&gt;Castle&lt;/a&gt; assemblies. Caliburn honors the &lt;a href=&quot;http://en.wikipedia.org/wiki/Dependency_inversion_principle&quot;&gt;Dependency-Injection principle&lt;/a&gt; by depending only on abstractions. The idea is to allow you to easily plug in your own implementation of that abstraction and customize how Caliburn components work. To do so, Caliburn uses an &lt;a href=&quot;http://en.wikipedia.org/wiki/Inversion_of_control&quot;&gt;IoC Container&lt;/a&gt; to lookup the services it requires.&lt;br/&gt;&lt;br/&gt;

If you're new to &lt;a href=&quot;http://martinfowler.com/articles/injection.html&quot;&gt;Dependency Injection&lt;/a&gt; stuff, don't worry, there is a built-in &lt;em&gt;SimpleContainer&lt;/em&gt; which will do the job for you but I'll be using Castle container (Windsor) here. If you're using other IoC containers such as &lt;a href=&quot;http://code.google.com/p/autofac/&quot;&gt;AutoFac&lt;/a&gt;, &lt;a href=&quot;http://ninject.org/&quot;&gt;Ninject&lt;/a&gt;, &lt;a href=&quot;http://structuremap.sourceforge.net/&quot;&gt;StructureMap&lt;/a&gt;, &lt;a href=&quot;http://www.springframework.net/&quot;&gt;Spring&lt;/a&gt; or even &lt;a href=&quot;http://www.codeplex.com/MEF&quot;&gt;MEF&lt;/a&gt; (&lt;a href=&quot;http://devlicio.us/blogs/casey/archive/2009/12/18/what-is-the-difference-between-an-ioc-container-and-mef.aspx&quot;&gt;not technically an IoC container&lt;/a&gt;), Caliburn comes with existing adapters for those too, so no worries. To lookup instances of the services it needs, Caliburn uses the &lt;a href=&quot;http://www.codeplex.com/CommonServiceLocator&quot;&gt;Common ServiceLocator&lt;/a&gt; and &lt;a href=&quot;http://en.wikipedia.org/wiki/Service_locator_pattern&quot;&gt;Service Locator&lt;/a&gt; design pattern. This allows looking up for services from various IoC containers, without actually depending on those containers.&lt;br/&gt;&lt;br/&gt;

Now to initialize Caliburn framework at startup there are various ways, but the easiest would be to create a CaliburnApplication. We already have an application object (App.xaml and App.xaml.cs) so we only need to change them to derive from CaliburnApplication class. To do so, open the App.xaml file first, and include the Caliburn namespace and change the type to Caliburn application. Also, we don't want to specify any StartupUri, so get rid of that too. The result would be this:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;cal:CaliburnApplication x:Class=&quot;PayRoll.App&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    xmlns:cal=&quot;http://www.caliburnproject.org&quot;&amp;gt;
    &amp;lt;Application.Resources&amp;gt;
         
    &amp;lt;/Application.Resources&amp;gt;
&amp;lt;/cal:CaliburnApplication&amp;gt;
&lt;/pre&gt;

&lt;p&gt;With this, the project won't compile! Because we've specified different base classes in our Xaml and Code Behind. Since the base class in code behind is inferred, open the code behind and remove the base class. The code would look like this:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
namespace PayRoll
{
    /// &amp;lt;summary&gt;
    /// Interaction logic for App.xaml
    /// &amp;lt;/summary&gt;
    public partial class App
    {
    }
}
&lt;/pre&gt;

&lt;p&gt;So far so good. Now, If you look at the Caliburn Application class, there are interesting things that we can do. The obvious one is a method called CreateContainer. The default implementation, as said before, will create a &lt;em&gt;SimpleContainer&lt;/em&gt; but we're going to use our own container, so let's do so:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    protected override IServiceLocator CreateContainer()
    {
        _container = new WindsorContainer();
        return new WindsorAdapter(_container);
    }
&lt;/pre&gt;

&lt;p&gt;Next step would be specifying a RootViewModel (also called ShellViewModel) that will act as ViewModel for our MainWindow. Notice that we have nothing to do with the actual View (UI) that will be displayed, we just specify the ViewModel for it:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    protected override object CreateRootModel()
    {
        return _container.Resolve&amp;lt;IShellViewModel&amp;gt;();
    }
&lt;/pre&gt;

&lt;p&gt;At this point, we need to create a ViewModel and a View for our Shell and register the VM in the container. Create two folders in your solution one named &lt;em&gt;Views&lt;/em&gt; and the other &lt;em&gt;ViewModels&lt;/em&gt;. Create an interface in ViewModels folder named IShellViewModel and create a class implementing this yet empty interface, named ShellViewModel. So now we need to register these (along with other services, view models, etc.) in the container:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public App()
    {
        RegisterComponents();
    }

    private void RegisterComponents()
    {
        _container.Register(Component.For&amp;lt;IShellViewModel&amp;gt;()
                                     .ImplementedBy&amp;lt;ShellViewModel&amp;gt;()
                                     .LifeStyle.Singleton);
    }
&lt;/pre&gt;
	
&lt;p&gt;Notice that lifestyle of ShellViewModel is set to singleton. This is logical because there's always one instance of the ShellView running. We'll see how this allow us interact from other ViewModels with Shell VM.&lt;/p&gt;

&lt;span class=&quot;subtitle&quot;&gt;Marrying the View and ViewModel&lt;/span&gt;
&lt;p&gt;Now, let's run the application and see what happens. When we run the application, Caliburn throws an exception complaining that a View can not be created for the ShellViewModel. Since we didn't specify any information about our Views, you might say: How is Caliburn supposed to create a View for my ViewModel anyway? Well, Caliburn tries many things before giving up and throwing an exception:&lt;/p&gt;

&lt;ul&gt;
   &lt;li&gt;First, if your ViewModel implements the IMetadataContainer interface, the GetMetadata&lt;T&gt; method is called on your VM, asking for a view. Since this not a good option for us, let's skip it.&lt;/li&gt;
   &lt;li&gt;Second, if the ViewModel is decorated with a ViewAttribute, the specified view will be created. This is relatively easy, but it clutters your ViewModel with an attribute and I don't like it.&lt;/li&gt;
   &lt;li&gt;Third, specified assemblies will be searched to find the matching view according to a specified naming convention. This sound interesting, let's use this method.&lt;/li&gt;
   &lt;li&gt;Fourth, if you don't like any of these behaviors, you can plug in your own IViewStrategy implementation.&lt;/li&gt;
&lt;/ul&gt;
   
&lt;p&gt;If you remember, we've created an empty &lt;em&gt;Views&lt;/em&gt; folder. If you create a UserControl named &lt;em&gt;ShellView&lt;/em&gt; (mind the naming), Caliburn will automagically pick it up as the View for our &lt;em&gt;ShellViewModel&lt;/em&gt;. How is this done, you may ask? According to &lt;a href=&quot;http://en.wikipedia.org/wiki/Convention_over_configuration&quot;&gt;pre-defined naming rules&lt;/a&gt;, Caliburn will look in folders named &lt;em&gt;Presenter&lt;/em&gt;, &lt;em&gt;Model&lt;/em&gt;, &lt;em&gt;ViewModel&lt;/em&gt; and &lt;em&gt;PresentationModel&lt;/em&gt; to create a ViewModel instance, and to create a View instance, it will look for it in the &lt;em&gt;Views&lt;/em&gt; folder. An example might clear it up a little bit. Supposing you have an &lt;em&gt;IShellPresenter&lt;/em&gt;, the implementation would be named &lt;em&gt;ShellPresenter&lt;/em&gt; in the folder named &lt;em&gt;Presenters&lt;/em&gt;. You should name the view for this presenter &lt;em&gt;ShellView&lt;/em&gt; and place it in &lt;em&gt;Views&lt;/em&gt; folder. The ViewModel names refers to different implementation of &lt;a href=&quot;http://martinfowler.com/eaaDev/PresentationModel.html&quot;&gt;Presentation Model&lt;/a&gt; design pattern, but those terms are used interchangeably in Caliburn.&lt;br/&gt;&lt;br/&gt;

So, we're going to use the naming convention (fourth method). Let's create an empty UserControl named &lt;em&gt;ShellView&lt;/em&gt; and put it in &lt;em&gt;Views&lt;/em&gt; folder:&lt;/p&gt;

&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;UserControl x:Class=&quot;PayRoll.Views.ShellView&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&amp;gt;
    
&amp;lt;/UserControl&amp;gt;
&lt;/pre&gt;

&lt;p&gt;You can run the application now and it works. Caliburn has created a View (UI) and a POCO class as ViewModel and set the DataContext property of the View to the instance of the ViewModel. If you've noticed, we've set a UserControl as our root View. While you can create a Window object as your root View, if you create a UserControl (or anything other than a Window), Caliburn will create a MainWindow for you and place the View object as its content. This behavior is for Caliburn v1.1 so if you're using older version 1.0 you can either upgrade or use a Window as your root view.&lt;/p&gt;

&lt;span class=&quot;subtitle&quot;&gt;Binding&lt;/span&gt;
&lt;p&gt;To check if View and ViewModel are really bound together, let's create a commmand on the ViewModel and invoke it from the View. When invoked, it will change a Message property on the ViewModel. So first, open the IShellViewModel interface and add the ICommand and Message properties to the interface definition:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public interface IShellViewModel
    {
        /// &amp;lt;summary&gt;
        /// A command that says hello when invoked.
        /// &amp;lt;/summary&gt;
        ICommand SayHelloCommand { get; }

        /// &amp;lt;summary&gt;
        /// Message
        /// &amp;lt;/summary&gt;
        string Message { get; set; }
    }
&lt;/pre&gt;
	
&lt;p&gt;...and implement the command property on your ShellViewModel class. To facilitate command handling, we'll use a DelegateCommand class (originally &lt;a href=&quot;http://msdn.microsoft.com/en-us/magazine/dd419663.aspx&quot;&gt;RelayCommand&lt;/a&gt;) introduced by &lt;a href=&quot;http://joshsmithonwpf.wordpress.com/&quot;&gt;Josh Smith&lt;/a&gt;. Then instead of just displaying a MessageBox, let's Create a TextBlock and bind it to the Message property on our ViewModel. When binding some element to a property on the ViewModel, we need to implement INotifyPropertyChanged interface on the ViewModel. Fortunately, there's a base class in Caliburn which does exactly that:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public class ShellViewModel : PropertyChangedBase, IShellViewModel
    {
        private ICommand _sayHelloCommand;
        private string _message;

        public virtual ICommand SayHelloCommand
        {
            get
            {
                if (_sayHelloCommand == null)
                    _sayHelloCommand = new DelegateCommand(SayHello);

                return _sayHelloCommand;
            }
        }

        public virtual string Message
        {
            get { return _message; }
            set
            {
                _message = value;
                NotifyOfPropertyChange(&quot;Message&quot;);
            }
        }

        private void SayHello()
        {
            Message = &quot;Greetings from Caliburn!&quot;;
        }
    }
&lt;/pre&gt;

&lt;p&gt;...Finally, let's place a Button and a TextBlock on the View and bind those to our ViewModel:&lt;/p&gt;

&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;Window x:Class=&quot;PayRoll.Views.ShellView&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; Width=&quot;320&quot; Height=&quot;200&quot; &amp;gt;
    &amp;lt;StackPanel&amp;gt;
        
        &amp;lt;Button Command=&quot;{Binding Path=SayHelloCommand}&quot; Content=&quot;Say Hello&quot;  /&amp;gt;
        
        &amp;lt;TextBlock Text=&quot;{Binding Path=Message}&quot; FontSize=&quot;16&quot; FontWeight=&quot;Bold&quot; /&amp;gt;
        
    &amp;lt;/StackPanel&amp;gt;
&amp;lt;/Window&amp;gt;
&lt;/pre&gt;

&lt;p&gt;In next post, I'll show you how to add &lt;a href=&quot;http://www.devexpress.com/Products/NET/Controls/WPF/&quot;&gt;DevExpress components&lt;/a&gt; to the pot and how to create a re-usable shell and along the way. We'll see how to host other ViewModels in our ShellView and how to manage them. You can get the source code of this part from &lt;a href=&quot;http://cid-4962b6ceabc2cbd7.skydrive.live.com/self.aspx/BlogFiles/PayRoll%20-%20Caliburn%20Part%20One.zip&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Entity Framework 4 - Part Three : Repository Pattern</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/Entity-Framework-Four-Part-Three-Repository-Pattern"/>
    <id>http://www.hightech.ir/SeeSharp/Entity-Framework-Four-Part-Three-Repository-Pattern</id>
    <updated>2009-12-12T11:02:00.963</updated>
    <published>2009-12-12T14:27:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="EntityFramework" />
    <content type="html" xml:lang="en">
      &lt;p&gt;&lt;a href=&quot;http://www.hightech.ir/SeeSharp/Entity-Framework-Four-Part-Deux-Audit-Info&quot;&gt;Last post&lt;/a&gt; showed how to use a “ObjectContext” derivation to automatically generate audit information. Now instead of using a “ObjectContext” directly, a rather different approach, a pattern called “Repository Pattern” is used to encapsulate access to the entities.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: I’m using the bits included in Visual Studio 2010 Beta 2 with additional features included in Entity Framework 4 CTP 2 (not included in VS 2010) which you can download &lt;a href=&quot;http://www.microsoft.com/downloads/details.aspx?FamilyID=13FDFCE4-7F92-438F-8058-B5B4041D0F01&amp;displaylang=en&quot;&gt;here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;span class=&quot;subtitle&quot;&gt;Specification Pattern&lt;/span&gt;&lt;br/&gt;

&lt;p&gt;What is &lt;a href=&quot;http://en.wikipedia.org/wiki/Specification_pattern&quot;&gt;“Specification Pattern”&lt;/a&gt; and what does it have to do with &lt;a href=&quot;http://martinfowler.com/eaaCatalog/repository.html&quot;&gt;“Repository Pattern”&lt;/a&gt;? In simple terms, a specification is a piece of business logic that specifies if an entity is matching a certain criteria. Let’s suppose we need to fetch list of high profile Customers. We can hard code this criteria in UI code behind which is a bad practice you probably agree. We can also place this on our entity class, the “Customer”. This may not seem so bad. Maybe it is even a good practice to build the business logics like these into the entity, right? But this will only lead to a polluted interface on our entity class as more business logic is introduced. Using “Specification Pattern” and &lt;a href=&quot;http://en.wikipedia.org/wiki/Separation_of_concerns&quot;&gt;Separation of Concerns&lt;/a&gt;, these pieces of business logic can be placed in a separate class where they belong. Later, we'll pass this criteria as a parameter into the repository to specify which entities we want to be returned.&lt;/p&gt;

&lt;p&gt;The Specification interface we're going to use would look like this:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public interface ISpecification&amp;lt;TEntity&amp;gt; where TEntity : EntityBase
    {
        Expression&amp;lt;Func&amp;lt;TEntity, bool&amp;gt;&amp;gt; IsSatisfied { get; }
    }
&lt;/pre&gt;

&lt;p&gt;...and implementation for our example above would be this:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public class HighProfileCustomersSpecification : ISpecification&amp;lt;Customer&amp;gt;
    {
        public Expression&amp;lt;Func&amp;lt;Customer, bool&amp;gt;&amp;gt; IsSatisfied
        {
            get 
            {
                return c =&amp;gt; c.Orders.Count &amp;gt; 50;
            }
        }
    }
&lt;/pre&gt;

&lt;br/&gt;
&lt;span class=&quot;subtitle&quot;&gt;Generic Repository&lt;/span&gt;&lt;br/&gt;
&lt;p&gt;First let’s specify an interface for our repository. We need generic method like FindByKey, Save, Update and methods that accept an ISpecification parameter like FindOne and FindMany. &lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public interface IRepository&amp;lt;TEntity&amp;gt; where TEntity : EntityBase
    {
        /// &lt;summary&gt;
        /// Saves the transient entity.
        /// &lt;/summary&gt;
        TEntity Save(TEntity entity);

        /// &lt;summary&gt;
        /// Updates the existing entity.
        /// &lt;/summary&gt;
        TEntity Update(TEntity entity);

        /// &lt;summary&gt;
        /// Finds the entity by its key.
        /// &lt;/summary&gt;
        TEntity FindByKey(long id);

        /// &lt;summary&gt;
        /// Finds entities based on provided criteria.
        /// &lt;/summary&gt;
        IList&amp;lt;TEntity&amp;gt; FindMany(ISpecification&amp;lt;TEntity&amp;gt; criteria);

        /// &lt;summary&gt;
        /// Finds one entity based on provided criteria.
        /// &lt;/summary&gt;
        TEntity FindOne(ISpecification&amp;lt;TEntity&amp;gt; criteria);
    }
&lt;/pre&gt;

&lt;p&gt;Let’s start with the easiest one, FindByKey method. To find an entity an ObjectContext that exposes the entity using IObjectSet&amp;lt;TEntity&amp;gt; is needed so in our generic repository, we’ll create those.&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public abstract class Repository&amp;lt;TEntity&amp;gt; : IRepository&amp;lt;TEntity&amp;gt; where TEntity : EntityBase
    {
        private readonly ObjectContext _context;
        private readonly ObjectSet&amp;lt;TEntity&amp;gt; _entity;

        protected Repository(ObjectContext context)
        {
            _context = context;
            _entity = Context.CreateObjectSet&amp;lt;TEntity&amp;gt;();
        }

        protected ObjectContext Context
        {
            get { return _context; }
        }

        protected IObjectSet&amp;lt;TEntity&amp;gt; Entity
        {
            get { return _entity; }
        }
    }
&lt;/pre&gt;

&lt;p&gt;With this a lot of our implementation would just call the related method on Entity property.&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public TEntity FindByKey(long id)
    {
        return Entity.Where(x =&amp;gt; x.Id == id)
                         .FirstOrDefault();
    }
&lt;/pre&gt;

&lt;p&gt;For Save and Update methods, the ObjectContext does provide a method that has a parameter accepting a fully qualified entity name. What’s FQEN, you may ask? Each object that is in a EntityFramework container has a fully qualified name which is in “ContainerName.EntityName” format. These are the MetaData information that is exposed through EntitySet property and usually are stored in the .edmx file which we don't have because we're using the &quot;All Code&quot; feature, remember? Fortunately, there is one place that we can get the EntitySet metadata for our POCO entity and that is through the ObjectSet instance.&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    private string GetEntityName()
    {
        return string.Format(&amp;quot;{0}.{1}&amp;quot;, _entity.EntitySet.EntityContainer, _entity.EntitySet.Name);
    }
&lt;/pre&gt;

&lt;p&gt;Now it is possible to write the generic Save and Update methods as follows: &lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public TEntity Update(TEntity entity)
    {
        var fqen = GetEntityName();

        Context.ApplyCurrentValues(fqen, entity);
        Context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);

        return entity;
    }

    public TEntity Save(TEntity entity)
    {
        var fqen = GetEntityName();

        Context.AddObject(fqen, entity);
        Context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);

        return entity;
    }
&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;Note: I’ve wraped the call to SaveChanges in Save and Update methods. You can provide additional SaveChanges method in the repository that will be called explicitly by the code that uses the repository instance.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;For remaining query methods that return one or multiple instances of the Entity, we’ll use the generic CreateQuery method on the ObjectContext and feed the ISpecification’s criteria to the Where method.&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public TEntity FindOne(ISpecification&amp;lt;TEntity&amp;gt; spec)
    {
        var entityName = GetEntityName();
        var query = _context.CreateQuery&amp;lt;TEntity&amp;gt;(entityName)
                                      .Where(spec.IsSatisfied());

        return query.FirstOrDefault();
    }

    public IList&amp;lt;TEntity&amp;gt; FindMany(ISpecification&amp;lt;TEntity&amp;gt; spec)
    {
        var entityName = GetEntityName();
        var query = _context.CreateQuery&amp;lt;TEntity&amp;gt;(entityName)
                                     .Where(spec.IsSatisfied());

        return query.ToList();
    }
&lt;/pre&gt;

&lt;p&gt;That sums it up. Our concrete repositories are now just a breeze to create. We can build any missing fine grained methods into our concrete repository using the Entity property. With this approach, you only need one Repository per each &lt;a href=&quot;http://dddstepbystep.com/wikis/ddd/blogged-aggregates-and-aggregate-roots.aspx&quot;&gt;Aggregate Root&lt;/a&gt; and EF4 will take care of any related transient child entities that should be persisted when aggregate root is saved.&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public interface ICustomerRepository : IRepository&amp;lt;Customer&amp;gt;
    {
        IList&amp;lt;Customer&amp;gt; NewlySubscribed();
    }

    public class CustomerRepository : RepositoryBase&amp;lt;Customer&amp;gt;, ICustomerRepository
    {
        public CustomerRepository(ObjectContext context) 
            : base(context)
        {
        }

        public IList&amp;lt;Customer&amp;gt; NewlySubscribed()
        {
            var lastMonth = DateTime.Now.Date.AddMonths(-1);
            return base.Entity.Where(c =&amp;gt; c.Inserted &amp;gt;= lastMonth)
                            .ToList();
        }
    }
&lt;/pre&gt;

&lt;p&gt;You can get the whole project containing complete API from &lt;a href=&quot;http://cid-4962b6ceabc2cbd7.skydrive.live.com/self.aspx/BlogFiles/EF4RepositoryPattern.zip&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">EntityFramework 4 – Part Deux : Audit Info</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/Entity-Framework-Four-Part-Deux-Audit-Info"/>
    <id>http://www.hightech.ir/SeeSharp/Entity-Framework-Four-Part-Deux-Audit-Info</id>
    <updated>2009-12-11T18:04:24.087</updated>
    <published>2009-12-08T15:24:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="EntityFramework" />
    <content type="html" xml:lang="en">
      &lt;p&gt;In &lt;a href=&quot;http://www.hightech.ir/SeeSharp/Entity-Framework-Four-Part-One-Persistence-Ignorance&quot;&gt;last post&lt;/a&gt; showed how easy it was to use POCO classes in EntityFramework v4, a feature called “All Code”. This new feature, facilitates creating domain models but how about other features you may already have using other ORMs like NHibernate? Let’s see how we can achieve automatic audit logging in EF v4.&lt;/p&gt;&lt;br/&gt;

&lt;p&gt;&lt;em&gt;Note: I’m using the bits included in Visual Studio 2010 Beta 2 with additional features included in Entity Framework 4 CTP 2 (not included in VS 2010) which you can download &lt;a href=&quot;http://www.microsoft.com/downloads/details.aspx?FamilyID=13FDFCE4-7F92-438F-8058-B5B4041D0F01&amp;displaylang=en&quot;&gt;here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;For running Linq queries, we probably already have an existing “ObjectContext” implementation (see previous post). The “ObjectContext” class provides.  To create audit log, we need to tap into “SavingChanges” event and populate audit properties. Having an “EntityBase” class as layer super-type that contains “Inserted”, “InsertedBy”, “Updated” and “UpdatedBy” audit fields we can add this cross cutting concern, across all of our entities which is what I’ve done here, but obviously instead of using a base class, you can do this with an Interface. Let’s create an “AuditableObjectContext” which will do the auditing part when the entity is saved by either an Update or an Insert:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class AuditableObjectContext : ObjectContext
{
    public AuditableObjectContext(EntityConnection connection) : base(connection)
    {
        SubscribeEvents();
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            UnSubscribeEvents();
        }

        base.Dispose(disposing);
    }

    private void SubscribeEvents()
    {
        SavingChanges += OnSavingChangesCore;
    }

    private void UnSubscribeEvents()
    {
        SavingChanges -= OnSavingChangesCore;
    }

    private void OnSavingChangesCore(object sender, EventArgs e)
    {
        OnSavingChanges();
    }

    public virtual void OnSavingChanges()
    {
        FillAuditFields();
    }

    private void FillAuditFields()
    {
        var stateManager = ObjectStateManager;
        var inserted = stateManager.GetObjectStateEntries(EntityState.Added);
        var modified = stateManager.GetObjectStateEntries(EntityState.Modified);

        inserted.Where(x =&amp;gt; x.Entity is EntityBase).Select(x =&amp;gt; x.Entity).Cast&amp;lt;EntityBase&amp;gt;().ForEach(x =&amp;gt;
        {
            x.Inserted = DateTime.Now;
            x.InsertedBy = Thread.CurrentPrincipal.Identity.Name;
        });

        modified.Where(x =&amp;gt; x.Entity is EntityBase).Select(x =&amp;gt; x.Entity).Cast&amp;lt;EntityBase&amp;gt;().ForEach(x =&amp;gt;
        {
            x.Updated = DateTime.Now;
            x.UpdatedBy = Thread.CurrentPrincipal.Identity.Name;
        });
    }
}
&lt;/pre&gt;

&lt;br /&gt;&lt;p&gt;Our existing “SalesObjectContext” class from &lt;a href=&quot;http://www.hightech.ir/SeeSharp/Entity-Framework-Four-Part-One-Persistence-Ignorance&quot;&gt;previous post&lt;/a&gt;, now looks like this:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class SalesObjectContext : AuditableObjectContext
{
    public SalesObjectContext(EntityConnection connection)
        : base(connection)
    {
    }

    public IObjectSet&amp;lt;Category&amp;gt; Categories
    {
        get { return CreateObjectSet&amp;lt;Category&amp;gt;(); }
    }

    public IObjectSet&amp;lt;Product&amp;gt; Products
    {
        get { return CreateObjectSet&amp;lt;Product&amp;gt;(); }
    }
}
&lt;/pre&gt;

&lt;p&gt;It was pretty easy and painless to create auditing fields, don’t you think? In the next post, we'll see how to implement repository pattern using POCO mode and EF v4.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">EntityFramework 4 - Part One : Persistence Ignorance</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/Entity-Framework-Four-Part-One-Persistence-Ignorance"/>
    <id>http://www.hightech.ir/SeeSharp/Entity-Framework-Four-Part-One-Persistence-Ignorance</id>
    <updated>2009-12-02T09:54:36.347</updated>
    <published>2009-12-02T01:22:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="EntityFramework" />
    <content type="html" xml:lang="en">
      &lt;p&gt;With the release of &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx&quot;&gt;EntityFramework&lt;/a&gt; v1 and lack of features such as &lt;a href=&quot;http://martinfowler.com/eaaCatalog/lazyLoad.html&quot;&gt;Lazy Loading&lt;/a&gt; and Persistence Ignorance leading to &lt;a href=&quot;http://efvote.wufoo.com/forms/ado-net-entity-framework-vote-of-no-confidence/&quot;&gt;Vote of No Confidence&lt;/a&gt; resulted the team working on Entity Framework project to actually change route and as the result, a lot of improvements has been made in EntityFramework v4. Wait a second…What happened to v2 and v3, you might ask? Well, EntityFramework vNext that will be released with .NET Framework 4 is named EntityFramework v4, so you didn’t miss anything. Let’s see how PI works in this version.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: I’m using the bits included in Visual Studio 2010 Beta 2 with additional features included in Entity Framework 4 CTP 2 (not included in VS 2010) which you can download &lt;a href=&quot;http://www.microsoft.com/downloads/details.aspx?FamilyID=13FDFCE4-7F92-438F-8058-B5B4041D0F01&amp;displaylang=en&quot;&gt;here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;span class=&quot;subtitle&quot;&gt;No base class required&lt;/span&gt;
&lt;p&gt;Unlike previous version, your entity classes may have no base class at all and you don’t have to implement a lot of interfaces to make your &lt;a href=&quot;http://en.wikipedia.org/wiki/Plain_Old_CLR_Object&quot;&gt;POCO&lt;/a&gt; class an entity. Whether you’re designing your models in code or using the model designer, the choice for a base class on your entities is an optional one. This makes things a lot easier and you’ll end up with a much simpler domain model.&lt;/p&gt;

&lt;div class=&quot;center&quot;&gt;&lt;img src=&quot;/Images/BlogPics/EntityFramework_EntityProperties.png&quot; alt=&quot;Entity Properties&quot; /&gt;&lt;/div&gt;&lt;br/&gt;

&lt;span class=&quot;subtitle&quot;&gt;All Code Development&lt;/span&gt;
&lt;p&gt;Also referred to as Model First, this is where you create the domain model without actually using a designer and use code instead. You now do this by creating regular Plain Old CLR Objects (&lt;a href=&quot;http://en.wikipedia.org/wiki/Plain_Old_CLR_Object&quot;&gt;POCO&lt;/a&gt;) to act as your domain entities. The good thing is, you don’t need XML mapping files, you don’t need to decorate your model with cluttering Attributes : just bare POCO classes will do.&lt;/p&gt;

&lt;p&gt;Creating a domain model is self explanatory. Here’s the code for a simple Product / Category model:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public class Category
    {
        public int Id
        {
            get; set;
        }

        public string Name
        {
            get; set;
        }

        public List Products
        {
            get; set;
        }
    }

    public class Product
    {
        public int Id
        {
            get; set;
        }

        public string Name
        {
            get; set;
        }
        
        public int CategoryId
        {
            get; set;
        }

        public Category Category
        {
            get; set;
        }
    }
&lt;/pre&gt;

&lt;p&gt;To query your entity classes you need to create another class that inherits from ObjectContext. This model defines your interactions with your entities and returns your domain entities as a new queryable interface which is IObjectSet&lt;T&gt;. This new interface is made up of IQuerable&lt;T&gt; plus Attach, Detach, Add and Delete functions. Should you need to keep your domain model clean, you can move this class out of your main domain model assemblies:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public class SalesObjectContext : ObjectContext
    {
        public SalesObjectContext(EntityConnection connection) : base(connection)
        {
        }

        private ObjectSet _categorySet;
        public IObjectSet Categories
        {
            get
            {
                return _categorySet ?? (_categorySet = CreateObjectSet());
            }
        }

        private ObjectSet _productSet;
        public IObjectSet Products
        {
            get
            {
                return _productSet ?? (_productSet = CreateObjectSet());
            }
        }
    }
&lt;/pre&gt;
&lt;br/&gt;

&lt;span class=&quot;subtitle&quot;&gt;What about Meta-Data?&lt;/span&gt;
&lt;p&gt;As in almost any &lt;a href=&quot;http://en.wikipedia.org/wiki/Object-relational_mapping&quot;&gt;ORM&lt;/a&gt; framework, you need “some” meta-data regarding your domain entities. These metadata are normally data-centric things such as PrimaryKeys, Constraints, Indexes, etc. so are not considered as a part of the domain model, but are needed anyway. Since there’s no EDMX file, how does EntityFramework know about such things? The answer is: It does not. We need to create some mapping files for these metadata. This is like how &lt;a href=&quot;http://fluentnhibernate.org/&quot;&gt;FluentNHibernate&lt;/a&gt; works. &lt;/p&gt;

&lt;p&gt;First create your mapping classes using the &lt;a href=&quot;http://en.wikipedia.org/wiki/Fluent_interface&quot;&gt;Fluent API&lt;/a&gt; available in EF v4:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public class ProductMapping : EntityConfiguration
    {
        public ProductMapping()
        {
            HasKey(x =&gt; x.Id);

            Property(x =&gt; x.Id).IsIdentity();
            Property(x =&gt; x.Name).HasMaxLength(20).IsRequired();

            Relationship(x =&gt; x.Category).HasConstraint((x, y) =&gt; x.CategoryId == y.Id);
        }
    }
&lt;/pre&gt;

&lt;p&gt;Although there could be some improvements here, things such as support for other PrimaryKey generation other than Identity, adding prefix / suffix to table names, etc. it works for now. Finally, you need to register these mappings when creating the ObjectContext:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    public static void FindDVDs()
    {
        var conn = new SqlConnection(); //or any DbConnection instance
        var builder = new ContextBuilder();

        builder.Configurations.Add(new ProductMapping());
        builder.Configurations.Add(new CategoryMapping());

        using(var ctx = builder.Create(conn))
        {
            var dvds = from c in ctx.Categories
                       where c.Name == &quot;DVDs&quot;
                       select c;

            var products = from p in ctx.Products
                           where p.Category == dvds
                           select p;
        }
    }
&lt;/pre&gt;
&lt;br/&gt;

&lt;span class=&quot;subtitle&quot;&gt;Closing&lt;/span&gt;
&lt;p&gt;No doubt, there’s been a lot of improvements in EntityFramework v4 and it is going the right direction, but a lot needs to be done before I can call it a robust, full feature and more importantly mature framework, but it is not a released product yet. In next port, I’ll add some IoC to the pot and show how to implement repository pattern using EF v4.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">BiDi applications with Silverlight 4</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/Silverlight-Four-With-Right-To-Left-Support"/>
    <id>http://www.hightech.ir/SeeSharp/Silverlight-Four-With-Right-To-Left-Support</id>
    <updated>2009-11-26T10:46:18.97</updated>
    <published>2009-11-25T14:15:57</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Silverlight" />
    <category term="FarsiLibrary" />
    <category term="RightToLeft" />
    <content type="html" xml:lang="en">
      &lt;p&gt;I started checking out the new Silverlight 4 Beta this week and the most important feature (for me) added to this release : FlowDirection. If you’re not a WPF guy, this is the equivalent of RightToLeft in WinForm world, just recently added to Silverlight. If this works the way the same feature in WPF works, all custom controls built in this platform will automagically have correct RightToLeft behavior, “Almost” without any additional code from component vendor / developer. Sounds too good to be true, but it is.&lt;/p&gt;

&lt;p&gt;To test how this works, we need a Silverlight 4 control first. Well, look no further! AgDataGrid from DevExpress is both free and open-source! Register and grab your version from &lt;a href=&quot;http://www.devexpress.com/Products/NET/Controls/Silverlight/Register/
&quot;&gt;here&lt;/a&gt;. Should you need to see some demos of this control's features go &lt;a href=&quot;http://demos.devexpress.com/AgDataGridDemos/&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The build is for latest released version of Silverlight 3, so you need to compile it against Silverlight 4 runtime. Open the solution and change the framework version to SL 4 and build it. That’s it. &lt;/p&gt;

&lt;p&gt;Now a Silverlight Application and remember to select “Silverlight 4” runtime when Visual Studio asks which runtime version to use. Add reference to assemblies you just built and add a agDataGrid instance to your page:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;dg:AgDataGrid x:Name=&quot;grid&quot; FlowDirection=&quot;RightToLeft&quot; 
               ShowGroupPanel=&quot;Visible&quot;&amp;gt;
   &amp;lt;dg:AgDataGrid.Columns&amp;gt;
        &amp;lt;dg:AgDataGridTextColumn x:Name=&quot;colFirstname&quot; FieldName=&quot;Firstname&quot; HeaderContent=&quot;نام&quot; /&amp;gt;
        &amp;lt;dg:AgDataGridTextColumn x:Name=&quot;colLastname&quot; FieldName=&quot;Lastname&quot; HeaderContent=&quot;نام خانوادگی&quot; /&amp;gt;
        &amp;lt;dg:AgDataGridColumn x:Name=&quot;colDateOfBirth&quot; FieldName=&quot;DateOfBirth&quot; HeaderContent=&quot;تاریخ تولد&quot;/&amp;gt;
    &amp;lt;/dg:AgDataGrid.Columns&amp;gt;
&amp;lt;/dg:AgDataGrid&amp;gt;
&lt;/pre&gt;

&lt;p&gt;Note the new FlowDirection property on AgDataGrid is added automatically just by compiling it against SL 4.&lt;/p&gt;

&lt;p&gt;To make it a better example, let’s add some more sugar to the pot. To localize the GroupPanel text, let’s use a DataTemplate. I also needed to display the DateOfBirth values in PersianCalendar, so I’m going to create a converter for that. The final xaml looks like this:&lt;/p&gt;

&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;UserControl.Resources&amp;gt;

    &amp;lt;cnv:PersianDateConverter x:Key=&quot;DefaultConverter&quot; /&amp;gt;

    &amp;lt;DataTemplate x:Key=&quot;DateTemplate&quot;&amp;gt;
        &amp;lt;TextBlock Text=&quot;{Binding Converter={StaticResource DefaultConverter}}&quot; /&amp;gt;
    &amp;lt;/DataTemplate&amp;gt;

    &amp;lt;DataTemplate x:Key=&quot;GroupTemplate&quot;&amp;gt;
        &amp;lt;TextBlock Text=&quot;برای ایجاد یک گروه ، یک ستون را به اینجا بکشید&quot; Foreground=&quot;White&quot; Margin=&quot;15,11,0,11&quot;/&amp;gt;
    &amp;lt;/DataTemplate&amp;gt;
&amp;lt;/UserControl.Resources&amp;gt;

&amp;lt;dg:AgDataGrid x:Name=&quot;grid&quot; FlowDirection=&quot;RightToLeft&quot; 
               ShowGroupPanel=&quot;Visible&quot;
               EmptyGroupPanelTemplate=&quot;{Binding Source={StaticResource GroupTemplate}}&quot;&amp;gt;
   &amp;lt;dg:AgDataGrid.Columns&amp;gt;
        &amp;lt;dg:AgDataGridTextColumn x:Name=&quot;colFirstname&quot; FieldName=&quot;Firstname&quot; HeaderContent=&quot;نام&quot; /&amp;gt;
        &amp;lt;dg:AgDataGridTextColumn x:Name=&quot;colLastname&quot; FieldName=&quot;Lastname&quot; HeaderContent=&quot;نام خانوادگی&quot; /&amp;gt;
        &amp;lt;dg:AgDataGridColumn x:Name=&quot;colDateOfBirth&quot; FieldName=&quot;DateOfBirth&quot; HeaderContent=&quot;تاریخ تولد&quot; CellDisplayTemplate=&quot;{StaticResource DateTemplate}&quot; /&amp;gt;
    &amp;lt;/dg:AgDataGrid.Columns&amp;gt;
&amp;lt;/dg:AgDataGrid&gt;&amp;gt;

&lt;/pre&gt;

&lt;p&gt;Unfortunately, unlike full version of .NET Framework, in beta version of Silverlight 4, there’s no PersianCalendar class! I’m not sure about the justification SL team has made in order to exclude this class, but I hope they’ll include it in the final version. I’ve opened a thread &lt;a href=&quot;http://betaforums.silverlight.net/forums/t/145947.aspx&quot;&gt;here&lt;/a&gt;, requesting this calendar to be added to SL 4, you may want to follow it up.&lt;/p&gt;

&lt;p&gt;For now, to do the date conversion “sans” PersianCalendar, I’m going to use my old FarsiLibrary project, now supporting with Silverlight. It is in fact the same projects that existed for WinForm and WPF, now built against Silverlight. You can get it here if you’re interested.
  &lt;br /&gt;

  &lt;br /&gt;Back to work, the date converted looks like this:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class PersianDateConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
        var cell = (AgDataGridCellData) value; 

        if (cell.CellValue == null) 
            return null; 

        var date = DateTime.Parse(cell.CellValue.ToString()); 
        var converted = FarsiLibrary.Utils.PersianDateConverter.ToPersianDate(date); 

        return converted.ToString(&quot;D&quot;); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
        throw new InvalidOperationException(&quot;one way conversion&quot;); 
    } 
}
&lt;/pre&gt;

&lt;p&gt;…and here’s the output.&lt;/p&gt;

&lt;div class=&quot;center&quot;&gt;&lt;img src=&quot;/Images/BlogPics/SL_RTL_AgDataGrid.png&quot;/&gt;&lt;/div&gt;&lt;br/&gt;&lt;br/&gt;

&lt;p&gt;You can get the sources of this demo from &lt;a href=&quot;http://cid-4962b6ceabc2cbd7.skydrive.live.com/self.aspx/BlogFiles/agDataGridDemo.zip&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Create your own validator, TDD style</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/create-your-own-validator-tdd-style"/>
    <id>http://www.hightech.ir/SeeSharp/create-your-own-validator-tdd-style</id>
    <updated>2009-11-18T11:03:59.82</updated>
    <published>2009-11-18T02:28:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Validator" />
    <category term="TDD" />
    <content type="html" xml:lang="en">
      There are many validation frameworks out there but sometimes you need to build one your own. Let's see how easy it is to build a simple validation framework in &lt;a href=&quot;http://en.wikipedia.org/wiki/Test-driven_development&quot;&gt;TDD style&lt;/a&gt; using functionalities in System.ComponentModel.DataAnnotations. This is a rather new assembly introduced in .NET Framework 3.5, mainly used to define metadata for ASP.NET Dynamic Data controls. We're going to use the validation attributes containing in this assembly to validate our entities and models. There's a &lt;a href=&quot;http://annotationscontrib.codeplex.com/&quot;&gt;contrib&lt;/a&gt; project on &lt;a href=&quot;http://www.codeplex.com&quot;&gt;CodePlex&lt;/a&gt; which contains extentions to this assembly, if you need to use it further.
&lt;br/&gt;&lt;br/&gt;

&lt;em&gt;Note: If you need to use a more powerful validation framework, it is advised to use CastleValidator, NHibernate Validator or other validation frameworks out there.&lt;/em&gt;&lt;br/&gt;
&lt;br/&gt;

&lt;div id=&quot;gallery&quot; style=&quot;float:left&quot;&gt;
    &lt;a href=&quot;/Images/BlogPics/Validator_ProjectStructure.png&quot; title=&quot;Project Structure&quot;&gt;
        &lt;img src=&quot;/Images/BlogPics/Validator_iProjectStructure.png&quot; width=&quot;175&quot; height=&quot;216&quot; alt=&quot;&quot; /&gt;
    &lt;/a&gt;
&lt;/div&gt;

For starters, let's create a project structure. We need two projects, one for the unit tests with reference to &lt;a href=&quot;http://www.nunit.org/&quot;&gt;NUnit&lt;/a&gt; assemblies, and another project containing our actual validation framework. Remember to add a reference to System.ComponentModel.DataAnnotations assembly.
&lt;br/&gt;
&lt;br/&gt;

When developing in TDD style, you write a failing test before you write the actual code, then implement the functionality and make the test pass. After the test is passed, you can do some refactoring and continue the procedure from the start. 

Other development styles that also use &quot;some&quot; kind of test or unit testing should not be thought of as TDD. The emphasis on TDD style is to write the test first, not after the implementation which is usually referred to as &lt;a href=&quot;http://stephenwalther.com/blog/archive/2009/04/08/test-after-development-is-not-test-driven-development.aspx&quot;&gt;Test After&lt;/a&gt; style.

&lt;br/&gt;&lt;br/&gt;&lt;br/&gt;
&lt;div id=&quot;gallery&quot;&gt;
    &lt;a href=&quot;/Images/BlogPics/Validator_TDD-Workflow.png&quot; title=&quot;TDD Workflow&quot;&gt;
        &lt;img src=&quot;/Images/BlogPics/Validator_iTDD-Workflow.png&quot; width=&quot;196&quot; height=&quot;371&quot; alt=&quot;&quot; /&gt;
    &lt;/a&gt;
&lt;/div&gt;
&lt;br/&gt;

As the workflow suggests, let's create our very first test. We want to test that the default validator instance can validate a model / entity. Here's the test:
&lt;br/&gt;
&lt;pre class='brush:csharp'&gt;
[TestFixture]
public class ValidatorTests
{
    [Test]
    public void Can_Validate_Models()
    {
        var validator = new DefaultValidator() as IValidator;
        var model = new Person();

        Assert.DoesNotThrow(() =&amp;lt; validator.Validate(model));
    }
}
&lt;/pre&gt;
&lt;br/&gt;
As you can see, the test won't even compile. We need to create missing classes and compile the solution first to make sure the test fails.
&lt;br/&gt;&lt;br/&gt;
&lt;em&gt;Note: If you're using &lt;a href=&quot;http://www.jetbrains.com/resharper/&quot;&gt;Resharper&lt;/a&gt; addin, it can create almost every missing piece of the puzzle for you. To do this, click the missing class, interface or method, press ALT + Enter and select proper option from appearing menu. Resharper has a plugin called &lt;a href=&quot;http://code.google.com/p/resharper-tdd-productivity-plugin/&quot;&gt;TDD Productivity&lt;/a&gt; plugin which helps you create missing types in referenced projects more easily.&lt;/em&gt;
&lt;br/&gt;&lt;br/&gt;
Create a new interface in the project containing the implementation named &quot;IValidator&quot; and create the &quot;Validate&quot; method:
&lt;br/&gt;
&lt;pre class='brush:csharp'&gt;
/// &amp;lt;summary&amp;gt;
/// Validates an object
/// &amp;lt;/summary&amp;gt;
public interface IValidator
{
    void Validate&amp;lt;TEntity&amp;gt;(TEntity entity);
}
&lt;/pre&gt;
&lt;br/&gt;
We need a default implementation of &quot;IValidator&quot;, to no surprise named &quot;DefaultValidator&quot;:
&lt;br/&gt;
&lt;pre class='brush:csharp'&gt;
public class DefaultValidator : IValidator
{
    public void Validate&amp;lt;TEntity&amp;gt;(TEntity entity)
    {
        throw new NotImplementedException();
    }
}
&lt;/pre&gt;
&lt;br/&gt;
The last remaining bit before we can compile the project is to create a Person class in our test project. This will be used as the object which we'll try to validate:
&lt;br/&gt;
&lt;pre class='brush:csharp'&gt;
public class Person
{
}
&lt;/pre&gt;
&lt;br/&gt;
Let's compile and run the test. The test will fail as expected. Since our test was over simplified, making it pass would be as easy as removing the exception:
&lt;br/&gt;
&lt;pre class='brush:csharp'&gt;
public void Validate&amp;lt;TEntity&amp;gt;(TEntity entity)
{
}
&lt;/pre&gt;
&lt;br/&gt;
Not much of an implementation. Let's create a new test and change the Validate method to return a list of validation errors.
&lt;br/&gt;
&lt;pre class='brush:csharp'&gt;
[Test]
public void Validate_Returns_ValidationErrors()
{
    //Arrange
    var validator = new DefaultValidator() as IValidator;
    var model = new Person();

    //Act
    var result = validator.Validate(model);
            
    //Assert
    Assert.That(result.Count, Is.EqualTo(0));
}
&lt;/pre&gt;
&lt;br/&gt;
&lt;em&gt;Note: The Arrange-Act-Assert (or AAA) is a readable test authoring pattern. Tests written in AAA are composed of 3 phases, Arrange in which test preconditions are defined, Act in which code under test is called and Assert in which results are inspected and failures are reported.&lt;/em&gt;
&lt;br/&gt;&lt;br/&gt;
Once again, the code won't compile. Let's create missing pieces by changing the method signatures and adding ValidationError class.
&lt;br/&gt;
&lt;pre class='brush:csharp'&gt;
/// &amp;lt;summary&amp;gt;
/// Validates an object
/// &amp;lt;/summary&amp;gt;
public interface IValidator
{
    IList&amp;lt;ValidationError&amp;gt; Validate&amp;lt;TEntity&amp;gt;(TEntity entity);
}

public class DefaultValidator : IValidator
{
    public IList&amp;lt;ValidationError&amp;gt; Validate&amp;lt;TEntity&amp;gt;(TEntity entity)
    {
        return null;
    }
}

public class ValidationError
{
    public ValidationError(string property, string errorMessage)
    {
        Property = property;
        ErrorMessage = errorMessage;
    }

    public string Property
    {
        get; 
        private set;
    }

    public string ErrorMessage
    {
        get; 
        private set;
    }
}
&lt;/pre&gt;
&lt;br/&gt;
Running the test, we'll see that it won't pass. Again, having &quot;Doing the simplest thing possible&quot; rule in mind, the implementation would be easy as:
&lt;br/&gt;
&lt;pre class='brush:csharp'&gt;
public IList&amp;lt;ValidationError&amp;gt; Validate&amp;lt;TEntity&amp;gt;(TEntity entity)
{
    var errors = new List&amp;lt;ValidationError&amp;gt;();

    return errors;
}
&lt;/pre&gt;
&lt;br/&gt;
&lt;em&gt;Note: An important TDD principal is to &quot;Do the simplest thing possible that works&quot;. This is closely related to &lt;a href=&quot;http://en.wikipedia.org/wiki/You_ain%27t_gonna_need_it&quot;&gt;YAGNI&lt;/a&gt;.&lt;/em&gt;

We should have two passing tests so far.

&lt;div id=&quot;gallery&quot;&gt;
    &lt;a href=&quot;/Images/BlogPics/Validator_PassingTest.png&quot; title=&quot;Passing Test&quot;&gt;
        &lt;img src=&quot;/Images/BlogPics/Validator_iPassingTest.png&quot; width=&quot;467&quot; height=&quot;111&quot; alt=&quot;&quot; /&gt;
    &lt;/a&gt;
&lt;/div&gt;
&lt;br/&gt;
It is time to implement the actual validation method. Let's start by creating a failing test:
&lt;br/&gt;
&lt;pre class='brush:csharp'&gt;
[Test]
public void Validating_Invalid_Model_Will_Return_Errors()
{
    var validator = new DefaultValidator() as IValidator;
    var model = new Person { Firstname = &quot;John&quot; };

    var result = validator.Validate(model);

    Assert.That(result.Count, Is.EqualTo(1));
    Assert.That(result[0].Property, Is.EqualTo(&quot;Lastname&quot;));
    Assert.That(result[0].ErrorMessage, Is.EqualTo(&quot;Lastname is required.&quot;));
}
&lt;/pre&gt;
&lt;br/&gt;
Before we run the test, let's add missing properties to our Person class and decorate it with some validation attributes:
&lt;br/&gt;
&lt;pre class='brush:csharp'&gt;
public class Person
{
    [Required(ErrorMessage = &quot;Firstname is required.&quot;)]
    public string Firstname
    {
        get; set;
    }

    [Required(ErrorMessage = &quot;Lastname is required.&quot;)]
    public string Lastname
    {
        get; set;
    }
}
&lt;/pre&gt;
&lt;br/&gt;
Let's run the test which will fail at this state. We're going to use reflection to read the attributes on the model and see if the property values matches the decorating attribute. Combined with a LINQ query the implementation would be:
&lt;br/&gt;
&lt;pre class='brush:csharp'&gt;
public IList&amp;lt;ValidationError&amp;gt; Validate&amp;lt;TEntity&amp;gt;(TEntity entity)
{
    var type = typeof (TEntity);
    var properties = TypeDescriptor.GetProperties(type);
    var errors = from PropertyDescriptor pd in properties
                      let value = pd.GetValue(entity)
                      from attrib in pd.Attributes.OfType&amp;lt;ValidationAttribute&amp;gt;()
                      where !attrib.IsValid(value)
                      select new ValidationError(pd.Name, attrib.ErrorMessage);

    return errors.ToList();
}
&lt;/pre&gt;
&lt;br/&gt;
If you run the test, you still see one failing test, but that is actually another test that used to pass. So what went wrong? Check out the Assertion we made in test &quot;Validate_Returns_ValidationErrors&quot;. The problem is that we have not specified &quot;Firstname&quot; and &quot;Lastname&quot; property on Person instance, and we're asserting that there won't be any errors. To make this test pass again, we should pass a valid person instance. So let's refactor this test into this:
&lt;br/&gt;
&lt;pre class='brush:csharp'&gt;
[Test]
public void Validate_Returns_ValidationErrors()
{
    var validator = new DefaultValidator() as IValidator;
    var model = new Person { Firstname = &quot;John&quot;, Lastname = &quot;Doe&quot; };
            
    var result = validator.Validate(model);

    Assert.That(result.Count, Is.EqualTo(0));
}
&lt;/pre&gt;
&lt;br/&gt;
We're almost done. There are some things we can still improve, like reading the error message from resource files instead of ErrorMessage property but I'm satisfied with this implementation so I won't do it in this post. Finally, let's see how good we did implementing this using TDD style by creating a coverage report. 
&lt;br/&gt;
&lt;div id=&quot;gallery&quot;&gt;
    &lt;a href=&quot;/Images/BlogPics/Validator_CoverageReport.png&quot; title=&quot;Coverage Report&quot;&gt;
        &lt;img src=&quot;/Images/BlogPics/Validator_iCoverageReport.png&quot; width=&quot;467&quot; height=&quot;158&quot; alt=&quot;&quot; /&gt;
    &lt;/a&gt;
&lt;/div&gt;
&lt;br/&gt;
Programming in TDD style has lots of &quot;hidden&quot; benefits too: The effort making things testable will lead you to decoupled components and by creating the tests first, you'll have wider range of unit test compared to test-after style, hence better test coverage.
&lt;br/&gt;&lt;br/&gt;
You can download the source code of this post &lt;a href=&quot;http://cid-4962b6ceabc2cbd7.skydrive.live.com/self.aspx/BlogFiles/Hightech.Validator.zip&quot;&gt;here&lt;/a&gt;.
    </content>
  </entry>
  <entry>
    <title type="html">Reflecting on Interface Inheritance</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/Reflecting-On-Interface-Inheritance"/>
    <id>http://www.hightech.ir/SeeSharp/Reflecting-On-Interface-Inheritance</id>
    <updated>2009-10-06T12:43:51.3</updated>
    <published>2009-10-06T07:01:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Reflection" />
    <content type="html" xml:lang="en">
      The other day I was working on an interceptor that listened to calls to some &amp;ldquo;Services&amp;rdquo; and redirected the calls to services hosted on remote machine, instead of running it locally when strangest thing happened. I was trying to find and invoke existing methods on my interface that according to reflection, were not there. Those services were using inherited interface:

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public interface IServiceBase&amp;lt;T&amp;gt;
{
   T FindOne(Criteria c);
   
   T[] FindMany(Criteria c);
}

public interface ICustomerService : IServiceBase&amp;lt;Customer&amp;gt;
{
    Customer FindByName(string name);
}
&lt;/pre&gt;

I was trying to get methods of ICustomerSerivce defined and inherited from the base interface:

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[TestMethod]
public void Can_Find_Base_Method_On_Interface()
{
    var service = typeof (ICustomerService);
    var method = service.GetMethod(&quot;FindOne&quot;);

    Assert.IsNotNull(method);
}
&lt;/pre&gt;

Unfortunately, this fails! It seems reflection does not work consistently on inherited interfaces. To solve this, you'd have all the base methods &amp;ldquo;redefined&amp;rdquo;, which becomes very nasty if you have multiple interface inheritances, or if you extensively use generics on interface level. So changing the above code to this will make the test go green:

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public interface ICustomerService : IServiceBase&amp;lt;Customer&amp;gt;
{
    Customer FindByName(string name);
    
    new Customer FindOne(Criteria c);
   
    new Customer[] FindMany(Criteria c);
}
&lt;/pre&gt;

I still don't know why this behavior, or maybe this is a known issue?
&lt;br /&gt;&lt;br/&gt;
&lt;em&gt;&lt;strong&gt;Update&lt;/strong&gt;: Found out that the behavior in fact is inline with ECMA CLI specifications. You can however check the methods on Interface's other interfaces. See a solution &lt;a href=&quot;http://stackoverflow.com/questions/358835/getproperties-to-return-all-properties-for-an-interface-inheritance-hierarchy&quot;&gt;here&lt;/a&gt;&lt;/em&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Anatomy of an ASP.NET MVC Control</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/anatomy-of-aspnet-mvc-control"/>
    <id>http://www.hightech.ir/SeeSharp/anatomy-of-aspnet-mvc-control</id>
    <updated>2009-09-27T09:11:03.963</updated>
    <published>2009-09-08T15:49:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="ASPNETMVC" />
    <content type="html" xml:lang="en">
      One of the great things about ASP.NET WebForms was that it wasy very easy to creat reuseable custom controls and components, but with appearance of ASP.NET MVC and lots of developers moving towards it, which is a good thing, what happens to component oriented development? Is is possible to create custom controls in MVC? Can we port our existing controls to MVC? ASP.NET MVC while may not be as good as WebForms when it comes to drag-and-drop style of using components, but it is fairly easy to use and to create custom controls in MVC! Let's see how.

To create a control in WebForms world, you'd extend the existing &lt;em&gt;WebControl&lt;/em&gt; class and override Render method which takes a HtmlTextWriter that you can use to output the desired HTML code to the browser. A control rendering &lt;em&gt;Hello World&lt;/em&gt; on the screen would be as simple as this:

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class HelloWorldControl : WebControl 
{
    protected override void Render(HtmlTextWriter writer)
    {
        base.Render(writer);
        
        writer.Write(&quot;&amp;lt;span&amp;gt;HelloWorld&amp;lt;/span&amp;gt;&quot;);
    }
}
&lt;/pre&gt;

You'd put this on your web page and you're all set. But what's the best approach in MVC controls? There's no WebControl or Control classes inside Mvc assemblies, so can either use any existing class you have as a base class or it from scratch. 

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class WebControl
{
    /// &amp;lt;summary&amp;gt;
    /// Renders the control by writing the html code into the text writer.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&quot;textWriter&quot;&amp;gt;&amp;lt;/param&amp;gt;
    public virtual void Render(TextWriter textWriter)
    {
    }
    
    /// &amp;lt;summary&amp;gt;
    /// Renders the control and outputs the generated HTML code.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;
    public string OnRender()
    {
        var tw = new StringWriter();
        
        Render(tw);
        
        return tw.ToString();
    }
}
&lt;/pre&gt;

With this, you have a ready to use base class for your controls. You need to override the Render method and construct the right HTML code. The code would look almost identical:

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class HelloWorldControl : WebControl
{
    public override void Render(TextWriter writer)
    {
        base.Render(writer);
        
        writer.Write(&quot;&amp;lt;span&amp;gt;Hello World!&amp;lt;/span&amp;gt;&quot;);
    }
}
&lt;/pre&gt;

Note: There's a catch here. We'd use existing methods on HtmlTextWriter in WebForms, which emitted correct HTML code per Browser. If you're writing the HTML code manually (as I did in this example) you'd be careful in case you need to support different browsers.

How do we use this in an MVC application you might ask? The way to do this, as it is already done in the MVC framework with other controls such as TextBox, CheckBox, etc. is to create an extension method on HtmlHelper class:

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public static class HelloWorldControlExtensions
{
    public static string HelloWorld(this HtmlHelper helper)
    {
        var control = new HelloWorldControl();
        
        return control.OnRender();
    }
}
&lt;/pre&gt;
Now you can add this controls to your views, as easy as other controls such as TextBoxes:
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;%= Html.HelloWorld() %&amp;gt;
&lt;/pre&gt;

That's almost it. The only thing remaining here is to implement control specific logic of your components and that part is left to you.
    </content>
  </entry>
  <entry>
    <title type="html">Caliburn = Less Code?</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/caliburn-less-code"/>
    <id>http://www.hightech.ir/SeeSharp/caliburn-less-code</id>
    <updated>2009-09-27T12:02:39.413</updated>
    <published>2009-09-02T11:59:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="MVVM" />
    <category term="WPF" />
    <category term="Caliburn" />
    <content type="html" xml:lang="en">
      &lt;a href=&quot;http://www.codeplex.com/caliburn&quot;&gt;Caliburn&lt;/a&gt; is an application framework for WPF / Silverlight. If you're developing applications for these platforms, there are many reasons why you definitely need to be using this framework, but today, I noticed how using this framework resulted writing less code while doing more. Let's see how writing a small WPF application using &lt;a href=&quot;http://en.wikipedia.org/wiki/Model_View_ViewModel&quot;&gt;MVVM&lt;/a&gt; pattern is different when using &lt;a href=&quot;http://www.codeplex.com/caliburn&quot;&gt;Caliburn&lt;/a&gt;.
&lt;i&gt;&lt;b&gt;Note: There are many other ways to skin a cat. This is how I do things, there may be other, better ways to do the same thing.&lt;/b&gt;&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;&lt;span class=&quot;subtitle&quot;&gt;Application Startup&lt;/span&gt;&lt;br /&gt;When creating an application using MVVM and &lt;em&gt;&lt;a href=&quot;http://wildermuth.com/2009/05/22/Which_came_first_the_View_or_the_Model&quot;&gt;ViewModel First&lt;/a&gt;&lt;/em&gt; development, you'd create the root View and VM, bind them through DataContext and show the main window of the application.  &lt;br /&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
///
/// Interaction logic for App.xaml
///
public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        
        var container = new WindsorContainer();
        var rootView = new RootView();
        var rootModel = new RootViewModel();
        
        rootView.DataContext = rootModel;
        this.MainWindow = rootView;
        this.MainWindow.Show();
    }
}
&lt;/pre&gt;
With caliburn, all you need to do is to create the root VM. There's no trace of any View creation and binding the DataContext to VM. All this is done automatically by Caliburn. To do this, use &lt;em&gt;&lt;a href=&quot;http://caliburn.codeplex.com/Wiki/View.aspx?title=Application&quot;&gt;CaliburnApplication&lt;/a&gt;&lt;/em&gt; as your base application class which will configure Caliburn framework upon startup. There are &lt;a href=&quot;http://caliburn.codeplex.com/Wiki/View.aspx?title=Project%20Setup&amp;amp;referringTitle=Home&quot;&gt;other ways&lt;/a&gt; to do the configuration but let's stick to this simple configuration scenario that installs default implementations of Calburn &lt;em&gt;Components&lt;/em&gt;.&lt;br /&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
///
/// Interaction logic for App.xaml
///
public partial class App : CaliburnApplication
{
    protected override IServiceLocator CreateContainer()
    {
        var container = new WindsorContainer();
        var adapter = new WindsorAdapter(container);
        
        return adapter;
    }
    
    protected override object CreateRootModel()
    {
        return new RootViewModel();
    }
}
&lt;/pre&gt;
One thing a little different is that Caliburn uses &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/dd458913.aspx&quot;&gt;IServiceLocator&lt;/a&gt; insterface (from &lt;a href=&quot;http://www.codeplex.com/CommonServiceLocator/&quot;&gt;Common Service Locator&lt;/a&gt;) and has no direct dependency on a vendor specific &lt;a href=&quot;http://martinfowler.com/articles/injection.html&quot;&gt;IoC Container&lt;/a&gt;, which is a good thing. This means, you can choose various IoC containers and adapters for major IoC containers like &lt;a href=&quot;http://www.castleproject.org/container/index.html&quot;&gt;Windsor&lt;/a&gt;, &lt;a href=&quot;http://ninject.org/&quot;&gt;Ninject&lt;/a&gt;, &lt;a href=&quot;http://code.google.com/p/autofac/&quot;&gt;Autofac&lt;/a&gt;, etc. are already included in Caliburn bits. If you're not a fan of IoC containers and won't be using one in your application (now, come on!), Caliburn uses a lightweight built-in container, in case you don't specify any other.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: #0080c0; font-size: 100%;&quot;&gt;&lt;b&gt;Actions and Commands&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;Should you bind an action to a ICommand instance on the VM, in pure MVVM application you would bind the &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms752308.aspx&quot;&gt;Command&lt;/a&gt; property to an &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx&quot;&gt;ICommand&lt;/a&gt; instance on the VM. You can specify the condition on which the command will be executable and you'll also implement the action execute by the command.&lt;br /&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;Button Command=&quot;{Binding ExitCommand}&quot; Content=&quot;Exit Application&quot;&amp;gt;

public class RootViewModel : BaseViewModel
{
    private ICommand _exitCommand;
    public ICommand ExitCommand
    {
        get
        {
            if (_exitCommand == null)
                _exitCommand = new RelayCommand(this.Exit, this.CanExit);
            
            return _exitCommand;
        }
    }
    
    public bool CanExit()
    {
        return true;
    }
    
    public void Exit()
    {
        Application.Current.Shutdown();
    }
}
&lt;/pre&gt;
Notice there are other &lt;em&gt;hidden&lt;/em&gt; code here too. You'll need to create a new Command, or use &lt;a href=&quot;http://www.codeproject.com/KB/WPF/VMCommanding.aspx&quot;&gt;RelayCommand&lt;/a&gt; (kudos to &lt;a href=&quot;http://joshsmithonwpf.wordpress.com/&quot;&gt;Josh&lt;/a&gt;) and you probably need a common &lt;a href=&quot;http://martinfowler.com/eaaCatalog/layerSupertype.html&quot;&gt;layer supertype&lt;/a&gt; that implements &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx&quot;&gt;INotifyPropertyChanged&lt;/a&gt;&lt;i&gt;&lt;/i&gt; interface. Using Caliburn you'd bind the &lt;a href=&quot;http://caliburn.codeplex.com/Wiki/View.aspx?title=Action%20Basics&amp;amp;referringTitle=Home&quot;&gt;action&lt;/a&gt; directly to the VM and there's no dependency to ICommand instances. The good thing is, you're not limited to Command property anymore and you can bind various other events such as Click, MouseOver, etc. to actions on your VM.&lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;Button cal:Message.Attach=&quot;[Event Click] = [Action Exit]&quot; Content=&quot;Exit Application&quot;&amp;gt;

public class RootViewModel : Presenter
{
    public bool CanExit()
    {
        return true;
    }
    
    public void Exit()
    {
        Application.Current.Shutdown();
    }
}
&lt;/pre&gt;
There are lots of existing boilerplate functionalities already available in Caliburn, so you can drop BaseViewModel and use &lt;a href=&quot;http://caliburn.codeplex.com/Wiki/View.aspx?title=IPresenter%20Component%20Model&quot;&gt;Presenter&lt;/a&gt; class (IPresenter implementation).&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: #0080c0; font-size: 100%;&quot;&gt;&lt;b&gt;Displaying Views&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;To display other views in the RootView (e.g. Shell), we'd constructed a new VM and set it to a Content property of a ContentControl. This will actually pick up the view specified in the DataTemplate from Application Resources, and display it on the UI. You have to maintain a mapping between your Views and your VMs in a resource dictionary and as your application grows this gets harder to maintain.&lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;Application.Resources&amp;gt;
    &amp;lt;DataTemplate DataType=&quot;{x:Type vm:CustomerViewModel}&quot;&amp;gt;
        &amp;lt;view:CustomerView /&amp;gt;
    &amp;lt;/DataTemplate&amp;gt;
&amp;lt;/Application.Resources&amp;gt;

&amp;lt;ContentControl Content=&quot;{Binding Path=CurrentView}&quot;/&amp;gt;

public class RootViewModel : BaseViewModel
{
    public void ShowCustomer()
    {
        CurrentView = IoC.Resolve&amp;lt;Customerviewmodel&amp;gt;();
    }
    
    private BaseViewModel _currentView;
    public BaseViewModel CurrentView
    {
        get { return _currentView; }
        set
        {
            _currentView = value;
            RaisePropertyChanged(&quot;CurrentView&quot;);
        }
    }
}
&lt;/pre&gt;
Let's see how we can do this using Caliburn. First off, we do not need to maintain any ViewModel mapping if we name our Views and ViewModels according to the Caliburn &lt;a href=&quot;http://caliburn.codeplex.com/Wiki/View.aspx?title=IBinder%20and%20Convention%20over%20Configuration&quot;&gt;Conventions&lt;/a&gt; that is, your view names should ending in View, presenters / VMs ending in &lt;em&gt;ViewModel&lt;/em&gt;or &lt;em&gt;Presenter&lt;/em&gt; and each should be in a separate namespace, namingly &lt;em&gt;Views&lt;/em&gt; and &lt;em&gt;ViewModels&lt;/em&gt; or &lt;em&gt;Presenters&lt;/em&gt;. This is just by convention and you can always override if you need to. Caliburn will automatically create the view for you, set the &lt;em&gt;CurrentPresenter&lt;/em&gt; property on the main window (i.e. &lt;a href=&quot;http://caliburn.codeplex.com/Wiki/View.aspx?title=IPresenter%20Component%20Model&quot;&gt;IPresenterHost&lt;/a&gt;) and do any required bindings. Did I mention you don't need the whole mapping of View &amp;lt;-&amp;gt; &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.windows.datatemplate.aspx&quot;&gt;DataTemplate&lt;/a&gt; in your Application / Form resource?&lt;br /&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;ContentControl x:Name=&quot;CurrentPresenter&quot; &amp;gt;

[Singleton(&quot;RootViewModel&quot;)]
public class RootViewModel : PresenterManager
{
    public void ShowCustomer()
    {
        var presenter = ServiceLocator.Current.GetInstance&amp;lt;Customerviewmodel&amp;gt;();
        this.Open(presenter);
    }
}
&lt;/pre&gt;

&lt;span style=&quot;color: #0080c0; font-size: 100%;&quot;&gt;&lt;b&gt;Conclusion&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;What's the catch? How does Caliburn do this? Caliburn uses &lt;em&gt;&lt;a href=&quot;http://caliburn.codeplex.com/Wiki/View.aspx?title=IBinder%20and%20Convention%20over%20Configuration&quot;&gt;Convention over Configuration&lt;/a&gt;&lt;/em&gt; pattern, so if you do things according to the convention you'll end up saving a lot of code. There's always the possibility to change the default behavior too. By complying to these conventions, clearly you'll end up writing less code, but more importantly the code you do write is cleaner, more robust and probably with better testabilty. With the help of &lt;em&gt;Binding Tests&lt;/em&gt; utilities existing in Caliburn, you can test your bindings the easy way, which is some thought for later posts.
    </content>
  </entry>
  <entry>
    <title type="html">Windsor Registration : Service Interface</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/windsor-registration-service-interface"/>
    <id>http://www.hightech.ir/SeeSharp/windsor-registration-service-interface</id>
    <updated>2009-09-27T12:11:23.283</updated>
    <published>2009-08-20T12:08:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Windsor" />
    <content type="html" xml:lang="en">
      &lt;p&gt;Sometimes when registering classes on Windsor container, that extend an existing base class with an interface, using auto registration and FirstInterface method is useless, because first interface finds the interface implemented by base class:&lt;/p&gt;  

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[TestFixture]
public class RegistrationFixture : ContainerTest
{
    [Test]
    public void Can_Find_Service_Using_Interface()
    {
        var service = TryResolve&amp;lt;IService&amp;gt;();

        Assert.That(service, Is.Not.Null);
    }

    protected override void OnSetup()
    {
        base.OnSetup();

        Container.Register(AllTypes.From(typeof(ServiceImpl))
                     .Where(null)
                     .Configure(x =&gt; x.LifeStyle.Is(LifestyleType.Transient))
                     .WithService.FirstInterface());
    }
 
    private interface IBaseService
    {
    }

    private interface IService
    {
    }

    private class BaseService : IBaseService
    {
    }

    private class ServiceImpl : BaseService, IService
    {
    }
}
&lt;/pre&gt;
If you run the test, it will fail, because ServiceImpl is registered with IBaseService interface, which is the first interface on the class hierarchy. But that is not what I intended to do. I wanted the to register it using the first interface on the same type, e.g. IService. Extension methods come to the rescue:&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public static class ContainerExtensions
{
   public static BasedOnDescriptor FirstInterfaceOnClass(this ServiceDescriptor serviceDescriptor)
   {
       return serviceDescriptor.Select((t, bt) =&amp;gt;
       {
           var baseInterfaces = t.BaseType.GetInterfaces();
           var interfaces = t.GetInterfaces().Except(baseInterfaces);

           return interfaces.Count() != 0 ? new[] {interfaces.First()} : null;
       });
   }
}
&lt;/pre&gt;
Changing the registration to this would pass the failing test:&lt;br /&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
    Container.Register(AllTypes.From(typeof(ServiceImpl))
                 .Where(null)
                 .Configure(x =&amp;gt; x.LifeStyle.Is(LifestyleType.Transient))
                 .WithService.FirstInterfaceOfClass());
&lt;/pre&gt;
    </content>
  </entry>
  <entry>
    <title type="html">LOB Application in WPF</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/lob-application-in-wpf"/>
    <id>http://www.hightech.ir/SeeSharp/lob-application-in-wpf</id>
    <updated>2009-10-18T14:07:33.827</updated>
    <published>2009-07-30T13:11:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="General" />
    <category term="WPF" />
    <content type="html" xml:lang="en">
      &lt;p&gt;I've been working on a small LoB application to manage sales of a small sales office. I thought it'd be a good idea to put to use my WPF knowledge and use WPF to create this application. The reason is obvious : Programming in WPF is as easy as it gets, more testable (as in Unit Testing and Acceptance Testing) and more end-user friendly. &lt;/p&gt;  &lt;p&gt;Following applicaiton components and patterns were used:&lt;/p&gt;  &lt;ul class=&quot;square&quot;&gt;   &lt;li&gt;NHibernate &lt;/li&gt;    &lt;li&gt;NHibernate Validator to validate both entities and ViewModels &lt;/li&gt;    &lt;li&gt;FarsiLibrary (globalizing Dates, DatePickers, etc.) &lt;/li&gt;    &lt;li&gt;MVVM pattern &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&lt;strong&gt;&lt;span style=&quot;color:#0080ff;&quot;&gt;&lt;/span&gt;&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;One part that took more effort than expected was localization and globalization of the application. In general, there are three things you need to check to achieve full localization, if you provide both Left-To-Right reading order languages (English) as well as Right-To-Left (Farsi, Arabic) :&lt;/p&gt;  &lt;h4&gt;&lt;strong&gt;&lt;span style=&quot;color:#0080ff;&quot;&gt;Flow Direction&lt;/span&gt;&lt;/strong&gt;&lt;/h4&gt;  &lt;p&gt;Thanks to WPF engine, most of the calculation of LTR reading order to RTL for Forms, UserControls and even Custom Controls is done automagically, although in custom controls, you might need to add some triggers to switch things like shadows, etc. and if you use a 3rd party custom control or library, you need to make sure component vendor has take care of issue like that.&lt;/p&gt;    &lt;h4&gt;&lt;strong&gt;&lt;span style=&quot;color:#0080ff;&quot;&gt;Texts&lt;/span&gt;&lt;/strong&gt;&lt;/h4&gt;    &lt;p&gt;WPF uses LocaBaml to extract localizable properties' values to an excel file and  after translation (e.g. assigning values for other languages), puts them in a  satelite assembly. This approach looks rough to maintain but there are lots of  libraries on Codeplex that will help you do this with xml files or .resx files. My suggestion is to use &lt;a href=&quot;http://wpflocalizeextension.codeplex.com/&quot;&gt;WPF Localization Extension&lt;/a&gt; which supports localizing FlowDirection, Brush, Texts, Images, etc.&lt;br /&gt;&lt;/p&gt;  &lt;h4&gt;&lt;strong&gt;&lt;span style=&quot;color:#0080ff;&quot;&gt;Dates&lt;/span&gt;&lt;/strong&gt;&lt;/h4&gt;  &lt;p&gt;Not eveyone use Gregorian Calendar available in english language cultures. For example in Arabic language HijriCalendar is used and for Farsi, PersianCalendar is used and sometimes just setting thread's culture to the language (e.g. Farsi) would not be enough. If you use dates in your applications (who doesn't?) you need to use date controls that work fluently with various languages and cultures. I used my own &lt;a href=&quot;http://blog.hightech.ir/search/label/FarsiLibrary&quot;&gt;FarsiLibrary control for WPF&lt;/a&gt; which allows you to work with PersianCalendar, HijriCalendar and GregorianCalendar seamlessly.&lt;/p&gt;    &lt;h4&gt;&lt;strong&gt;&lt;span style=&quot;color:#0080ff;&quot;&gt;System Messages&lt;/span&gt;&lt;/strong&gt;&lt;/h4&gt;  &lt;p&gt;With all the efforts and steps mentioned above, one part of the application still remains in native language of the Windows Installation. That is when using Windows's MessageBox to alert user and display messages. Fortunately, I already have my Expression Clone styles which come with a Expression style messagebox that come with localizable icons / button texts. &lt;/p&gt; &lt;center&gt;   &lt;table border=&quot;0&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; width=&quot;500&quot;&gt;&lt;tbody&gt;       &lt;tr&gt;         &lt;td align=&quot;left&quot; valign=&quot;top&quot;&gt;&lt;a href=&quot;http://lh3.ggpht.com/_Z5KTIfnfuNs/SnFbnFTpc4I/AAAAAAAAAQA/kXkyVSgQMzk/s1600-h/ScreenShot003%5B5%5D.png&quot;&gt;&lt;img title=&quot;Waring_English_MsgBox&quot; alt=&quot;Waring_English_MsgBox&quot; src=&quot;http://lh4.ggpht.com/_Z5KTIfnfuNs/SnFbpAM22II/AAAAAAAAAQE/ZmmOhorU3xM/ScreenShot003_thumb%5B3%5D.png?imgmax=800&quot; border=&quot;0&quot; height=&quot;93&quot; width=&quot;218&quot; /&gt;&lt;/a&gt;&lt;/td&gt;          &lt;td align=&quot;left&quot; valign=&quot;top&quot;&gt;&lt;a href=&quot;http://lh4.ggpht.com/_Z5KTIfnfuNs/SnFbqh50bFI/AAAAAAAAAQI/KSQGM9kar1o/s1600-h/ScreenShot002%5B9%5D.png&quot;&gt;&lt;img title=&quot;Warning_Persian_MsgBox&quot; alt=&quot;Warning_Persian_MsgBox&quot; src=&quot;http://lh4.ggpht.com/_Z5KTIfnfuNs/SnFbsPkK3bI/AAAAAAAAAQM/d7XeMazXDqE/ScreenShot002_thumb%5B7%5D.png?imgmax=800&quot; border=&quot;0&quot; height=&quot;94&quot; width=&quot;244&quot; /&gt;&lt;/a&gt;&lt;/td&gt;       &lt;/tr&gt;     &lt;/tbody&gt;&lt;/table&gt; &lt;/center&gt;  &lt;p&gt;&lt;strong&gt;&lt;span style=&quot;color:#0080ff;&quot;&gt;Styling&lt;/span&gt;&lt;/strong&gt;&lt;/p&gt;      &lt;p&gt;No doubt one of the features that comes with WPF is the ability to style everything that makes sense to provide a better UX. I used my &lt;a href=&quot;http://blog.hightech.ir/2008/04/expression-clone.html&quot;&gt;Expression styles&lt;/a&gt; which you can download &lt;a href=&quot;http://blog.hightech.ir/2008/04/expression-clone.html&quot;&gt;here&lt;/a&gt; to style your WPF applications very easily to make it look like Expression series.&lt;br /&gt;&lt;/p&gt;  &lt;p align=&quot;center&quot;&gt;&lt;a href=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/SnFbvKJcDuI/AAAAAAAAAQQ/YV8S_HkzPd0/s1600-h/ScreenShot001%5B7%5D.png&quot;&gt;&lt;img style=&quot;border-width: 0px; display: block; float: none; margin-left: auto; margin-right: auto;&quot; title=&quot;Before Styling&quot; alt=&quot;Before Styling&quot; src=&quot;http://lh5.ggpht.com/_Z5KTIfnfuNs/SnFbyHL7C0I/AAAAAAAAAQU/aD5Sm5efyT8/ScreenShot001_thumb%5B5%5D.png?imgmax=800&quot; border=&quot;0&quot; height=&quot;361&quot; width=&quot;500&quot; /&gt;&lt;/a&gt;&lt;span style=&quot;font-style: italic;font-size:78%;&quot; &gt;Before Styling&lt;/span&gt;&lt;br /&gt;&lt;/p&gt;     &lt;div style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;http://lh5.ggpht.com/_Z5KTIfnfuNs/SnFb4LjrRLI/AAAAAAAAAQY/oBAonC9WY_Q/s1600-h/ScreenShot001%5B8%5D.png&quot;&gt;&lt;img style=&quot;border-width: 0px; display: block; float: none; margin-left: auto; margin-right: auto;&quot; title=&quot;After Styling&quot; alt=&quot;After Styling&quot; src=&quot;http://lh3.ggpht.com/_Z5KTIfnfuNs/SnFczyKmthI/AAAAAAAAAQg/OfxoBPEQoB0/ScreenShot001_thumb%5B6%5D.png?imgmax=800&quot; border=&quot;0&quot; height=&quot;403&quot; width=&quot;500&quot; /&gt;&lt;/a&gt;&lt;span style=&quot;font-style: italic;font-size:78%;&quot; &gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;&lt;/span&gt;Using Expression Styles&lt;/span&gt;  &lt;/div&gt;&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6069495622049300789-1082298095406063296?l=heskandari.blogspot.com'/&gt;&lt;/div&gt;
    </content>
  </entry>
  <entry>
    <title type="html">XamDataGrid Validation with NHibernate Validator</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/xamdatagrid-validation-with-nhibernate"/>
    <id>http://www.hightech.ir/SeeSharp/xamdatagrid-validation-with-nhibernate</id>
    <updated>2009-09-27T12:05:59.017</updated>
    <published>2009-07-22T17:09:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="NHibernateValidator" />
    <category term="xamDataGrid" />
    <category term="WPF" />
    <content type="html" xml:lang="en">
      &lt;p&gt;One of the good grid controls in WPF world belongs to Infragistics. With all the bells and whistles, there are still some limitation, some are WPF engine limitation and some are not. One thing that is very limiting is validation of data prior them being added to datasource. This is rather a broad subject, but I intended to use NHibernate entities (POCO objects) decorated with NHiberante validator attributes to do the validation for me. &lt;br /&gt;&lt;br /&gt;&lt;/p&gt;

&lt;span class=&quot;subtitle&quot;&gt;NHibernate Validator&lt;/span&gt;&lt;br/&gt;
&lt;p&gt;NHibernate Validator is a subproject in &lt;a href=&quot;http://sourceforge.net/projects/nhcontrib/&quot;&gt;NHibernate Contrib&lt;/a&gt; which allows you validate plain business classes by using predefined set of validation attributes. The good thing is, as good as NHibernate uses &lt;a href=&quot;http://en.wikipedia.org/wiki/Plain_Old_CLR_Object&quot;&gt;POCO&lt;/a&gt; (Plain Old CLR Object) objects you can also validate any kind of simple classes using NHibernate validator. There are other validation frameworks out there but I didn't wanted to clutter my object with the validation mechanism and I also didn't want to write unnecessary properties on my domain objects (e.g. IsValid, etc.) so NHibernate Validator was a right choice for me. Let's see how a POCO entity along with validation looks like:

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class Product
{
    public Product()
    {
    }

    public long ProductId
    {
        get;
        private set;
    }

    [NotNullNotEmpty]
    public string Title
    {
        get; set;
    }

    [NotNull]
    public Category Category
    {
        get; set;
    }

    public string Description
    {
        get; set;
    }

    [Min(0)]
    public long Quantity
    {
        get; set;
    }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;span class=&quot;subtitle&quot;&gt;Binding To XamDataGrid&lt;/span&gt;&lt;br/&gt;
&lt;p&gt;&lt;a href=&quot;http://www.infragistics.com/dotnet/netadvantage/wpf/xamdatagrid.aspx&quot;&gt;XamDataGrid&lt;/a&gt; supports binding to &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx&quot;&gt;IEnumerable&lt;/a&gt;&lt;em&gt;&lt;/em&gt; interface, so an &lt;em&gt;IList&amp;lt;Product&amp;gt;&lt;/em&gt; would work. Also, XamDataGrid needs a public parameterless constructor if you're going to add to that collection from the grid control. If this requirement is not met, grid control will silently ignore the NewLine setting value. Here's the xaml snippet to display a grid with predefined fields (columns) and a NewLine row:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;igdp:XamDataGrid DataSource=&quot;{Binding ProductList}&quot;&amp;gt;
    &amp;lt;igdp:XamDataGrid.FieldLayouts&amp;gt;
        &amp;lt;igdp:FieldLayout&amp;gt;
            &amp;lt;igdp:FieldLayout.Settings&amp;gt;
                &amp;lt;igdp:FieldLayoutSettings AddNewRecordLocation=&quot;OnTopFixed&quot; AllowDelete=&quot;False&quot;
                             AllowAddNew=&quot;True&quot; ExpansionIndicatorDisplayMode=&quot;Never&quot;
                /&amp;gt;
            &amp;lt;/igdp:FieldLayout.Settings&amp;gt;
            &amp;lt;igdp:FieldLayout.Fields&amp;gt;
                &amp;lt;igdp:Field Name=&quot;Title&quot;       Label=&quot;Product Name&quot; /&amp;gt;
                &amp;lt;igdp:Field Name=&quot;Category&quot;    Label=&quot;Category&quot; /&amp;gt;
                &amp;lt;igdp:Field Name=&quot;Description&quot; Label=&quot;Comment&quot;/&amp;gt;
                &amp;lt;igdp:Field Name=&quot;Quantity&quot;    Label=&quot;Qtty&quot; /&amp;gt;
                &amp;lt;igdp:Field Name=&quot;ProductId&quot;   Visibility=&quot;Collapsed&quot;/&amp;gt;
            &amp;lt;/igdp:FieldLayout.Fields&amp;gt;
        &amp;lt;/igdp:FieldLayout&amp;gt;
    &amp;lt;/igdp:XamDataGrid.FieldLayouts&amp;gt;
&amp;lt;/igdp:XamDataGrid&amp;gt;
&lt;/pre&gt;
Now when you run the application and add a new Product object to the datasource, there's no way to check if all the predefined validation rules are okay. So, how do we change the behavior of the grid control to:&lt;br /&gt;
  
&lt;ul class='square'&gt;
  &lt;li&gt;Validate the product object PRIOR being added to the datasource so if an object is not validate, it won't get added to the data source.&lt;br /&gt;&lt;br/&gt;&lt;/li&gt;
  &lt;li&gt;No redundant validation code should be written. We need to use NHibernate Validator infrastructure we already have in place.&lt;br /&gt;&lt;br/&gt;&lt;/li&gt;
  &lt;li&gt;A reusable mechanism. Our application might end up with lots of grid controls.&lt;br /&gt;&lt;br/&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One way would be to subclass the grid control which although might work, is a heavy handed solution to our rather little problem. It is not right to put the code in our ViewModel (I'm using &lt;a href=&quot;http://msdn.microsoft.com/en-us/magazine/dd419663.aspx&quot;&gt;MVVM pattern&lt;/a&gt;), which introduces coupling betwee UI and ViewModel. Fortunately, this grid control exposes good events we can tap into and change the default validation behavior and we can do this by creating a new Attached Behavior.&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;

&lt;span class=&quot;subtitle&quot;&gt;Validation Attached Behavior&lt;/span&gt;&lt;br/&gt;&lt;p&gt;Attaching a behavior to an object, as the name puts it, means making the object do something that it would not do by default. According to &lt;a href=&quot;http://joshsmithonwpf.wordpress.com/&quot;&gt;Josh Smith&lt;/a&gt;:&lt;br /&gt;&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;&amp;ldquo;The idea is that you set an attached property on an element so that you can gain access to the element from the class that exposes the attached property. Once that class has access to the element, it can hook events on it and, in response to those events firing, make the element do things that it normally would not do. It is a very convenient alternative to creating and using subclasses, and is very XAML-friendly.&amp;rdquo;&lt;/p&gt;&lt;/blockquote&gt; and that's exactly what we're going to do. We're going to listen to one event in particular : &amp;ldquo;RecordUpdating&amp;rdquo; which fires when the user had edited an item and the control wants to submit the changes back to the data source. Here's the part that does the validation:&lt;br /&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
private static void OnRecordUpdating(object sender, RoutedEventArgs e)
{
    var arg = (RecordUpdatingEventArgs)e;
    var dataobject = arg.Record.DataItem;
    var rules = GetAllInvalidRules(dataobject);
    var grid = (XamDataGrid)sender;

    if (rules != null &amp;&amp; rules.Count &gt; 0)
    {
        var propertyName = rules[0].PropertyPath;
        var propertyTitle = grid.DefaultFieldLayout.Fields[propertyName].Label;

        arg.Action = RecordUpdatingAction.CancelUpdateRetainChanges;
        arg.Record.Tag = string.Format(&quot;Check Field : {0}&quot;, propertyTitle);
    }
    else
    {
        arg.Record.Tag = null;
    }

    e.Handled = true;
}
&lt;/pre&gt;

&lt;h4&gt;&lt;em&gt;Note : We only display one error at a time. If you need to display all of them at once, you can do so by changing the code a little bit.&lt;/em&gt;&lt;/h4&gt;

We place the error information on the Record object's Tag information. In our little RecordSelector style, we'll display an error icon in case Tag property is set to some error information:&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;Style TargetType=&quot;{x:Type igdp:RecordSelector}&quot;&amp;gt;
    &amp;lt;Setter Property=&quot;Template&quot;&amp;gt;
        &amp;lt;Setter.Value&amp;gt;
            &amp;lt;ControlTemplate TargetType=&quot;{x:Type igdp:RecordSelector}&quot;&amp;gt;
                &amp;lt;Image x:Name=&quot;ErrorIcon&quot; Source=&quot;pack://application:,,,/GridValidation;component/Images/FieldError.png&quot;
                 Width=&quot;16&quot; Height=&quot;16&quot; Margin=&quot;4,0,0,0&quot; Visibility=&quot;Collapsed&quot; ToolTip=&quot;{Binding Tag}&quot; /&amp;gt;
                &amp;lt;ControlTemplate.Triggers&amp;gt;
                    &amp;lt;DataTrigger Binding=&quot;{Binding Path=Tag, Converter={StaticResource DefaultNullConverter}}&quot; Value=&quot;False&quot;&amp;gt;
                        &amp;lt;Setter TargetName=&quot;ErrorIcon&quot; Property=&quot;Visibility&quot; Value=&quot;Visible&quot; /&amp;gt;
                    &amp;lt;/DataTrigger&amp;gt;
                &amp;lt;/ControlTemplate.Triggers&amp;gt;
            &amp;lt;/ControlTemplate&amp;gt;
        &amp;lt;/Setter.Value&amp;gt;
    &amp;lt;/Setter&amp;gt;
&amp;lt;/Style&amp;gt;
&lt;/pre&gt;

One last thing that is remaining, is to connect our attached behavior to our xamDataGrid control. The great thing about the attached behaviors (one of them, at least) is that you can use them from XAML code directly and no code-behind is required at all. So back to our xamDataGrid code, here's how to do the trick:&lt;br /&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;igdp:XamDataGrid DataSource=&quot;{Binding ProductList}&quot;
                                 bhv:DataGridValidationBehavior.HasRowValidation=&quot;true&quot;&amp;gt;
&lt;/pre&gt;

&lt;span class=&quot;subtitle&quot;&gt;Conclusion&lt;/span&gt;&lt;br/&gt;The final application looks like this picture. If you try to enter something wrong, either when creating a new item or editing one, validation mechanism will automagically kick in and does the work for you. The very important point is that data is retained in the new line but is it not added to the datasource, because the data is not validated. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/SmcIfVGFI1I/AAAAAAAAAP4/REI4BmqG1C4/s1600-h/xamGrid-Validation%5B7%5D.png&quot;&gt;&lt;img style=&quot;border: 0px none ; display: inline;&quot; title=&quot;xamGrid-Validation&quot; alt=&quot;xamGrid-Validation&quot; src=&quot;http://lh5.ggpht.com/_Z5KTIfnfuNs/SmcIhWEs9yI/AAAAAAAAAP8/CMK6zn-7le0/xamGrid-Validation_thumb%5B5%5D.png?imgmax=800&quot; border=&quot;0&quot; height=&quot;292&quot; width=&quot;464&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;You can download the source code from &lt;a href=&quot;http://cid-4962b6ceabc2cbd7.skydrive.live.com/self.aspx/BlogFiles/Misc/Infragistics.GridValidation.zip&quot;&gt;here&lt;/a&gt;. In order to fully compile and run the application, you need to install Infragistics WPF components which you can download &lt;a href=&quot;http://www.infragistics.com/downloads/default.aspx&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Infragistics WPF Reporting</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/infragistics-wpf-reporting"/>
    <id>http://www.hightech.ir/SeeSharp/infragistics-wpf-reporting</id>
    <updated>2009-09-28T09:12:41.387</updated>
    <published>2009-07-13T15:18:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="WPF" />
    <category term="Reporting" />
    <content type="html" xml:lang="en">
      &lt;p&gt;I've been looking for flexible Reporting components for the WPF application I'm working on, and strangely enough, there are just a few. I think WPF component in general is still a work in progress, and even if you have the chance to find a working component, there ALL have a lot of short comings and lack design-mode features, developer-friendliness, etc. and when it comes down to reporting component, there is &lt;a href=&quot;http://www.infragistics.com/dotnet/netadvantage/wpf/reporting.aspx&quot;&gt;Infragistics&lt;/a&gt; with very basic feature set, &lt;a href=&quot;http://www.componentone.com&quot;&gt;ComponentOne&lt;/a&gt; with years of background in reporting tools and &lt;a href=&quot;http://www.stimulsoft.com/&quot;&gt;Stimulsoft&lt;/a&gt; with complete reporting set for WinForm, WPF and Web. &lt;/p&gt;

&lt;p&gt;So, I start evaluating each one. Stimusoft WPF reporting looked very promising with all bells and whistles like end-user WPF designer and the whole UI (designer and preview) were in WPF, but If I'm going to buy a component I need more that just a reporting tool, how about having bunch of other controls as well? I skipped to ComponentOne and after downloading their package (around 100 MB download), the damn installation did not work and I was staring at the installation error message that had to do something with packaging. So in reality, I had only one more choice : Infragistics. &lt;/p&gt;&lt;br /&gt;

&lt;span class=&quot;subtitle&quot;&gt;Infragistics Reporting&lt;/span&gt;&lt;br/&gt;
&lt;p&gt;With very basic feature, Infragistics reporting is also easy to use. Since there is no designer (yet?) you have to code your report and create various report sections (Header, Footer, etc.) and add related stuff into that sections, all in code. The great thing about this reporting control (also a feature of ComponentOne) is that you can print any kind of UIElement, this means you can print your whole UserControl or Form which comes in handy. &lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://lh4.ggpht.com/_Z5KTIfnfuNs/SlsQzr0-TmI/AAAAAAAAAPs/07hfZWtQtKw/s1600-h/Infragistics-Reporting%5B11%5D.jpg&quot;&gt;&lt;img style=&quot;border: 0px none ; display: block; float: none; margin-left: auto; margin-right: auto;&quot; title=&quot;Infragistics-Reporting&quot; alt=&quot;Infragistics-Reporting&quot; src=&quot;http://lh4.ggpht.com/_Z5KTIfnfuNs/SlsQ5HsoPII/AAAAAAAAAPw/nyiJgngkmrY/Infragistics-Reporting_thumb%5B9%5D.jpg?imgmax=800&quot; border=&quot;0&quot; width=&quot;200&quot; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The real power of Infragistics reporting is when combined with their &amp;ldquo;Data Presenter&amp;rdquo; or &amp;ldquo;XamDataGrid&amp;rdquo; control. End-user can apply filtering, grouping, sorting, etc. and just print the result, easy as that.&lt;/p&gt;

&lt;span class=&quot;subtitle&quot;&gt;RightToLeft Issue&lt;/span&gt;&lt;br/&gt;
&lt;p&gt;When evaluating my application which is a multi-lingual application that supports RightToLeft and LeftToRight reading ordered languages, I came across a problem when printing controls with RightToLeft flow direction. The problem was that the whole control is &amp;ldquo;Mirrored&amp;rdquo;. Not that this mirroring is an issue, but all the texts and values printed are also mirrored which makes the whole report useless.&lt;/p&gt;  &lt;p&gt;&lt;img style=&quot;border: 0px none ; display: block; float: none; margin-left: auto; margin-right: auto;&quot; title=&quot;Mirrorred Report&quot; alt=&quot;Mirrorred Report&quot; src=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/SlsQ74ejcdI/AAAAAAAAAP0/X9Z4uML9wzI/IFG-Mirrorred%20Report_thumb%5B3%5D.jpg?imgmax=800&quot; border=&quot;0&quot; width=&quot;419&quot; /&gt;&lt;/p&gt;

&lt;span class=&quot;subtitle&quot;&gt;Workaround&lt;/span&gt;&lt;br/&gt;
&lt;p&gt;The workaround is, of course, not to print the control in RightToLeft and use LeftToRight for the time being until the bug is fixed. As easy as this sounds, it is not very easy to do for some reasons:&lt;/p&gt;
&lt;ul&gt;
   &lt;li&gt;RightToLeft is usually set on the parent (Form), and controls just &amp;ldquo;inherit&amp;rdquo; the setting from their parent.&lt;/li&gt;
   &lt;li&gt;If you do change parent's RightToLeft end-user will see the effect. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But you can always clone the object and change the behavior, right? But you can not do so with Visual Elements. There's no Copy / Clone method on Visual elements in WPF, so how do we &amp;ldquo;clone&amp;rdquo; the control, change the FlowDirection, and hand it to the reporting?&lt;/p&gt;  &lt;p&gt;Fortunately, WPF comes with two neglected classes : &amp;ldquo;XamlWriter&amp;rdquo; and &amp;ldquo;XamlReader&amp;rdquo; each of which do as exactly as the name puts it. Using &amp;ldquo;XamlWriter&amp;rdquo; you can write a Visual object (UIElement) into a string, then use &amp;ldquo;XamlReader&amp;rdquo; ton construct it back. This is just about the UI, so you'll have to re-attach the &amp;ldquo;DataSource&amp;rdquo; and &amp;ldquo;DataContext&amp;rdquo; you might have. Here's the snippet to do the trick:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public XamDataGrid Clone(XamDataGrid printable)
{
    //Clone the grid control
    var o = XamlWriter.Save(printable);
    var sr = new StringReader(o);
    var reader = XmlReader.Create(sr, new XmlReaderSettings());
    var result = (XamDataGrid)XamlReader.Load(reader);

    //It's a clone, need to reassign data source
    result.DataSource = printable.DataSource;

    //Set flow direction to LTR
    result.FlowDirection = FlowDirection.LeftToRight;

    return result;
}
&lt;/pre&gt;
You can &lt;a href=&quot;http://cid-4962b6ceabc2cbd7.skydrive.live.com/self.aspx/BlogFiles/Misc/Infragistics.ReportingRTLDemo.zip&quot;&gt;download&lt;/a&gt; the whole sample that shows the issue and the workaround. To compile and run it you need to have Infragistics 2009.1 installed. You can download Infragistics package &lt;a href=&quot;http://www.infragistics.com/downloads/default.aspx&quot;&gt;here&lt;/a&gt;.
    </content>
  </entry>
  <entry>
    <title type="html">Additional CallContext information in WCF</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/additional-callcontext-information-in"/>
    <id>http://www.hightech.ir/SeeSharp/additional-callcontext-information-in</id>
    <updated>2009-10-18T09:20:50.333</updated>
    <published>2009-07-05T12:07:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <content type="html" xml:lang="en">
      &lt;p&gt;Yeah, this might be a little old, but someone asked me how to send context information from client to the service with WCF.&lt;/p&gt;    &lt;p&gt;&lt;strong&gt;&lt;em&gt;Note: In general, you should not rely on client provided information about security, authentication, licensing, etc. Use this code and sample as an idea on how to implement your custom security. If you're trying to send sensitive information over the network, use this at your own risk.&lt;/em&gt;&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;WCF client and services might be (and probably are) in two separate AppDomain or even on separate machines across the network, so how do we send extra information from the client to the service when the service call is made? Fortunately, WCF provides enough extensibility points for us to participate in the action and change the default behavior. It is pretty much easy to add context information to the message header on the client side, and the on the server side extract the custom data from the message header. Added data to the message header can be a DataContract / Serialized class. &lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[DataContract]
public class MessageInfo
{
   public MessageInfo(Guid sessionId, CultureInfo culture, DateTime requestDate)
   {
       this.sessionId = sessionId;
       this.culture = culture;
       this.requestDate = requestDate;
   }

   [DataMember]
   public DateTime RequestDate
   {
       get;
       set;
   }

   [DataMember]
   public Guid SessionId
   {
       get;
       set;
   }

   [DataMember]
   public CultureInfo Culture
   {
       get;
       set;
   }
}
&lt;/pre&gt;

Client uses IClientMessageInspector to add context data before the message is handed over to WCF for the delivery.&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
/// &lt;summary&gt;
/// Flows the client's MessageInfo to the service.
/// &lt;/summary&gt;
public class ClientMessageInfoInspector : IClientMessageInspector
{
   public object BeforeSendRequest(ref Message request, IClientChannel channel)
   {
       request.Headers.Add(MessageHeader.CreateHeader(MessageHeaderKeys.MessageInfoKey, string.Empty, GetInfo()));
       return null;
   }

   public void AfterReceiveReply(ref Message reply, object correlationState)
   {
   }

   private MessageInfo GetInfo()
   {
       return new MessageInfo(Guid.NewGuid(), Thread.CurrentThread.CurrentUICulture, DateTime.Now);
   }
}
&lt;/pre&gt;

On the other hand, the service side uses IDispatchMessageInspector interface to extract the data from message header.&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
/// &lt;summary&gt;
/// Reads the MessageInfo of client and updates the service.
/// &lt;/summary&gt;
public class ServiceMessageInfoInspector : IDispatchMessageInspector
{
   public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
   {
       int headerIndex = request.Headers.FindHeader(MessageHeaderKeys.MessageInfoKey, string.Empty);
       if (headerIndex != -1)
       {
           MessageInfo ui = request.Headers.GetHeader&amp;lt;MessageInfo&amp;gt;(headerIndex);
          
           Thread.CurrentThread.CurrentUICulture = ui.Culture;
           Thread.CurrentThread.CurrentCulture = ui.Culture;

            Console.WriteLine(&quot;Request recieved on {0}&quot;, ui.RequestDate);
       }

       return null;
   }

   public void BeforeSendReply(ref Message reply, object correlationState)
   {
   }
}
&lt;/pre&gt;

&lt;p&gt;To wire things up, you also need to create a new behavior by implementing IEndpointBehavior and registering it with your endpoint, either by code, or configuration. Should you use a single behavior for both client and server, here's how to do it:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class MessageInfoBehavior : IEndpointBehavior
{
   public void Validate(ServiceEndpoint endpoint)
   {
   }

   public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
   {
   }

   public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
   {
       ServiceMessageInfoInspector inspector = new ServiceMessageInfoInspector();
       endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
   }

   public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
   {
       ClientMessageInfoInspector inspector = new ClientMessageInfoInspector();
       clientRuntime.MessageInspectors.Add(inspector);
   }
}
&lt;/pre&gt;

&lt;p&gt;Hope this helps.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">File Download with ASP.NET MVC</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/file-download-with-aspnet-mvc"/>
    <id>http://www.hightech.ir/SeeSharp/file-download-with-aspnet-mvc</id>
    <updated>2009-10-18T09:33:58.077</updated>
    <published>2009-06-23T10:45:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="ASPNETMVC" />
    <content type="html" xml:lang="en">
      &lt;p&gt;One of the things that might be less obvious when doing applications with ASP.NET MVC, is the ability to download files without exposing your files directly and possibly applying other mechanisms such as authentication or registering emails before allowing someone download your files. This is pretty much easy. The &quot;Controller&quot; class has a File method which returns a &quot;FilePathResult&quot;.&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class DownloadsController : Controller
{
    private readonly IProductService _productService;

    public DownloadsController(IProductService productService)
    {
        _productService = productService;
    }

    [SessionPerRequest]
    public ActionResult Index()
    {
        var products = _productService.GetDownloadableProducts();
        var model = new DownloadViewModel(products);

        return View(model);
    }

    [SessionPerRequest]
    public ActionResult File(int id)
    {
        var download = _productService.FindDownload(id);

        if (download != null)
        {
            var path = Server.MapPath(download.URL);
            var file = new FileInfo(path);
            if (file.Exists)
            {
                return File(download.URL, &quot;application/binary&quot;, download.FileName);
            }
        }

        return RedirectToAction(&quot;Index&quot;);
    }
}
&lt;/pre&gt;

&lt;br/&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;table&amp;gt;
   
    &amp;lt;% foreach (var p in Model.Products) { %&amp;gt;
         &amp;lt;tr&amp;gt;
           &amp;lt;td&amp;gt;
             &amp;lt;strong&amp;gt;&amp;lt;%= p.Title %&amp;gt;&amp;lt;/strong&amp;gt;&amp;lt;br /&amp;gt;
              
             &amp;lt;%foreach(var d in p.Downloads) { %&amp;gt;
               
                &amp;lt;a href=&quot;/Downloads/File/&amp;lt;%= d.Id %&amp;gt;&quot;&amp;gt;
                   Version: &amp;lt;%= d.Version %&amp;gt;- &amp;lt;%= d.DownloadSize %&amp;gt; KB
                &amp;lt;/a&amp;gt;
                &amp;lt;br /&amp;gt;
            &amp;lt;%} %&amp;gt;
               
           &amp;lt;/td&amp;gt;
        &amp;lt;/tr&amp;gt;
     &amp;lt;% } %&amp;gt;
&amp;lt;/table&amp;gt;
&lt;/pre&gt;
    </content>
  </entry>
  <entry>
    <title type="html">NHibernate JetDriver : Another Issue</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/nhibernate-jetdriver-another-issue"/>
    <id>http://www.hightech.ir/SeeSharp/nhibernate-jetdriver-another-issue</id>
    <updated>2009-10-19T13:56:11.3</updated>
    <published>2009-05-26T10:50:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="NHibernate" />
    <content type="html" xml:lang="en">
      &lt;p&gt;There is yet another issue with NHibernate and JetDriver I encountered yesterday. It seems that a select query containing &quot;Order By&quot;, will gets its &quot;From&quot; keyword cut off at some stage by the Jet Driver. It means simple object querying won't work:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public IList&amp;lt;Account&amp;gt; GetAllAccounts()
{
  using (UnitOfWork.Start())
  {
      var repository = new NHRepository&amp;lt;Account&amp;gt;();
      var orders = new[] { new Order(&quot;Firstname&quot;, true), new Order(&quot;Lastname&quot;, true) };

      return repository.FindAll(orders).ToList();
  }
}
&lt;/pre&gt;

&lt;p&gt;To fix it, let's first pin point the problem by creating a failing test. It was a good thing I was already running everything from the trunk build, so I opened up the JetDriver project (from NHContrib) and luckily there is already a test project. Since I didn't want to actually change any method visibility, I used reflection to call the private methods that fails this test:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[TestFixture]
public class JetOrderByFixture
{
  [Test]
  public void Select_Statement_With_OrderBy_Should_Run()
  {
      SqlString sql = new SqlString(&quot;SELECT * FROM ACCOUNTS ORDER BY Firstname ASC, Lastname ASC&quot;);
      JetDriver driver = new JetDriver();

      SqlString processedSql = driver.GetType()
                                     .GetMethod(&quot;FinalizeJoins&quot;, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod)
                                     .Invoke(driver, new object[] { sql }) as SqlString;

      Assert.That(processedSql, Is.Not.Null);
      Assert.That(processedSql.LastIndexOfCaseInsensitive(&quot;FROM&quot;), Is.GreaterThan(0));
  }
}
&lt;/pre&gt;

&lt;p&gt;The problem is the private FinalizeJoins method, so the test, to no surprise, fails. I have created a &lt;a href=&quot;http://nhjira.koah.net/browse/NHCD-33&quot;&gt;task&lt;/a&gt; in NHibernate's Jira and the patch to fix this is attached, if you need it.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Unit Testing with TypeMock</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/unit-testing-with-typemock"/>
    <id>http://www.hightech.ir/SeeSharp/unit-testing-with-typemock</id>
    <updated>2009-10-19T13:57:10.24</updated>
    <published>2009-05-21T13:31:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Testing" />
    <content type="html" xml:lang="en">
      &lt;p&gt;&lt;a href=&quot;http://www.typemock.com/&quot;&gt;Unit Testing&lt;/a&gt; ASP.NET? &lt;a href=&quot;http://www.typemock.com/ASP.NET_unit_testing_page.php&quot;&gt;ASP.NET unit testing&lt;/a&gt; has never been this easy. &lt;/p&gt;  &lt;p&gt;Typemock is launching a new product for ASP.NET developers : the ASP.NET Bundle - and for the launch will be giving out FREE licenses to bloggers and their readers. &lt;/p&gt;  &lt;p&gt;The ASP.NET Bundle is the ultimate ASP.NET unit testing solution, and offers both &lt;a href=&quot;http://www.typemock.com/&quot;&gt;Typemock Isolator&lt;/a&gt;, a &lt;a href=&quot;http://www.typemock.com/&quot;&gt;unit test&lt;/a&gt; tool and &lt;a href=&quot;http://sm-art.biz/Ivonna.aspx&quot;&gt;Ivonna&lt;/a&gt;, the Isolator add-on for &lt;a href=&quot;http://sm-art.biz/Ivonna.aspx&quot;&gt;ASP.NET unit testing&lt;/a&gt;, for a bargain price. &lt;/p&gt;  &lt;p&gt;Typemock Isolator is a leading &lt;a href=&quot;http://www.typemock.com/&quot;&gt;.NET unit testing&lt;/a&gt; tool (C# and VB.NET) for many &#226;€˜hard to test&#226;€™ technologies such as &lt;a href=&quot;http://typemock.com/sharepointpage.php&quot;&gt;SharePoint&lt;/a&gt;, &lt;a href=&quot;http://www.typemock.com/ASP.NET_unit_testing_page.php&quot;&gt;ASP.NET&lt;/a&gt;, &lt;a href=&quot;http://www.typemock.com/ASP.NET_unit_testing_page.php&quot;&gt;MVC&lt;/a&gt;, &lt;a href=&quot;http://www.typemock.com/wcfpage.php&quot;&gt;WCF&lt;/a&gt;, WPF, &lt;a href=&quot;http://www.typemock.com/Silverlight_unit_testing_page.php&quot;&gt;Silverlight&lt;/a&gt; and more. Note that for &lt;a href=&quot;http://www.typemock.com/Silverlight_unit_testing_page.php&quot;&gt;unit testing Silverlight&lt;/a&gt; there is an open source Isolator add-on called &lt;a href=&quot;http://www.typemock.com/Silverlight_unit_testing_page.php&quot;&gt;SilverUnit&lt;/a&gt;. &lt;/p&gt;  &lt;p&gt;The first 60 bloggers who will blog this text in their blog and &lt;a href=&quot;http://blog.typemock.com/2009/05/get-free-typemock-licenses-aspnet.html&quot;&gt;tell us about it&lt;/a&gt;, will get a Free Isolator ASP.NET Bundle license (Typemock Isolator + Ivonna). If you post this in an ASP.NET dedicated blog, you'll get a license automatically (even if more than 60 submit) during the first week of this announcement. &lt;/p&gt;  &lt;p&gt;Also 8 bloggers will get an additional 2 licenses (each) to give away to their readers / friends. &lt;/p&gt;  &lt;p&gt;Go ahead, click the following link for &lt;a href=&quot;http://blog.typemock.com/2009/05/get-free-typemock-licenses-aspnet.html&quot;&gt;more information&lt;/a&gt; on how to get your free license.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">NHibernate and DateTime</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/nhibernate-and-datetime"/>
    <id>http://www.hightech.ir/SeeSharp/nhibernate-and-datetime</id>
    <updated>2009-10-18T09:53:58.573</updated>
    <published>2009-05-20T16:20:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="NHibernate" />
    <content type="html" xml:lang="en">
      &lt;p&gt;I've been working on a WPF application which is maybe another post. The work is done and I have started localizing the applications. Localization was mostly chanding the FlowDirection and lables / texts for other languages, but when testing the application, I came across an intresting problem with Nhibernate. The application worked correctly in default (en-us) culture, but not in fa-ir, as NHibernate reported problems when running the working query. This highlights the problem:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[Test]
public void Can_Run_Query_In_Persian_Culture()
{
  using(new CultureContext(new PersianCultureInfo()))
  {
      using (UnitOfWork.Start())
      {
          var todayStart = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 0, 0, 0, CultureHelper.DefaultCalendar);
          var todayEnd = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 23, 59, 59, CultureHelper.DefaultCalendar);

          var queryable = UnitOfWork.CurrentSession.Linq&amp;lt;Purchase&amp;gt;();
          var query = from sales in queryable
                      where sales.PurchaseDate &amp;gt;= todayStart &amp;&amp; sales.PurchaseDate &amp;lt;= todayEnd
                      select sales;

          Assert.DoesNotThrow(() =&amp;gt; query.ToList());
      }
  }
}
&lt;/pre&gt;

The test which is totally working on other cultures, fails miserably in fa-ir. The reason is somewhere in the criteria parameter being converted to string. The output of the query being run on the database is this:&lt;br /&gt;

&lt;pre class=&quot;brush:sql&quot;&gt;
[SELECT this_.PurchaseId as PurchaseId4_0_, this_.PaidValue as PaidValue4_0_, this_.PurchaseDate as Purchase3_4_0_, this_.Quantity as Quantity4_0_, this_.IsOwed as IsOwed4_0_, this_.Product_id as Product6_4_0_, this_.PurchaseRegisteredBy_id as Purchase7_4_0_, this_.Purchaser_id as Purchaser8_4_0_ from `Purchase` this_ WHERE (this_.PurchaseDate &amp;gt;= ? and this_.PurchaseDate &amp;lt;= ?) ]
&lt;/pre&gt;

&lt;br /&gt;Positional parameters:  #0&amp;gt;1388/02/30 12:00:00 &#217;‚.&#216;&#184; #1&amp;gt;1388/02/30 11:59:59 &#216;&#168;.&#216;&#184;&lt;br /&gt;&lt;br /&gt;

&lt;p&gt;It is obvious that date values are converted to String using current Culture of the running thread, while the conversion should use invariant culture instead:&lt;/p&gt;

&lt;strong&gt;&lt;span style=&quot;color: rgb(255, 0, 0);&quot;&gt;Invalid:&lt;/span&gt;&lt;/strong&gt;&lt;br/&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
var dateValue = todayStart.ToString();
&lt;/pre&gt;
&lt;br/&gt;
&lt;strong&gt;&lt;span style=&quot;color: rgb(0, 128, 0);&quot;&gt;Valid:&lt;/span&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
var dateValue = todayStart.ToString(CultureInfo.InvariantCulture);
&lt;/pre&gt;
&lt;br/&gt;
Any workaround for this? I haven't found any yet. In fact I still do not exactly know if this is NH core problem or the Linq extensions and since I'm running a build from the trunk, I'm not sure if this is reproducible on released versions.&lt;br /&gt;&lt;br /&gt;
&lt;span style=&quot;font-style: italic; font-weight: bold;&quot;&gt;Update : The problem was actually related to JET Driver of NHibernate Contrib project. A patch is created and sent to authorities.&lt;/span&gt;
    </content>
  </entry>
  <entry>
    <title type="html">MVVM Validation With NHibernate Validator</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/mvvm-validation-with-nhibernate"/>
    <id>http://www.hightech.ir/SeeSharp/mvvm-validation-with-nhibernate</id>
    <updated>2009-10-18T11:40:33.907</updated>
    <published>2009-05-16T13:19:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="NHibernateValidator" />
    <category term="MVVM" />
    <category term="WPF" />
    <content type="html" xml:lang="en">
      &lt;p&gt;&lt;a href=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/Sg5-Fzj07XI/AAAAAAAAAOk/0ca2oK3AUjs/s1600-h/MVVM-Validation%5B7%5D.png&quot;&gt;&lt;img style=&quot;border: 0px none ; margin: 5px 20px 0px 10px; display: inline;&quot; title=&quot;MVVM-Validation&quot; alt=&quot;MVVM-Validation&quot; src=&quot;http://lh4.ggpht.com/_Z5KTIfnfuNs/Sg5-LYic86I/AAAAAAAAAOo/YhoCqfl99Bk/MVVM-Validation_thumb%5B5%5D.png?imgmax=800&quot; border=&quot;0&quot; height=&quot;150&quot; width=&quot;294&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  
&lt;p&gt;Simplest way to do Validation in WPF is usually implementing IDataErrorInfo interface, and do the validation in the indexer's getter. It turns out to be ugly and gets out of hand when your model / viewmodel gets a little larger. Implementing the IDataErrorInfo is as simple as this:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public string this[string propertyName]
{
  get
  {
      //Validate property that is being set,
      //and return an error message if there's
      //any error.

      return null;
  }
}

public string Error
{
  get { return string.Empty; }
}
&lt;/pre&gt;

&lt;p&gt;I intend to use NHibernate Validator attributes to add non-intrusive validation to my ViewModel classes. So you'd just decorate properties of your ViewModel and let WPF and NHibernate Validator do the rest for you. Before we do that, let's create a more elegant way to show the errors by restyling the TextBox control and add an Error Icon and tooltip to it in case of an error existing:&lt;/p&gt;

&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;Style TargetType=&quot;{x:Type TextBox}&quot;&amp;gt;
   &amp;lt;Setter Property=&quot;Validation.ErrorTemplate&quot;&amp;gt;
       &amp;lt;Setter.Value&amp;gt;
           &amp;lt;ControlTemplate&amp;gt;
               &amp;lt;DockPanel LastChildFill=&quot;True&quot;&amp;gt;
                   &amp;lt;Image x:Name=&quot;ErrorIcon&quot; Source=&quot;Images/FieldError.png&quot; DockPanel.Dock=&quot;Right&quot; Width=&quot;16&quot; Height=&quot;16&quot; Margin=&quot;4,0,0,0&quot; /&amp;gt;
                   &amp;lt;Border BorderBrush=&quot;Red&quot; BorderThickness=&quot;1&quot;&amp;gt;
                       &amp;lt;AdornedElementPlaceholder /&amp;gt;
                   &amp;lt;/Border&amp;gt;
               &amp;lt;/DockPanel&amp;gt;
           &amp;lt;/ControlTemplate&amp;gt;
       &amp;lt;/Setter.Value&amp;gt;
   &amp;lt;/Setter&amp;gt;
   &amp;lt;Style.Triggers&amp;gt;
       &amp;lt;Trigger Property=&quot;Validation.HasError&quot; Value=&quot;true&quot;&amp;gt;
           &amp;lt;Setter Property=&quot;ToolTip&quot; Value=&quot;{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}&quot;/&amp;gt;
       &amp;lt;/Trigger&amp;gt;
   &amp;lt;/Style.Triggers&amp;gt;
&amp;lt;/Style&amp;gt;
&lt;/pre&gt;

Now that styles are all set, let's configure NHibenrate Validator's engine on application startup. Nothing fancy, just a straightforeward configuration. We'll use a shared validation engine:&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public void RegisterValidatorEngine()
{
  var config = new NHVConfigurationBase();

  config.Properties[Environment.ApplyToDDL] = &quot;false&quot;;
  config.Properties[Environment.AutoregisterListeners] = &quot;true&quot;;
  config.Properties[Environment.ValidatorMode] = &quot;UseAttribute&quot;;
  config.Properties[Environment.SharedEngineClass] = typeof(ValidatorEngine).FullName;
  config.Mappings.Add(new MappingConfiguration(DomainAssemblyName, null));

  Environment.SharedEngineProvider = new NHibernateSharedEngineProvider();
  Environment.SharedEngineProvider.GetEngine().Configure(config);

  ValidatorInitializer.Initialize(NHibernateConfig);
}
&lt;/pre&gt;

And to make things reusable, why not create a base ViewModel:&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public abstract class ValidatableViewModel : IDataErrorInfo
{
  private readonly ValidatorEngine validation;

  protected ValidatableViewModel()
  {
      validation = Environment.SharedEngineProvider.GetEngine();
  }

  public string this[string propertyName]
  {
      get
      {
          var rules = GetInvalidRules(propertyName);
          if (rules != null &amp;&amp; rules.Count &amp;gt; 0)
          {
              return rules[0].Message;
          }

          return null;
      }
  }

  public string Error
  {
      get { return string.Empty; }
  }

  public IList&lt;InvalidValue&gt; GetInvalidRules(string propertyName)
  {
      var type = this.GetType();

      return validation.ValidatePropertyValue(type, propertyName, GetPropertyValue(type, propertyName));
  }

  public IList&lt;InvalidValue&gt; GetAllInvalidRules()
  {
      return validation.Validate(this);
  }

  private object GetPropertyValue(Type objectType, string properyName)
  {
      return objectType.GetProperty(properyName).GetValue(this, null);
  }
}
&lt;/pre&gt;

&lt;p&gt;The rest is just to inherit the ValidatableViewModel and add necessary attributes to our binded properties. A sample ViewModel containing a Save command, which is invocable only when there's no error on the model and a couple of other business properties would look like this:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class NewAccountViewModel : ValidatableViewModel, INotifyPropertyChanged
{
  private string _firstName;
  private string _lastName;
  private string _currentBalance;

  [NotNullNotEmpty]
  public string Firstname
  {
      get { return _firstName; }
      set
      {
          _firstName = value;
          this.Notify(this.PropertyChanged, o =&amp;gt; o.Firstname);
      }
  }

  [NotNullNotEmpty]
  public string Lastname
  {
      get { return _lastName; }
      set
      {
          _lastName = value;
          this.Notify(this.PropertyChanged, o =&amp;gt; o.Lastname);
      }
  }

  [IsNumeric]
  [NotNullNotEmpty]
  public string CurrentBalance
  {
      get { return _currentBalance; }
      set
      {
          _currentBalance = value;
          this.Notify(this.PropertyChanged, o =&amp;gt; o.CurrentBalance);
      }
  }

  public event PropertyChangedEventHandler PropertyChanged = delegate { };

  private ICommand _cmdSave;
  public ICommand SaveCommand
  {
      get
      {
          if (_cmdSave == null)
              _cmdSave = new RelayCommand(Save, CanSave);

          return _cmdSave;
      }
  }

  public void Save()
  {
      MessageBox.Show(&quot;Save&quot;);
  }

  public bool CanSave()
  {
      return GetAllInvalidRules().Count == 0;
  }
}
&lt;/pre&gt;

&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;UserControl x:Class=&quot;Jimba.UI.View.NewAccountView&quot;
  xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&amp;gt;
  &amp;lt;StackPanel&amp;gt;
      &amp;lt;StackPanel Orientation=&quot;Horizontal&quot;&amp;gt;
          &amp;lt;Label Width=&quot;100&quot;&amp;gt;Firstname:&amp;lt;/Label&amp;gt;
          &amp;lt;TextBox Text=&quot;{Binding Path=Firstname, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}&quot; /&amp;gt;
      &amp;lt;/StackPanel&amp;gt;

      &amp;lt;StackPanel Orientation=&quot;Horizontal&quot;&amp;gt;
          &amp;lt;Label Width=&quot;100&quot;&amp;gt;Lastname:&amp;lt;/Label&amp;gt;
          &amp;lt;TextBox Text=&quot;{Binding Path=Lastname, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}&quot; /&amp;gt;
      &amp;lt;/StackPanel&amp;gt;

      &amp;lt;StackPanel Orientation=&quot;Horizontal&quot;&amp;gt;
          &amp;lt;Label Width=&quot;100&quot;&amp;gt;Current Balance:&amp;lt;/Label&amp;gt;
          &amp;lt;TextBox Text=&quot;{Binding Path=CurrentBalance, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}&quot; /&amp;gt;
      &amp;lt;/StackPanel&amp;gt;
  &amp;lt;/StackPanel&amp;gt;
&amp;lt;/UserControl&amp;gt;
&lt;/pre&gt;
    </content>
  </entry>
  <entry>
    <title type="html">ASP.NET MVC Validation with Ajax and Json</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/aspnet-validation-with-ajax-and-json"/>
    <id>http://www.hightech.ir/SeeSharp/aspnet-validation-with-ajax-and-json</id>
    <updated>2009-10-18T12:21:15.527</updated>
    <published>2009-05-03T14:42:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="NHibernateValidator" />
    <category term="ASPNETMVC" />
    <category term="Json" />
    <category term="jQuery" />
    <content type="html" xml:lang="en">
      &lt;p&gt;&lt;a href=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/Sf1u-xLJUtI/AAAAAAAAAOc/4hC9Eb8hNCU/s1600-h/AjaxValidation%5B3%5D.png&quot;&gt;&lt;img style=&quot;border: 0px none ; margin: 0px 15px 0px 0px; display: inline;&quot; title=&quot;AjaxValidation&quot; alt=&quot;AjaxValidation&quot; src=&quot;http://lh4.ggpht.com/_Z5KTIfnfuNs/Sf1vCip88MI/AAAAAAAAAOg/3GfC-WrV1N0/AjaxValidation_thumb%5B1%5D.png?imgmax=800&quot; width=&quot;244&quot; align=&quot;left&quot; border=&quot;0&quot; height=&quot;223&quot; /&gt;&lt;/a&gt;ASP.NET MVC has great ajax integration with no doubt. Simply by using ajax forms you can use partial page rendering and there are also controller callbacks. One thing that will break if you switch to Ajax / JsonResult is the built-in Validation result (ModelErrors) rendering of the MVC engine.&lt;br /&gt;&lt;br /&gt;It won't work because of a simple fact: The built-in validation will take place when the page is being rendered on the server. When you use ajax and callbacks page will not re-render on the server-side, hence validation can not mark fields with error and add validation information to the already rendered page.&lt;/p&gt;
&lt;p&gt; Let's see how you can do this, without using a client-side validation framework.&lt;br /&gt;&lt;/p&gt;
&lt;span class=&quot;subtitle&quot;&gt;Creating a Contact Form&lt;/span&gt;
&lt;p&gt;First, let's create a form using Ajax.BeginForm and provide a javascript action to process the results. You can get rid of the ValidationMessage and ValidationSummary, since we don't need it anymore:&lt;br /&gt;&lt;/p&gt;  
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;% using (Ajax.BeginForm(new AjaxOptions { OnComplete = &quot;ProcessResult&quot; })) { %&amp;gt;
    &amp;lt;p&amp;gt;
   &amp;lt;label for=&quot;Name&quot; class=&quot;contactLabel&quot;&amp;gt;Your Name:&amp;lt;/label&amp;gt;
   &amp;lt;%= Html.TextBox(&quot;SenderName&quot;, Model.SenderName)%&amp;gt;
    &amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;
   &amp;lt;label for=&quot;Email&quot; class=&quot;contactLabel&quot;&amp;gt;Your Email:&amp;lt;/label&amp;gt;
   &amp;lt;%= Html.TextBox(&quot;Email&quot;, Model.Email)%&amp;gt;
    &amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;
   &amp;lt;label for=&quot;Subject&quot; class=&quot;contactLabel&quot;&amp;gt;Subject:&amp;lt;/label&amp;gt;
   &amp;lt;%= Html.TextBox(&quot;Subject&quot;, Model.Subject)%&amp;gt;
    &amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;
   &amp;lt;label for=&quot;Message&quot; class=&quot;contactLabel&quot;&amp;gt;Message:&amp;lt;/label&amp;gt;
   &amp;lt;%= Html.TextBox(&quot;Message&quot;, Model.Message)%&amp;gt;
    &amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;
   &amp;lt;br /&amp;gt;
   &amp;lt;input type=&quot;submit&quot; value=&quot;Send&quot; class=&quot;inputButton&quot; /&amp;gt;
   &amp;lt;br /&amp;gt;
&amp;lt;/p&amp;gt;
&amp;lt;div id=&quot;operationMessage&quot;&gt;&amp;lt;ul&amp;gt;&amp;lt;/ul&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;% } %&gt;
&lt;/pre&gt;
&lt;p&gt;Notice that there is a div at the bottom which acts as an error placeholder and will be used to display validation information.&lt;br /&gt;&lt;br /&gt;To actually bind these fields to data, we need to create an &lt;a href=&quot;http://en.wikipedia.org/wiki/Plain_Old_CLR_Object&quot;&gt;POCO&lt;/a&gt; class acting as a backing entity. In this example, I've used a poco class and decorate it with &lt;a href=&quot;http://sourceforge.net/projects/nhcontrib/files/NHibernate.Validator/&quot;&gt;NHibernate Validator&lt;/a&gt;'s attributes to do the validation. See &lt;a href=&quot;http://www.hightech.ir/SeeSharp/nhibernate-automatic-validation&quot;&gt;here&lt;/a&gt; for more info on how to configure NHibernate Validator using ASP.NET MVC:&lt;/p&gt;&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class ContactMessage : IValidatable
{
  public ContactMessage()
  {
     MessageDate = DateTime.Today;
  }

  public virtual int Id
  {
     get; private set;
  }

  [NotNullNotEmpty]
  public virtual string SenderName
  {
     get; set;
  }

  [NotNullNotEmpty]
  [Email]
  public virtual string Email
  {
     get; set;
  }

  [NotNullNotEmpty]
  public virtual string Subject
  {
     get; set;
  }

  [NotNullNotEmpty]
  public virtual string Message
  {
     get; set;
  }

  public virtual DateTime MessageDate
  {
     get; private set;
  }
}
&lt;/pre&gt;

&lt;span class=&quot;subtitle&quot;&gt;Controller Action&lt;/span&gt;
&lt;p&gt;Two methods are needed to handle to Post / Get separately. Our Get method returns a new instance of our contact entity to the view, and Post method is where the operation results is returned to the client using &lt;a href=&quot;http://en.wikipedia.org/wiki/Json&quot;&gt;Json&lt;/a&gt;. The OperationResultInfo class containing the elaborate error information is what returned as Json to the client:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class OperationResultInfo
{
  public OperationResultInfo()
  {
     Errors = new List&amp;lt;ErrorReasonInfo&amp;gt;();
  }

  public bool Successfull { get; set; }

  public string Message { get; set; }

  public IList&amp;lt;ErrorReasonInfo&amp;gt; Errors { get; set; }
}

public class ErrorReasonInfo
{
  public string PropertyName { get; set; }

  public string Error { get; set; }
}

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Contact()
{
  return View(new ContactMessage());
}

[AcceptVerbs(HttpVerbs.Post)]
[AutoValidate]
public ActionResult Contact(ContactMessage msg)
{
  if (ModelState.IsValid)
  {
     try
     {
         this.messengerService.SendMail(msg);

         return Json(new OperationResultInfo
         {
             Successfull = true,
             Message = &quot;Thank you. Your message was sent successfully.&quot;
         });
     }
     catch (Exception ex)
     {
         ModelState.AddUnhandledError(ex);
         return Json(new OperationResultInfo
         {
             Successfull = false,
             Message = &quot;There was an error processing your request. Retry later.&quot;
         });
     }
  }

  return Json(new OperationResultInfo
  {
     Successfull = false,
     Message = &quot;Could not send your information.&quot;,
     Errors = ModelState.GetAllErrors()
  });
}

public static class ModelStateExtensions
{
  public static IList&amp;lt;ErrorReasonInfo&amp;gt; GetAllErrors(this ModelStateDictionary modelState)
  {
     var errors = new List&amp;lt;ErrorReasonInfo&amp;gt;();

     foreach (var state in modelState)
     {
         if (state.Value.Errors.Count &amp;gt; 0)
         {
             var err = new ErrorReasonInfo { PropertyName = state.Key };
             state.Value.Errors.ForEach(x =&amp;gt; err.Error += x.ErrorMessage);

             errors.Add(err);
         }
     }

     return errors;
  }
}
&lt;/pre&gt;
&lt;span class=&quot;subtitle&quot;&gt;Displaying The Json Result&lt;/span&gt;
&lt;p&gt;The Json result returned to the client contains all the fields having errors and the related error message. A typical result would look like this:&lt;br /&gt;&lt;/p&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
{
   &quot;Successfull&quot;:false, &quot;Message&quot;:&quot;Could not send your information:&quot;,
   &quot;Errors&quot;:
   [
      {&quot;PropertyName&quot;:&quot;SenderName&quot;, &quot;Error&quot;:&quot;may not be null or empty&quot;},
      {&quot;PropertyName&quot;:&quot;Email&quot;, &quot;Error&quot;:&quot;may not be null or empty&quot;},
      {&quot;PropertyName&quot;:&quot;Subject&quot;, &quot;Error&quot;:&quot;may not be null or empty&quot;},
      {&quot;PropertyName&quot;:&quot;Message&quot;, &quot;Error&quot;:&quot;may not be null or empty&quot;}
   ]
}
&lt;/pre&gt;
&lt;p&gt;How do we format this data on the client and display it in a user-friendly fashion on our page? Let's process the Json object using javascript and add the result to the error place holder using &lt;a href=&quot;http://en.wikipedia.org/wiki/Jquery&quot;&gt;jQuery&lt;/a&gt;:&lt;/p&gt;
&lt;pre class=&quot;brush:javascript&quot;&gt;
&amp;lt;script type=&quot;text/javascript&quot;&amp;gt;
function ProcessResult(content) {

   var json = content.get_response().get_object();
   var result = eval(json);

   $(&quot;#operationMessage &amp;gt; span&quot;).empty();
   $(&quot;#operationMessage &amp;gt; ul&quot;).empty();
   $(':input').removeClass('input-validation-error');

   if (result.Successfull) {
       $('#operationMessage').append('&amp;lt;span&amp;gt;' + result.Message + '&amp;lt;/span&amp;gt;')
                             .removeClass('error')
                             .addClass('success');
   }
   else {

       $('#operationMessage').append('&amp;lt;span&amp;gt;&amp;lt;br&amp;gt;' + result.Message + '&amp;lt;/span&amp;gt;')
                             .removeClass('success')
                             .addClass('error');

       for (var err in result.Errors) {
           var propertyName = result.Errors[err].PropertyName;
           var errorMessage = result.Errors[err].Error;
           var message = propertyName + ' ' + errorMessage;

           $('#' + propertyName).addClass('input-validation-error');
           $('#operationMessage &amp;gt; ul').append('&amp;lt;li&amp;gt;# ' + message + '&amp;lt;/li&amp;gt;');
       }
   }
}
&amp;lt;/script&amp;gt;
&lt;/pre&gt;&lt;br/&gt;&lt;p&gt;Pretty neat, ha? Hope this helps.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Google Analytics in Silverlight</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/google-analytics-in-silverlight"/>
    <id>http://www.hightech.ir/SeeSharp/google-analytics-in-silverlight</id>
    <updated>2009-10-18T12:32:53.203</updated>
    <published>2009-04-29T12:26:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="RIA" />
    <category term="Silverlight" />
    <content type="html" xml:lang="en">
      &lt;p&gt;I've been trying to setup &lt;a href=&quot;http://www.google.com/analytics&quot;&gt;Google Analytics&lt;/a&gt; Event Tracking in a Silverlight application for a while and despite all the how-tos and artilces on the web, I just couldn't get it running. I kept doing everything proposed, but when the application was run on IE, a javascript error was occurred. Firefox didn't even bother reporting the JS error. So, if you happen to have the same problem, here's how you should do it to get it working.&lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html&quot;&gt;Event Tracking&lt;/a&gt; is when you want to track users accessing various parts of you &lt;a href=&quot;http://en.wikipedia.org/wiki/Rich_Internet_application&quot;&gt;RIA&lt;/a&gt; application, which works differently comparing to html based websites. The basic setup is almost the same: include ga.js javascript on your page hosting the Silverlight application. Include this snippet before &amp;lt;/body&amp;gt; tag:&lt;/p&gt;

&lt;pre class=&quot;brush:javascript&quot;&gt;
&amp;lt;script type=&quot;text/javascript&quot;&amp;gt;
   var gaJsHost = ((&quot;https:&quot; == document.location.protocol) ? &quot;https://ssl.&quot; : &quot;http://www.&quot;);
   document.write(unescape(&quot;%3Cscript src='&quot; + gaJsHost + &quot;google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E&quot;));
&amp;lt;/script&amp;gt;
&lt;/pre&gt;
Next step would be to create a helper javascript function which we'll call in our silverlight application. The script would help us track events on our Silverlight application. Add this just below the above script:&lt;br /&gt;

&lt;pre class=&quot;brush:javascript&quot;&gt;
&amp;lt;script type=&quot;text/javascript&quot;&amp;gt;
   function trackPage(category, action, label) {
       try {
           var pageTracker = _gat._getTracker(&quot;xx-xxxxxxxx-x&quot;);
           pageTracker._trackPageview();
           pageTracker._trackEvent(category, action, label);
       }
       catch (err) {
       }
   }
&amp;lt;/script&amp;gt;
&lt;/pre&gt;

&lt;br/&gt;
&lt;a href=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/SfgIEOyJy1I/AAAAAAAAAOU/FEsEXTHmd5U/s1600-h/EventTracking%5B3%5D.png&quot;&gt;&lt;img style=&quot;border: 0px none ; margin: 0px 20px 0px 0px; display: inline;&quot; title=&quot;EventTracking&quot; alt=&quot;EventTracking&quot; src=&quot;http://lh5.ggpht.com/_Z5KTIfnfuNs/SfgIE5i5stI/AAAAAAAAAOY/ozsPNtgSCMs/EventTracking_thumb%5B1%5D.png?imgmax=800&quot; width=&quot;244&quot; align=&quot;left&quot; border=&quot;0&quot; height=&quot;139&quot; /&gt;&lt;/a&gt;
&lt;br/&gt;
&lt;strong&gt;&lt;em&gt;Note: It is essential that calls to_trackPageview is made prior to calling  _trackEvent. &lt;/em&gt;&lt;/strong&gt;&lt;br /&gt;

&lt;p&gt;Notice how the function is wrapped in a try-catch block so if there is any issues with ga.js loading, we silently ignore the tracking. Strangely, when there was any javascript error in IE 8, some parts of my silverlight application didn't work properly. This helped getting around it.&lt;/p&gt;Usually, you'd call an existing javascript in your silverlight app by calling it this way:&lt;br /&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
HtmlPage.Window.Invoke(&quot;functionName&quot;, new[] { args });
&lt;/pre&gt;

But to make things easier, let's create an extension method to help us calling the tracking function:&lt;br /&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public static class ViewExtension
{
   public static void Track(this UserControl view, string action, string page, string label)
   {
       HtmlPage.Window.Invoke(&quot;trackPage&quot;, new string[] { action, page, label });
   }
}
&lt;/pre&gt;

&lt;p&gt;Just need to start tracking now!&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">NHibernate Automatic Validation</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/nhibernate-automatic-validation"/>
    <id>http://www.hightech.ir/SeeSharp/nhibernate-automatic-validation</id>
    <updated>2009-10-18T12:53:42.513</updated>
    <published>2009-04-28T13:15:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="ASPNETMVC" />
    <category term="NHibernate" />
    <content type="html" xml:lang="en">
      &lt;p&gt;NHibernate is for sure one of the prodigy childs of the .NET open-source movement, yet there are some other great libraries and frameworks. One of them is NHibernate Validator which belongs to &lt;a href=&quot;http://sourceforge.net/projects/nhcontrib/&quot;&gt;NHibernate Contrib&lt;/a&gt; project. What it does is to validate your domain entities that supposedly are being persisted using NHibernate, but it provides so much flexibility that you can validate almost every POCO class using attributes.&lt;/p&gt;

&lt;p&gt;I'm using it in an ASP.NET MVC project, so first let's see how to configure and make it work here.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note: I'm using the trunk build of the Castle and NH Contrib Projects. Things may work differently on other versions.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First thing you need to do is to initialize Validator's engine. I'm using it on a web application so let's initialize and use a shared engine. I'm also using the attribute based validation, but you can write the validation logic in your .hbm mapping files.&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class MvcApplication : System.Web.HttpApplication, IMvcApplication
{
  protected void Application_Start()
  {
      RegisterRoutes(RouteTable.Routes);
      CreateDependencyInjectionContainer();
      RegisterControllerFactory();
      RegisterSessionFactory();
      RegisterValidatorEngine();
  }

  private void RegisterValidatorEngine()
  {
      var config = new NHVConfigurationBase();

      config.Properties[Environment.ApplyToDDL] = &quot;false&quot;;
      config.Properties[Environment.AutoregisterListeners] = &quot;true&quot;;
      config.Properties[Environment.ValidatorMode] = &quot;UseAttribute&quot;;
      config.Properties[Environment.SharedEngineClass] = typeof (ValidatorEngine).FullName;
      config.Mappings.Add(new MappingConfiguration(&quot;MyApp.Domain&quot;, null));

      Environment.SharedEngineProvider = new NHibernateSharedEngineProvider();
      Environment.SharedEngineProvider.GetEngine().Configure(config);

      ValidatorInitializer.Initialize(NHibernateConfig);
  }
}
&lt;/pre&gt;

...and that's it. You can validate entities passed to your controller's action by creating an extension method which simplifies things and automatically adds all the errors to the ModelState:&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public static class ControllerExtensions
{
  /// &lt;summary&gt;
  /// Validates an entity
  /// &lt;/summary&gt;
  public static void Validate(this Controller controller, IValidatable entity)
  {
      var engine = Environment.SharedEngineProvider.GetEngine();
      var errors = engine.Validate(entity);

      foreach (var error in errors)
      {
          controller.ModelState.AddModelError(error.PropertyName, error.Message);
      }
  }
}
&lt;/pre&gt;
Note that IValidatable is just a marker interface. To call this method and do the actual validation, you need to call the validate method:&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Contact(ContactMessage msg)
{
  try
  {
      this.Validate(msg);

      if (ModelState.IsValid)
      {
          this.messengerService.SendMail(msg);
          return RedirectToAction(&quot;Index&quot;);
      }
  }
  catch (Exception ex)
  {
      ModelState.AddUnhandledError(ex);
  }

  return View(msg);
}
&lt;/pre&gt;
Easy, right? but it can even get easier! With the power of ASP.NET MVC ActionFilters we can automagically validate our parameters when the action is invoked:&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
/// &lt;summary&gt;
/// Automatically validates all the action
/// parameters of type IValidatable.
/// &lt;/summary&gt;
public class AutoValidate : ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
      var controller = filterContext.Controller as Controller;
      if(controller == null)
          return;

      foreach (var entity in GetEntitiesFromParameters(filterContext.ActionParameters))
      {
          controller.Validate(entity);
      }
  }

  private static IEnumerable&amp;lt;IValidatable&amp;gt; GetEntitiesFromParameters(IEnumerable&amp;lt;KeyValuePair&amp;lt;string, object&amp;gt;&amp;gt; dictionary)
  {
      var validatableParameters = new List&amp;lt;IValidatable&amp;gt;();

      foreach (var keyValue in dictionary)
      {
          if(keyValue.Value is IValidatable)
          {
              validatableParameters.Add((IValidatable)keyValue.Value);
          }
      }

      return validatableParameters;
  }
}
&lt;/pre&gt;
...and your action method looks as simple as this:&lt;br /&gt;
&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[AcceptVerbs(HttpVerbs.Post)]
[AutoValidate]
public ActionResult Contact(ContactMessage msg)
{
  if(ModelState.IsValid)
  {
      try
      {
          this.messengerService.SendMail(msg);
          return RedirectToAction(&quot;Index&quot;);
      }
      catch (Exception ex)
      {
          ModelState.AddUnhandledError(ex);
      }
  }

  return View(msg);
}
&lt;/pre&gt;
&lt;p&gt;Have fun validating!&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Code Review No. N, or Do chimps write code better than us?</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/code-review-no-n-or-do-chimps-write"/>
    <id>http://www.hightech.ir/SeeSharp/code-review-no-n-or-do-chimps-write</id>
    <updated>2009-10-18T13:07:29.463</updated>
    <published>2009-04-28T11:33:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="CodeAnalysis" />
    <content type="html" xml:lang="en">
      &lt;p&gt;Well, this is not actually my first code review, but this is supposed to be a copycat of &lt;a href=&quot;http://ayende.com/Blog/archive/2007/11/13/Code-review-WTF-number-N.aspx&quot;&gt;'Code Review WTF, Number N'&lt;/a&gt; series by &lt;a href=&quot;http://ayende.com&quot;&gt;Ayende Rahien&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I was inspecting an open-source code base which is a medical business application. So why am I reviewing the code base? I had a request to add persian calendar support to this application and I was trying to figure out how much time does this take and if it is possible.&lt;/p&gt;  &lt;p&gt;There are very serious issues here, I even don't know where to start! For a open-source project at its 6th version, I was hoping things to be pretty much solid. Apparently with all the bells and whistles on developer's website, it is not.&lt;/p&gt;

&lt;ul&gt;
   &lt;li&gt;Using a strange naming conversion for your project like xCodeBase, xODR is BAD.&lt;/li&gt;
   &lt;li&gt;Having A LOT of commented code in your code base is a BAD practice.&lt;/li&gt;
   &lt;li&gt;Exposing class fields as public is a BAD practice. Try using properties.&lt;/li&gt;
   &lt;li&gt;Using IF statements to check for database types ALL OVER THE PLACE is VERY BAD.&lt;/li&gt;
   &lt;li&gt;Obfuscated class and method names are considered BAD (unless you've used an obfuscator) as in Lan class which does the string translation job with public methods named g, F and C!!&lt;/li&gt;
   &lt;li&gt;Wrapping remote method names in an ENUM. What were you thinking?!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After going through some of the classes, I think I'm going crazy! Okay, let's see how's the business logic being handled. That's the major part of the application, right?&lt;/p&gt;

&lt;p&gt;Data is accessed by DataCore class in server AND client side (depending if remoting is used), which retrieves the data in an UnTyped dataset. To make things easier(?) there's one single method to invoke remote BusinessLayer implementation methods:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public static DataSet GetDsByMethod(MethodNameDS methodName, object[] parameters)
{
   switch (methodName)
   {
       default:
           throw new ApplicationException(&quot;MethodName not found&quot;);
       case MethodNameDS.AccountModule_GetAll:
           return AccountModules.GetAll((int)parameters[0], (bool)parameters[1], (DateTime)parameters[2], (DateTime)parameters[3], (bool)parameters[4]);
       case MethodNameDS.Appointment_GetApptEdit:
           return Appointments.GetApptEdit((int)parameters[0]);
       case MethodNameDS.Cache_Refresh:
           return Cache.Refresh((string)parameters[0]);
       case MethodNameDS.CovCats_RefreshCache:
           return CovCats.RefreshCache();
   }
}

public enum MethodNameDS
{
   AccountModule_GetAll,
   Appointment_GetApptEdit,
   Cache_Refresh,
   CovCats_RefreshCache,
}
&lt;/pre&gt;

&lt;p&gt;Dude! WTF is that?! and then there's a similar method to work with DataTables!&lt;br /&gt;
&lt;br /&gt;On the server where client requests are processed, data is being serialized / deserialzed by a &quot;WorkerClass&quot;. The code to perform the client's request is what makes me wonder!&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class WorkerClass
{
   private NetworkStream netStream;

   // The constructor obtains the state information.
   public WorkerClass(NetworkStream stream)
   {
       netStream = stream;
   }

   public void DoWork()
   {
   while(true) {//Each loop gets and returns one message pair.
       byte[] data =  null;
       // Retrieve data from client
       try {
           data = RemotingClient.ReadDataFromStream(netStream);
       }
       catch {//if connection was closed by client.
           break;
       }
       DataTransferObject dto=DataTransferObject.Deserialize(data);
       //Process and send response to client--------------------------------------
       XmlSerializer serializer;
       using (MemoryStream memStream = new MemoryStream()) {
           try {
               Type type = dto.GetType();
               if (type == typeof(DtoGetDS)) {
                   DataSet ds = DataCore.GetDsByMethod(((DtoGetDS)dto).MethodNameDS, ((DtoGetDS)dto).Parameters);
                   serializer = new XmlSerializer(typeof(DataSet));
                   serializer.Serialize(memStream, ds);
               }
               else if (type == typeof(DtoGetTable)) {
                   DataTable tb = DataCore.GetTableByMethod(((DtoGetTable)dto).MethodNameTable, ((DtoGetTable)dto).Parameters);
                   serializer = new XmlSerializer(typeof(DataTable));
                   serializer.Serialize(memStream, tb);
               }
               else if (type.BaseType == typeof(DtoCommandBase)) {
                   int result = BusinessLayer.ProcessCommand((DtoCommandBase)dto);
                   DtoServerAck ack = new DtoServerAck();
                   ack.IDorRows = result;
                   serializer = new XmlSerializer(typeof(DtoServerAck));
                   serializer.Serialize(memStream, ack);
               }
               else if (type.BaseType == typeof(DtoQueryBase)) {
                   DataSet ds = BusinessLayer.ProcessQuery((DtoQueryBase)dto);
                   serializer = new XmlSerializer(typeof(DataSet));
                   serializer.Serialize(memStream, ds);
               }
               else if (type.IsGenericType &amp;&amp; type.GetGenericTypeDefinition() == typeof(FactoryTransferObject&amp;lt;&amp;gt;)) {
                   // Pass the DTO to the FactoryServer&amp;lt;T&amp;gt;
                   Type factoryServerType = typeof(FactoryServer&amp;lt;&amp;gt;);
                   factoryServerType = factoryServerType.MakeGenericType(type.GetGenericArguments());

                   MethodInfo processCommandMethod = factoryServerType.GetMethod(&quot;ProcessCommand&quot;, BindingFlags.Public | BindingFlags.Static);
                   processCommandMethod.Invoke(null, new object[] { memStream, dto });
               }
               else {
                   throw new NotSupportedException(string.Format(Resources.DtoNotSupportedException, type.FullName));
               }
           }
           catch (Exception e) {
               DtoException exception = new DtoException();
               exception.Message = e.Message;
               serializer = new XmlSerializer(typeof(DtoException));
               serializer.Serialize(memStream, exception);
           }
           data = memStream.ToArray();
           RemotingClient.WriteDataToStream(netStream, data);
       }
   }//wait for the next message
   //connection was lost.  Client probably closed program
   netStream.Close();
}
&lt;/pre&gt;

&lt;p&gt;The code is so full of anti-patterns that I wonder how it even works. But wait...I just saw a Unit Test project! Something good, finally, eh? But nah...It is a WinForm application and the test code does not looks like a unit test:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
private void FormUnitTests_Load(object sender, EventArgs e)
{
   BenefitComputeRenewDate();
   ToothFormatRanges();
   //LabDueDate();
   textResults.Text += &quot;Done.&quot;;
   textResults.SelectionStart = textResults.Text.Length;
}

private void BenefitComputeRenewDate()
{
   DateTime asofDate = new DateTime(2006, 3, 19);
   bool isCalendarYear = true;
   DateTime insStartDate = new DateTime(2003, 3, 1);
   DateTime result = BenefitLogic.ComputeRenewDate(asofDate, isCalendarYear, insStartDate);
   if (result != new DateTime(2006, 1, 1))
   {
       textResults.Text += &quot;BenefitComputeRenewDate 1 failed.\r\n&quot;;
   }
   isCalendarYear = false; //for the remaining tests
   //earlier in same month
   result = BenefitLogic.ComputeRenewDate(asofDate, isCalendarYear, insStartDate);
   if (result != new DateTime(2006, 3, 1))
   {
       textResults.Text += &quot;BenefitComputeRenewDate 2 failed.\r\n&quot;;
   }
   //earlier month in year
   asofDate = new DateTime(2006, 5, 1);
   result = BenefitLogic.ComputeRenewDate(asofDate, isCalendarYear, insStartDate);
   if (result != new DateTime(2006, 3, 1))
   {
       textResults.Text += &quot;BenefitComputeRenewDate 3 failed.\r\n&quot;;
   }
}
&lt;/pre&gt;

I think that's enough proof for one day. You probably have heard the saying: &quot;Even a chimp can write code&quot;, but sometimes the saying goes like: &quot;Even chimp writes code better than that&quot;.
    </content>
  </entry>
  <entry>
    <title type="html">Dynamically Generated Images with ASP.NET MVC</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/dynamically-generated-images-with"/>
    <id>http://www.hightech.ir/SeeSharp/dynamically-generated-images-with</id>
    <updated>2009-10-18T13:39:47.257</updated>
    <published>2009-04-26T15:57:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="ASPNETMVC" />
    <category term="FarsiLibrary" />
    <category term="Calendars" />
    <content type="html" xml:lang="en">
      &lt;p&gt;For a site I'm working on using ASP.NET MVC, I intended to place a Date badge beside the blog and news posts I'm writing. Since in ASP.NET MVC there's no notion of custom controls (well, at least not like in WebForms) you'll have to do this manually, but as it turned out it was pretty easy to do.&lt;/p&gt;

&lt;p&gt;What I needed to do was to convert a Date instance, e.g. 04.23.2009 to a user friendly calendar icon like this one:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://lh4.ggpht.com/_Z5KTIfnfuNs/SfRPHgU55rI/AAAAAAAAAN0/Vh0wfwsvIow/s1600-h/CalendarIcon3.png&quot;&gt;&lt;img style=&quot;border-width: 0px; display: inline;&quot; title=&quot;CalendarIcon&quot; alt=&quot;CalendarIcon&quot; src=&quot;http://lh5.ggpht.com/_Z5KTIfnfuNs/SfRPJsWuV5I/AAAAAAAAAN4/LFz8ONgu5ko/CalendarIcon_thumb1.png?imgmax=800&quot; width=&quot;46&quot; border=&quot;0&quot; height=&quot;51&quot; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I've seen blogs and site using different icon for each day of the month or a similar trick to do this, but why not actually render it using Graphics API and a picture?&lt;/p&gt;

&lt;p&gt;The first step was to decide what should be returned in you Controller's action method, as the action result? Since there's nothing that returns an Image as the result, let's create one:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class ImageResult : ActionResult
{
  public Image Image
  {
      get; set;
  }

  public ImageFormat ImageFormat
  {
      get; set;
  }

  private static Dictionary&amp;lt;ImageFormat, string&amp;gt; FormatMap
  {
      get; set;
  }

  static ImageResult()
  {
      CreateContentTypeMap();
  }

  public override void ExecuteResult(ControllerContext context)
  {
      if (Image == null) throw new ArgumentNullException(&quot;Image&quot;);
      if (ImageFormat == null) throw new ArgumentNullException(&quot;ImageFormat&quot;);

      context.HttpContext.Response.Clear();
      context.HttpContext.Response.ContentType = FormatMap[ImageFormat];

      Image.Save(context.HttpContext.Response.OutputStream, ImageFormat);
  }

  private static void CreateContentTypeMap()
  {
      FormatMap = new Dictionary&amp;lt;ImageFormat, string&amp;gt;
      {
          { ImageFormat.Bmp,  &quot;image/bmp&quot;                },
          { ImageFormat.Gif,  &quot;image/gif&quot;                },
          { ImageFormat.Icon, &quot;image/vnd.microsoft.icon&quot; },
          { ImageFormat.Jpeg, &quot;image/Jpeg&quot;               },
          { ImageFormat.Png,  &quot;image/png&quot;                },
          { ImageFormat.Tiff, &quot;image/tiff&quot;               },
          { ImageFormat.Wmf,  &quot;image/wmf&quot;                }
      };
  }
}
&lt;/pre&gt;

Pretty easy, ha? You just need to specify the image and the format and it is rendered to the HttpContext as an image. The controller action to render the text would something like this:&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public ActionResult GetCalendarBadge(DateTime displayDate)
{
  Graphics graphics = ?;
  Bitmap bmp = ?;

  //Draw using graphics

  //Direct the output to the bitmap

  return new ImageResult { Image = bmp, ImageFormat = ImageFormat.Png };
}
&lt;/pre&gt;

...and on the view:&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
&amp;lt;% foreach(var item in this.Model.News) %&amp;gt;
     &amp;lt;%= Html.Image&amp;lt;NewsController&amp;gt;(o =&amp;gt; o.GetCalendarBadge(item.DisplayDate), 100, 100) %&amp;gt;
&amp;lt;% } %&amp;gt;
&lt;/pre&gt;

&lt;br /&gt;
&lt;a href=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/SfRPL2NGqZI/AAAAAAAAAN8/SLmInKZkrKA/s1600-h/Calendar%5B4%5D.png&quot;&gt;&lt;img style=&quot;border: 0px none ; margin: 0px 15px 0px 0px; display: inline;&quot; title=&quot;Calendar&quot; alt=&quot;Calendar&quot; src=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/SfRPN0r2QLI/AAAAAAAAAOA/eN7vVPK8XTY/Calendar_thumb%5B2%5D.png?imgmax=800&quot; width=&quot;90&quot; align=&quot;left&quot; border=&quot;0&quot; height=&quot;83&quot; /&gt;&lt;/a&gt;Now, to make things easier, le's use an existing bitmap as our canvas and just draw the values on it. To do this, add an existing image to your project and load it. The rest is just GDI API that renders the date values according to user's Cultural setting.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public ActionResult GetCalendarBadge(DateTime displayDate)
{
  var bmp = Images.Calendar;
  var g = Graphics.FromImage(bmp);

  using (var genericFormat = GetStringFormat())
  {
      var yearRect = new Rectangle(24, 13, 40, 15);
      var dayOfMonthRect = new Rectangle(10, 29, 70, 44);
      var dayNameRect = new Rectangle(10, 30, 70, 10);
      var monthNameRect = new Rectangle(10, 61, 70, 10);

      using(var headerFont = new Font(&quot;Tahoma&quot;, 7.5f, FontStyle.Regular))
      using(var footerFont = new Font(&quot;Tahoma&quot;, 7.5f, FontStyle.Regular))
      using (var dayFont = new Font(&quot;Tahoma&quot;, 14, FontStyle.Bold))
      {
          var day = CurrentCulture.Calendar.GetDayOfMonth(displayDate).ToString();
          var month = CurrentCulture.Calendar.GetMonth(displayDate);
          var year = CurrentCulture.Calendar.GetYear(displayDate).ToString();
        
          var weekDay = CurrentCulture.Calendar.GetDayOfWeek(displayDate);
          var dayName = CurrentCulture.DateTimeFormat.GetDayName(weekDay);
          var monthName = CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(month);
        
          g.DrawString(year, headerFont, Brushes.White, yearRect, genericFormat);
          g.DrawString(day, dayFont, Brushes.Black, dayOfMonthRect, genericFormat);
          g.DrawString(dayName, footerFont, Brushes.Black, dayNameRect, genericFormat);
          g.DrawString(monthName, footerFont, Brushes.Black, monthNameRect, genericFormat);
      }
  }

  return new ImageResult { Image = bmp, ImageFormat = ImageFormat.Png };
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;a href=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/SfRPQPntsmI/AAAAAAAAAOE/gz3ScPNikS0/s1600-h/CalendarBadge%5B14%5D.png&quot;&gt;&lt;img style=&quot;border: 0px none ; display: inline; margin-left: 0px; margin-right: 0px;&quot; title=&quot;CalendarBadge&quot; alt=&quot;CalendarBadge&quot; src=&quot;http://lh4.ggpht.com/_Z5KTIfnfuNs/SfRPUGljIaI/AAAAAAAAAOI/ytgRZXKpubI/CalendarBadge_thumb%5B12%5D.png?imgmax=800&quot; width=&quot;436&quot; border=&quot;0&quot; height=&quot;244&quot; /&gt;&lt;/a&gt;
&lt;br /&gt;
&lt;br /&gt;Note that CurrentCulture property returns the running user's CultureInfo which will help 'Translating' the date value correctly for different Cultures. What we achieved is a nice calendar badge with render date values and it is not even constrained to our Canvas size. Hope this helps.
    </content>
  </entry>
  <entry>
    <title type="html">Using Windsor IoC in ASP.NET MVC</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/using-windsor-ioc-in-aspnet-mvc"/>
    <id>http://www.hightech.ir/SeeSharp/using-windsor-ioc-in-aspnet-mvc</id>
    <updated>2009-10-18T13:44:47.043</updated>
    <published>2009-04-26T15:30:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="ASPNETMVC" />
    <category term="Windsor" />
    <content type="html" xml:lang="en">
      &lt;p&gt;With the power of an IoC engine, you can inject your repositories, services, etc. when building applications using ASP.NET MVC framework. Since one of the best IoC engines out there IMHO is Castle Windsor using it has become natural more than ever, but as soon as I did, strange problems occurred when testing very simple scenarios. Two major pains were:&lt;/p&gt;

&lt;p&gt;
&lt;span class=&quot;subtitle&quot;&gt;Model Binders&lt;/span&gt;&lt;br /&gt;
ModelBinders automatically bind form values to your object properties. When using Windsor, I noticed that almost all the parameter values are null when passed to the controller action.&lt;br /&gt;&lt;br /&gt;

&lt;span class=&quot;subtitle&quot;&gt;Parameter Values&lt;/span&gt;&lt;br /&gt;
When a controller action was called with a parameter for the first time, all subsequent calls somehow cached the parameter values. Type and Value of the parameter has no effect, and even disabling caching didn't work.&lt;br /&gt;&lt;br /&gt;
I've been pulling my hair for a couple of days (yeah, I kinda went bald because of this) before I figure this out, and when I thinking about it, the reason of this behavior is clearly obvious!
&lt;/p&gt;

&lt;h4&gt;&lt;em&gt;Windsor uses Singleton lifetime for registered services. All you need to do when registering controllers, is to use Transient lifetime!&lt;/em&gt;&lt;/h4&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
Container.Register(AllTypes.FromAssemblyContaining&amp;lt;MvcApplication&amp;gt;()
                           .Where(o =&amp;gt; o.Namespace == typeof(HomeController).Namespace)
                           .Configure(o =&amp;gt; o.LifeStyle.Is(LifestyleType.Transient)));
&lt;/pre&gt;
&lt;br /&gt;Problem solved, Case closed! &lt;br /&gt;&lt;br /&gt;
    </content>
  </entry>
  <entry>
    <title type="html">ASP.NET MVC : Best way to go?</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/aspnet-mvc-best-way-to-go"/>
    <id>http://www.hightech.ir/SeeSharp/aspnet-mvc-best-way-to-go</id>
    <updated>2009-10-18T13:48:02.437</updated>
    <published>2009-04-23T11:17:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="ASPNETMVC" />
    <content type="html" xml:lang="en">
      &lt;p&gt;With total control over html rendering in ASP.NET MVC there are a lot of things you can do, and this actually is correct the other way around, meaning you have to do a lot of things yourself: No fancy ASP.NET Custom Controls. It somehow reminds me of the old days, when you had to do everything to display a list of data. Back then, everything seemed manual. You had to emit html, control page state, etc. but with the rise of ASP.NET everything was amazingly done for you behind the scene. You no longer had to waste your time on the basics and you could focus on the problem at hand. Great, right?&lt;/p&gt;

&lt;p&gt;Now with ASP.NET MVC, you might think we're back where we started, but I wouldn't go that far. While ASP.NET MVC offers control, maintainability and simplicity it also provides you &lt;a href=&quot;http://en.wikipedia.org/wiki/Separation_of_concern&quot;&gt;Separation of Concerns&lt;/a&gt; which [ is one of the things that] was lacking in Classic ASP.&lt;/p&gt;

&lt;p&gt;The question is, should you use it, instead of well established ASP.NET WebForms? That depends. Are you working on a &lt;a href=&quot;http://en.wikipedia.org/wiki/Greenfield_project&quot;&gt;greenfield&lt;/a&gt; project? Are you eager to learn the new stuff? Are you looking for more control and power on what the actual html outcome is? If you answer to these questions is positive, then you definitely need to use ASP.NET MVC for your project.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">ASP.NET MVC and Testing FilterActions</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/aspnet-mvc-and-testing-filteractions"/>
    <id>http://www.hightech.ir/SeeSharp/aspnet-mvc-and-testing-filteractions</id>
    <updated>2009-10-18T13:56:11.913</updated>
    <published>2009-04-22T12:50:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Testing" />
    <category term="ASPNETMVC" />
    <category term="TDD" />
    <content type="html" xml:lang="en">
      &lt;p&gt;I'm preparing my website, which benefits NHibernate and ASP.NET MVC so I finally got a chance to actually do something with this nice pair. Since the pattern of SessionPerRequest and TransactionPerRequest is useful, I intended to automagically create a new session upon activating my Controller's action, where necessary, since this cross-cutting of concerns will make your session management code separate from your controller's code and you no longer need to worry about it. This part is very easy to do thanks to ActionFilterAttributes in ASP.NET MVC:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class TransactionPerRequest : ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
       NHibernateSessionHolder.Current.BeginTransaction();
   }

   public override void OnResultExecuted(ResultExecutedContext filterContext)
   {
       if(filterContext.Exception == null)
       {
           Commit();
       }
       else
       {
           Rollback();
       }
   }

   protected virtual void Commit()
   {
       if (NHibernateSessionHolder.Current.Transaction.IsActive)
       {
           NHibernateSessionHolder.Current.Transaction.Commit();
       }
   }

   protected virtual void Rollback()
   {
       if (NHibernateSessionHolder.Current.Transaction.IsActive)
       {
           NHibernateSessionHolder.Current.Transaction.Rollback();
       }           
   }
}
&lt;/pre&gt;

&lt;p&gt;NHibernateSessionHolder is actually a static class and is initialized in Global.asax when application is started. Is stores the session in current HttpContext object.&lt;/p&gt;

&lt;p&gt;So, how do we test this, you might ask? This leads to another question that how do you generally test ActionFilterAttributes? There are two ways to achieve this.&lt;br /&gt;&lt;br /&gt;If you can test the filter attribute's behavior in your controller, the easiest way would be to directly call the action on the controller. You need to create the route values and use the ControllerActionInvoker to call the action of your controller. Also mocking HttpContext is preferred for obvious reasons. My test case would look like this:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[TestMethod]
public void Transaction_Is_Automatically_Opened_Using_Transaction_Per_Request()
{
   var httpContext = new Mock&amp;lt;HttpContextBase&amp;gt;().Object;
   var controller = new AccountController();
   var controllerContext = new ControllerContext(httpContext, controller.GetCreateActionRouteData(), controller);
   var controllerInvoker = new ControllerActionInvoker();
  
   controllerInvoker.InvokeAction(controllerContext, &quot;Create&quot;);

   Assert.IsTrue(controller.TransactinWasCreated);
}
&lt;/pre&gt;

&lt;p&gt;
But sometimes, you need to test the internal behavior of your filter attribute and it would not be possible doing so in your Controller classes. Let's say, you want to check if the OnResultExecuted method handles exception properly by rolling back the transaction. To do it this way, you need to create or mock ActionExecutingContext and ResultExecutedContext:&lt;br /&gt;&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[TestMethod]
public void Transaction_Is_Automatically_Rolled_Back_If_Exception_Thrown()
{
   var httpContext = new Mock&amp;lt;HttpContextBase&amp;gt;().Object;
   var actionDescriptor = new Mock&amp;lt;ActionDescriptor&amp;gt;().Object;
   var actionResult = new Mock&amp;lt;ActionResult&amp;gt;().Object;

   var controller = new AccountController();
   var controllerContext = new ControllerContext(httpContext, new RouteData(), controller);
   var filterContext = new ActionExecutingContext(controllerContext, actionDescriptor, new RouteValueDictionary());
   var resultContext = new ResultExecutedContext(controllerContext, actionResult, false, new Exception(&quot;an exception is thrown&quot;));
   var transactionAttrib = new TestableTransactionAttribute();

   transactionAttrib.OnActionExecuting(filterContext);
   transactionAttrib.OnResultExecuted(resultContext);

   Assert.IsFalse(NHibernateSessionHolder.Current.Transaction.IsActive);
   Assert.IsFalse(transactionAttrib.IsCommitted);
   Assert.IsTrue(transactionAttrib.IsRolledback);
}
&lt;/pre&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Key-Gen for .NET Apps!</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/key-gen-for-net-apps"/>
    <id>http://www.hightech.ir/SeeSharp/key-gen-for-net-apps</id>
    <updated>2009-10-18T14:02:01.123</updated>
    <published>2009-04-13T17:31:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Security" />
    <category term="Cracking" />
    <content type="html" xml:lang="en">
      &lt;p&gt;You all know that .NET generated application convert the high-level codes from source language (e.g. C#) and converts them to IL. Basically, if you could convert the IL code back to the high-level language, you'd have the original source code of the application, and to some extent, you can do this, but this is the story for another post. Today, I'd want to show you how your public licensing API would provide a very easy way to crack open your own application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note: I take no responsibility for how you use the piece of information. By reading these instructions  you accept the sole responsibility of any illegal use. The names and information provided here are changed to save the innocent.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Suppose you've put a lot of energy and time and written your state-of-the-art application and you've released it to the market. After a while some junior software developer tries to inspect your assembly to see how you've managed to do a special tricks or two. (Mind you, that's not what I'd suggest you do, dear reader, because you might end-up facing copyright infringement lawsuits). 

Now when he's inspecting the API, he encounters your licensing API, and even worst, those API are public:&lt;/p&gt;  

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class RSALicenseCodec : IEncoder, IDecoder
{
}

public class License
{
   public Guid LicenseId = Guid.NewGuid();
   public DateTime EndTime;   public string LicensedTo;
   public DateTime PurchaseDate;
   public LicenseType Type;
   public DateTime StartTime;
}

public static string LicenseToKey(IEncoder encoder, License license)
{
}

public static License KeyToLicense(IDecoder decoder, string key)
{
}
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note: Actual implementation was cut off!&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;http://lh5.ggpht.com/_Z5KTIfnfuNs/SeM3oQHECXI/AAAAAAAAANo/1VHcQuUrtKA/s1600-h/Licensing-API%5B4%5D.png&quot;&gt;&lt;img style=&quot;border: 0px none ; display: inline;&quot; title=&quot;Licensing-API&quot; alt=&quot;Licensing-API&quot; src=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/SeM3pRERlsI/AAAAAAAAANs/ZD6epIBV_3M/Licensing-API_thumb%5B2%5D.png?imgmax=800&quot; width=&quot;305&quot; border=&quot;0&quot; height=&quot;109&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;/p&gt;

&lt;p&gt;Now with all these public API, only thing between a novice developer with bad intentions and a perfect key-gen to for application, is the copyright infringement lawsuit! Do you think that alone is enough?&lt;/p&gt;

&lt;p&gt;I don't want to give you the idea that by only making these API private you're safe, no. There are a lot of things you should do before you're even close to being safe with hackers and crackers, but in my opinion taking all the care would no save you either. Almost nothing can stop a motivated cracker.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Resharper 4.5 Released</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/resharper-45-released"/>
    <id>http://www.hightech.ir/SeeSharp/resharper-45-released</id>
    <updated>2009-10-18T14:24:05.85</updated>
    <published>2009-04-09T09:31:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Resharper" />
    <content type="html" xml:lang="en">
      &lt;p&gt;Great guys at &lt;a href=&quot;http://www.jetbrains.com/&quot;&gt;JetBrains&lt;/a&gt; have release next version of their productivity tool, Resharper. It seems this release fixes performance and memory usage issues and performance is tuned for big projects. &lt;a href=&quot;http://www.jetbrains.com/resharper/features/newfeatures.html&quot;&gt;According&lt;/a&gt; to JetBrains, following features are significantly faster now:&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;Renaming Symbols&lt;/li&gt;
    &lt;li&gt;Finding Usages&lt;/li&gt;
    &lt;li&gt;Creating Symbol from Usage&lt;/li&gt;
    &lt;li&gt;Analyzing large XAML files&lt;/li&gt;
&lt;/ul&gt;
&lt;br/&gt;
&lt;p&gt;I've been using their nightly builds for a while and there are a couple of nice new features added to version 4.5. Things like enforcing a naming convention, native support for MSTest unit testing, and copying XML comment from existing (base class / interfaces) sources are some of them. To give it a try, download a trial copy &lt;a href=&quot;http://www.jetbrains.com/resharper/download/index.html&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Windows Seven and Sidebar Gadgets</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/windows-seven-and-sidebar-gadgets"/>
    <id>http://www.hightech.ir/SeeSharp/windows-seven-and-sidebar-gadgets</id>
    <updated>2009-10-18T14:27:03.153</updated>
    <published>2009-04-05T15:37:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Win7" />
    <content type="html" xml:lang="en">
      &lt;p&gt;I've been using Windows 7 for a while now and my test experience is nearly great, with some exceptions like for occasional NVidia driver crashing the kernel and a few restarts because of it. The other day, I found something new : my sidebar gadget was missing completely! After searching for it and googling, it turns out disable UAC altogether (setting to &quot;Never Notify&quot;) will make sidebar completely disappear and as soon as you bring it up only one notch (setting it to &quot;Do not dim my desktop&quot;) will automagically bring it back after a restart.&lt;/p&gt;

&lt;p&gt;
&lt;br /&gt;&lt;a href=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/SdiQzXmgqJI/AAAAAAAAANg/Or96dnrQDKA/s1600-h/UAC%5B5%5D.png&quot;&gt;&lt;img style=&quot;border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px&quot; title=&quot;UAC&quot; border=&quot;0&quot; alt=&quot;UAC&quot; src=&quot;http://lh4.ggpht.com/_Z5KTIfnfuNs/SdiQ5WkuPQI/AAAAAAAAANk/VBJLsMEQDRM/UAC_thumb%5B3%5D.png?imgmax=800&quot; width=&quot;458&quot; height=&quot;299&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;/p&gt;

&lt;p&gt;Luckily for me, guys on &lt;a href=&quot;http://www.mydigitallife.info&quot;&gt;My Digital Life&lt;/a&gt; forum have a hack to get this going :&lt;/p&gt;

&lt;p&gt;1- Close all gadgets.&lt;/p&gt;
&lt;p&gt;2- Take the ownership of the Gadget folder and grant permission to Administrators (folder is located on Windows Drive:\Program Files\Windows Sidebar)&lt;/p&gt;
&lt;p&gt;3- There are a couple of file here, create a backup copy.&lt;/p&gt;
&lt;p&gt;4- Download the patched files &lt;a href=&quot;http://www.ziddu.com/download/3042059/Win7-Sidebar-Fix.zip.html&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;5- Overwrite the existing files with the ones in the zip file.&lt;/p&gt;  &lt;p&gt;6- Re-add all your gadgets to your desktop.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;&lt;u&gt;Note that this is a patch. It worked on my machine but use it at your own risk.&lt;/u&gt;&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">FarsiLibrary 2.1 Released</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/farsilibrary-21-released"/>
    <id>http://www.hightech.ir/SeeSharp/farsilibrary-21-released</id>
    <updated>2009-10-18T14:28:31.693</updated>
    <published>2009-03-16T16:19:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="FarsiLibrary" />
    <content type="html" xml:lang="en">
      &lt;p&gt;Finally the 2.1 version of FarsiLibrary is released. Here are the changes made into this version:&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;- &lt;font color=&quot;#008000&quot;&gt;&lt;strong&gt;Fixed&lt;/strong&gt;&lt;/font&gt; : Rendering of controls in non-official themes or when a 3rd party windows skinning (e.g. WindowsBlinds) is installed.    &lt;br /&gt;- &lt;font color=&quot;#008000&quot;&gt;&lt;strong&gt;Fixed&lt;/strong&gt;&lt;/font&gt; : Problem when setting SelectedDateTime property of FXDatePicker control to null value.    &lt;br /&gt;- &lt;font color=&quot;#008000&quot;&gt;&lt;strong&gt;Fixed&lt;/strong&gt;&lt;/font&gt; : Painting of FADatePicker in readonly mode when Readonly property is set fixed.    &lt;br /&gt;- &lt;font color=&quot;#008000&quot;&gt;&lt;strong&gt;Fixed&lt;/strong&gt;&lt;/font&gt; : Problem of setting ForeColor and BackColor in FADatePicker    &lt;br /&gt;- &lt;font color=&quot;#008000&quot;&gt;&lt;strong&gt;Fixed&lt;/strong&gt;&lt;/font&gt; : Certain usage of WinForms control resulted wrong display of Week Of Day in header part of the FAMonthView.    &lt;br /&gt;- &lt;font color=&quot;#008000&quot;&gt;&lt;strong&gt;Fixed&lt;/strong&gt;&lt;/font&gt; : Certain usage of FAMonthView resulted in wrong displaying of date when culture is invariant.    &lt;br /&gt;    &lt;br /&gt;- &lt;font color=&quot;#0080ff&quot;&gt;&lt;strong&gt;Added&lt;/strong&gt;&lt;/font&gt; : Methods SetTodayDate and SetEmptyDate added to FXDatePicker and FXMonthView which lets you call the code that represents Today and Empty buttons clicks respectively.    &lt;br /&gt;- &lt;font color=&quot;#0080ff&quot;&gt;&lt;strong&gt;Added&lt;/strong&gt;&lt;/font&gt; : PersianCultureInfo which is a FA-IR Culture with correct PersianCalendar and DateTimeFormatInfo.    &lt;br /&gt;- &lt;font color=&quot;#0080ff&quot;&gt;&lt;strong&gt;Added&lt;/strong&gt;&lt;/font&gt; : PersianDateTimeFormatInfo that represents datetime formatting information for FA-IR culture.    &lt;br /&gt;- &lt;font color=&quot;#0080ff&quot;&gt;&lt;strong&gt;Added&lt;/strong&gt;&lt;/font&gt; : DateTimeExtensions to help convert between PersianDate and DateTime instances via extension methods.    &lt;br /&gt;- &lt;font color=&quot;#0080ff&quot;&gt;&lt;strong&gt;Added&lt;/strong&gt;&lt;/font&gt; : XmlnsDefinition is added to WPF namespaces. You can reference the controls assembly with &lt;a href=&quot;http://schemas.hightech.ir/wpf/2008/FarsiLibrary&quot;&gt;http://schemas.hightech.ir/wpf/2008/FarsiLibrary&lt;/a&gt; namespace.    &lt;br /&gt;- &lt;font color=&quot;#0080ff&quot;&gt;&lt;strong&gt;Added&lt;/strong&gt;&lt;/font&gt; : Methods to add / remove validation errors on BaseControl.    &lt;br /&gt;- &lt;font color=&quot;#0080ff&quot;&gt;&lt;strong&gt;Added&lt;/strong&gt;&lt;/font&gt; : PersianDateValueConverter which can be used in WPF applications to convert strings representing DateTime to their PersianDate equivalant.    &lt;br /&gt;- &lt;font color=&quot;#0080ff&quot;&gt;&lt;strong&gt;Added&lt;/strong&gt;&lt;/font&gt; : WPF Demo to show usage of custom date converters.    &lt;br /&gt;- &lt;font color=&quot;#0080ff&quot;&gt;&lt;strong&gt;Added&lt;/strong&gt;&lt;/font&gt; : Ability to show and hide Today and Empty buttons on FAMonthView.     &lt;br /&gt;- &lt;font color=&quot;#0080ff&quot;&gt;&lt;strong&gt;Added&lt;/strong&gt;&lt;/font&gt; : VisualStudio designer for WPF and actions for WinForm controls is added.    &lt;br /&gt;    &lt;br /&gt;- &lt;font color=&quot;#ff8000&quot;&gt;&lt;strong&gt;Modified&lt;/strong&gt;&lt;/font&gt; : Localization of WPF controls are using mechanism like WinForm controls (using StringIDs). Redundant .resx files are removed.    &lt;br /&gt;- &lt;font color=&quot;#ff8000&quot;&gt;&lt;strong&gt;Modified&lt;/strong&gt;&lt;/font&gt; : Merged WinForm and WPF controls into one solution.     &lt;br /&gt;- &lt;font color=&quot;#ff8000&quot;&gt;&lt;strong&gt;Modified&lt;/strong&gt;&lt;/font&gt; : ValueValidatingEventArgs now passes HasErrors property of the control when raising event.    &lt;br /&gt;- &lt;font color=&quot;#ff8000&quot;&gt;&lt;strong&gt;Modified&lt;/strong&gt;&lt;/font&gt; : PersianWeekDayNames and PersianMonthNames have became internal. Use PersianDateTimeFormatInfo class instead.    &lt;br /&gt;- &lt;font color=&quot;#ff8000&quot;&gt;&lt;strong&gt;Modified&lt;/strong&gt;&lt;/font&gt; : When parsing a string representation of PersianDate e.g. 1382/08/23 time part was initialized from system time, but now initialized to 00:00 to be consistent with DateTime behavior.    &lt;br /&gt;- &lt;font color=&quot;#ff8000&quot;&gt;&lt;strong&gt;Modified&lt;/strong&gt;&lt;/font&gt; : PersianDateConverter is changed access modifier to Internal. You should not use this class, and instead either cast instances of DateTime / PersianDate or use newly provided extension methods.    &lt;br /&gt;- &lt;font color=&quot;#ff8000&quot;&gt;&lt;strong&gt;Modified&lt;/strong&gt;&lt;/font&gt; : Strings representing DateTime is now parsed using InvariantCulture when parsed to DateTime instance.    &lt;br /&gt;- &lt;font color=&quot;#ff8000&quot;&gt;&lt;strong&gt;Modified&lt;/strong&gt;&lt;/font&gt; : Static Parse and TryParse method accepting DateTime instance is removed. Use constructor overload instead.    &lt;br /&gt;- &lt;font color=&quot;#ff8000&quot;&gt;&lt;strong&gt;Modified&lt;/strong&gt;&lt;/font&gt; : &amp;quot;Readonly&amp;quot; property in FAContainerComboBox is made obsolete. Use IsReadonly property.    &lt;br /&gt;- &lt;font color=&quot;#ff8000&quot;&gt;&lt;strong&gt;Modified&lt;/strong&gt;&lt;/font&gt; : Border color of control in Office2000 and WindowsXP was near white color. Now uses SystemColors.ControlDarkDark value.    &lt;br /&gt;- &lt;font color=&quot;#ff8000&quot;&gt;&lt;strong&gt;Modified&lt;/strong&gt;&lt;/font&gt; : Created a new base class for FAMonthView, which will be base of other upcoming controls.    &lt;br /&gt;- &lt;font color=&quot;#ff8000&quot;&gt;&lt;strong&gt;Modified&lt;/strong&gt;&lt;/font&gt; : CurrentMonthName property from FAMonthView is made obsolete. You can use the GetMonthName method on BaseCulturedControl class instead.    &lt;br /&gt;- &lt;font color=&quot;#ff8000&quot;&gt;&lt;strong&gt;Modified&lt;/strong&gt;&lt;/font&gt; : Arrows of the FAMonthView will gray-out if the control is in disabled state. Change of selected date is not available if the control is disabled.&lt;/p&gt;  &lt;p&gt;Notice that &quot;Modified&quot; entries might be breaking your existing code base, but you are encouraged to use this latest version as there were some rather important bugs fixed and some useful features is added.&lt;/p&gt;  &lt;p&gt;   &lt;br /&gt;Like always, get the files from my web sky-drive &lt;a href=&quot;http://cid-4962b6ceabc2cbd7.skydrive.live.com/browse.aspx/BlogFiles/Farsi%20Library&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Unit Testing : Fact or Fantasy?</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/unit-testing-fact-or-fantasy"/>
    <id>http://www.hightech.ir/SeeSharp/unit-testing-fact-or-fantasy</id>
    <updated>2009-10-18T14:32:56.24</updated>
    <published>2009-03-09T10:55:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Testing" />
    <category term="General" />
    <content type="html" xml:lang="en">
      &lt;p&gt;I proposed a &lt;a href=&quot;http://www.codeproject.com/script/Surveys/Results.aspx?srvid=666&quot;&gt;poll&lt;/a&gt; to &lt;a href=&quot;http://www.codeproject.com/&quot;&gt;CodeProject&lt;/a&gt; web site a while ago to see how community is embracing the TDD and agile. There are a lot of talks in .NET community regarding writing tests (Unit Tests, Acceptance Tests, etc.) and even Microsoft is taking this seriously by providing new frameworks and tools to support the idea and encourage the developers. I could argue that ASP.NET MVC, supporting TDD in VisualStudio 2010 and lots of other things coming from the &quot;&lt;a href=&quot;http://blogs.msdn.com/somasegar/&quot;&gt;Bosses&lt;/a&gt;&quot; is a sign of this, don't you agree? But how community in general and specifically developers are embracing this? That's what I intended to find out.&lt;/p&gt;&lt;p&gt;Here's the result:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://lh5.ggpht.com/_Z5KTIfnfuNs/SbTEd__JbjI/AAAAAAAAANI/DNIbmblTQKo/s1600-h/Chart%5B11%5D.png&quot;&gt;&lt;img style=&quot;BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: block; FLOAT: none; MARGIN-LEFT: auto; BORDER-TOP: 0px; MARGIN-RIGHT: auto; BORDER-RIGHT: 0px&quot; title=&quot;Chart&quot; border=&quot;0&quot; alt=&quot;Chart&quot; src=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/SbTEgbJQ9CI/AAAAAAAAANM/ITsmdl8YLb0/Chart_thumb%5B7%5D.png?imgmax=800&quot; width=&quot;650&quot; height=&quot;220&quot; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Interesting, right? You can see that 18% not know what unit testing is! and this makes almost half of 1000 voted people (exactly 42%) not testing their code! What do you make of it? I'd say it is a disaster! How could the application developers have a night's sleep if they have absolutely ZERO testing code? I'm sure they say unit testing is not for us, we just write business applications. Well, writing a business application with 50,000 - 70,000 LoC should have SOME bugs in it, right? How do you make sure there's no bug at least in your core functionality!?&lt;/p&gt;

&lt;p&gt;Thanks Chris for shedding some lights on this. What about you, dear reader? Do you find unit testing important? Do you test the code you've written?&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Design-Time Properties</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/design-time-properties"/>
    <id>http://www.hightech.ir/SeeSharp/design-time-properties</id>
    <updated>2009-10-19T07:18:38.377</updated>
    <published>2009-03-05T10:35:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="WinForms" />
    <category term="Designer" />
    <content type="html" xml:lang="en">
      &lt;p&gt;Ever wanted to have a Designer-Only properties, whose only purpose is to do something in Visual Studio? I guess you already almost know how to do this. Simply create a property with Getters / Setters and assign an Editor to it, but there are a few things you can do to enhance it.&lt;/p&gt;&lt;p&gt;Let's say we want to create a property that will be shown on PropertyEditor and assign it an editor so that when the editor is activated we get an About dialog about our control / component. Fancy enough?&lt;/p&gt;&lt;p&gt;so let's create our basic property. After thinking about it, we don't need a setter at all and since this is a design time property the return value and return type are also unimportant. So we're down to this:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public object About
{
    get { return null; }
}
&lt;/pre&gt;
&lt;p&gt;Assigning an property Editor is relatively easy. Create a new class and inherit from UITypeEditor override a couple of methods and you're all set:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[EditorBrowsable(EditorBrowsableState.Never)]
internal sealed class AboutDialogEditor : UITypeEditor
{
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        return UITypeEditorEditStyle.Modal;
    }

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        About about = new About();
        about.ShowDialog();
        about.Dispose();

        return null;
    }
}
&lt;/pre&gt;
&lt;p&gt;What we're doing here is first to specify our editor should be opened in Modal mode, and second when the value is requested for that property (Editor is invoked), we just display our about dialog. So, by assigning this editor to our property, it should work:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[Editor(typeof(AboutDialogEditor), typeof(UITypeEditor))]
public object About
{
    get { return null; }
}
&lt;/pre&gt;

&lt;p&gt;&lt;a href=&quot;http://lh5.ggpht.com/_Z5KTIfnfuNs/Sa92bYDIlkI/AAAAAAAAAM4/3WuW3LCCbmk/s1600-h/AboutDialog-FirstTake%5B4%5D.png&quot;&gt;&lt;img style=&quot;BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px&quot; title=&quot;AboutDialog-FirstTake&quot; border=&quot;0&quot; alt=&quot;AboutDialog-FirstTake&quot; src=&quot;http://lh5.ggpht.com/_Z5KTIfnfuNs/Sa92e0E2VlI/AAAAAAAAAM8/B2jIV6vv2kw/AboutDialog-FirstTake_thumb%5B2%5D.png?imgmax=800&quot; width=&quot;640&quot; height=&quot;251&quot; /&gt;&lt;/a&gt; &lt;/p&gt;&lt;p&gt;There are some other things to do. First, our property is displayed &quot;somewhere&quot; in the PropertyEditor. That's not what we want for an About dialog, is it? We need the property to appear always first and we need to somehow distinct it from other normal properties. What we can do about it is to use ParenthesizePropertyNameAttribute which simply signifies what our property should be treated specially, just like the standard Name property which is displayed above the others and is in parentheses. Also, to explicitly declare that our property is only a design-time property we'll add a DesignOnlyAttribute:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[DesignOnly(true)]
[ParenthesizePropertyName(true)]
[Editor(typeof(AboutDialogEditor), typeof(UITypeEditor))]
public object About
{
    get { return null; }
}
&lt;/pre&gt;

&lt;p&gt;The only thing left here is that we don't want developers working with our controls see this property, because of the fact that it is a design-time property. To do this we add a EditorBrowsableAttribute and make our property Hidden in the texteditor of Visual Studio. So here's how our final property looks like:&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[DesignOnly(true)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[ParenthesizePropertyName(true)]
[Editor(typeof(AboutDialogEditor), typeof(UITypeEditor))]
public object About
{
    get { return null; }
}
&lt;/pre&gt;

&lt;p&gt;&lt;a href=&quot;http://lh5.ggpht.com/_Z5KTIfnfuNs/Sa92gGqF5SI/AAAAAAAAANA/2Qok8Bu9EnM/s1600-h/AboutDialog-SecondTake%5B4%5D.png&quot;&gt;&lt;img style=&quot;BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px&quot; title=&quot;AboutDialog-SecondTake&quot; border=&quot;0&quot; alt=&quot;AboutDialog-SecondTake&quot; src=&quot;http://lh5.ggpht.com/_Z5KTIfnfuNs/Sa92hlLjDEI/AAAAAAAAANE/afda9oGcCGs/AboutDialog-SecondTake_thumb%5B2%5D.png?imgmax=800&quot; width=&quot;375&quot; height=&quot;191&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Gmail on IE8</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/gmail-on-ie8"/>
    <id>http://www.hightech.ir/SeeSharp/gmail-on-ie8</id>
    <updated>2009-10-18T14:42:46.517</updated>
    <published>2009-02-15T14:25:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="General" />
    <content type="html" xml:lang="en">
      &lt;p&gt;Looks like Gmail guys don't like my new browser. Sometimes (notice, just sometimes) things get broken in IE8 beta when using Gmail resulting strange layout problems. Even in turning compatibility mode to on has no effect on this.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://lh5.ggpht.com/_Z5KTIfnfuNs/SZf0mq5jvpI/AAAAAAAAAMY/avec-d-u6tE/s1600-h/Gmail-Compose%5B8%5D.png&quot;&gt;&lt;img style=&quot;border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px&quot; title=&quot;Gmail-Compose&quot; border=&quot;0&quot; alt=&quot;Gmail-Compose&quot; src=&quot;http://lh5.ggpht.com/_Z5KTIfnfuNs/SZf0pFyR-XI/AAAAAAAAAMc/5EFQqcK36WI/Gmail-Compose_thumb%5B6%5D.png?imgmax=800&quot; width=&quot;412&quot; height=&quot;167&quot; /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;http://lh4.ggpht.com/_Z5KTIfnfuNs/SZf0rXNTdQI/AAAAAAAAAMg/HRvhT_Dedwo/s1600-h/Gmail-Inbox%5B5%5D.png&quot;&gt;&lt;img style=&quot;border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px&quot; title=&quot;Gmail-Inbox&quot; border=&quot;0&quot; alt=&quot;Gmail-Inbox&quot; src=&quot;http://lh3.ggpht.com/_Z5KTIfnfuNs/SZf0tmM1wMI/AAAAAAAAAMk/tPI1xVMbagM/Gmail-Inbox_thumb%5B3%5D.png?imgmax=800&quot; width=&quot;410&quot; height=&quot;166&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6069495622049300789-1771244682538079907?l=heskandari.blogspot.com'/&gt;&lt;/div&gt;
    </content>
  </entry>
  <entry>
    <title type="html">VS.NET Designer Errors</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/vs-designer-errors-rsod-again"/>
    <id>http://www.hightech.ir/SeeSharp/vs-designer-errors-rsod-again</id>
    <updated>2009-10-19T06:13:12.583</updated>
    <published>2009-02-14T15:01:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="WinForms" />
    <category term="VSNET" />
    <content type="html" xml:lang="en">
      &lt;p&gt;&lt;a href=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/SZariGi7oII/AAAAAAAAAMI/yovDr_7SnQA/s1600-h/Unknown-Designer-Exceptions%5B6%5D.png&quot;&gt;&lt;img style=&quot;BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; MARGIN: 5px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px&quot; title=&quot;Unknown-Designer-Exceptions&quot; border=&quot;0&quot; alt=&quot;Unknown-Designer-Exceptions&quot; align=&quot;right&quot; src=&quot;http://lh4.ggpht.com/_Z5KTIfnfuNs/SZarjgq75cI/AAAAAAAAAMM/iQbV6HMsOhE/Unknown-Designer-Exceptions_thumb%5B4%5D.png?imgmax=800&quot; width=&quot;488&quot; height=&quot;181&quot; /&gt;&lt;/a&gt; Maintaining old applications has always been something painful for me. Old application, for me, means Winform applications using DataSets for binding operations. When converting and opening an old application, the least thing you want on your hands is to open a form and see Designer screen of death. This is due to the fact that in the WinForm world when you open a form, all the extra codes in the constructor and Load events will get executed, and this where things can go wrong. Think about a pieced of code in constructor of a form doing something innocent in nature like saving / loading data from registry, connecting to a service. Almost always VS.NET shows a cryptic message. How would you know which code / form / usercontrol is causing this?&lt;br /&gt;&lt;/p&gt;

&lt;span class=&quot;subtitle&quot;&gt;Debugging the Designer&lt;/span&gt;
&lt;p&gt;There are just a few steps to catch the buggy piece of code ruining your day. Open up your visual studio solution containing your application's code and compile. Locate the form that is breaking the designer. Open another instance of VS.NET and Goto &quot;Tools&quot; &amp;gt; &quot;Attach To Process&quot; and locate the process named &quot;Devenv.exe&quot; which is Visual Studio's process name. There are two processes named &quot;Devenv&quot;. Make sure you select the one with loaded solution. To catch all the thrown exceptions go to &quot;Debug&quot; &amp;gt; &quot;Exceptions&quot; and check the column &quot;Thrown&quot; in front of &quot;Common Language Runtime Exceptions&quot;. This will tell the VS.NET to catch all the exception thrown by CLR. At this point you're good to go. Switch to your VS.NET containing the solution and open the Form / Usercontrol. The exception will be caught so you can have a very good idea what the problem is.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://lh3.ggpht.com/_Z5KTIfnfuNs/SZarnCiMxrI/AAAAAAAAAMQ/tPAp_WKnw58/s1600-h/VSDebugger%5B7%5D.png&quot;&gt;&lt;img style=&quot;BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: block; FLOAT: none; MARGIN-LEFT: auto; BORDER-TOP: 0px; MARGIN-RIGHT: auto; BORDER-RIGHT: 0px&quot; title=&quot;VSDebugger&quot; border=&quot;0&quot; alt=&quot;VSDebugger&quot; src=&quot;http://lh4.ggpht.com/_Z5KTIfnfuNs/SZarruWDzSI/AAAAAAAAAMU/3jV-YgDh2Zc/VSDebugger_thumb%5B3%5D.png?imgmax=800&quot; width=&quot;644&quot; height=&quot;430&quot; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It is very easy to avoid this. &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Make sure the codes written in Form and Usercontrol constructors / OnLoaded / Loaded event (except for InitializeComponents in constructors) will not get executed.&lt;/li&gt;
  &lt;li&gt;Use the DesignMode property&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you're extending functionality of a custom control you need to be aware of this problem. The constructors of custom controls will be called in InitializeComponent anyway, so if there's something wrong with the code in there, you'll end up with this problem.&lt;br /&gt;

&lt;br /&gt;There's also an issue with the DesignMode property in UserControls. The design mode only works when the user control is Sited so you may be in design mode and get &quot;False&quot; value when checking DesignMode property. The trick is to use a property on System.ComponentModel.LicenseManager which is more reliable.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">MIX 10K</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/mix-10k"/>
    <id>http://www.hightech.ir/SeeSharp/mix-10k</id>
    <updated>2009-10-19T06:27:08.077</updated>
    <published>2009-02-14T13:06:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="WPF" />
    <content type="html" xml:lang="en">
      &lt;p&gt;There's been a new competition around for WPFers. You need to submit an application created with WPF technology (being a WPF app or Silverlight) which should not exceed 10 KB in size. Tricky, eh? What kind of an app can be 10 K? Check out the &lt;a href=&quot;http://2009.visitmix.com/MIXtify/TenKGallery.aspx&quot;&gt;gallery&lt;/a&gt; to see for yourself. You can vote on your favorite app until 16th of February.&lt;/p&gt;&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6069495622049300789-8183648265405487841?l=heskandari.blogspot.com'/&gt;&lt;/div&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Windsor and Automatic Properties</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/windsor-and-automatic-properties"/>
    <id>http://www.hightech.ir/SeeSharp/windsor-and-automatic-properties</id>
    <updated>2009-10-19T06:32:12.19</updated>
    <published>2009-02-06T20:19:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Windsor" />
    <content type="html" xml:lang="en">
      &lt;p&gt;When maintaining an old application that uses Windsor as IoC container, a strange NullReferenceException throwed when trying to resolve an instance of a specific class. Our project has been recently upgraded to VS 2008 so it was natural to use C# 3.0 specific features. One thing I used in the failing class was Automated Properties. The implementation looked like this :&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
public class GridRepositoryFactory : IGridRepositoryFactory
{
   public GridRepositoryFactory()
   {
   }

   public IDynamicFormDataService Service
   {
       get;
       private set;
   }
}
&lt;/pre&gt;

&lt;p&gt;as the stacktrace showed, Castle Windsor version 1.0.3.4333 does not work correctly with inject automated properties. I had to use properties with backing field to solve this, but updating to a more recent version may also get it fixed.&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Error Messages in Silverlight</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/silverlight"/>
    <id>http://www.hightech.ir/SeeSharp/silverlight</id>
    <updated>2009-10-19T06:37:23.467</updated>
    <published>2009-02-03T15:14:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Silverlight" />
    <category term="XAML" />
    <content type="html" xml:lang="en">
      &lt;p&gt;Can you guess what's wrong with this Xaml code, without running it?&lt;/p&gt;

&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;Application xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
             x:Class=&quot;Test.UI.App&quot;&amp;gt;
    &amp;lt;Application.Resources&amp;gt;

        &amp;lt;Color x:Key=&quot;HeaderRectangleStrokeColor&quot;&gt;#FF777676&amp;lt;/Color&gt;
        &amp;lt;Color x:Key=&quot;AppInvertTitleForegroundColor&quot;&amp;gt;#16FFFFFF&amp;lt;/Color&amp;gt;
        &amp;lt;Color x:Key=&quot;AppTitleForegroundColor&quot;&amp;gt;FFFFF8F8&amp;lt;/Color&amp;gt;
        &amp;lt;Color x:Key=&quot;PageBackground&quot;&amp;gt;#FF000000&amp;lt;/Color&amp;gt;

        &amp;lt;SolidColorBrush x:Key=&quot;HeaderRectangleStrokeBrush&quot; Color=&quot;{StaticResource HeaderRectangleStrokeColor}&quot; /&amp;gt;
        &amp;lt;SolidColorBrush x:Key=&quot;AppInvertTitleForegroundBrush&quot; Color=&quot;{StaticResource AppInvertTitleForegroundColor}&quot; /&amp;gt;
        &amp;lt;SolidColorBrush x:Key=&quot;AppTitleForegroundBrush&quot; Color=&quot;{StaticResource AppTitleForegroundColor}&quot; /&amp;gt;

        &amp;lt;LinearGradientBrush x:Key=&quot;HeaderRectangleBrush&quot; EndPoint=&quot;0.5,1.011&quot; StartPoint=&quot;0.5,-0.011&quot;&amp;gt;
            &amp;lt;GradientStop Color=&quot;#FF343333&quot; Offset=&quot;0&quot;/&amp;gt;
            &amp;lt;GradientStop Color=&quot;#FF3E3E3E&quot; Offset=&quot;1&quot;/&amp;gt;
        &amp;lt;/LinearGradientBrush&amp;gt;
         
    &amp;lt;/Application.Resources&amp;gt;
&amp;lt;/Application&amp;gt;
&lt;/pre&gt;

&lt;p&gt;Application compiles just fine. Even Resharper can not detect a problem in it. But when you running it a hard error happens that fails the Silverlight plug-in! What's worse, is that the error message is cryptic as can be :&lt;br /&gt;&lt;a href=&quot;http://lh5.ggpht.com/_Z5KTIfnfuNs/SYgt_OTEdVI/AAAAAAAAALo/kKBShsXmDiM/s1600-h/Silverlight-TestPage-Error%5B5%5D.png&quot;&gt;&lt;img style=&quot;BORDER-RIGHT-WIDTH: 0px; DISPLAY: inline; BORDER-TOP-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-LEFT-WIDTH: 0px&quot; title=&quot;Silverlight-TestPage-Error&quot; border=&quot;0&quot; alt=&quot;Silverlight-TestPage-Error&quot; src=&quot;http://lh6.ggpht.com/_Z5KTIfnfuNs/SYguCRN4tfI/AAAAAAAAALs/8t9wbwYgKMw/Silverlight-TestPage-Error_thumb%5B3%5D.png?imgmax=800&quot; width=&quot;650&quot; height=&quot;320&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;/p&gt;

&lt;p&gt;My Application resource had more Colors and Brushes than the example here, so it was much harder to find the needle in haystack. Luckily I found out what the problem was. The Color value for one of the resource has missing # mark. Shouldn't there be a more explicit error message?&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Efficient Code</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/efficient-code"/>
    <id>http://www.hightech.ir/SeeSharp/efficient-code</id>
    <updated>2009-10-19T06:43:23.793</updated>
    <published>2009-01-30T12:22:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="CodeAnalysis" />
    <category term="C" />
    <content type="html" xml:lang="en">
      &lt;p&gt;Writing code may look easy to some and hard to others, but some programmers always tend to write messy, smelling, ugly-looking, inefficient code. Here's one :&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
protected override AppointmentForm CreateAppointmentForm(SchedulerControl control, Appointment apt, bool openRecurrenceForm)
{
  //return new CustomAppointmentForm(control, apt, openRecurrenceForm);
  if (Thread.CurrentThread.CurrentUICulture.Name == &quot;fa-IR&quot;)
  {
      if (openRecurrenceForm)
          return new CustomAppointmentForm(control, apt,openRecurrenceForm);
      else
      return new CustomAppointmentForm(control, apt);
  }

  if (openRecurrenceForm)
      return new AppointmentForm(control, apt,openRecurrenceForm);
  else
      return new AppointmentForm(control, apt);
}
&lt;/pre&gt;

&lt;p&gt;What's wrong with it you might say? Other than the logic implemented wrong (for specific culture instead of all RTL cultures), &quot;A lot&quot;, I'd answer.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Commenting out code instead of deleting it will leave a lot of &quot;Ghost&quot; codes in your source. If you have a source-control in place why do you need to keep old code as commented out? it is always available in your source control, isn't it??&lt;/li&gt;
  &lt;li&gt;Embedding culture-specific code in not a good idea. What we want to achieve here can be easily achieved using factory patterns.&lt;/li&gt;
  &lt;li&gt;Control flow is very important for other programmers to understand what you wanted to achieve. Writing nested if / else and multiple returns in a method tend to make this harder.&lt;/li&gt;
  &lt;li&gt;Having braces in C style programmings is more a matter of style, but always be consistent.&lt;/li&gt;
  &lt;li&gt;Efficiently use constructor / method overloads. Know what are the default values for overloaded parameters. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The above code could be refactored into this :&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
protected override AppointmentForm CreateAppointmentForm(SchedulerControl control, Appointment apt, bool openRecurrenceForm)
{
  AppointmentForm form = null;

  if (CultureHelper.IsCultureRightToLeft)
  {
      form = new CustomAppointmentForm(control, apt, openRecurrenceForm);
  }
  else
  {
      form = new AppointmentForm(control, apt, openRecurrenceForm);
  }

  return form;
}
&lt;/pre&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Silverlight + RESTful POX</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/silverlight-restful-pox"/>
    <id>http://www.hightech.ir/SeeSharp/silverlight-restful-pox</id>
    <updated>2009-10-19T06:50:31.17</updated>
    <published>2009-01-28T15:45:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="Silverlight" />
    <category term="WCF" />
    <category term="REST" />
    <content type="html" xml:lang="en">
      &lt;p&gt;I'm working on a small project for a Swedish company. They need their application be available via web, so it's time to put that Silverlight knowledge at work. I decided to use Silverlight for UI technology and have a REST service layer to provide the required data. After all Silverlight and REST services should have no problem. Silverlight experience was great. You have LINQ at your disposal to process the REST results and although the set of available commands in Silverlight is less than WPF, but this makes it is easier to learn and work with at the same time. There was a couple of gatchas along the way, so I'm writing this as a note-to-self.&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;

&lt;span class=&quot;subtitle&quot;&gt;Service Contract vs. Object Model&lt;/span&gt;
&lt;p&gt;The domain model is very simple and consist of a couple of entities, so what REST Services expose as data contracts are more or less the same as what I use in application layer. Silverlight's class library is not the same as a normal class library so I can not reuse the domain model available in my Silverlight library. This will lead to two set of object models. One for the domain model and the other for the service layer as data contracts. This separation or concern is a good idea, but for this small application it is overkill, but there's nothing I can do with it. With the help of LINQ2XML the best choice for exposing the contract model is POX (Plain old XML) so result of our services would be in XML parse by LINQ and converted to our domain model.&lt;/p&gt;&lt;br /&gt;

&lt;span class=&quot;subtitle&quot;&gt;Unit Testing&lt;/span&gt;
&lt;p&gt;Also because of different class library outputs, you can not use unit testing frameworks the way you usually do. This means you can not use xUnit, nUnit, etc. Hopefully there's a test harness to allow both UI and API level testing when developing Silverlight and it works just like MSTest does. Download the binary files &lt;a href=&quot;http://www.microsoft.com/downloads/details.aspx?FamilyId=EA93DD89-3AF2-4ACB-9CF4-BFE01B3F02D4&amp;amp;displaylang=en&quot;&gt;here&lt;/a&gt; and read &lt;a href=&quot;http://www.jeff.wilcox.name/2008/03/silverlight2-unit-testing/&quot;&gt;this&lt;/a&gt; to know how to add templates to your VS.NET to easily create a test application.&lt;/p&gt;&lt;br /&gt;

&lt;span class=&quot;subtitle&quot;&gt;RESTful POX&lt;/span&gt;
&lt;p&gt;To achieve this the service contract is decorated with REST attributes, That is a WebGetAttribute if you're exposing the operation via GET verb or a WebInvokeAttribute if you're exposing it via POST.&lt;br /&gt;&lt;br /&gt;&lt;em&gt;Note : The thing was that exposing &lt;strong&gt;IList&amp;lt;T&amp;gt;&lt;/strong&gt; as a returned result of a service resulted a non functioning service with the following message : &quot;Request Error : The server encountered an error processing the request. See server logs for more details.&quot; It turned out exposing the &lt;strong&gt;List&amp;lt;T&amp;gt;&lt;/strong&gt; worked. The reason behind this is probably the same thing as exposing an object&#226;€™s interface via normal (Soap) WCF service which also doesn't work due to interfaces not being serializable.&lt;br /&gt;&lt;br /&gt;&lt;/em&gt;So here's the service contract :&lt;br /&gt;&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
[ServiceContract]
public interface IDataServices
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = &quot;/Advertisers&quot;)]
    List&amp;lt;Advertiser&amp;gt; GetAdvertisers();
}
&lt;/pre&gt;

&lt;p&gt;and the implementation is self explanatory. What you get is a service exposed at a URL like &lt;a title=&quot;http://localhost:9999/Services/DataServices.svc/Advertisers&quot; href=&quot;http://localhost/Services/DataServices.svc/Advertisers&quot;&gt;http://localhost/Services/DataServices.svc/Advertisers&lt;/a&gt;. In order to get rid of the nasty .svc extension you either need to use IIS URL Rewriting Module which is only available on IIS 7 or use IIS Wildcard Mapping plus a HttpModule to make this happen. Read &lt;a href=&quot;http://www.west-wind.com/weblog/posts/570695.aspx&quot;&gt;here&lt;/a&gt; for complete information.&lt;br /&gt;&lt;br /&gt;&lt;em&gt;Note : The .svc extension does not matter from operational perspective. It is computer applications that connect to these URLs after all, but from purists point of view it does matter.&lt;br /&gt;&lt;br /&gt;&lt;/em&gt;The final part is the configuration which is standard WCF configuration like identifying service and contract, exposing EndPoints, etc. :&lt;br /&gt;&lt;/p&gt;

&lt;pre class=&quot;brush:xml&quot;&gt;
&amp;lt;system.serviceModel&amp;gt;
   &amp;lt;serviceHostingEnvironment aspNetCompatibilityEnabled=&quot;true&quot; /&amp;gt;
   &amp;lt;behaviors&amp;gt;
     &amp;lt;endpointBehaviors&amp;gt;
       &amp;lt;behavior name=&quot;WebBehavior&quot;&amp;gt;
         &amp;lt;webHttp/&amp;gt;
       &amp;lt;/behavior&amp;gt;
     &amp;lt;/endpointBehaviors&amp;gt;
   &amp;lt;/behaviors&amp;gt;

   &amp;lt;services&amp;gt;
     &amp;lt;service name=&quot;Reklam.UI.Web.Services.DataServices&quot;&amp;gt;
       &amp;lt;endpoint behaviorConfiguration=&quot;WebBehavior&quot;
                 binding=&quot;webHttpBinding&quot;
                 contract=&quot;Reklam.UI.Web.Services.IDataServices&quot; /&amp;gt;
     &amp;lt;/service&amp;gt;
   &amp;lt;/services&amp;gt;
&amp;lt;/system.serviceModel&amp;gt;
&lt;/pre&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Using Windows Seven Beta</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/using-windows-seven-beta"/>
    <id>http://www.hightech.ir/SeeSharp/using-windows-seven-beta</id>
    <updated>2009-10-19T13:55:24.867</updated>
    <published>2009-01-28T10:47:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="General" />
    <category term="Win7" />
    <content type="html" xml:lang="en">
      &lt;p&gt;It's been a few weeks since I've installed Windows 7 on my work development box. During the installation everything went fine and all the applications I had on my Windows Vista installed and worked fine under new windows 7, except for Skype for which I had to download and install their version 4.0 Beta. As a Vista user, I found myself immediately familiar with the environment but there are a lot of goodies here and there which made me say &quot;Nice&quot; loud and clear. Performance gain is totally noticeable compared to Vista and memory usage is as low as it can be. Fresh installation of Windows 7 occupies just 700 MB of memory which is obviously way lower than Vista.&lt;/p&gt;  

&lt;p&gt;I had very few problems using it. The disastrous one was two occasional system crashes when I was designing WPF apps in Visual Studio 2008. The design screen of my WPF UI was frozen and with just a mouse click system had a hard crash. The other issue is using Virtual PC. When windows overlap the VPC window, it goes black and I have to move the window a little bit to see the content (I'm using VPC in Windowed mode, not fullscreen). This too is very annoying because Windows are overlapping each other all the time and its giving me a hard time. &lt;/p&gt;

&lt;p&gt;I know this is beta stuff and things may be broken and not working, but I see that guys at Windows 7 team have done a great job.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Update : If you have a Nvidia graphic card, upgrading the driver via Windows Update will solve the VPC going black.&lt;/em&gt;&lt;/p&gt;
    </content>
  </entry>
  <entry>
    <title type="html">Paint API on Vista</title>
    <link rel="alternate" type="text/html" href="http://www.hightech.ir/SeeSharp/paint-api-on-vista"/>
    <id>http://www.hightech.ir/SeeSharp/paint-api-on-vista</id>
    <updated>2009-10-19T06:56:11.197</updated>
    <published>2009-01-08T19:09:00</published>
    <author>
      <name>HEskandari</name>
    </author>
    <category term="GDI" />
    <content type="html" xml:lang="en">
      &lt;p&gt;I was testing bunch of custom controls using Managed paint API on Windows Vista. Basically, managed and unmanaged paint API use native resources of the OS to paint controls, so if you run your controls on Windows XP you'll get XP look and feel and if you run it on Vista, you get new vistaish look and feel, right? All control parts I've tested seems to work, but there is a catch! If you draw a disabled TextBox, it looks strange in Windows Vista, but looks right in XP :&lt;/p&gt;

&lt;pre class=&quot;brush:c-sharp&quot;&gt;
VisualStyleRenderer renderer = new VisualStyleRenderer(VisualStyleElement.Button.PushButton.Disabled);
renderer.DrawBackground(e.Graphics, ClientRectangle);
&lt;/pre&gt;

&lt;p&gt;While this code looks fine in XP, it produces a flat blue textbox on Vista :&lt;br /&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://www.hightech.ir/BlogPics/ManagedPaintAPIonVista_105B6/VistaPaintAPINormal.png&quot;&gt;&lt;img title=&quot;VistaPaintAPI-Normal&quot; style=&quot;border: 0px none ; display: inline;&quot; alt=&quot;VistaPaintAPI-Normal&quot; src=&quot;http://www.hightech.ir/BlogPics/ManagedPaintAPIonVista_105B6/VistaPaintAPINormal_thumb.png&quot; width=&quot;256&quot; border=&quot;0&quot; height=&quot;87&quot; /&gt;&lt;/a&gt; &lt;a href=&quot;http://www.hightech.ir/BlogPics/ManagedPaintAPIonVista_105B6/VistaPaintAPIReadonly.png&quot;&gt;&lt;img title=&quot;VistaPaintAPI-Readonly&quot; style=&quot;border: 0px none ; display: inline;&quot; alt=&quot;VistaPaintAPI-Readonly&quot; src=&quot;http://www.hightech.ir/BlogPics/ManagedPaintAPIonVista_105B6/VistaPaintAPIReadonly_thumb.png&quot; width=&quot;255&quot; border=&quot;0&quot; height=&quot;80&quot; /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;As far as I could tell, this is an issue with textbox only and other controls like buttons, etc render correctly in both OSes.&lt;br /&gt;&lt;/p&gt;

&lt;p&gt;I wonder why?! From end-user's perspective this does not look like disabled piece of UI and even worse it doesn't look like a native disabled texbox on Vista. I still don't know about any workarounds and I doubt it if native calls to UxTheme API would solve this.&lt;/p&gt;
    </content>
  </entry>
</feed>
