Thursday, March 27, 2008


  • Use the ON DELETE CASCADE option to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table.
  • If you do not specify cascading deletes, the default behavior of the database server prevents you from deleting data in a table if other tables reference it.
  • If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table.
  • The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.

Here is a demo on how to do it:

1. Create tables.

2. Add foreign key.


5. Delete a row in the parent table.

6. Child table rows got deleted as well.
If you having a M-to-M relationship, it is the same. Just add the cascade delete on the M-to-M table.

Wednesday, March 26, 2008

Sites, Site collection & Web Application

Site Collection (SPSite)
  • The Site Collection is the root site of the web site.
  • A site collection consists of a top-level site and its subsites.
  • It is a logical unit for administration - there are settings that can only be configured at the site collection level (in other words, at the top-level site).

Site (SPWeb)

  • Must belongs to a Site Collection.
  • A Site can contains sub sites.

Web Application (SPWebApplication)

  • Just a web application in IIS
  • Each Web application can host many site collections.
  • A web application needs to have at least one Site Collection


Essential SharePoint 2007

Thursday, March 20, 2008

Virtual Directory

Here is just a scenario where I use virtual directory in IIS as opposed to virtual application.

If you have a big Visual studio solution which has several core projects under it and this solution applies on almost all the clients' web sites. And on occasion, you want to include a customisation project in the solution for a particular client. During testing, you need to run this customisation as part of the main product on your localhost for this client. And since the customisation is not the part of the main product, the folder is in another location. You can however put the customisation in your main product root folder, but if you want your customisation located elsewhere, here are the steps you can do to run your customisation on your local:

  • Firstly, you will need to copy the dlls of the customisation project and put them in the bin folder of the core product.
  • Secondly, you will need to create a virtual application under the core project's IIS application. And right click the application, go to property, and then click the remove button. For example, say your core product can be accessed through then the customisation will be accessed through

Wednesday, March 19, 2008

UpdatePanel with IE back button

This is yet another Ajax problem I have encountered.

I have a data listing page contains a gridview which has a ButtonField column which has a CommandName="edit". In code behind where I handle the OnRowEditing GridViewEditEvent, I have a Response.Redirect in this OnRowEditing Sub to redirect to the detail page. So if you run the page, and view the source, the edit button will be wrapped with a __doPostBack js function.

Now I have the gridview inside the updatepanel, the gridview has paging enabled. When I clicked the page 4, and on page 4 of the gridview I clicked the edit button on any row, it redirect me to the detail page, that's fine. But when I click the IE7 back button, since the browser caches the page content, it will go back to where I was which is the page 4 of the gridview. But actually, it didn't. It went to page 1 of the gridview.

So I put a breakpoint in the page_load of the page, and when I click the back button, the page_load was hit which is not normally the case. Now if you click any edit button on page 1, if will throw you an exception saying "Invalid Callback Or Postback Argument". That's reasonable since the content posted back(page 1) is not the content it suppose to be (page 4).

Since the page that is dynamically created will not automatically register with the history engine of the browser, the back button will not work in this case.

There are fixes available for this problem:

Back Button Support for Atlas UpdatePanels

UpdateControls: UpdateHistory and AnimatedUpdatePanel

But I personally don't want to use it since it is not the Microsoft official solutions.

Ajax UpdatePanel has problems with 'action' keyword

I came across a problem when I was trying to use the updatepanel within an page. Basically, when I click a button in the page, it is still a normal postback as opposed to an asynchronous postback. What I found is that there was a hidden field named 'action' that conflicts with the Ajax library. So if we rename it to 'action1', it will sure work.

Tuesday, March 18, 2008

Web Part (2)


  • When a user makes changes to a Web Part’s properties, the Web Part Framework automatically saves these changes. For example, a user can add one or more Web Parts to a page and arrange the Web Parts with a particular layout. If the user returns to the page in the future, the Web Parts will remember the layout. This feature of the Web Part Framework is called personalization.
  • The Web Part Framework supports two types of personalization: User and Shared.
  • By default, all changes made to a Web Parts page have User scope.
  • An administrator of a Web Part application can make changes that have an effect on everyone who uses the application.
  • The default personalization provider in the Web Part Framework requires that users be authenticated. If you use the default provider, then an unauthenticated user can browse, but not customize, a Web Part application.

Creating web part:

  • The easiest way to create new Web Parts is to create User Controls.
  • Every page that contains Web Parts must include one, and only one, WebPartManager control.
  • The WebPartManager control is responsible for tracking the state of all the Web Parts on the page.
  • The WebPartManager control must appear before any other Web Parts on the page. It is a good idea to place the WebPartManager control immediately after the server-side form control in the page.

Web Part Property Attributes

  • Personalizable attribute: Any property marked with the Personalizable attribute is automatically saved and loaded by the Web Part Framework.
  • WebBrowsable attribute: Only properties marked with the WebBrowsable attribute are displayed in the property grid rendered by the PropertyGridEditorPart control.


ASP.NET 2.0 Unleashed

Monday, March 17, 2008

Web Part (1)

Types of zones included in the Web Part Framework:

  • Web Part Zones —This type of zone is used to render Web Parts. You can add Web Parts to a Web Part Zone and drag and drop Web Parts between different Web Part Zones.
  • Editor Zones—This type of zone is used to render Editor Parts. Use Editor Parts to enable a user to edit Web Part properties.
  • Catalog Zones—This type of zone is used to render Catalog Parts. Use Catalog Parts to display lists of Web Parts that a user can add to a page.
  • Connections Zones—This type of zone is used to display an interface that enables users to connect Web Parts dynamically.

A page can be in one of the following Display Modes:

  • Browse—The default mode. In this mode, you cannot rearrange or edit Web Parts.
  • Design—In this mode, you can drag and drop Web Parts from one Web Part Zone to
  • Edit—In this mode, you can edit a Web Part’s properties by using one or more Editor Parts.
  • Catalog—In this mode, you can add new Web Parts to a page from one or more Catalog Parts.
  • Connect—In this mode, you can create dynamic connections between Web Parts.

ASP.NET 2.0 Unleashed

Thursday, March 13, 2008

Page_Init vs Page_Load

  • During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.
  • During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.
  • Use Page_Init when you have to create controls dynamically. The controls are created every time that the page is run. The best place to do this is in the Page_Init function.


ASP.NET Page Life Cycle Overview

HOW TO: Dynamically Create Controls in ASP.NET with Visual Basic .NET

Wednesday, March 12, 2008

global.asax vs httpmodule

  • The idea is that if you implement a httpmodule, you will need to implement the Ihttpmodule interface. And then you will need to implement the init method of the Ihttpmodule interface.
  • The init method take an object of the httpapplication as a parameter. So that in the init method of this httpmodule class you can hook up an event handler for all the events of the httpapplication object. For example, you can hook up the beginrequest event or error event.
  • But since doing this in a class encourages code reuse because you can compile the module class into a dll and reference it, it is preferable to use httpmodule as oppose to global.asax.
  • You can also separate different logics into different module classes to tidy up the code.
  • You can also add/remove httpmodule by modifiying the web.config without re-compiling
  • The only time you want to use Global.asax is when using OutputCaching with the VaryByCustom property.

HttpModule is used for handling application level events, here are some examples of using httpmodule:

  • User/AD authentication
  • Url rewriting
  • Handling application_error


Global.asax? Use HttpModules Instead!

Global.asax or an HttpModule?

Log4Net tips

  • If you want to store connection string in one place in the web.config, you can remove the connectionString node under AdoNetAppender. And set the ConnectionString property of the log4net.Appender.ADONetAppender at code behind. You need to make it a function and then put this function in the Application_Start of the global.asax.vb file. So next time instead of calling log4net.Config.DOMConfigurator.Configure(), you can call this function. Here is how you can do it.
  • If you want to add more columns to the log table, say the client's IP address. You will need create the column in the log table. And then modified the commandText node to insert the IP address to the log table under AdoNetAppender in the web.config. Also need to add the parameter node for the IP address. Then use the MDC.Set(...) function to set the IP address in the code behind before call the logger.Error(...) function. Here is an good example.

Thursday, March 6, 2008

XPath to find an attribute value (2)

I wanted to find the first occurrence of 'yweather:forecast' node and then find the value of the 'low' attribute. Here is how I got it:

Dim dom As XmlDocument = New XmlDocument


Dim lowTempPath As String = "/rss/channel/item/*[local-name()='forecast']/@low"

Dim lowTemp As String = dom.SelectSingleNode(lowTempPath).InnerText

local-name function:

The local-name function returns the name of the XML element in the local context. Therefore, if an XML element has a namespace prefix, it’s considered to be within that namespace. Using local-name removes the namespace prefix and returns the raw element name.

Professional BizTalk Server 2006

XPath to find an attribute value (1)

The following is the XML which I need to examine:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

<rss version="2.0" xmlns:yweather="" xmlns:geo="">



    <title>Yahoo! Weather - Sydney Regional Office, AS</title>


    <description>Yahoo! Weather for Sydney Regional Office, AS</description>


    <lastBuildDate>Thu, 06 Mar 2008 9:30 pm AEDT</lastBuildDate>


    <yweather:location city="Sydney Regional Office" region=""  country="AS"/>

    <yweather:units temperature="C" distance="km" pressure="mb" speed="kph"/>

    <yweather:wind chill="23"  direction="30"  speed="16.09" />

    <yweather:atmosphere humidity="78"  visibility="9.99"  pressure="0"  rising="1" />

    <yweather:astronomy sunrise="6:47 am"  sunset="7:25 pm"/>


      <title>Yahoo! Weather</title>







      <title>Conditions for Sydney Regional Office, AS at 9:30 pm AEDT</title>




      <pubDate>Thu, 06 Mar 2008 9:30 pm AEDT</pubDate>

      <yweather:condition  text="Fair"  code="33"  temp="23"  date="Thu, 06 Mar 2008 9:30 pm AEDT" />



<img src=""/><br />

<b>Current Conditions:</b><br />

Fair, 23 C<BR />

<BR /><b>Forecast:</b><BR />

Thu - Clear. High: 27 Low: 17<br />

Fri - Mostly Sunny. High: 26 Low: 19<br />

Sat - AM Showers. High: 25 Low: 19<br />

Sun - Sunny. High: 26 Low: 16<br />

Mon - Sunny. High: 26 Low: 16<br />

<br />

<a href="*">Full Forecast at Yahoo! Weather</a><BR/>

(provided by The Weather Channel)<br/>



      <yweather:forecast day="Thu" date="6 Mar 2008" low="17" high="27" text="Clear" code="31" />

      <yweather:forecast day="Fri" date="7 Mar 2008" low="19" high="26" text="Mostly Sunny" code="34" />

      <yweather:forecast day="Sat" date="8 Mar 2008" low="19" high="25" text="AM Showers" code="39" />

      <yweather:forecast day="Sun" date="9 Mar 2008" low="16" high="26" text="Sunny" code="32" />

      <yweather:forecast day="Mon" date="10 Mar 2008" low="16" high="26" text="Sunny" code="32" />

      <guid isPermaLink="false">ASXX0274_2008_03_06_21_30_AEDT</guid>




<!-- compressed Thu Mar  6 02:59:57 PST 2008 -->

Sunday, March 2, 2008

Finalization (2)

Finalization list:
  • If the object's type defines a Finalize method, a pointer to the object is placed on the finalization list just before the type's instance constructor is called.
  • The finalization list is an internal data structure controlled by the garbage collector.
  • Each entry in the list points to an object that should have its Finalize method called before the object's memory can be reclaimed.
  • Even though System.Object defines a Finalize method, the CLR knows to ignore it; that is, when constructing an instance of a type, if the type's Finalize method is the one inherited from System.Object, the object isn't considered finalizable. One of the derived types must override Object's Finalize method.

Freachable queue:

  • When a garbage collection occurs, some objects are determined to be garbage. The garbage collector scans the finalization list looking for pointers to these objects. When a pointer is found, the pointer is removed from the finalization list and appended to the freachable queue.
  • The freachable queue is another of the garbage collector's internal data structures.

Dedicated Thread:

  • A special high-priority CLR thread is dedicated to calling Finalize methods.
  • When the freachable queue is empty, this thread sleeps. But when entries appear, this thread wakes, removes each entry from the queue, and then calls each object's Finalize method.
  • So if an object is in the freachable queue, the object is reachable and is not garbage.
  • The next time the garbage collector is invoked, it will see that the finalized objects are truly garbage because the application's roots don't point to it and the freachable queue no longer points to it either. The memory for the object is simply reclaimed.
  • Two garbage collections are required to reclaim memory used by objects that require finalization. In reality, more than two collections will be necessary because the objects get promoted to another generation.

CLR via C#

Saturday, March 1, 2008

Finalization (1)


  • Finalization is a mechanism offered by the CLR that allows an object to perform some graceful cleanup prior to the garbage collector reclaiming the object's memory.
  • Finalizers should release unmanaged resources only. You very rarely need to use finalization with managed resources.
  • Any type that wraps a native resource, such as a file, network connection, socket, mutex, or other type, must support finalization.
  • The framework does not guarantee that a finalizer will execute at all on any given instance.

Finalize method:

  • Basically, the type implements a method named Finalize. When the garbage collector determines that an object is garbage, it calls the object's Finalize method.
  • The earlier versions of the C# Programming Language Specification called this method a destructor.
  • The problem is that developers mistakenly believe that using the C# destructor syntax means that the type's objects will be deterministically destructed, just as they would be in C++. However, the CLR doesn't support deterministic destruction.
  • In version 2 of the C# Programming Language Specification, a method using this syntax is now officially called a finalizer.
  • You have no control over when the Finalize method will execute.
  • The CLR doesn't make any guarantees as to the order in which Finalize methods are called

What Causes Finalize Methods to Be Called:

Finalize methods are called at the completion of a garbage collection, which is started by one of the following five events. The following force a GC to start:

  • Generation 0 is full (most common way for Finalize methods to be called)
  • Code explicitly calls System.GC's static Collect method (Microsoft strongly discourages)
  • Windows is reporting low memory conditions (If Windows reports low memory, the CLR will force a garbage collection in an effort to free up dead objects to reduce the size of a process' working set.)
  • The CLR is unloading an AppDomain.
  • The CLR is shutting down.

What might cause the Finalize method not to execute:

  • The CLR uses a special, dedicated thread to call Finalize methods. For the above first four events, if a Finalize method enters an infinite loop, this special thread is blocked, and no more Finalize methods can be called. This is a very bad situation because the application will never be able to reclaim the memory occupied by the finalizable objects—the application will leak memory as long as it runs.
  • Under low memory conditions, the CLR might not be able to find enough memory in order to compile the Finalize method, which would prevent it from executing causing the native resource to leak.
  • Or the resource might not be freed if the Finalize method contained code that referred to a type in another assembly, and the CLR failed to locate this other assembly.


  • You can use CriticalFinalizerObject class which guarantees that the native resource will be released.

SafeHandle Types:

  • The SafeHandle-derived classes are extremely useful because they ensure that the native resource is freed when a garbage collection occurs.

CLR via C#

Garbage Collection

Unmanaged resourse:

  • Most types, including String, Attribute, Delegate, and Exception, represent resources that don't require any special cleanup.
  • A type that represents an unmanaged or native resource, such as a file, a database connection, a socket, a mutex, a bitmap, an icon, and so on, always requires the execution of some cleanup code when the object is about to have its memory reclaimed.


  • Every application has a set of roots.
  • A single root is a storage location containing a memory pointer to a reference type object.
  • Only variables that are of a reference type are considered roots; value type variables are never considered roots.

Two phases:

1. Marking phase:

  • GC go through the stack, checking all the roots, if a root is found to refer to an object, the object is marked.
  • Once all of the roots have been checked, the heap contains a set of marked and unmarked
  • The marked objects are reachable via the application's code, and the unmarked objects
    are unreachable.
  • The unreachable objects are considered garbage, and the memory that they occupy can be reclaimed.

2. Compact phase:

  • This is when the collector traverses the heap linearly looking for contiguous blocks of unmarked (garbage) objects.
  • If small blocks are found, the garbage collector leaves the blocks alone. If large free contiguous blocks are found, however, the garbage collector shifts the nongarbage objects down in memory to compact the heap.

3 Generations:

  • Generations are a mechanism within the CLR garbage collector whose sole reason for being is to improve an application's performance.
  • Objects in generation 0 are newly constructed objects that the garbage collector has never examined.
  • When the CLR initializes, it selects a budget size for generation 0 of, say, 256 KB. (The exact size is subject to change.) So if allocating a new object causes generation 0 to surpass its budget, a garbage collection must start.
  • After one collection: generation 0 survivors are promoted to generation 1; generation 0 is empty.
  • When the CLR initializes, it selects a budget for generation 0. It also selects a budget for generation 1. Let's say that the budget selected for generation 1 is 2 MB.
  • If generation 1 occupies less than 2 MB, so the garbage collector examines only the objects in generation 0 which will speed up the garbage collection process.
  • So if allocating a new object causes generation 0 to surpass its budget, a garbage collection must start. Generation 0 survivors are promoted to generation 1. At this time, if generation 1's budget is full, generation 1 survivors are promoted to generation 2.
  • The managed heap supports only three generations: generation 0, generation 1, and generation 2; there is no generation 3.
  • When future collections occur, any surviving objects currently in generation 2 simply stay in generation 2.


  • The newer an object is, the shorter its lifetime will be.
  • The older an object is, the longer its lifetime will be.
  • Collecting a portion of the heap is faster than collecting the whole heap.

CLR via C#