Archive

Archive for March, 2009

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

Examples

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

Others
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
Advertisements
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.

Workaround

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.

Workaround

There are a few paid solutions, and the only free one so far which is able to address this is can be found at http://enyimmemcached.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=13095 or http://www.codeproject.com/KB/aspnet/memcached_aspnet.asp

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.

Workaround

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

Custom Controls

March 25, 2009 Leave a comment

ASP.NET makes custom controls extremely easy to write, but if you are not careful, hard to manage.

There are 2 ways to create a custom control

  1. Writing your own HTML code
  2. Using the controls property

Writing your own HTML code

Using your own properties, you can easily write HTML code to generate the
output

e.g consider a simple scenario where you take in a text and color input and
render the control.

You can simply create a class and extend it from the WebControl base class to
have the functions available to your custom control.
Thereafter, just create the properties you require and use them inside the
Render function.
Do note that you can render different output when in design mode and actual
rendering, all you need is to check the DesignMode property.
If however you need input boxes, do take note that you need to handle the
postback event and put the value back into the inputs manually.

public class
SimpleControl :
WebControl

{

public
SimpleControl()

{

}

[BindableAttribute(true),
Category(“UI”),
DefaultValue(“”)]

public
string Text

{

get

{

object obj =
this.ViewState[“Text”];

if (obj ==
null)
return
“”;

else
return obj.ToString();

}

set {
this.ViewState[“Text”]
=
value; }

}

[BindableAttribute(true),
Category(“UI”),
DefaultValue(“”)]

public
string Color

{

get

{

object obj =
this.ViewState[“Color”];

if (obj ==
null)
return
“”;

else
return obj.ToString();

}

set {
this.ViewState[“Color”]
=
value; }

}

protected
override
void Render(HtmlTextWriter
writer)

{

writer.Write(“<font color='”
+ Color +
“‘>” +
Text +
“</font>”);

//base.Render(writer);

}

}

Using the controls property

The good thing about using the controls property is that you do not need to
care about ViewState (it is handled by the individual control), Postback
inputs handling (handled again by the individual control).

The bad thing is

  1. Have to write your own custom event handlers
  2. Everything needs to be control based, you cannot emit your own html.

public class
LabelExtendedControl
:
Label

{

public
SimpleControl()

{

}

[BindableAttribute(true),
Category(“UI”),
DefaultValue(“”)]

public
string xText

{

get

{

object obj =
this.ViewState[“Text”];

if (obj ==
null)
return
“”;

else
return obj.ToString();

}

set {
this.ViewState[“Text”]
=
value; }

}

[BindableAttribute(true),
Category(“UI”),
DefaultValue(“”)]

public
string xColor

{

get

{

object obj =
this.ViewState[“Color”];

if (obj ==
null)
return
“”;

else
return obj.ToString();

}

set {
this.ViewState[“Color”]
=
value; }

}

protected
override
void Render(HtmlTextWriter
writer)

{

this.Text = xText;

this.ForeColor =
System.Drawing.
Color.FromKnownColor(xColor);

base.Render(writer);

}

}

Custom Events

To create your own custom events, you need
to write 3 main items

  1. A readonly object containg the event
  2. A function which will call the Event
  3. The actual event handler itself

private
readonly
object EventCreate =
new
object();

protected
virtual
void OnCreate(EventArgs
e)

{

EventHandler
onCreateHandler = (
EventHandler)Events[EventCreate];

if
(onCreateHandler !=
null)
onCreateHandler(
this,
e);

}

[Category(“Action”),Description(“Raised
when a CommandEvent occurs within an item.”
)]

public
event
EventHandler Create

{

add

{

Events.AddHandler(EventCreate, value);

}

remove

{

Events.RemoveHandler(EventCreate, value);

}

}

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

List<UserID_CN>
result =
new
List<UserID_CN>();

using
(var
de = getEntry())
{
object
obj = de.Properties[
“member”].Value;

if
(obj
is
string)
{

result.Add(new
UserID_CN()
{

CN = obj.ToString(),
ID = Regex.Match(obj.ToString(),
“CN=(.*?),”,
RegexOptions.IgnoreCase).Groups[1].Value

});
}
else
if (obj
is
object[])
{

foreach
(object
o
in (object[])obj)

{
result.Add(new
UserID_CN()
{

CN = o.ToString(),
ID = Regex.Match(o.ToString(),
“CN=(.*?),”,
RegexOptions.IgnoreCase).Groups[1].Value

});
}
}
else

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

return
result;
}

Delete Users in Group

using (var
de = getEntry())

{

foreach (UserID_CN
u
in GetUsersInGroup)

{

de.Properties[“member”].Remove(u.CN);

}

de.CommitChanges();

de.Close();

}

Add Users to Group

de.Properties[“member”].Add(userDN);

Get all properties of directory entry

foreach(string
key
in
dirEntry.Properties.PropertyNames)

{

// Each property contains a collection
of its own

// that may contain multiple values

Label1.Text += “–“
+ key +
“–<br>”;

foreach(
object propVal
in dirEntry.Properties[key]
)

{

if
(propVal.GetType() ==
typeof(System.Byte[]))

{

Label1.Text += “(“;

for (int
i=((
byte[])propVal).GetLowerBound(0);i<((byte[])propVal).GetUpperBound(0)+1;i++)

Label1.Text += (char)
((
byte[])propVal)[i];

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

}

else
if
(propVal.GetType().ToString() ==

“System.__ComObject”
)

{

try

{

Label1.Text += “(“;

long val_int64 =
GetInt64(dirEntry, key);

//DateTime dt =
DateTime.FromFileTime(val);

try

{

if (val_int64 >
0)

{

DateTime T =
DateTime.FromFileTime(val_int64);

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

}

else

{

throw
new
Exception();

}

}

catch

{

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

}

}

catch

{

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

}

}

else

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

}

}

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

Categories: ASP.NET, Uncategorized

Application Caching

March 22, 2009 Leave a comment

Introduction

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

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

Summary

  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)

Caveats

  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