<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Rajeesh&#039;s Blog &#187; .NET</title>
	<atom:link href="http://www.rajeeshcv.com/category/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.rajeeshcv.com</link>
	<description>Sharing my knowledge</description>
	<lastBuildDate>Sun, 18 Jul 2010 06:09:25 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Asp.Net MVC &#8211; Fluent Html helper for FlexiGrid</title>
		<link>http://www.rajeeshcv.com/2010/04/asp-net-mvc-fluent-html-helper-for-flexigrid/</link>
		<comments>http://www.rajeeshcv.com/2010/04/asp-net-mvc-fluent-html-helper-for-flexigrid/#comments</comments>
		<pubDate>Sun, 18 Apr 2010 10:31:00 +0000</pubDate>
		<dc:creator>Rajeesh</dc:creator>
				<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://www.rajeeshcv.com/2010/04/asp-net-mvc-fluent-html-helper-for-flexigrid/</guid>
		<description><![CDATA[There are so many free JQuery Grid plugins out there, in that I liked FlexiGrid just because of it’s look and style. In order to use it in your MVC application you may have to put the Javascript code into your view, which requires the property names of your model in order to generates the [...]]]></description>
			<content:encoded><![CDATA[<p>There are so many free JQuery Grid plugins out there, in that I liked <a title="FlexiGrid" href="http://flexigrid.info/" target="_blank">FlexiGrid</a> just because of it’s look and style. In order to use it in your MVC application you may have to put the Javascript code into your view, which requires the property names of your model in order to generates the Grid columns as well the search options etc… as everybody knows when you deal with hard coded string as the property names in any code, it is error prone. </p>
<p>In order to avoid this problem I thought of creating a html extension which is tightly coupled with your data that is going to bound to the Grid. Which helps the developer from writing any javascript codes(I know those who hates(not me! <img src='http://www.rajeeshcv.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) writing Javascript code like this extension).</p>
<p>This project has been uploaded to &#8211; <a href="http://code.google.com/p/mvc-fluent-jquery-plugin-controls/">http://code.google.com/p/mvc-fluent-jquery-plugin-controls/</a>. You could find more details from there.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rajeeshcv.com/2010/04/asp-net-mvc-fluent-html-helper-for-flexigrid/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JQueryUI Datepicker in ASP.Net MVC</title>
		<link>http://www.rajeeshcv.com/2010/02/jqueryui-datepicker-in-asp-net-mvc/</link>
		<comments>http://www.rajeeshcv.com/2010/02/jqueryui-datepicker-in-asp-net-mvc/#comments</comments>
		<pubDate>Mon, 01 Mar 2010 02:39:00 +0000</pubDate>
		<dc:creator>Rajeesh</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Datepicker]]></category>
		<category><![CDATA[JQueryUI]]></category>

		<guid isPermaLink="false">http://www.rajeeshcv.com/2010/02/jqueryui-datepicker-in-asp-net-mvc/</guid>
		<description><![CDATA[Technocrati code : M2U2PWSNTKW3 
Datepicker is nice and cool plugin for displaying the calendar with ease. It is very easy to use JQuery plugin, it comes as part of JQueryUI library, so if you want to use this – first download JQueryUI from http://jqueryui.com/download and also download JQuery(http://docs.jquery.com/Downloading_jQuery) if you haven’t done yet.
&#160;
For e.g. if [...]]]></description>
			<content:encoded><![CDATA[<p>Technocrati code : M2U2PWSNTKW3 </p>
<p>Datepicker is nice and cool plugin for displaying the calendar with ease. It is very easy to use JQuery plugin, it comes as part of JQueryUI library, so if you want to use this – first download JQueryUI from <a href="http://jqueryui.com/download">http://jqueryui.com/download</a> and also download JQuery(<a title="http://docs.jquery.com/Downloading_jQuery" href="http://docs.jquery.com/Downloading_jQuery">http://docs.jquery.com/Downloading_jQuery</a>) if you haven’t done yet.</p>
<p><a href="http://www.rajeeshcv.com/wp-content/uploads/2010/02/image.png" rel="lightbox"><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="230" alt="image" src="http://www.rajeeshcv.com/wp-content/uploads/2010/02/image_thumb.png" width="270" border="0" /></a>&#160;</p>
<p>For e.g. if you have a form like one below</p>
<pre class="brush: xml;">&lt;% using(Html.BeginForm()){%&gt;
  &lt;fieldset&gt;
    &lt;legend&gt;Event Information&lt;/legend&gt;
     &lt;p&gt;
        &lt;label for=&quot;EventName&quot;&gt;Event Name:&lt;/label&gt;
        &lt;%= Html.TextBox(&quot;EventName&quot;)%&gt;
            &lt;/p&gt;
            &lt;p&gt;
            &lt;label for=&quot;StartDate&quot;&gt;Start Date:&lt;/label&gt;
            &lt;%= Html.TextBox(&quot;StartDate&quot;)%&gt;
            &lt;/p&gt;
            &lt;p&gt;
            &lt;label for=&quot;EndDate&quot;&gt;End Date:&lt;/label&gt;
            &lt;%= Html.TextBox(&quot;EndDate&quot;)%&gt;
            &lt;/p&gt;
            &lt;p&gt;
                &lt;input type=&quot;submit&quot; value=&quot;Save&quot; /&gt;
            &lt;/p&gt;
  &lt;/fieldset&gt;
&lt;% }%&gt;</pre>
<p>and you want to attach datepicker to “StartDate” and “EndDate” input fields,</p>
</p>
<p><span id="more-162"></span></p>
<p>what you needs to do is call the datepicker function on the these input field selector like below.</p>
<pre class="brush: js;">&lt;script language=&quot;javascript&quot;&gt;
    $(document).ready(function() {
    $('#StartDate').datepicker();
    $('#EndDate').datepicker();
    });
&lt;/script&gt;</pre>
<p>This works fine as we expected <img src='http://www.rajeeshcv.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong><u>Difference in Date format patterns</u></strong></p>
<p>Consider a scenario where your MVC application supports localization, then the selected date displayed in the input fields also should display the in the same date format of the current culture(This format could be custom one or default one). This leads to you another issue – Datepicker plugin given by the JQueryUI supports different date formats, but it is different from one that is available in .NET. For e.g. in order to display a long day name (“Thursday”) .NET uses “<strong>dddd</strong>” its equivalent in Datepicker is “<strong>DD”</strong>.</p>
<p>In order to solve this disparity between the .NET world and Datepicker world, I have created a html helper function, which could generate the Datepicker format from a .Net date format.</p>
<pre class="brush: csharp;">/// &lt;summary&gt;
/// JQuery UI DatePicker helper.
/// &lt;/summary&gt;
public static class JQueryUIDatePickerHelper
{
    /// &lt;summary&gt;
    /// Converts the .net supported date format current culture format into JQuery Datepicker format.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;html&quot;&gt;HtmlHelper object.&lt;/param&gt;
    /// &lt;returns&gt;Format string that supported in JQuery Datepicker.&lt;/returns&gt;
    public static string ConvertDateFormat(this HtmlHelper html)
    {
        return ConvertDateFormat(html, Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern);
    }

    /// &lt;summary&gt;
    /// Converts the .net supported date format current culture format into JQuery Datepicker format.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;html&quot;&gt;HtmlHelper object.&lt;/param&gt;
    /// &lt;param name=&quot;format&quot;&gt;Date format supported by .NET.&lt;/param&gt;
    /// &lt;returns&gt;Format string that supported in JQuery Datepicker.&lt;/returns&gt;
    public static string ConvertDateFormat(this HtmlHelper html, string format)
    {
        /*
         *  Date used in this comment : 5th - Nov - 2009 (Thursday)
         *
         *  .NET    JQueryUI        Output      Comment
         *  --------------------------------------------------------------
         *  d       d               5           day of month(No leading zero)
         *  dd      dd              05          day of month(two digit)
         *  ddd     D               Thu         day short name
         *  dddd    DD              Thursday    day long name
         *  M       m               11          month of year(No leading zero)
         *  MM      mm              11          month of year(two digit)
         *  MMM     M               Nov         month name short
         *  MMMM    MM              November    month name long.
         *  yy      y               09          Year(two digit)
         *  yyyy    yy              2009        Year(four digit)             *
         */

        string currentFormat = format;

        // Convert the date
        currentFormat = currentFormat.Replace(&quot;dddd&quot;, &quot;DD&quot;);
        currentFormat = currentFormat.Replace(&quot;ddd&quot;, &quot;D&quot;);

        // Convert month
        if (currentFormat.Contains(&quot;MMMM&quot;))
        {
            currentFormat = currentFormat.Replace(&quot;MMMM&quot;, &quot;MM&quot;);
        }
        else if (currentFormat.Contains(&quot;MMM&quot;))
        {
            currentFormat = currentFormat.Replace(&quot;MMM&quot;, &quot;M&quot;);
        }
        else if (currentFormat.Contains(&quot;MM&quot;))
        {
            currentFormat = currentFormat.Replace(&quot;MM&quot;, &quot;mm&quot;);
        }
        else
        {
            currentFormat = currentFormat.Replace(&quot;M&quot;, &quot;m&quot;);
        }

        // Convert year
        currentFormat = currentFormat.Contains(&quot;yyyy&quot;) ? currentFormat.Replace(&quot;yyyy&quot;, &quot;yy&quot;) : currentFormat.Replace(&quot;yy&quot;, &quot;y&quot;);

        return currentFormat;
    }
}</pre>
<p>So how we could make use this helper method, just replace the datepicker initialization code we have written earlier with this</p>
<pre class="brush: xml;">&lt;script language=&quot;javascript&quot;&gt;
    $(document).ready(function() {
    $('#StartDate').datepicker({ dateFormat: '&lt;%= Html.ConvertDateFormat() %&gt;' });
    $('#EndDate').datepicker({ dateFormat: '&lt;%= Html.ConvertDateFormat() %&gt;' });
    });
&lt;/script&gt;</pre>
<p>Hope this helps.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rajeeshcv.com/2010/02/jqueryui-datepicker-in-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Logging execution time using AOP</title>
		<link>http://www.rajeeshcv.com/2010/02/logging-execution-time-using-aop/</link>
		<comments>http://www.rajeeshcv.com/2010/02/logging-execution-time-using-aop/#comments</comments>
		<pubDate>Sat, 27 Feb 2010 18:27:00 +0000</pubDate>
		<dc:creator>Rajeesh</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[PostSharp]]></category>
		<category><![CDATA[Profiling]]></category>

		<guid isPermaLink="false">http://www.rajeeshcv.com/?p=155</guid>
		<description><![CDATA[Download the source code for this tutorial from&#160; &#8211; http://www.rajeeshcv.com/download/ProfilingSample.zip
What happens if your client complains that your application is running very slow!!! or in your load/stress testing you found that some functionalities are very slow in executing than expected. This is the time where you go for profiling the execution, to analyse the root cause [...]]]></description>
			<content:encoded><![CDATA[<p><em>Download the source code for this tutorial from&#160; &#8211; </em><a title="http://www.rajeeshcv.com/download/ProfilingSample.zip" href="http://www.rajeeshcv.com/download/ProfilingSample.zip"><em>http://www.rajeeshcv.com/download/ProfilingSample.zip</em></a></p>
<p>What happens if your client complains that your application is running very slow!!! or in your load/stress testing you found that some functionalities are very slow in executing than expected. This is the time where you go for profiling the execution, to analyse the root cause of these issues.</p>
<p>So how we could develop a profiler, where we don’t have to wrap our normal code in a profiling code.</p>
<p>Before going to create the profiler, we have to decide where to put the profiled information. In this tutorial, I am making use of <a href="http://logging.apache.org/log4net/" target="_blank">Log4Net</a> as underlying layer to store this information. If you have not used <a href="http://logging.apache.org/log4net/" target="_blank">Log4Net</a> before, I suggest you to read <a href="http://www.beefycode.com/post/Log4Net-Tutorial-pt-1-Getting-Started.aspx">http://www.beefycode.com/post/Log4Net-Tutorial-pt-1-Getting-Started.aspx</a> as a starting point.</p>
<p>With the help of AOP (Aspect-Oriented Programming) we could do the profiling task without interrupting the actual code.</p>
<blockquote><p>AOP is a programming paradigm in which secondary or supporting functions are isolated from the main program&#8217;s business logic </p>
<p>Source : Wikipedia</p>
</blockquote>
<p>So in order bring the AOP functionality into this application, I am going to use a third party library <a href="http://www.sharpcrafters.com/" target="_blank">PostSharp</a>&#160; which I believe this is one of the best that is available in the market. Please download it from <a title="http://www.sharpcrafters.com/postsharp/download" href="http://www.sharpcrafters.com/postsharp/download">http://www.sharpcrafters.com/postsharp/download</a>.</p>
<p>So, now we have got the basic things to start with and now let’s start coding….</p>
<p>Start a new solution in visual studio and add a new console application project to it. Then add the below references to the newly created project</p>
<ol>
<li>Add reference to the Log4Net.dll </li>
<li>Add reference to PostSharp.Laos.dll and PostSharp.Public.dll (Please read <a href="http://www.sharpcrafters.com/postsharp/documentation/getting-started">http://www.sharpcrafters.com/postsharp/documentation/getting-started</a> to get the basic installation procedure) </li>
</ol>
<p>Next, create a new attribute class called “ProfileMethodAttribute” – this class is responsible for doing the profiling work. Make sure that you have decorated this class with “Serializable” attribute</p>
<p> <span id="more-155"></span>
</p>
<pre class="brush: csharp;">[Serializable]
public class ProfileMethodAttribute : OnMethodBoundaryAspect
{

    public override void OnEntry(MethodExecutionEventArgs eventArgs)
    {
        ........
    }

    public override void OnExit(MethodExecutionEventArgs eventArgs)
    {
       ......
    }
}</pre>
<p>This class actually derives from “OnMethodBoundaryAspect”,&#160; it has got two methods “OnEntry” and “OnExit” which we needed. These method will be called before the start of a method execution and at the end of method execution respectively, when this attribute is decorated against a method.</p>
<p>When a call comes to “OnEntry” method, we will first log the execution call using the LoggerHelper, then start a clock using another helper class “Profiler”</p>
<pre class="brush: csharp;">public class LoggerHelper
{
    /// &lt;summary&gt;
    /// Static instance of ILogger.
    /// &lt;/summary&gt;
    private static ILog logger;

    /// &lt;summary&gt;
    /// Initializes static members of the &lt;see cref=&quot;LoggerHelper&quot;/&gt; class.
    /// &lt;/summary&gt;
    static LoggerHelper()
    {
        log4net.Config.XmlConfigurator.Configure();
        logger = LogManager.GetLogger(typeof(Program));
    }

    /// &lt;summary&gt;
    /// Logs the specified message.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;message&quot;&gt;The message.&lt;/param&gt;
    public static void Log(string message)
    {
        string enableProfiling = ConfigurationManager.AppSettings[&quot;EnableProfiling&quot;];
        if (string.IsNullOrEmpty(enableProfiling) || enableProfiling.ToLowerInvariant() == &quot;true&quot;)
        {
            logger.Debug(message);
        }
    }

    /// &lt;summary&gt;
    /// Logs the specified method name.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;methodName&quot;&gt;Name of the method.&lt;/param&gt;
    /// &lt;param name=&quot;url&quot;&gt;The URL to log.&lt;/param&gt;
    /// &lt;param name=&quot;executionFlowMessage&quot;&gt;The execution flow message.&lt;/param&gt;
    /// &lt;param name=&quot;actualMessage&quot;&gt;The actual message.&lt;/param&gt;
    public static void Log(string methodName, string url, string executionFlowMessage, string actualMessage)
    {
        Log(ConstructLog(methodName, url, executionFlowMessage, actualMessage));
    }

    /// &lt;summary&gt;
    /// Logs the specified method name.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;methodName&quot;&gt;Name of the method.&lt;/param&gt;
    /// &lt;param name=&quot;url&quot;&gt;The URL to log.&lt;/param&gt;
    /// &lt;param name=&quot;executionFlowMessage&quot;&gt;The execution flow message.&lt;/param&gt;
    /// &lt;param name=&quot;actualMessage&quot;&gt;The actual message.&lt;/param&gt;
    /// &lt;param name=&quot;executionTime&quot;&gt;The execution time.&lt;/param&gt;
    public static void Log(string methodName, string url, string executionFlowMessage, string actualMessage, int executionTime)
    {
        Log(ConstructLog(methodName, url, executionFlowMessage, actualMessage, executionTime));
    }

    /// &lt;summary&gt;
    /// Constructs the log.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;methodName&quot;&gt;Name of the method.&lt;/param&gt;
    /// &lt;param name=&quot;url&quot;&gt;The URL to be logged.&lt;/param&gt;
    /// &lt;param name=&quot;executionFlowMessage&quot;&gt;The execution flow message.&lt;/param&gt;
    /// &lt;param name=&quot;actualMessage&quot;&gt;The actual message.&lt;/param&gt;
    /// &lt;returns&gt;Formatted string.&lt;/returns&gt;
    private static string ConstructLog(string methodName, string url, string executionFlowMessage, string actualMessage)
    {
        var sb = new StringBuilder();

        if (!string.IsNullOrEmpty(methodName))
        {
            sb.AppendFormat(&quot;MethodName : {0}, &quot;, methodName);
        }

        if (!string.IsNullOrEmpty(url))
        {
            sb.AppendFormat(&quot;Url : {0}, &quot;, url);
        }

        if (!string.IsNullOrEmpty(executionFlowMessage))
        {
            sb.AppendFormat(&quot;ExecutionFlowMessage : {0}, &quot;, executionFlowMessage);
        }

        if (!string.IsNullOrEmpty(actualMessage))
        {
            sb.AppendFormat(&quot;ActualMessage : {0}, &quot;, actualMessage);
        }

        string message = sb.ToString();

        message = message.Remove(message.Length - 2);

        return message;
    }

    /// &lt;summary&gt;
    /// Constructs the log.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;methodName&quot;&gt;Name of the method.&lt;/param&gt;
    /// &lt;param name=&quot;url&quot;&gt;The URL to be logged.&lt;/param&gt;
    /// &lt;param name=&quot;executionFlowMessage&quot;&gt;The execution flow message.&lt;/param&gt;
    /// &lt;param name=&quot;actualMessage&quot;&gt;The actual message.&lt;/param&gt;
    /// &lt;param name=&quot;executionTime&quot;&gt;The execution time.&lt;/param&gt;
    /// &lt;returns&gt;Formatted string.&lt;/returns&gt;
    private static string ConstructLog(string methodName, string url, string executionFlowMessage, string actualMessage, int executionTime)
    {
        var sb = new StringBuilder();

        sb.Append(ConstructLog(methodName, url, executionFlowMessage, actualMessage));
        sb.AppendFormat(&quot;, ExecutionTime : {0}&quot;, executionTime);

        return sb.ToString();
    }
}</pre>
<p>LoggerHelper is a just uses the Log4Net objects to log the message to configured location.</p>
<p>The “Profiler” class</p>
<pre class="brush: csharp;">/// &lt;summary&gt;
/// Helper class that wraps the timer based functionalities.
/// &lt;/summary&gt;
internal static class Profiler
{
    /// &lt;summary&gt;
    /// Lock object.
    /// &lt;/summary&gt;
    private static readonly object SyncLock = new object();

    /// &lt;summary&gt;
    /// Variable that tracks the time.
    /// &lt;/summary&gt;
    private static readonly Dictionary&lt;int, Stack&lt;long&gt;&gt; ProfilePool;

    /// &lt;summary&gt;
    /// Initializes static members of the &lt;see cref=&quot;Profiler&quot;/&gt; class.
    /// &lt;/summary&gt;
    static Profiler()
    {
        ProfilePool = new Dictionary&lt;int, Stack&lt;long&gt;&gt;();
    }

    /// &lt;summary&gt;
    /// Starts this timer.
    /// &lt;/summary&gt;
    public static void Start()
    {
        lock (SyncLock)
        {
            int currentThreadId = Thread.CurrentThread.ManagedThreadId;
            if (ProfilePool.ContainsKey(currentThreadId))
            {
                ProfilePool[currentThreadId].Push( Environment.TickCount );
            }
            else
            {
                var timerStack = new Stack&lt;long&gt;();
                timerStack.Push(DateTime.UtcNow.Ticks);
                ProfilePool.Add(currentThreadId, timerStack);
            }
        }
    }

    /// &lt;summary&gt;
    /// Stops timer and calculate the execution time.
    /// &lt;/summary&gt;
    /// &lt;returns&gt;Execution time in milli seconds&lt;/returns&gt;
    public static int Stop()
    {
        lock (SyncLock)
        {
            long currentTicks = DateTime.UtcNow.Ticks;
            int currentThreadId = Thread.CurrentThread.ManagedThreadId;

            if (ProfilePool.ContainsKey(currentThreadId))
            {
                long ticks = ProfilePool[currentThreadId].Pop();
                if (ProfilePool[currentThreadId].Count == 0)
                {
                    ProfilePool.Remove(currentThreadId);
                }

                var timeSpan = new TimeSpan(currentTicks - ticks);

                return (int)timeSpan.TotalMilliseconds;
            }
        }

        return 0;
    }
}</pre>
<p>which stores the starting tick and calculate the time taken to execute when “Stop” is called.</p>
<p>Below is code snippet from “OnEntry” method</p>
<pre class="brush: csharp;">public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
    this._methodName = this.ExcludeMethodName ? string.Empty : eventArgs.Method.Name;
    this._url = this.IncludeUrl ? string.Empty : (HttpContext.Current == null) ? string.Empty : HttpContext.Current.Request.Url.ToString();

    LoggerHelper.Log(this._methodName, this._url, this.EntryMessage, this.Message);
    Profiler.Start();
}</pre>
<p>And OnExist, is almost similar expect there we will stop the profile timer.</p>
<pre class="brush: csharp;">public override void OnExit(MethodExecutionEventArgs eventArgs)
{
    int count = Profiler.Stop();
    LoggerHelper.Log(this._methodName, this._url, this.EntryMessage, this.Message, count);
}</pre>
<p>I haven’t explained each line of the code,&#160; so please find the attached sample(<a title="http://www.rajeeshcv.com/download/ProfilingSample.zip" href="http://www.rajeeshcv.com/download/ProfilingSample.zip">http://www.rajeeshcv.com/download/ProfilingSample.zip</a>) for all of these source codes.</p>
<p>Next step is to use this and see whether it is logged properly.</p>
<p>In order enable profiling for a method, you just needs to decorate it with the “ProfileMethod” attribute. Like below</p>
<pre class="brush: csharp;">[ProfileMethod()]
public void SimpleMethod()
{
    Thread.Sleep(5000);
}</pre>
<p>Then if you run the application and somebody calls this above method, a log entry will be created where you have configured.</p>
<p>The out of that log file will be something like below</p>
<p>PROFILING 2010-02-26 00:19:59,838 [1] Log MethodName : SimpleMethod<br />
  <br />PROFILING 2010-02-26 00:20:04,865 [1] Log MethodName : SimpleMethod, ExecutionTime : 5002</p>
<p>Please least me know, if this helped you.</p>
<p><em>Download the source code for this tutorial from&#160; &#8211; </em><a title="http://www.rajeeshcv.com/download/ProfilingSample.zip" href="http://www.rajeeshcv.com/download/ProfilingSample.zip"><em>http://www.rajeeshcv.com/download/ProfilingSample.zip</em></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rajeeshcv.com/2010/02/logging-execution-time-using-aop/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC &#8211; Conditional rendering Partial Views with Action&lt;T&gt; delegate</title>
		<link>http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering-partial-views-with-actiont-delegate/</link>
		<comments>http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering-partial-views-with-actiont-delegate/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 02:23:40 +0000</pubDate>
		<dc:creator>Rajeesh</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[HTML Extension]]></category>

		<guid isPermaLink="false">http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering-partial-views-with-actiont-delegate/</guid>
		<description><![CDATA[This is an update to my previous post regarding conditional rendering partial views, in that I used the internal implementation of the Html.RenderPartail(…) method to create the Html extension. Later I found a simple way to achieve the same using Action&#60;T&#62; delegate
&#60;p&#62;Partial rendering with Action Methods&#60;/p&#62;
&#60;% Html.PartialIf(this.Model.Exists, html =&#62; html.RenderPartial(&#34;MyPartialView&#34;)); %&#62;
If you look at the [...]]]></description>
			<content:encoded><![CDATA[<p>This is an update to my previous <a href="http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering-partial-views/" target="_blank">post</a> regarding conditional rendering partial views, in that I used the internal implementation of the Html.RenderPartail(…) method to create the Html extension. Later I found a simple way to achieve the same using Action&lt;T&gt; delegate</p>
<pre class="brush: xml;">&lt;p&gt;Partial rendering with Action Methods&lt;/p&gt;
&lt;% Html.PartialIf(this.Model.Exists, html =&gt; html.RenderPartial(&quot;MyPartialView&quot;)); %&gt;</pre>
<p>If you look at the “PartialIf” implementation, it is simple, cleaner than the previous technique I have mentioned in my <a href="http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering-partial-views/" target="_blank">post</a>.</p>
<pre class="brush: csharp;">public static void PartialIf(this HtmlHelper htmlHelper, bool condition, Action&lt;HtmlHelper&gt; action)
{
    if (condition)
    {
        action.Invoke(htmlHelper);
    }
}</pre>
<p>That’s it <img src='http://www.rajeeshcv.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering-partial-views-with-actiont-delegate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC &#8211; Conditional rendering Partial Views</title>
		<link>http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering-partial-views/</link>
		<comments>http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering-partial-views/#comments</comments>
		<pubDate>Fri, 22 Jan 2010 01:43:42 +0000</pubDate>
		<dc:creator>Rajeesh</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering-partial-views/</guid>
		<description><![CDATA[

Update : Later I found a cleaner and simple approach to do the same – read this post ASP.Net MVC – Conditional rendering Partial Views with Action&#60;T&#62; delegate

Following my previous post about Conditional Rendering, one of my colleague asked me how to render the partial view based on a condition. 
Normal way of doing this [...]]]></description>
			<content:encoded><![CDATA[<p><br />
<blockquote>
<p>Update : Later I found a cleaner and simple approach to do the same – read this post <a href="http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering-partial-views-with-actiont-delegate/" target="_blank">ASP.Net MVC – Conditional rendering Partial Views with Action&lt;T&gt; delegate</a></p>
</blockquote>
<p>Following my previous post about <a href="http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering/" target="_blank">Conditional Rendering</a>, one of my colleague asked me how to render the partial view based on a condition. </p>
<p>Normal way of doing this is </p>
<pre class="brush: xml;">&lt;p&gt;Normal partial rendering based on condition&lt;/p&gt;
&lt;% if(this.Model.Exists)
 {
     Html.RenderPartial(&quot;MyPartialView&quot;);
 } %&gt;</pre>
<p>I am not sure about any other technique for rendering partial view conditionally other than this (correct me if I am wrong <img src='http://www.rajeeshcv.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ).</p>
<p>Then I thought about copying the pattern I have used in my <a href="http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering/" target="_blank">previous post</a> and came up with this code which could conditionally render partial views and you could use the Html extension like below, which more clean than the previous</p>
<pre class="brush: xml;">&lt;% Html.PartialIf(this.Model.Exists, &quot;MyPartialView&quot;); %&gt;</pre>
</p>
<p><span id="more-135"></span></p>
<p>Below is the Html extension I have created</p>
<pre class="brush: csharp;">public static void PartialIf(this HtmlHelper htmlHelper, bool condition, string viewName)
       {
           if (condition)
           {
               RenderPartialInternal(
                   htmlHelper.ViewContext,
                   htmlHelper.ViewDataContainer,
                   viewName,
                   htmlHelper.ViewData,
                   null,
                   ViewEngines.Engines);
           }
       }

public static void PartialIf(this HtmlHelper htmlHelper, bool condition, string viewName, ViewDataDictionary viewData)
       {
           if (condition)
           {
               RenderPartialInternal(
                   htmlHelper.ViewContext,
                   htmlHelper.ViewDataContainer,
                   viewName,
                   viewData,
                   null,
                   ViewEngines.Engines);
           }
       }

public static void PartialIf(this HtmlHelper htmlHelper, bool condition, string viewName, object model)
       {
           if (condition)
           {
               RenderPartialInternal(
                   htmlHelper.ViewContext,
                   htmlHelper.ViewDataContainer,
                   viewName,
                   htmlHelper.ViewData,
                   model,
                   ViewEngines.Engines);
           }
       }

public static void PartialIf(this HtmlHelper htmlHelper, bool condition, string viewName, object model, ViewDataDictionary viewData)
       {
           if (condition)
           {
               RenderPartialInternal(
                   htmlHelper.ViewContext,
                   htmlHelper.ViewDataContainer,
                   viewName,
                   viewData,
                   model,
                   ViewEngines.Engines);
           }
       }</pre>
<p>And here is the helper method I have used in the about extension ( most of the code snippet is taken from the MVC method Html.Renderpartial(…), thanks to open source )</p>
<pre class="brush: csharp;">internal static IView FindPartialView(ViewContext viewContext, string partialViewName, ViewEngineCollection viewEngineCollection)
{
    var result = viewEngineCollection.FindPartialView(viewContext, partialViewName);
    if (result != null)
    {
        if (result.View != null)
        {
            return result.View;
        }
    }

    throw new InvalidOperationException(&quot;Partial view not found&quot;);
}

internal static void RenderPartialInternal(ViewContext viewContext, IViewDataContainer viewDataContainer, string partialViewName, ViewDataDictionary viewData, object model, ViewEngineCollection viewEngineCollection)
{
    if (String.IsNullOrEmpty(partialViewName))
    {
        throw new ArgumentException(&quot;PartialViewName can't be empty or null.&quot;);
    }

    ViewDataDictionary newViewData = null;

    if (model == null)
    {
        newViewData = viewData == null ? new ViewDataDictionary(viewDataContainer.ViewData) : new ViewDataDictionary(viewData);
    }
    else
    {
        newViewData = viewData == null ? new ViewDataDictionary(model) : new ViewDataDictionary(viewData) { Model = model };
    }

    var newViewContext = new ViewContext(viewContext, viewContext.View, newViewData, viewContext.TempData);
    var view = FindPartialView(newViewContext, partialViewName, viewEngineCollection);
    view.Render(newViewContext, viewContext.HttpContext.Response.Output);
}</pre>
<p>&#160;</p>
<p>Hope this helps</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering-partial-views/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC &#8211; Conditional Rendering</title>
		<link>http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering/</link>
		<comments>http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 06:47:23 +0000</pubDate>
		<dc:creator>Rajeesh</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://www.rajeeshcv.com/?p=119</guid>
		<description><![CDATA[
We come across situations like rendering elements based on the conditions in Model. For example, in the view if we want to show a TextBox if some property is true. A normal way of doing this is like below
&#60;% if (this.Model.Exists)
      {%&#62;
      &#60;%= Html.TextBox(&#34;Test&#34;) %&#62;
 [...]]]></description>
			<content:encoded><![CDATA[<p>
<p>We come across situations like rendering elements based on the conditions in Model. For example, in the view if we want to show a TextBox if some property is true. A normal way of doing this is like below</p>
<pre class="brush: xml;">&lt;% if (this.Model.Exists)
      {%&gt;
      &lt;%= Html.TextBox(&quot;Test&quot;) %&gt;
   &lt;% } </pre>
<p>This looks like old classic asp style, and when it comes to code maintenance this will be a pain. So a clean way is to use an Html helper to generate this</p>
<pre class="brush: xml;">  &lt;%= Html.If(this.Model.Exists, action =&gt; action.TextBox(&quot;Name&quot;)) %&gt;</pre>
<p>which looks cleaner than the old one. Source code for this helper method is </p>
<pre class="brush: csharp;">public static string If(this HtmlHelper htmlHelper, bool condition, Func&lt;HtmlHelper, string&gt; action)
{
    if (condition)
    {
        return action.Invoke(htmlHelper);
    }

    return string.Empty;
}</pre>
<p>What about IfElse condition, we could write another helper method for that</p>
<p><span id="more-119"></span></p>
<pre class="brush: csharp;">public static string IfElse(this HtmlHelper htmlHelper, bool condition, Func&lt;HtmlHelper, string&gt; trueAction, Func&lt;HtmlHelper, string&gt; falseAction)
{
    if (condition)
    {
        return trueAction.Invoke(htmlHelper);
    }

    return falseAction.Invoke(htmlHelper);
}</pre>
<p>Ok, now we got a conditionally rendered element, sometimes we may have to put a wrapper around this element. So I have written another Html helper method which will help you to put any html element around a particular element.</p>
<pre class="brush: csharp;">public static string HtmlTag(this HtmlHelper htmlHelper, HtmlTextWriterTag tag, object htmlAttributes, Func&lt;HtmlHelper, string&gt; action)
{
    var attributes = new RouteValueDictionary(htmlAttributes);

    using (var sw = new StringWriter())
    {
        using (var htmlWriter = new HtmlTextWriter(sw))
        {
            // Add attributes
            foreach (var attribute in attributes)
            {
                htmlWriter.AddAttribute(attribute.Key, attribute.Value != null ? attribute.Value.ToString() : string.Empty);
            }

            htmlWriter.RenderBeginTag(tag);
            htmlWriter.Write(action.Invoke(htmlHelper));
            htmlWriter.RenderEndTag();
        }

        return sw.ToString();
    }

    return string.Empty;
}</pre>
<p>An overloaded version which doesn’t accept HtmlAttributes as parameter</p>
<pre class="brush: csharp;">public static string HtmlTag(this HtmlHelper htmlHelper, HtmlTextWriterTag tag, Func&lt;HtmlHelper, string&gt; action)
{
    return HtmlTag(htmlHelper, tag, null, action);
}</pre>
<p>Below are some examples of using these helpers.</p>
<pre class="brush: csharp;">&lt;%= Html.HtmlTag(HtmlTextWriterTag.Div, action =&gt; action.ActionLink(&quot;Without attributes&quot;,&quot;About&quot;) ) %&gt;

&lt;%= Html.HtmlTag(HtmlTextWriterTag.Div, new { name = &quot;wrapper&quot;, @class = &quot;styleclass&quot; }, action =&gt; action.ActionLink(&quot;With Attributes&quot;, &quot;About&quot;)) %&gt;

&lt;%= Html.HtmlTag(HtmlTextWriterTag.Div, null, action =&gt; action.ActionLink(&quot;Null attributes&quot;, &quot;About&quot;)) %&gt;

&lt;%= Html.IfElse(this.Model.Exists, trueAction =&gt; trueAction.Encode(&quot;Sample&quot;), falseAction =&gt; falseAction.TextBox(&quot;SampleName&quot;)) %&gt;

&lt;%--
Nesting
&lt;div&gt;
   &lt;span&gt;
       &lt;a href=&quot;/Home/About&quot;&gt;About&lt;/a&gt;
   &lt;/span&gt;
&lt;/div&gt;
--%&gt;
&lt;%= Html.If(this.Model.Exists,
    div =&gt; div.HtmlTag(HtmlTextWriterTag.Div,
        span =&gt; span.HtmlTag(HtmlTextWriterTag.Span,
anchor =&gt; anchor.ActionLink(&quot;About&quot;, &quot;About&quot;))
)) %&gt;</pre>
<p>Hope this will help you.</p>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rajeeshcv.com/2010/01/asp-net-mvc-conditional-rendering/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FluentConfigurationException: An invalid or incomplete configuration was used while creating Session Factory. Check Pot</title>
		<link>http://www.rajeeshcv.com/2010/01/fluentconfigurationexception-an-invalid-or-incomplete-configuration-was-used-while-creating-session-factory-check-pot/</link>
		<comments>http://www.rajeeshcv.com/2010/01/fluentconfigurationexception-an-invalid-or-incomplete-configuration-was-used-while-creating-session-factory-check-pot/#comments</comments>
		<pubDate>Fri, 01 Jan 2010 05:23:00 +0000</pubDate>
		<dc:creator>Rajeesh</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://www.rajeeshcv.com/2010/01/fluentconfigurationexception-an-invalid-or-incomplete-configuration-was-used-while-creating-session-factory-check-pot/</guid>
		<description><![CDATA[I got this exception when I tried to run my Repository tests and couldn&#8217;t find the exact reason why these tests failed. 
All the unit tests where passing before I removed the default constructors from Domain Model, when I reverted the default constructors back, everything started working again&#8230;.. !!!
Do you know the exact reason for [...]]]></description>
			<content:encoded><![CDATA[<p>I got this exception when I tried to run my Repository tests and couldn&#8217;t find the exact reason why these tests failed. </p>
<p>All the unit tests where passing before I removed the default constructors from Domain Model, when I reverted the default constructors back, everything started working again&#8230;.. !!!</p>
<p>Do you know the exact reason for this?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rajeeshcv.com/2010/01/fluentconfigurationexception-an-invalid-or-incomplete-configuration-was-used-while-creating-session-factory-check-pot/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Comet a.k.a server pushing</title>
		<link>http://www.rajeeshcv.com/2009/12/comet-aka-server-pushing/</link>
		<comments>http://www.rajeeshcv.com/2009/12/comet-aka-server-pushing/#comments</comments>
		<pubDate>Sun, 20 Dec 2009 18:14:47 +0000</pubDate>
		<dc:creator>Rajeesh</dc:creator>
				<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://www.rajeeshcv.com/2009/12/comet-aka-server-pushing/</guid>
		<description><![CDATA[Have you ever thought about how chatting in Gmail works? I think it works using a programming technique called “Comet”.
What is comet programming

In web development, Comet is a neologism to describe a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever thought about how chatting in Gmail works? I think it works using a programming technique called “Comet”.
<p>What is comet programming<br />
<blockquote>
<p>In web development, <b>Comet</b> is a neologism to describe a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it. Comet is an umbrella term for multiple techniques for achieving this interaction. All these methods rely on features included by default in browsers, such as JavaScript, rather than on non-default plugins &#8211; – <strong>Wikipedia</strong></p>
</blockquote>
<p>Last few days, I was reading about this technology and thought about sharing the information with you all. Please find the attached sample application which demonstrates how comet works using Asp.Net (<b><i>Note:</i></b><i> Right now it works only in firefox, fixes or patches to make it work in IE/Safari.. or all the browsers in this world are welcome</i> J )
<p>Please download it from here &#8211; <a title="http://www.rajeeshcv.com/download/comet.zip" href="http://www.rajeeshcv.com/download/comet.zip">http://www.rajeeshcv.com/download/comet.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rajeeshcv.com/2009/12/comet-aka-server-pushing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tip for writing better NUnit test cases</title>
		<link>http://www.rajeeshcv.com/2009/12/tip-for-writing-better-nunit-test-cases/</link>
		<comments>http://www.rajeeshcv.com/2009/12/tip-for-writing-better-nunit-test-cases/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 18:03:03 +0000</pubDate>
		<dc:creator>Rajeesh</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://www.rajeeshcv.com/2009/12/tip-for-writing-better-nunit-test-cases/</guid>
		<description><![CDATA[If you have method, which does the string reverse. So normally we writes test cases in Nunit something like this
[Test]
public void TestCase1()
{
ExString exString = new ExString();
Assert.AreEqual("dcba", exString.Reverse("abcd"));
}

[Test]
public void TestCase2()
{
ExString exString = new ExString();
Assert.AreEqual("abba", exString.Reverse("abba"));
}

This means, you are repeating the same code again and again in order to test different possibilities. The down side of this [...]]]></description>
			<content:encoded><![CDATA[<p>If you have method, which does the string reverse. So normally we writes test cases in Nunit something like this</p>
<pre class="csharp" name="code">[Test]
public void TestCase1()
{
ExString exString = new ExString();
Assert.AreEqual("dcba", exString.Reverse("abcd"));
}

[Test]
public void TestCase2()
{
ExString exString = new ExString();
Assert.AreEqual("abba", exString.Reverse("abba"));
}
</pre>
<p>This means, you are repeating the same code again and again in order to test different possibilities. The down side of this approach is, in long run it will be very difficult to manage the test case when compared to the actual code. </p>
<p>To solve this particular problem NUnit has got parameterised test cases attribute, so the same could be re write above test case to </p>
<pre class="csharp" name="code">[TestCase("abcd", "dcba", TestName = "Test Case 1")]
[TestCase("abcd1", "1dcba", TestName = "Test Case 2")]
[TestCase("aaaa", "aaaa", TestName = "Test Case 3")]
[TestCase("abba", "abba", TestName = "Test Case 4")]
public void Can_Reverse_A_Text(string actual, string expected)
{
ExString exString = new ExString();
Assert.AreEqual(expected, exString.Reverse(actual));
}
</pre>
<p>This gives a clean way for testing different possibilities, all these shown in the NUnit test runner as different test cases like below. </p>
<p><a href="http://www.rajeeshcv.com/wp-content/uploads/2009/12/image.png"><img alt="image" src="http://www.rajeeshcv.com/wp-content/uploads/2009/12/image-thumb.png" width="191" height="112"></a> </p>
<p>Hope this will help in some way or other</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rajeeshcv.com/2009/12/tip-for-writing-better-nunit-test-cases/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code generation &#8211; An easy way</title>
		<link>http://www.rajeeshcv.com/2009/06/code-generation-an-easy-way/</link>
		<comments>http://www.rajeeshcv.com/2009/06/code-generation-an-easy-way/#comments</comments>
		<pubDate>Fri, 05 Jun 2009 17:50:48 +0000</pubDate>
		<dc:creator>Rajeesh</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://www.rajeeshcv.com/2009/06/code-generation-an-easy-way/</guid>
		<description><![CDATA[Recently I read about Text Template Transformation Toolkit (T4), I was really amazed by this because I thought only CodeDOM was the only way to generate code.
Text Template Transformation Toolkit (T4) is template based code generation engine which comes with Visual Studio 2008(It is not a framework feature).

This simple example shows how powerful it is [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I read about <a href="http://msdn2.microsoft.com/en-us/library/bb126445.aspx" target="_blank">Text Template Transformation Toolkit</a> (T4), I was really amazed by this because I thought only <a href="http://msdn.microsoft.com/en-us/library/y2k85ax6.aspx" target="_blank">CodeDOM</a> was the only way to generate code.</p>
<blockquote><p><a href="http://msdn2.microsoft.com/en-us/library/bb126445.aspx" target="_blank">Text Template Transformation Toolkit</a> (T4) is template based code generation engine which comes with Visual Studio 2008(It is not a framework feature).</p>
</blockquote>
<p>This simple example shows how powerful it is &#8211; </p>
<p>if you have a string array and you want to generate a strongly typed enum from this.</p>
<p><strong><u>Steps</u></strong></p>
<p>1) Open up VS 2008 and Create a project.</p>
<p><span id="more-100"></span>
</p>
<p>2) Add a file called &#8220;EnumGenerator.tt&#8221; to the project. Accept the warning when add this file. Paste these code into the file you have created right now.</p>
<p>&nbsp;</p>
<pre class="csharp" name="code">&lt;#@ template language="C#" hostspecific="True" debug="True" #&gt;
&lt;#@ output extension="cs" #&gt;
&lt;#
// <copyright file="EnumGenerator.tt" company="">
//  Copyright © . All Rights Reserved.
// </copyright>

string[] values = new string[]{"Red","Green","Blue"};

#&gt;
namespace TextTemplate
{
&lt;#
PushIndent("\t");
#&gt;
enum Color
{
&lt;#
for(int i = 0; i &lt; values.Length; i++)
{
	PushIndent("\t");
	WriteLine(values[i] + ((i != values.Length -1) ? "," : ""));
	PopIndent();
}
#&gt;
}
&lt;#
PopIndent();
#&gt;
</pre>
<p>Step 3) Done! Click the plus sign near the &#8220;EnumGenerator.tt&#8221;, you can see the source code.</p>
<p>The beauty of this technique is, it is not runtime or compile time. The code is generated at design time which allow you to use this enum(or whatever code you have generated) at the same time you write your code.</p>
<p>To learn more about this, here is the great link &#8211; <a href="http://www.olegsych.com/2007/12/text-template-transformation-toolkit/" target="_blank">http://www.olegsych.com/2007/12/text-template-transformation-toolkit/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rajeeshcv.com/2009/06/code-generation-an-easy-way/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
