Category: C#

With MVC 3, <text></text> is a useful way to mix your Razor and JavaScript syntax.

 if (ViewBag.Blog != null)

 var blogPost = '@ViewBag.Blog.Post';
 $('#wysiwyg').wysiwyg("setContent", blogPost);

Continue reading

A broad look at Web Application Performance

So does your web application perform well? Is it responsive enough so that it increases the web user experience? It is a fact that user can relate only to what they see and what they click, that is the user interface (UI) and the experience with it (UX) largely depends on the performance of the overall
application. But what is the complaint that we usually hear, “this page is slow”, “this grid takes for ever to load”, “we click on that button and then we go for a coffee break”…and UI is always blamed first. We all know that it has to do with the perception a lot, but a services guy ignores it, database developer closes his eyes too, till someone proves where is the actual bottleneck.
Performance Tips
My cose friend and ex-colleague called me the other morning asking me help to figure out why the application was timing out, users are screaming and cursing this particular search page, it started timing out suddenly last week. They did all the usual tricks, iisreset, checking logs, checking db connections, even few server restarts, no avail. So this morning, we started looked thru the logs, stack traces and we could easily spot the culprit, a stored procedure in SQL Server, has gone rogue and slow. So in this case, we need to look closely at that proc, probably data has grown so much in one of the table that now a bad join has created performance issues.

I shared that experience, to point to fact that performance and thus performance tuning has to start at the very tail end (or head depends the way your look at the layered architecture :). So now lets take the layers, there is presentation layer, business layer, database access layer (persistence layer) and then there is the database itself.

Lets start with Database: What are the performance optimizations that you can think of, here is some starters.

  • Good logical design, helps in how db is physically stored, think thru your normalization levels depending on your usage, make sure you dont over-normalize, it will kill your joins and thus leads to bad performing queries.
  • Good key selection, have a good candidate for primary key, have proper foreign keys that are indexed (create non-clusterd index)
  • When writing queries, do not return all columns (i.e., no select * …)
  • Use SET NO COUNT ON, think about providing sql hints
  • There is 2 camps about using temp tables, some hate it, some love it, according to me temp table can be very useful when you are dealing with a large amount of tables to join. Create temp tables to divide and conquer. Always think about “number of rows” in the table when you make these decisions and potential growth of data. Check query plans, avoid table scans.
  • Use sp_executesql when you want to execute a dynamic sql
  • Reduce round trips to the server, try to do bulk operations.
  • This is just few I can think of now, Google database tuning and I am sure you can find a tons of good tuning tips from database gurus.

    Now how about Data Access Layer (DAL)? So what is DAL? DAL is nothing but a mechanism that provides us some CRUD capability along with some transactions, querying and concurrency control. In simpler systems, ADO.Net provides an database independent way to achieve this, So ADO.Net is our DAL layer. Or you might choose to absract the core features provided by ADO.Net into another library where you have tighter control and ability to switch databases at will, a DB Services Factory. If you are following a Domain Driven Design, then your OR/M plays the role of DAL.

    Lets see some ADO.Net related performance tips,

  • For connection pooling to work, always use the same connection string. By default pool size is 100, you can increase this (rarely you will need to)
  • Use db server IP rather than the server name in connection string to avoid a domain name resolution lookup. (This is a performance tip, but not a governance tip, for better governance, always use DNS name)
  • Always close the connections explicitly
  • Connect using a service account. Use windows authentication.
  • Use stored procedures, return only what you need.
  • Use some caching strategy to cache frequently used static data.
  • Again this is tip of the iceberg on what performance considerations you can use, for a more complete ADO.Net performance tuning tips, refer to “Improving .Net Application Performance and Scalability” from Microsoft patterns and practices.

    We will continue to explore performance from a OR/M layer perspective, then a Business Layer and finally UI layer in a future post.

    Until then Cheers and Happy Programming.

    Aspect Oriented (AOP) Logging

    Aspect Oriented ProgrammingLogging can be an aspect in your code that can be treated separately from you real business processing code. In most of the systems I worked on, we ended up putting logging code dispersed among our other code. This may not be a *very* bad practice but too many lines of repeat code ! Even if you have a nice logging framework where the mechanics of logging, its configuration, etc. are abstracted away, you still have to call your “Log” or “Trace” public methods to do the actual logging. Using AOP style of design, we can abstract away these aspects to a central place where individual developers need not worry about adding these to their code.
    Logging and Exception Handling are 2 common aspects that can be handled in this manner for most of the systems, (there are many other aspects too depending on what you are building).

    Read about Aspect Oriented Programming (AOP) here (Wiki article) and here (

    This is not that hard as you might think if you use some of the great frameworks like Castle Windsor or PostSharp. Ayende @ Rahien has a great blog (as always) explaining AOP way of logging using Castle Windsor IoC container. [Link] Simple and straight-forward and works great!

    Another approach is to use PostSharp. It weaves aspect code at compile time. Its clean and simple to implement. Follow the steps below to setup some basic AOP logging using PostSharp. In my example, I have an MVC web application and want to trace all the controller methods,

    We will create a new class first, call it TraceAspect, derive this class from PostSharp.Aspects.OnMethodBoundaryAspect. OnMethodBoundaryAspect is an abstract class with
    4 virtual methods, OnEntry(), OnExit(), OnSucess() and OnException(). You can override these methods to get information about the logging context.

    (Note: I am working with PostSharp 2.0, can be downloaded for a 45 day evaluation from here.)

        using System;
        using System.Diagnostics;
        using System.Text;
        using PostSharp.Aspects;
        public sealed class TraceAspect : OnMethodBoundaryAspect
            private readonly string _controllerName;
            public TraceAspect(string controllerName)
                this._controllerName = controllerName;
            public string Category
                get { return _controllerName; }
            public override void OnEntry(MethodExecutionArgs args)
                Trace.WriteLine(string.Format("Entering {0}.{1}.",args.Method.DeclaringType.Name, args.Method.Name), this._controllerName);
                if (args.Arguments != null)
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < args.Arguments.Count; i++)
                        sb.AppendFormat("{0}:'{1}'", args.Method.GetParameters()[i], Convert.ToString(args.Arguments.GetArgument(i)));
            public override void OnSuccess(MethodExecutionArgs args)
                Trace.WriteLine(string.Format("Return Value = {0}",args.ReturnValue));
            public override void OnException(MethodExecutionArgs args)
                Trace.WriteLine(string.Format("Return Value = {0}", args.Exception.Message));
                args.FlowBehavior = FlowBehavior.Continue;   
            public override void OnExit(MethodExecutionArgs args)
                Trace.WriteLine(string.Format("Exiting {0}.{1}.",args.Method.DeclaringType.Name, args.Method.Name), this._controllerName);
                Trace.WriteLine(string.Format("Method returned {0}", args.ReturnValue));

    If I was not using any AOP style logging, my controller will look like this,

            public JsonResult DoSomething(string inputParam)
                Trace.WriteLine("Inside DoSomething()");
                    //Call downstream method calls to do something
                    Trace.WriteLine("Result :: " + DateTime.Now.ToShortTimeString());
                    return Json(DateTime.Now.ToShortTimeString());
                catch (Exception exception)
                    Trace.WriteLine("Exiting DoSomething()");
                return (null);

    and all those Trace calls can go away with one line of code (attribute decoration) to your method with PostSharp AOP logging!

            public JsonResult DoSomething(string inputParam)
               return Json(DateTime.Now.ToShortTimeString());

    Run your application and you will see trace like this:

    DoSomething: Entering ServiceController.DoSomething.
    System.String p:'time'
    Return Value = System.Web.Mvc.JsonResult
    DoSomething: Exiting ServiceController.DoSomething.
    Method returned System.Web.Mvc.JsonResult

    In my case, input I passed from my client code that is calling this controller was ‘time’, and since the result is a JsonResult, you will need to deserialize to see the actual result. If you are any scalar values you will be able to see that with ReturnValue property directly. If you are passing a custom object/DTO, may be you can override ToString() to print state of the object and that can be used to trace here, essentially many ways to do it! Also, in this example I am using Trace class to write the trace log, You can replace this with your enterprise logging library where you can turn ON and OFF and adjust your trace levels too.


    VB.Net and C# Co-Evolution

    Read Scott Wiltamuth’s blog about future of VB.Net…Its not going away anytime soon, in fact MS is planning
    to have a co-evolution strategy for C# and (and other .Net languages). I think this is effort should be
    welcomed, because somewhere after v1.1 of .net, language features introduced have very different usage syntax in VB.Net and C# ! This would mean that it is more and more difficult for a good .Net programmer to code in VB.Net and C# with the same ease.
    Have you noticed that if you search for a solution in web, you always get tons of C# samples but not many VB.Net samples..its a fact. So what does a VB.Net developer do? He takes C# code and converts to VB.Net, so if there is a lot of syntactical differences, his life is a mess, if not “all is well”


    JSON Serialization and Circular Reference Error !

    I have a table that references a child table with reference to parent (!), I am using LINQ to SQL, for a paricular scenario, when I want to serialize my result using Json(obj) in my controller code, I got an error saying.. “A circular reference was detected while serializing an object of type..”

    This issue is very well explained by Rick Strahl in his blog (link here)

    If we are using WCF services, setting SerializationMode of the data context to “Unidirectional” would do the trick. In my case I was using MVC and it was a controller action invoke from javascript!! Also I did not want to try setting the Access Level to internal because I was not sure whether I get deep serialization if I do that! (did not try, because I was half convinced that It may not work for me)

    Issue was Json() call in my controller to convert my object to Json and send back as JsonResult… So I ended up serializing it in my biz layer, biz layer method now returned a Json String, changed my controller to return ActionResult/ContentResult and used Content(jsonString) to send back a ContentResult.

    It worked because Javascript library expected a Json Literal and it got that. All is good for now!

    Visual Studio 2010 Beta 2

    Yesterday I installed Visual Studio 2010 Beta 2 Ultimate Edition. As expected installation process was long. (not sure how long because I fell asleep and had to continue this morning to finish installation). Here is link to download site.
    At the first look itself, I can see that there are a tons of new features this edition of Visual Studio going to offer. There seems like a lot of improvements and additions to tool sets and project templates, new project planning features, test development, TFS integration, MVC 2.0, Sliverlight support, More sharepoint development support, Enterprise Data, etc..etc…list goes on. Its going to take a lot of time to get a handle of all these new features.
    I will post what ever i find interesting…so keep watching this space.


    Gettting ClientIDs of controls in an external javascript file

    When maintaining external javascript files for our webpages the biggest hurdle we face is the getting clientID of our server side controls in the javascript file. Let me demonstrate a workwround for this that I usually adopt.
    Step 1:
    In the page load event create an array of json objects representing the clIentIDs of all the controls that we would be requiring to use in javascript functions. Store this in a javascript global variable using window::onload function.

    private void SaveControlClientIDs()
        System.Text.StringBuilder ctlObj = new System.Text.StringBuilder();
        ctlObj.Append("{""Id"":'" + ddlEmployee.ClientID & "',""Type"":'" + ddlEmployee.GetType().ToString() + "',""DefaultValue"":'0'},");
        ctlObj.Append("{""Id"":'" + txtName.ClientID & "',""Type"":'" + txtName.GetType().ToString() + "',""DefaultValue"":''},");
        ctlObj.Append("{""Id"":'" + txtEndDt.ClientID & "',""Type"":'" + txtEndDt.GetType().ToString() + "',""DefaultValue"":''}");
        string bodyOnloadScript = "<script type='text/javascript'>function body_onload() { ctlIds=" + ctlObj.ToString() + ";}</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", bodyOnloadScript);

    Step 2:

    In your javascript file use the following function to retrieve the clientID using the actual id of your control

    var ctlIds; //this is the global variable which will store the json objects
    function GetCtlClientId(id) {
        var arr = ctlIds;
        var res = ”;
        var i = 0;
        for (i = 0; i < arr.length; i++) {         if (arr[i].Id.indexOf(id) != -1) {             res = arr[i].Id;             break;         }     }     return res; } [/sourcecode] In .NET 4.0 the issue of ClientIDs has been addressed to an extent. Till you move to 4.0 hope this helps:-)