JQueryUI Datepicker in ASP.Net MVC

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://jquery.com/download/) if you haven’t done yet.

Assume you have a form like one below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<% using(Html.BeginForm()){%>
<fieldset>
<legend>Event Information</legend>
<p>
<label for="EventName">Event Name:</label>
<%= Html.TextBox("EventName")%>
</p>
<p>
<label for="StartDate">Start Date:</label>
<%= Html.TextBox("StartDate")%>
</p>
<p>
<label for="EndDate">End Date:</label>
<%= Html.TextBox("EndDate")%>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% }%>

and you want to attach datepicker to StartDate and EndDate input fields, what you needs to do is call the datepicker function on the these input field selector like below.

1
2
3
4
$(document).ready(function() {
$('#StartDate').datepicker();
$('#EndDate').datepicker();
});

This works fine as we expected :)

###Difference in Date format patterns

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 dddd* its equivalent in Datepicker is DD.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/// <summary>
/// JQuery UI DatePicker helper.
/// </summary>
public static class JQueryUIDatePickerHelper
{
/// <summary>
/// Converts the .net supported date format current culture format into JQuery Datepicker format.
/// </summary>
/// <param name="html">HtmlHelper object.</param>
/// <returns>Format string that supported in JQuery Datepicker.</returns>
public static string ConvertDateFormat(this HtmlHelper html)
{
return ConvertDateFormat(html, Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern);
}

/// <summary>
/// Converts the .net supported date format current culture format into JQuery Datepicker format.
/// </summary>
/// <param name="html">HtmlHelper object.</param>
/// <param name="format">Date format supported by .NET.</param>
/// <returns>Format string that supported in JQuery Datepicker.</returns>
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("dddd", "DD");
currentFormat = currentFormat.Replace("ddd", "D");

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

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

return currentFormat;
}
}

So how we could make use this helper method, just replace the datepicker initialization code we have written earlier with this

1
2
3
4
$(document).ready(function() {
$('#StartDate').datepicker({ dateFormat: '<%= Html.ConvertDateFormat() %>' });
$('#EndDate').datepicker({ dateFormat: '<%= Html.ConvertDateFormat() %>' });
});

Hope this helps.

Logging Execution Time Using AOP

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.

So how we could develop a profiler, where we don’t have to wrap our normal code in a profiling code.

Before going to create the profiler, we have to decide where to put the profiled information. In this tutorial, I am making use of Log4Net as underlying layer to store this information. If you have not used Log4Net before, I suggest you to read http://www.beefycode.com/post/Log4Net-Tutorial-pt-1-Getting-Started.aspx as a starting point.

With the help of AOP (Aspect-Oriented Programming) we could do the profiling task without interrupting the actual code.

AOP is a programming paradigm in which secondary or supporting functions are isolated from the main program’s business logic

Wikipedia

So in order bring the AOP functionality into this application, I am going to use a third party library PostSharp which I believe this is one of the best that is available in the market.

So, now we have got the basic things to start with and now let’s start coding….

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

Add reference to the Log4Net.dll, PostSharp.Laos.dll and PostSharp.Public.dll (Please read https://www.postsharp.net/documentation to get the basic installation procedure). 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

1
2
3
4
5
6
7
8
9
10
11
12
13
[Serializable]
public class ProfileMethodAttribute : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
........
}

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

This class actually derives from OnMethodBoundaryAspect, 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.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
public class LoggerHelper
{
/// <summary>
/// Static instance of ILogger.
/// </summary>
private static ILog logger;

/// <summary>
/// Initializes static members of the <see cref="LoggerHelper"/> class.
/// </summary>
static LoggerHelper()
{
log4net.Config.XmlConfigurator.Configure();
logger = LogManager.GetLogger(typeof(Program));
}

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

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

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

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

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

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

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

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

string message = sb.ToString();

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

return message;
}

/// <summary>
/// Constructs the log.
/// </summary>
/// <param name="methodName">Name of the method.</param>
/// <param name="url">The URL to be logged.</param>
/// <param name="executionFlowMessage">The execution flow message.</param>
/// <param name="actualMessage">The actual message.</param>
/// <param name="executionTime">The execution time.</param>
/// <returns>Formatted string.</returns>
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(", ExecutionTime : {0}", executionTime);

return sb.ToString();
}
}

LoggerHelper uses the Log4Net objects to log the message to configured location. Profiler class implemented like below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/// <summary>
/// Helper class that wraps the timer based functionalities.
/// </summary>
internal static class Profiler
{
/// <summary>
/// Lock object.
/// </summary>
private static readonly object SyncLock = new object();

/// <summary>
/// Variable that tracks the time.
/// </summary>
private static readonly Dictionary<int, Stack<long>> ProfilePool;

/// <summary>
/// Initializes static members of the <see cref="Profiler"/> class.
/// </summary>
static Profiler()
{
ProfilePool = new Dictionary<int, Stack<long>>();
}

/// <summary>
/// Starts this timer.
/// </summary>
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<long>();
timerStack.Push(DateTime.UtcNow.Ticks);
ProfilePool.Add(currentThreadId, timerStack);
}
}
}

/// <summary>
/// Stops timer and calculate the execution time.
/// </summary>
/// <returns>Execution time in milli seconds</returns>
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;
}
}

which stores the starting tick and calculate the time taken to execute when Stop is called.

Below is code snippet from OnEntry method

1
2
3
4
5
6
7
8
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();
}

And OnExist, is almost similar expect there we will stop the profile timer.

1
2
3
4
5
public override void OnExit(MethodExecutionEventArgs eventArgs)
{
int count = Profiler.Stop();
LoggerHelper.Log(this._methodName, this._url, this.EntryMessage, this.Message, count);
}

Next step is to use this and see whether it is logged properly. In order enable profiling for a method, you just needs to decorate it with the ProfileMethod attribute. Like below

1
2
3
4
5
[ProfileMethod()]
public void SimpleMethod()
{
Thread.Sleep(5000);
}

Then if you run the application and calls this above method, a log entry will be created where you have configured which looks like below

PROFILING 2010-02-26 00:19:59,838 [1] Log MethodName : SimpleMethod
PROFILING 2010-02-26 00:20:04,865 [1] Log MethodName : SimpleMethod, ExecutionTime : 5002

Please least me know, if this helped you.

Download the demo code from here

Logging Execution Time Using AOP

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.

So how we could develop a profiler, where we don’t have to wrap our normal code in a profiling code.

Before going to create the profiler, we have to decide where to put the profiled information. In this tutorial, I am making use of Log4Net as underlying layer to store this information. If you have not used Log4Net before, I suggest you to read http://www.beefycode.com/post/Log4Net-Tutorial-pt-1-Getting-Started.aspx as a starting point.

With the help of AOP (Aspect-Oriented Programming) we could do the profiling task without interrupting the actual code.

AOP is a programming paradigm in which secondary or supporting functions are isolated from the main program’s business logic

Wikipedia

So in order bring the AOP functionality into this application, I am going to use a third party library PostSharp which I believe this is one of the best that is available in the market.

So, now we have got the basic things to start with and now let’s start coding….

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

Add reference to the Log4Net.dll, PostSharp.Laos.dll and PostSharp.Public.dll (Please read https://www.postsharp.net/documentation to get the basic installation procedure). 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

1
2
3
4
5
6
7
8
9
10
11
12
13
[Serializable]
public class ProfileMethodAttribute : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
........
}

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

This class actually derives from OnMethodBoundaryAspect, 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.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
public class LoggerHelper
{
/// <summary>
/// Static instance of ILogger.
/// </summary>
private static ILog logger;

/// <summary>
/// Initializes static members of the <see cref="LoggerHelper"/> class.
/// </summary>
static LoggerHelper()
{
log4net.Config.XmlConfigurator.Configure();
logger = LogManager.GetLogger(typeof(Program));
}

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

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

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

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

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

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

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

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

string message = sb.ToString();

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

return message;
}

/// <summary>
/// Constructs the log.
/// </summary>
/// <param name="methodName">Name of the method.</param>
/// <param name="url">The URL to be logged.</param>
/// <param name="executionFlowMessage">The execution flow message.</param>
/// <param name="actualMessage">The actual message.</param>
/// <param name="executionTime">The execution time.</param>
/// <returns>Formatted string.</returns>
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(", ExecutionTime : {0}", executionTime);

return sb.ToString();
}
}

LoggerHelper uses the Log4Net objects to log the message to configured location. Profiler class implemented like below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/// <summary>
/// Helper class that wraps the timer based functionalities.
/// </summary>
internal static class Profiler
{
/// <summary>
/// Lock object.
/// </summary>
private static readonly object SyncLock = new object();

/// <summary>
/// Variable that tracks the time.
/// </summary>
private static readonly Dictionary<int, Stack<long>> ProfilePool;

/// <summary>
/// Initializes static members of the <see cref="Profiler"/> class.
/// </summary>
static Profiler()
{
ProfilePool = new Dictionary<int, Stack<long>>();
}

/// <summary>
/// Starts this timer.
/// </summary>
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<long>();
timerStack.Push(DateTime.UtcNow.Ticks);
ProfilePool.Add(currentThreadId, timerStack);
}
}
}

/// <summary>
/// Stops timer and calculate the execution time.
/// </summary>
/// <returns>Execution time in milli seconds</returns>
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;
}
}

which stores the starting tick and calculate the time taken to execute when Stop is called.

Below is code snippet from OnEntry method

1
2
3
4
5
6
7
8
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();
}

And OnExist, is almost similar expect there we will stop the profile timer.

1
2
3
4
5
public override void OnExit(MethodExecutionEventArgs eventArgs)
{
int count = Profiler.Stop();
LoggerHelper.Log(this._methodName, this._url, this.EntryMessage, this.Message, count);
}

Next step is to use this and see whether it is logged properly. In order enable profiling for a method, you just needs to decorate it with the ProfileMethod attribute. Like below

1
2
3
4
5
[ProfileMethod()]
public void SimpleMethod()
{
Thread.Sleep(5000);
}

Then if you run the application and calls this above method, a log entry will be created where you have configured which looks like below

PROFILING 2010-02-26 00:19:59,838 [1] Log MethodName : SimpleMethod
PROFILING 2010-02-26 00:20:04,865 [1] Log MethodName : SimpleMethod, ExecutionTime : 5002

Please least me know, if this helped you.

Download the demo code from here

ASP.Net MVC – Conditional Rndering Partial Views with Action<T> Delegate

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<T> delegate

<% Html.PartialIf(this.Model.Exists, html => html.RenderPartial("MyPartialView")); %>

If you look at the PartialIf implementation, it is simple, cleaner than the previous technique I have mentioned in my post.

1
2
3
4
5
6
7
public static void PartialIf(this HtmlHelper htmlHelper, bool condition, Action<HtmlHelper> action)
{
if (condition)
{
action.Invoke(htmlHelper);
}
}

That’s it :)

ASP.Net MVC – Conditional Rndering Partial Views with Action<T> Delegate

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<T> delegate

<% Html.PartialIf(this.Model.Exists, html => html.RenderPartial("MyPartialView")); %>

If you look at the PartialIf implementation, it is simple, cleaner than the previous technique I have mentioned in my post.

1
2
3
4
5
6
7
public static void PartialIf(this HtmlHelper htmlHelper, bool condition, Action<HtmlHelper> action)
{
if (condition)
{
action.Invoke(htmlHelper);
}
}

That’s it :)

ASP.Net MVC - Conditional Rendering Partial Views

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<T> 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 is

1
2
3
4
<% if(this.Model.Exists)
{
Html.RenderPartial("MyPartialView");
} %>

I am not sure about any other technique for rendering partial view conditionally other than this (correct me if I am wrong :) ).

Then I thought about copying the pattern I have used in my previous post 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

<% Html.PartialIf(this.Model.Exists, "MyPartialView"); %>

Below is the Html extension I have created

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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);
}
}

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 )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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("Partial view not found");
}

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

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);
}

Hope this helps

ASP.Net MVC - Conditional Rendering Partial Views

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<T> 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 is

1
2
3
4
<% if(this.Model.Exists)
{
Html.RenderPartial("MyPartialView");
} %>

I am not sure about any other technique for rendering partial view conditionally other than this (correct me if I am wrong :) ).

Then I thought about copying the pattern I have used in my previous post 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

<% Html.PartialIf(this.Model.Exists, "MyPartialView"); %>

Below is the Html extension I have created

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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);
}
}

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 )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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("Partial view not found");
}

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

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);
}

Hope this helps

ASP.Net MVC - Conditional Rendering

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

1
2
3
<% if (this.Model.Exists) { %>
<%= Html.TextBox("Test") %>
<% } %>

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

<%= Html.If(this.Model.Exists, action => action.TextBox("Name")) %>

which looks cleaner than the old one. Source code for this helper method is

1
2
3
4
5
6
7
8
9
public static string If(this HtmlHelper htmlHelper, bool condition, Func<HtmlHelper, string> action)
{
if (condition)
{
return action.Invoke(htmlHelper);
}

return string.Empty;
}

What about IfElse condition, we could write another helper method for that

1
2
3
4
5
6
7
8
9
public static string IfElse(this HtmlHelper htmlHelper, bool condition, Func<HtmlHelper, string> trueAction, Func<HtmlHelper, string> falseAction)
{
if (condition)
{
return trueAction.Invoke(htmlHelper);
}

return falseAction.Invoke(htmlHelper);
}

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static string HtmlTag(this HtmlHelper htmlHelper, HtmlTextWriterTag tag, object htmlAttributes, Func<HtmlHelper, string> 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;
}

An overloaded version which doesn’t accept HtmlAttributes as parameter

1
2
3
4
public static string HtmlTag(this HtmlHelper htmlHelper, HtmlTextWriterTag tag, Func<HtmlHelper, string> action)
{
return HtmlTag(htmlHelper, tag, null, action);
}

Below are some examples of using these helpers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%= Html.HtmlTag(HtmlTextWriterTag.Div, action => action.ActionLink("Without attributes","About") ) %>

<%= Html.HtmlTag(HtmlTextWriterTag.Div, new { name = "wrapper", @class = "styleclass" }, action => action.ActionLink("With Attributes", "About")) %>

<%= Html.HtmlTag(HtmlTextWriterTag.Div, null, action => action.ActionLink("Null attributes", "About")) %>

<%= Html.IfElse(this.Model.Exists, trueAction => trueAction.Encode("Sample"), falseAction => falseAction.TextBox("SampleName")) %>

<%--
Nesting
<div>
<span>
<a href="/Home/About">About</a>
</span>
</div>
--%>
<%= Html.If(this.Model.Exists,
div => div.HtmlTag(HtmlTextWriterTag.Div,
span => span.HtmlTag(HtmlTextWriterTag.Span,
anchor => anchor.ActionLink("About", "About"))
)) %>

Hope this will help you.

ASP.Net MVC - Conditional Rendering

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

1
2
3
<% if (this.Model.Exists) { %>
<%= Html.TextBox("Test") %>
<% } %>

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

<%= Html.If(this.Model.Exists, action => action.TextBox("Name")) %>

which looks cleaner than the old one. Source code for this helper method is

1
2
3
4
5
6
7
8
9
public static string If(this HtmlHelper htmlHelper, bool condition, Func<HtmlHelper, string> action)
{
if (condition)
{
return action.Invoke(htmlHelper);
}

return string.Empty;
}

What about IfElse condition, we could write another helper method for that

1
2
3
4
5
6
7
8
9
public static string IfElse(this HtmlHelper htmlHelper, bool condition, Func<HtmlHelper, string> trueAction, Func<HtmlHelper, string> falseAction)
{
if (condition)
{
return trueAction.Invoke(htmlHelper);
}

return falseAction.Invoke(htmlHelper);
}

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static string HtmlTag(this HtmlHelper htmlHelper, HtmlTextWriterTag tag, object htmlAttributes, Func<HtmlHelper, string> 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;
}

An overloaded version which doesn’t accept HtmlAttributes as parameter

1
2
3
4
public static string HtmlTag(this HtmlHelper htmlHelper, HtmlTextWriterTag tag, Func<HtmlHelper, string> action)
{
return HtmlTag(htmlHelper, tag, null, action);
}

Below are some examples of using these helpers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%= Html.HtmlTag(HtmlTextWriterTag.Div, action => action.ActionLink("Without attributes","About") ) %>

<%= Html.HtmlTag(HtmlTextWriterTag.Div, new { name = "wrapper", @class = "styleclass" }, action => action.ActionLink("With Attributes", "About")) %>

<%= Html.HtmlTag(HtmlTextWriterTag.Div, null, action => action.ActionLink("Null attributes", "About")) %>

<%= Html.IfElse(this.Model.Exists, trueAction => trueAction.Encode("Sample"), falseAction => falseAction.TextBox("SampleName")) %>

<%--
Nesting
<div>
<span>
<a href="/Home/About">About</a>
</span>
</div>
--%>
<%= Html.If(this.Model.Exists,
div => div.HtmlTag(HtmlTextWriterTag.Div,
span => span.HtmlTag(HtmlTextWriterTag.Span,
anchor => anchor.ActionLink("About", "About"))
)) %>

Hope this will help you.

FluentConfigurationException: An invalid or Incomplete Configuration was used while creating Session Factory

I got this exception when I tried to run my Repository tests and couldn’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….. !!!

Do you know the exact reason for this?

Update: In order to support lazy loading, NHibernate needs to create proxy objects. Those proxy classes derived from the actual domain model class itself, and they are instantiated using the default constructor. So the parent class also should have a default constructor.