Archive for the ‘ASP.NET’ Category

.NET Stack Trace

April 19, 2012 Leave a comment

To get the current Stack Trace, use the following function

var s = new System.Diagnostics.StackTrace();

And to access the stack frames, look at the GetFrames() function


Finally if you need to know what is the current class and function name, you can use

var theMethod = s.GetFrames().First().GetMethod();

var theClassDotMethod = theMethod.ReflectedType + "." + theMethod.Name

Categories: ASP.NET

Azure Access Control Service Part 2 – Prerequisites for development

May 11, 2011 1 comment

In order to start development for ACS, you will need the following

  1. Windows Identity Foundation Runtime
  2. Windows Identity Foundation SDK
  3. Visual Studio 2010

Once installed properly, you will notice a add STS reference option inside Visual Studio when you right click a web application or a website project.

To get the required link, login to your management service portal ( )

Click on Application integration under Development.

Copy the url for WS-Federation Metadata

Now to add STS to your application

  1. Right click the project and click on “Add STS”
  2. Click Next for the first screen
  3. If you are prompted for something about not secure, ignore and click ok
  4. Select “Use an existing STS”
  5. Paste the link you copied previously into the textbox
  6. Click Next until complete


Your website is now configured to use Azure ACS to perform authentication.

To test if its working correctly, add the following code inside your default.aspx.cs

        foreach(var claim in (User.Identity as Microsoft.IdentityModel.Claims.ClaimsIdentity).Claims)
            Response.Write(claim.ClaimType + ” = ” + claim.Value + “<br />”);

In case you wish to know the default claims returned by each provider




If you have noticed, YES for some reason Windows Live only returns quite useless data unlike the other providers, not sure why this is so as this makes it extremely useless.


Categories: ASP.NET, Azure

XCode and TFS 2010 Part 2 – Setting up a new TFS project for SVN

January 4, 2011 Leave a comment

Sorry for the delay, what with all the holidays and stuff, didn’t have time to sit down and create the next part in this series.

Anyway here’s the second part in this series.


Setting up a new TFS project for SVN


Before i proceed, let me assure you that YES, XCode and TFS can be made to cooperate even though they are from fellow competitors.

Now that you have got part 1 working, its time to setup the team project to work properly with XCode. Unless you use TFS purely as a source code repository (which is kind of wasted), otherwise chances are you will need to create a new team project to cater to the SVN implementation.

Because XCode connects to TFS via a SVN bridge, the project itself can only be used for source control and nothing else.

This means that the following are no no

  1. Check in rules
  2. Check out rules
  3. Multiple check out



Categories: ASP.NET, Visual Studio

Tabcontrols and Multiple Gridviews

April 23, 2009 Leave a comment

If you have a TabContainer with multiple Tabs, and more than 1 tab have a gridview, any postback actions on the gridview will cause your tabcontainer to jump back to the first tab if you are not did not enclose the TabContainer in an update panel.

Digging into the source code reveals that the ClientStateField property is not updated each time a tab new tab is selected.

To workaround this, include the following javascript into the head of the document

function ActiveTabChanged(sender, e) {
sender.get_clientStateField().value = sender.saveClientState();

and inside the TabContainer set the OnClientActiveTabChanged="ActiveTabChanged"

Categories: ASP.NET

Performance of Generics SortedDictionary and Dictionary

April 16, 2009 5 comments

Based on a Vladimir Bodurov blog post on IDictionary options – performance test – SortedList vs. SortedDictionary vs. Dictionary vs. Hashtable, it seems to indicate that SortedDictionary is slower during inserts as compared to Dictionary but faster during searching.

However during the course of my development in ASP.NET 3.5, there have been several occasions which seems to contradict this behaviour, perhaps it is because he is using WinForms and i’m using ASP.NET. So i took his code, did some modification for it to run several rounds and in IIS and went off from there (The source code can be found at the bottom of the page)

The test procedure is exactly the same as what he did, except since its only 2 i did 2 sets of 20, First doing SortedDictionary then Dictionary (Test result 1 to 20) and the second set doing Dictionary then SortedDictionary (Test result 21 to 40).

The averages of both set do seem to indicate negligible differences in the execution sequence.

The results are extremely interesting. Dictionary outperforms SortedDictionary on all counts! Memory usage, insertion time and search time are all much lower for Dictionary compared to SortedDictionary!

Not really sure why this is so, but if i remember correctly Dictionary uses hashes, so my best guess is it is easier to search for a hash as compared to string comparison..

Time Taken for Search

Time Taken for Search

Time Taken for Insert

Time Taken for Insert

Memory Usage for Insert

Memory Usage for Insert

The generated raw results from the web application

Test Memory Insert (Time taken in Ticks) Search (Time taken in Ticks)
SortedDictionary Dictionary SortedDictionary Dictionary SortedDictionary Dictionary
1 53919472 53376100 48921833 13100780 488 132
2 53919484 53376100 47371977 12744252 647 72
3 53919468 53376088 47386173 12994452 209 69
4 53919340 53376124 47428627 15464752 239 71
5 53919484 53376112 47508765 13040552 211 68
6 53919644 53376100 48597956 13617493 216 71
7 53919484 53376100 49073226 13166390 404 71
8 53919484 53376100 48807615 13104169 229 69
9 53919484 53376088 48633159 12904931 278 89
10 53919484 53376088 49147736 13043290 243 72
11 53919484 53376100 48755009 12901049 221 68
12 53919484 53376100 48720694 12851970 216 65
13 53919484 53376088 48968614 13938456 278 76
14 53919484 53376124 47349876 13072479 232 69
15 53917592 53376112 47436475 13217946 374 263
16 53919496 53376100 47271521 12936580 279 85
17 53919484 53376088 49116031 14775245 228 64
18 53919496 53376076 47675434 13543449 258 79
19 53919496 53376088 47454095 13330955 219 62
20 53919484 53376100 49053229 12932112 236 73
Average (Set 1) 53919390.6 53376098.8 48233902.25 13334065.1 285.25 84.4
21 53919496 53376052 35231348 9248780 245 108
22 53919544 53376064 35237264 8211268 183 312
23 53919544 53376052 35354053 8161178 170 82
24 53919516 53376040 35166182 8433640 248 117
25 53919984 53376000 35340838 8559027 161 92
26 53919532 53376064 35446193 8515937 190 87
27 53919532 53376040 35425444 8307412 301 89
28 53919484 53376124 35207419 8468252 173 88
29 53919532 53376064 35275126 8100160 326 193
30 53919532 53376064 35484239 8119661 188 86
31 53919532 53376064 35604412 8484580 180 82
32 53919532 53376052 35550023 8283421 247 108
33 53919532 53376076 35213423 8398157 187 85
34 53919484 53376136 35264521 8527381 183 89
35 53919484 53376136 35383377 8723896 179 84
36 53919484 53376100 35232178 8567521 162 83
37 53919544 53376064 35054454 8132677 174 80
38 53919532 53376052 35188672 8193882 184 86
39 53919496 53376136 35265145 8709565 179 103
40 53919532 53376064 35123234 8095966 199 87
Average (Set 2) 53919542.4 53376072.2 35302377.25 8412118.05 202.95 107.05
Average 53919466.5 53376085.5 41768139.75 10873091.58 244.1 95.725

Source Code (.aspx.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Data;

public partial class test_cittka : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
DataTable tbl = new DataTable();

for (int i = 0; i < 20; i++)
DataRow row = tbl.NewRow();
sortedDictionary = new SortedDictionary<string, string>();
dictionary = new Dictionary<string, string>();
Insert_Test(“SortedDictionary”, sortedDictionary, row, 0, 2);
Insert_Test(“Dictionary”, dictionary, row, 1,3);
Search_Test(“SortedDictionary”, sortedDictionary, row,4);
Search_Test(“Dictionary”, dictionary,row,5);
GridView gv = new GridView();
gv.DataSource = tbl;
private readonly int searchIndex = 88888;
private readonly int numberRepetition = 500000;
private SortedDictionary<string, string> sortedDictionary = new SortedDictionary<string, string>();
private Dictionary<string, string> dictionary = new Dictionary<string, string>();

private void Insert_Test(string name, IDictionary<string, string> dict, DataRow row, int idxMemory, int idxInsert)
Response.Write(String.Format(“<br>——–Insert {0}——–“, name));
string[] letters = { “A”, “B”, “C”, “D”, “E”, “F”, “G”, “H”, “I”, “J” };
long memoryStart = System.GC.GetTotalMemory(true);
Stopwatch watch = new Stopwatch();
Random rand = new Random();
for (int i = 0; i < numberRepetition; i++)
string key = GetRandomLetter(letters, rand, i) + “_key” + i;
string value = “value” + i;

dict.Add(key, value);
long memoryEnd = System.GC.GetTotalMemory(true);
Response.Write(String.Format(“<br>Memory Allocated by {0} is: {1}bytes”,
name, memoryEnd – memoryStart));
row[idxMemory] = (memoryEnd – memoryStart).ToString();
row[idxInsert] = watch.ElapsedTicks.ToString();
private void Search_Test(string name, IDictionary<string, string> dict, DataRow row, int idx)
Stopwatch watch = new Stopwatch();
Response.Write(String.Format(“<br>——–Search {0}——–“, name));
Response.Write(String.Format(“<br>Found:{0}”, dict[“A_key” + searchIndex]));
row[idx] = watch.ElapsedTicks.ToString();
private void PrintResults(Stopwatch watch)
Response.Write(String.Format(“<br>Elapsed: {0}”, watch.Elapsed));
Response.Write(String.Format(“<br>In milliseconds: {0}”, watch.ElapsedMilliseconds));
Response.Write(String.Format(“<br>In timer ticks: {0}”, watch.ElapsedTicks));
private string GetRandomLetter(string[] letters, Random rand, int i)
if (i == searchIndex)
return “A”;
return letters[rand.Next(0, 10)];

Categories: ASP.NET, Performance

HttpRunTime Cache vs Enterprise Library Cache

March 28, 2009 1 comment

This post aims to highlight the differences between the cache implementation of HttpRunTime and EnterpriseLibrary

HttpRuntime.Cache Enterprise Library Caching Block
Standard Actions
Add Item to Cache
Read Item from Cache
Update Item to Cache (using insert) (using add)
Delete Item from Cache
Flush all Items in Cache
Enumeration Actions
Enumerate all items in cache
Employ LINQ Expressions
Cache Dependencies
Cache Dependency – File
Cache Dependency – Other Cache Item (write your own extension)
Expiration – Absolute Time
Expiration  – Sliding Time
Expiration – Extended Formats

* Extended time format

“<Minute> <Hour> <Day of month> <Month> <Day of week>”

* means run every period


o “* * * * *” expires every minute

o “5 * * * *” expire 5th minute of every hour

o “* 21 * * *” expire every minute of the 21st hour of every day

o “31 15 * * *” expire 3:31 PM every day

o “7 4 * * 6” expire Saturday 4:07 AM

o “15 21 4 7 *” expire 9:15 PM on 4 July

Item priority
Run function when item is removed
Get number of items in cache
Limit number of items in cache
Can use persistent Storage
Run function to refresh item when expires
Categories: ASP.NET, General, Uncategorized

ASP.NET and Web Gardens

March 26, 2009 2 comments

When you are running your ASP.NET applications inside an application pool with only 1 worker process, everything works as expected. But things usually do not go so smoothly when you run the same application inside a web garden.

What is a web garden

Simply put, a web garden is a single web server running multiple IIS processes. The good thing about this is, there are multiple process which can service your http/https calls. So if a client is holding up one process, the other processes can still continue. Also if a particular process were to hang and restart itself, your website will still continue to serve clients as the other processes are running.

Read more about Microsoft’s explanation of web garden here

The article clearly states that

all processes have their own copy of application state, in-process session state, caches, and static data

Let us examine each one of these and see what we can do to workaround it

Application state

Problem Statement

As each process has their own application state, whatever you change in one process will not be updated in another process. As this exists purely for backward compatibility with classic ASP applicationstate, Microsoft does not recommend using this alot, especially for read/write operations.


Use Cache instead of ApplicationState if you can.
Cached Items

Problem Statement

Be it HttpRunTime.Cache or Enterprise Library Cache, the cache will not reflect latest updates inside a web garden. This is because only the worker process which updated the Cache Item will see the updated values, the other worker processes will not be notified that a change has happened and will continue using the value stored in their in memory cache.


There are a few paid solutions, and the only free one so far which is able to address this is can be found at or

Session state

Problem Statement

Using web gardens, you will find that the session values gets rotated around. Again this is due to the fact that different worker process is handling your request, and each worker process has its own session state management.


Simply change the inproc to either State Server or SQL Server to store the session state outside of the worker process. Performance will degrade when using either of these 2 options, but at least you can be assured of the persistancy of the data

Categories: ASP.NET, Development

Updating Active Directory using ASP.NET 3.5

March 25, 2009 6 comments

It is extremely easy to use ASP.NET to manage your Active Directory Users. This article shall list some of the common scenarios which is most frequently used.

Points to ensure

  1. add the reference to System.DirectoryServices
  2. The account running the website must have the appropriate access to the AD

Get Users in Group

result =

de = getEntry())
obj = de.Properties[



CN = obj.ToString(),
ID = Regex.Match(obj.ToString(),

if (obj

in (object[])obj)


CN = o.ToString(),
ID = Regex.Match(o.ToString(),


result = result.OrderBy(p => p.ID).ToList();


Delete Users in Group

using (var
de = getEntry())


foreach (UserID_CN
in GetUsersInGroup)







Add Users to Group


Get all properties of directory entry



// Each property contains a collection
of its own

// that may contain multiple values

Label1.Text += “–“
+ key +

object propVal
in dirEntry.Properties[key]


(propVal.GetType() ==


Label1.Text += “(“;

for (int

Label1.Text += (char)

Label1.Text += “)<br>”;


(propVal.GetType().ToString() ==





Label1.Text += “(“;

long val_int64 =
GetInt64(dirEntry, key);

//DateTime dt =



if (val_int64 >


DateTime T =

Label1.Text += T.ToString(“dd MMM yyyy
) + “)<br>”;









Label1.Text += val_int64 + “)<br>”;





Label1.Text += “(“
+ propVal +




Label1.Text += “(“
+ propVal +



Label1.Text += “—————<br>”;

Categories: ASP.NET, Uncategorized

Application Caching

March 22, 2009 Leave a comment


ASP.NET offers several forms of caching. They are output caching, HttpRuntime.Cache and finally Enterprise Library Cache. Each of these aims to meet the requirements of different scenarios.

This article shall explore the scenarios which each of these best fit.

Output caching

There are 2 variants of output caching, you can either cache the whole page or portions of the page (these portions must be in the form of user controls)

This is commonly used when the steps to reproduce the page is huge (e.g large database calls, long file read times, huge processing requirements), but the output does not change frequently, e.g a FAQ page listing all the FAQs and employing javascript for inline fuzzy search (employing different scripts for different browsers)

When you use output caching, the output is cached for a specific duration e.g 120 seconds and can be set to vary based on different parameters e.g querystring, browser. In the previous scenario of the FAQ page, you can use the VaryByCustom=”browser” parameter to cache and vary the output based on different browsers.

MSDN on Output Caching


HttpRuntime.Cache is used to store serializable objects in a cache for future use. This cache is more powerful compared to output caching, but using it requires more work. This is frequently used to cache the return data in business layers.

If you do not wish to bother about the technicalities behind this cache, you can easily add to it via the following code

HttpRuntime.Cache[“key”] = value

This will add the item to the cache with default values for all parameters. Alternatively you can look at the complete  declaration for adding an item to the cache

public Object Add(
string key,
Object value,
CacheDependency dependencies,
DateTime absoluteExpiration,
TimeSpan slidingExpiration,
CacheItemPriority priority,
CacheItemRemovedCallback onRemoveCallback

This allows you to add a serializable object to the cache with

  • Dependencies: This indicates that this cache item is dependent on another object (usually a file), so when the dependency is changed, the cache object is automatically removed from the cache.
  • Absolute Expiration: This indicates that the cache item will expire after a fixed amount of time. Once the object expires, it is removed from the cache
  • Sliding Expiration: This tells the cache to extend the cache item a fixed amount of time each time the cache item is accessed. Once this amount of time is reached and the cached item is not accessed, it will expire
  • Priority: This tells the cache the priority of the cache item. This comes into effect when the cache is full and items needs to be removed. Items with a lower priorities are removed first.
  • CacheItemRemovedCallback: This is a delegate function which is run when the item is removed from the cache, the key, value and reason for removal is sent to this function so that you can do the appropriate processing.

MSDN on HttpRuntime.Cache

Enterprise Library Cache

There are 5 main differences between this and HttpRuntime.Cache. If your needs meet any one of these points, then it is recommended that you use Enterprise Library Cache.

  1. The cache is stored independently of the web server, so even if you were to do an iisreset, the cache still remains
  2. You can configure the cache to be stored in a persistent backing store e.g SQL Server
  3. There can be multiple caches serving different needs in the same web application
  4. You need more control over expiration policies
  5. You do not need to know when the item expires, but you want to be able to reload the item if required

MSDN on Enterprise Library Caching Block


  1. Output caching: Used to store the page output so that ASP.NET does not need to render the content again
  2. HttpRuntime.Cache: Used by your web application to store items in a cache, the items will disappear when the website is reset
  3. Enterprise Library Cache: Separate cache mechanism which has its own memory and data store, is not affected by server restarts (if using persistent backing store)


  1. All of these caches is restricted to application domain scope, i.e you cannot share them across different application domains (e.g in web garden or multi server environment)
Categories: ASP.NET, Development

ASP.NET Advanced Grid View

February 18, 2009 Leave a comment

ASP.NET’s GridView is great, but admittedly there are limitations to what it can do.

Some nice features which are missing include

  1. Advanced Search
  2. Print
  3. Save

I’ve written an advanced gridview class which is able to perform all these

GridView Design Mode

This gridview comes with the ability to

  • Display Create button which goes to another url when clicked
  • Save button to save all the records in the Gridview (yes all the records)
  • Print button to print all the records in the GridView (same as save button, but will pop up a new window to do the print)
  • Advanced Search which gives you “google like” search e.g using “+” , “-“, quotation marks to mark words as one key term, OR. e.g aaa bbb “”ccc ddd”” +eee -fff OR ggg

Custom properties defined in this Gridview allow you to customize the top search portion

GridView Additional Properties

Click here to download the class and use it in your code

Categories: ASP.NET, Uncategorized