Wednesday, October 7, 2009

VS2008 Remote Debugging

First you need to create a user on your desktop and the remote machine with the same username and password on both machines.
Make sure msvsmon.exe is installed on the remote computer. It should be in your Visual studio 2008 directory.
on the remote computer do a runas /user:debuguser c:\fullpath\msvsmon.exe
where debuguser is the user you created above
You should see a window popup saying "3/31/2009 12:22:56 PM Msvsmon started a new server named 'debuguser@TSIK2552100'. Waiting for new connections."
now on your desktop do a runas /user:debuguser "c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe"
where debuguser is again the user you created above
the load your project and go to attach to process, enter debuguser@remotemachinename in the Qualifier box and you may need to select the show processes from all users check box. select your process and you should be able to debug.

Monday, September 28, 2009

Enable Sql Server Authentication Mode Over Network

Check the followings:
1. Right click the root node on Object Explorer, in Server Properties window->Security->Server authentication: SQL Server and Windows Authentication mode
2. Create a new user for login.
3. Right click the user on Object Explorer, in Login Properties window:
    3.1 User Mapping: Check the desired database to access
    3.2 Status->Permission to connect to database engine: Grant; Login: Enabled
4. Sql Server Configuration Manager -> Enable TCP/IP and Named Pipes

Thursday, September 17, 2009

Object.GetHashCode, Object.Equals, operator==, and related

After some research, I summarize some points below as guidelines.

1. Object.Equals method and operator== are supposed to be used interchangeably. (It applies to all the .net classes) Therefore, when implementing a new class, it's a good idea to always implement both of them.
Equals() is usually used (implemented) for value equality and Operator== is used for reference equality by default. When a type is an immutable type (e.g. String), overloading Operator== to compare value equality makes sense.

Guidelines for Overloading Equals() and Operator==

Override equals on overloading operator equals

When should I use == and when should I use Equals

2. It is important to override GetHashCode when overriding Equals method. Although failure to do so will not always break your code, things can go wrong if the class is used as a key in a dictionary etc. In that situation, if the hash-code for two items does not match, they may never be considered equal (Equals will never be called). To write the GetHashCode, we need to make sure that: if two objects are equal, then they must return the same value for GetHashCode. On the other hand, we do NOT have to make sure two different objects always return different values for GetHashCode.

Why is it important to override GetHashCode when Equals method is overriden in C#

3. A good implementation of GetHashCode that can be used in many situations:
public int GetHashCode()
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + field1.GetHashCode();
hash = hash * 23 + field2.GetHashCode();
hash = hash * 23 + field3.GetHashCode();
return hash;
What is the best algorithm for an overridden System.Object.GetHashCode

4. Implementing IEquatable Properly

Tuesday, August 25, 2009

Sql Server Script to Restore a Database

use master

alter database DBName
set single_user with rollback immediate

restore database DBName
from disk = 'C:\DBBackup.bak'

-- use the following to overwrite log in case the log file was not backed up
with replace

Tuesday, August 18, 2009

SQL Commands - Disable Constraints

The following commands are from this URL

--Disable Constraints & Triggers
exec sp_MSforeachtable 'ALTER TABLE ? DISABLE TRIGGER ALL'

--Perform delete operation on all table for cleanup
exec sp_MSforeachtable 'DELETE ?'

--Enable Constraints & Triggers again
exec sp_MSforeachtable 'ALTER TABLE ? ENABLE TRIGGER ALL'

--Reset Identity on tables with identity column
exec sp_MSforeachtable 'IF OBJECTPROPERTY(OBJECT_ID(''?''), ''TableHasIdentity'') = 1 BEGIN DBCC CHECKIDENT (''?'',RESEED,0) END'

I found the commands are very useful. For example, I once got the foreign key constraint error when trying to import data into my database. I executed the first two commands to disable constraints and triggers first, then imported the data, the errors were gone. After importing data, I then executed the last three commands to re-enable and reset stuff.

Wednesday, July 22, 2009

WaitCallback method has to be static

The following is a demo for using WaitCallback delegate. Note that the method ThreadProc has to be static.

using namespace System;
using namespace System::Threading;
ref class Example

// This thread procedure performs the task.
static void ThreadProc( Object^ stateInfo )

// No state object was passed to QueueUserWorkItem, so
// stateInfo is 0.
Console::WriteLine( "Hello from the thread pool." );


int main()

// Queue the task.
ThreadPool::QueueUserWorkItem( gcnew WaitCallback( Example::ThreadProc ) );
Console::WriteLine( "Main thread does some work, then sleeps." );

// If you comment out the Sleep, the main thread exits before
// the thread pool task runs. The thread pool uses background
// threads, which do not keep the application running. (This
// is a simple example of a race condition.)
Thread::Sleep( 1000 );
Console::WriteLine( "Main thread exits." );
return 0;

If it's not static, we'll get the following error:
error C3867: 'Example::ThreadProc': function call missing argument list; use '&Example::ThreadProc' to create a pointer to member
error C3350: 'System::Threading::WaitCallback' : a delegate constructor expects 2 argument(s)


Wednesday, June 24, 2009

Calling javascript from code behind

Previously, we know how to easily call server side method from javascript. The opposite is also simple enough.

Just use the RegisterClientScriptBlock method of ClientScriptManager (in case of full postback) or ScirptManager (in case of patial postback). Following is an example:

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "confirmInPageNav", "<script>confirmInPageNav()</script>", false);

confirmInPageNav can be any javascript function

Tuesday, June 16, 2009

Calling server side method from client (using javascript)

I didn't know how easy to achieve this until I read the post in this link:

The essence is to put the server side logic in a button's OnClick event handler; then use the HTML DOM click() method to raise the OnClick event.

<script type="text/javascript">

function myClientButton_onclick() {




<asp:Button ID="btn1" runat="server" Text="Original" OnClientClick="alert('abc')" onclick="btn1_Click" />

<input id="myClientButton" type="button" value="Press Me" onclick="return myClientButton_onclick()" />

Note that the HTML DOM click() method also raises btn1's OnClientClick event.

Wednesday, June 10, 2009


When we want to find a control by its ID, chances are it is usually nested in many levels. In this scenario, we need more powerful method than the .NET framework provided Control.FindControl.

Writing such a method actually is straightforward enough:

private static Control FindControlByID(Control root, string id)
if (id == string.Empty)
return null;

if (root.ID == id)
return root;

foreach (Control c in root.Controls)
Control t = FindControlByID(c, id);
if (t != null)
return t;
return null;

It works great no matter there is master page involved or not; no matter how many levels the control hierarchy has.

Tuesday, June 2, 2009

Using Validator as a Label

Occasionally, we have several validation logic and for some of them we use the validators ASP.NET provides and for some of them we may want to write our own code and have a label displaying the error message. As we know, a validator control has a label to display its error message. By using the validator's label, we can save a label control and more importantly, it may be easier for the layout. (This may not be a good practice since we are letting the validator doing some work it is not supposed to do. I want to log it anyway since sometimes this can be handy)

In our own logic, if we want to use the RequireFieldsValidator's (rfvVersion) build-in label to display our custom error message, we can write:

rfvVersion.IsValid = false;
rfvVersion.Text = "Incorrect Format";
rfvVersion.Enabled = true;

Wednesday, May 27, 2009

Enumerating enum

Probably all of us have encountered the situation where we need to enumerating a enum type. For example, we may want to put all the enum values in a listbox. The solution may not be so straight forward to come up with, but is simple enough: (RegistryValueKind is an enum type in Microsoft.Win32 namespace)

List<string> list = new List<string>();

foreach( RegistryValueKind kind in




list.Add(kind.ToString() + ((int)kind).ToString());


Monday, May 4, 2009

Accessing Data Bound to ListView

If we try to access data that are bound to listview by the following code:
ListViewDataItem lvDataItem = ListView.Item[index];

We'll find that lvDataItem is null.

In fact, all the ListViewDataItem in listview's Item collection are null. The only time it is not null is in ItemDataBound event of ListView. I guess it is designed this way to save memory space. So what if we need to access the data outside ItemDataBound event?

The answer is simple. Just specify DataKeyNames property of ListView like this:
DataKeyNames="ProductName, UnitPrice"

Then, we can access any data:

Friday, May 1, 2009

Javascript Code Meets Postback(full and partial)

Code in $(document).ready is NOT executed in partial postback; pageLoad() function works for partial postback. Both work in full(standard postback).

For the javascript code register in ClientScript.RegisterClientScriptBlock, it is on the page for both full and partial postback. (Because in partial postback, Page_Load event on server side also gets called.)

Monday, April 27, 2009

Restoring master and msdb Database

Restoring master database requires sql server running in single-user mode. We can do the following:
1. Start a cmd window
2. Stop SQL Server
net stop mssqlserver
3. Start SQL Server in single user mode
sqlservr -m
4. Start another cmd window
5. Restore the master database
osql -E -Q"restore database master from disk = 'D:\SQL2000\MSSQL\BACKUP\master-2007-03-12.bak'

NOTE: after executing this command you should see the following output:
The master database has been successfully restored. Shutting down SQL Server.
SQL Server is terminating this process.

In step 5, we can also restore the database in Query Analyzer by running: restore database master from disk = 'D:\SQL2000\MSSQL\BACKUP\master-2007-03-12.bak'

To restore msdb database, we should run sql server in multi-user mode. If there is an error indicating exclusive access, then try to stop sqlserveragent.

Friday, April 10, 2009

Color of Source Code in Blog

Paste the code in Word, copy it from there and paste here (in Compose mode). Then we'll have the source code color preserved!

function sayAlice() {

var sayAlert = function() { alert(alice); }

// Local variable that ends up within closure

var alice = 'Hello Alice';

return sayAlert;


Tuesday, March 24, 2009

javascript code not working when using updatepanel?

I have some javascript code gets executed when window.onload is fired. It basically modifies the appearance of my server controls. Everything works fine before I placed my server controls in an updatePanel(ASP.NET).

When the page got partially rendered(i.e. I clicked the button which is inside the updatePanel to cause a postback), the javascript code didn't work anymore.

I haven't delve into this issue to completely understand this, but I found a solution. It is to use PageRequestManager to register the javascript function I'd like to call each time there is a postback(async or sync). The code is:
function load() {
Then add onload="load()" to body tag.

For reference: Class)

Wednesday, March 18, 2009

Web page gets messy in IE6

The problem: Using background inside frames.
The solution: Use img instead of background and set its z-index properly.

Setup IIS for ASP.NET projects

1. Make sure .Net Framework and IIS are installed.
2. Register ASP.NET with IIS by executing ASPNET_REGIIS.EXE -i Use the one from version 2.0 (i.e. C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727)
3. Make sure ASP.NET 2.0 is the default framework:
1)Open IIS
2)Right-click on the default web site and click 'properties'.
3)Click on the ASP.NET tab.
4)Select ASP.NET 2.0 as the default version.
5)Repeat for the target web virtual directory
4. Click on Web Service Extensions and mark ASP.NET v2.0.50727 as 'allowed'. (For IIS 5.1, ignore this)
5. Right Click on the virtual directory - select properties and then click on "Create" next to the "Application" Label and the textbox. It will automatically create the "application" using the virtual directory's name. Now the application can be accessed.

Sunday, March 15, 2009

Coninental ticket number on eTicket Boarding Pass

My eTicket has 14 digits while the ticket number of Continental is 13 digits which starts with 005. Just ignore the damn last digit.

Tuesday, March 10, 2009

Making a table scrollable

The whole point is to make an html table( table or whatever is rendered as an html one) sitting inside a div element that has overflow attribute set to "auto" or "scroll".

For example:
<div style="border-style: solid; overflow: scroll; height: 100px; width: 100px;">

<asp:table id="table" runat="server" borderwidth="1px" width="100%">


asp:Panel is render as div, we can also use it:

<table border="1" width="100%">


<td>more stuff</td></tr>


<td>more stuff</td></tr>


<td>more stuff</td></tr>


<td>more stuff</td></tr>


<td>more stuff</td></tr>


Just aware that we need to set the "CssClass" attribute for asp:Panel (not "Style", not "overflow"). Same technique should be able to make other control scrollable (e.g. GridView).