Category: ASP.Net

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

Web.Config changes in Visual Studio 2010

In Visual Studio 2010, when you add a new project, it hard not to notice couple of things about the web.config files.

1) Web.config file is clean and lean ūüôā (Read about this in Scott Gu’s blog here)
2) Web.config has 2 files attached to it, Web.Debug.config and Web.Release.config (see image).

Visual Studio 2010

Visual Studio 2010 - Solution Explorer

These are new features that I think that are very valuable for the deployment process, In the past I have used manual swaps a lot to manage environment specfic information in the web.config files. This new feature will let you create deployment environment specific (Dev, QA, UAT, Stage, Prod, etc.) Web.config files using simple to write transformations. You can find detailed information on how to do this in this article. (Link)

Happy Programming!


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.

    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 and .Net 4.0

    Are you looking forward for this new edition of Visual Studio? Here is an article that introduces what is new in Visual Studio 2010, Read it here.

    BTW, Happy New Year everyone ***2010***, I hope to blog more this year. I have a list of new stuff I am planning to get my hands on soon, watch this space and you can learn about it (if you care ūüėČ

    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:-)

    How to bind Reorder List to an object data source

    The reorderlist is part of the Ajax Control toolkit which provides us with a  databound list control which can be reordered interactively. The reorder list can be bound to any datasource that implements the IList interface. Below is a sample code to use the reorder list bound to an object data source

    <cc1:ReorderList runat="server"
                  <asp:Label Text='<%# Eval("Name") %>' runat="server"  />
                                <asp:Panel runat="server" CssClass="reorderCue" />
    <asp:ObjectDataSource runat="server" SelectMethod="GetList"
            TypeName="BusinessLayer" OldValuesParameterFormatString="original_{0}"
             <asp:Parameter Name="Original_Id" Type="Int32" />
    	<asp:Parameter Name="Position" Type="Int32" />

    Once you have your get and update methods defined you are good to go.

    ¬†Many of you might have encountered a generic ‚Äúfaliled to reorder‚ÄĚ error message while trying to save the reorder list. The main reason for this error is the way the reorder list builds the parameter dictionary for the update method. The reorderlist uses ‚ÄúTypeDescriptor.Getproperties(row)‚ÄĚ which results in a parameter for each property of the custom data object to which you are binding. To work around this it would be advisable to create a datatable with only the required fields to display and update the data (See¬†our earlier¬†post on converting a generic list to a datatable). In our example the required fields to display are Id, Name and Position (Case sensitive). For update we would require only the Id and Position. Since our reorderlist will include ‚ÄúName‚ÄĚ also in the parameter dictionary please see that your update method includes the ‚ÄúName‚ÄĚ field¬† in its signature.


    public bool SaveList(int Original_Id,int Position, string Name)
    { }
     public DataTable GetList()
     List<Category> lst=GetCategories();
     //convert this lst to a datatable with just the required columns             

    That’s it. Your reorderlist is ready.