Friday, 17 January 2014

Checking Debug Mode on an MVC View

To check whether our project is in debug/release mode on a particular view, we would not be able to use #if DEBUG #endif on our view because a view is not compiled. To do this, we need to run the logic from the back end. Below is an example of an extension method to check that:
public static bool IsDebug(this HtmlHelper htmlHelper)
{
  #if DEBUG
  return true;
  #else
  return false;
  #endif                  
}

Then on our view, we could call the method:
@if (Html.IsDebug())
{
  @Html.Raw("<span style='color: red'>DEBUGGING MODE IS ON</span>");
}

Friday, 10 January 2014

Some Notes about TransactionScope in .NET

Basic usage of TransactionScope is as follow:
using (var scope = new TransactionScope())
{
    // some codes here . . .

    scope.Complete();
} 

By default, the isolation level used is Serializable and timeout is 1 minute.

According to this post on MSDN Blogs, the default isolation level is likely to introduce deadlock issues. The recommended isolation level is Read Committed.

If our codes are using more than one database (distributed transaction) then they will be much slower compare to only using one database (local transaction).

The maximum timeout of TransactionScope when setting this up via code (Timeout property) is 10 minutes. If we set the property to have a value larger than this, it would fall back to 10 minutes. If we want longer timeout value, we will need to set this in machine.config file. However that will affect other applications on the server.

Below is how to set isolation level and timeout in codes:
var transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted;
transactionOptions.Timeout = TransactionManager.MaximumTimeout;
var transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions);

If we want to change the timeout in machine.config:
<system.transactions>
   <machineSettings maxTimeout="00:30:00" />
</system.transactions>

When using SQL server, we also need to concern about the timeout of running query/command or stored procedure. The default timeout is 30 seconds. We can extend the timeout by setting CommandTimeout property.