Tagged: C#

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 (developer.com)

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 VB.net (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”


Gettting ClientIDs of asp.net 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:-)

A Cold Case Solved !

We have several web user controls in one of our sites. These controls are all placed in a \Controls sub directory. Many controls are created runtime and added to placeholders in the page. When we build this particular site (currently uses ASP.Net 3.5) we used to get this
error message…
The type or namespace name ‘Controls_XXXXX’ could not be found
(are you missing a using directive or an assembly reference?)

And design time Visual Studio was somehow not aware of these control’s classes!

Today I stumbled upon this MSDN link, addresses this very issue.


Essentialy what it says is to add class name to your controls ascx file’s directive:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PickList.ascx.cs" Inherits="Controls_PickList" ClassName="Controls_PickList" %>

And use Reference directive in your page where you use these control…

<%@ Register src="Controls/PickList.ascx" tagname="PickList" tagprefix="uc1" %>

Even if you are programmatically using these controls…

Cold case solved!!

GridView Sorting Trick when using Object Datasource with custom objects

When you are using Object DataSource in ASP.Net for GridView, if your select method is returning an object that is of type DataView, DataTable or DataSet, you will be able to get sorting automatically.
But if you are like me and your architecture has a distinct DTO (Entity) layer, and you pass back and forth custom objects or generic list of these custom objects, then you are in less luck with GridView. If you
are binding GridView with Object Datasource that returns a List, you will need to implement your own custom code to do sorting.

If you google this issue, you will find different implementation that will point you to add a OnSorting event handler and more than one way to implement a custom sorting.

What my thinking is, since DataTable and DataView provides us the automatic sorting that we need, then why don’t we create
a DataTable from the List we have. We can do this elegantly using generics and reflection. Once we create a DataTable, simply pass back a DataView based on this table as return parameter from your Select Method of Object Datasource.

Here is the code for converting a List to a DataTable, (CustomObject is my custom object defined in my DTO layer)

using System;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
public class Utilities

	public static DataTable ToDataTable(List lst) where T : CustomObject
            PropertyInfo[] propertyInfos;

            System.Data.DataTable table = new DataTable("GridViewTable");
            DataColumn column=null;
            DataRow row=null;

            foreach (CustomObject v in lst)
                propertyInfos = v.GetType().GetProperties();
                foreach (PropertyInfo propertyInfo in propertyInfos)
                    column = new DataColumn();
                    column.DataType = System.Type.GetType(propertyInfo.PropertyType.FullName);
                    column.ColumnName = propertyInfo.Name;
                //New table made, break the loop
            //Now populate the table with values
            foreach (CustomObject v in lst)
                 propertyInfos = v.GetType().GetProperties();
                 row = table.NewRow();
                 foreach (PropertyInfo propertyInfo in propertyInfos)
                     row[propertyInfo.Name] = propertyInfo.GetValue(v, null);
            return (table);



Build a web site using ASP.Net MVC – Part 1

At last, I have decided to get my hands dirty with some real project using ASP.Net MVC. This will give me an opportunity to explore various features that are offered with ASP.Net MVC extension. There are lots
of articles available to read about this online. I’ve been reading all these time and now its time to do something more than reading …

How to prepare for development?

    Install .Net Framework 3.5 SP1 – If you do not have it yet – get it from here.
    Install Visual Studio 2008 Service Packs – Good to have..
    Install ASP.Net MVC 1.0 – Get it from here.

Like I mentioned earlier in this note, there are a lot of articles out there, so I have decided to pick the best for my reading.

1. Scott Guthrie’s Blog
2. Asp.net MVC Official Site

I am planning to use these 2 great resources, to build the site. Guthrie has build a tutorial and a sample site named Nerd Dinner which I think should give me a good starting point.

This is it for now, I will posting notes as we progress…
Lot of reading and research to do…


Tip: C# Automatic Properties, k_BackingField and JSON

If you are using automatic properties to define your data objects and you are trying to serialize these objects to a JSON string using DataContractSerializer (WCF/3.5), make sure you mark your data classes with [DataContract] and [DataMember] attributes (even if you are not really using WCF), a simple [Serializable] attribute will not do. If you just use [Serializable], the emitted JSON string will have a prefix tag “k_backingField” and the string is all mumbo-jumbo!

So if you use automatic properties, your class should look like this 🙂

    public class Employee
        [DataMember(Name = "FirstName", Order = 1)]
        public string FirstName { get; set; }
        [DataMember(Name = "LastName", Order = 2)]
        public string LastName { get; set; }