I’m working on a web application that handles pages that are executed within the context of a chosen department. Some pages require a selected department, some don’t. The application is split into tiers, so I have a UI layer,business layer and data layer.

One of the customer requirements is that every change in the database is logged, this logging will occur in a separate database table. One of the fields in the logging is the selected department.

Because of the large amount of methods I wanted to implement a generic principle for transporting the current department, other than adding it to every method in every layer as a parameter. Something like

Thread.CurrentPrincipal.Identity.Name

 

It’s always there, and that rather helpful. It can be used in the data layer without passing it as a parameter.

A session variable won’t do, once it is set I will stay set. If I use a page that has no department context after a page that does, it will look like the page without a department context gets used in de department context. Unless I set and reset the session variable on every page… but that’s not a nice solution.

I would like to push the department on the callstack in the UI layer en pull it out again in the data layer. Took me some time to find it, but it can be done! CallContext is your friend, this is what it will do:

public void Method1()
{
   CallContext.SetData("Key", 1);
   Method2();
}

public void Method2()
{
    int value = (int)CallContext.GetData("Key");
}

Perfect for my problem, because this also works between different layers. According to MSDN this is the description:

Provides a set of properties that are carried with the execution code path.

So it can be used by all the methods in the callstack.

The rest is easy, create a BasePage class that inherits from Page for the pages with department context, and call the CallContext.SetData in the masterpage for the pages of the BasePage class.

Flores Eken

Author Flores Eken

I’m passionate about technology in general and particularly about software development and automation. Specializing in Infrastructure automation and Microsoft .NET, I can handle the entire process, from installing a Team Foundation Server to the smallest programming detail. Always innovating and on the cutting edge.

More posts by Flores Eken
20 November 2011

Leave a Reply