Saturday, August 05, 2006

Adaptor pattern

Adapter pattern applies to the situation where you want to adapt a third-party class into your own domain. The third party component will has no knowledge of your design, so the only way you can use to create a an adapter class to use.

There are two ways to in this adaption approach. One is called "Class Adaptor". In this case, a multiple inheritance will be used. Normally, the class in your design will inherit from both the base class and the class you want to adapt. Another approach is called "Object Adaptor", in this approach, you will declare an object of the adaptee type in your adaptor class. (In some languages like c# which doesn't support the multiple inheritance, this may be the only choice available.)

Tuesday, May 30, 2006

C# Delegate.

Each delegate object is really a wrapper around a method and an object to be operated on when the method is called.

The constructor takes an object and IntPtr value, in the constructor, these two arguments are saved in _target and _methodPtr private fields.
Tags:GISResearch

Sunday, May 21, 2006

FreshTag stop working.

I use FreshTags to help organize my blogs since the blog service I use (www.blogger.com) lacks the built-in support for this functionality. Honestly, I think the blogger service is kind of far behind of the other services offered by google.

For mysterious reason, the freshtags stop working two days ago, and I tried to use build page to experience different settings. It seems the samples it offered work perfectly, but after I change certain settings to mine, it just stops working.

I am not familar with the javascript code, and the javascript code the freshtags uses seems pretty complicated to me, so I didn't try to examine the code at the beginning. And it proved wrong, I should look into the code at the very beginning.

The issue is somehow, del.icio.us starts to offer all its feed only to query built in lowercase. At the beginning, I querid the tags using the upper case like this : http://del.icio.us/feeds/json/tags/yuren1978/GISresearch?sort=freq&count=100,
And after I changed this to the lower case : http://del.icio.us/feeds/json/tags/yuren1978/gisresearch?sort=freq&count=100,
Those tags are returned in correct way.




yuren1978

Friday, May 19, 2006

Private and GAC deployment.

I did a little test over the .Net dll deployment testing two nights ago. I thought I needed to write it down.

The thing confused me a little bit is if I install the same version of a dll both in the GAC and Private path ( the application path), will the application look for the dll in the GAC or Private Path.

I made a simple test dll, and there is a test method which will display a message box. In the dll which I depoloyed to GAC, I will disaplay a message box "Called from GAC", in the private deployed dll, I will display a message box "Called from Local".

I also made a simple test application which will refer to the test dll.

If I install the dll into GAC using the GACUtil /i, it will dispaly the following message box.








However, if I unistall the GAC , and then the test application will call the dll from the local private path, then the following message box will be displayed.









Conclusion, if an assembly is deployed both in the GAC and privately, the one in the GAC will be called firstly.
Tags:GISResearch

Wednesday, May 17, 2006

Non-generic - Generic mapping.

Comparer Comparer
Dictionary HashTable
LinkedList -
List ArrayList
Queue Queue
SortedDictionary SortedList
Stack Stack
ICollection ICollection
IComparable System.IComparable
IDictionary IDictionary
IEnumerable IEnumerable
IEnumerator IEnumerator
IList IList
Tags:GISResearch

Tuesday, May 16, 2006

Love the DPack.

DPack. http://www.usysware.com/dpack/

The most useful features missing in Visual Studio.

Alt + S : Solution Browser.
Alt + U: File Browser.
Alt + G: Code Browser.

This will increase code efficiency dramatically.

Love the DPack. Also on my favorites are GhostDoc, and SmartPaste.

Sunday, May 14, 2006

A good web programmer needs.

1. Good understading of javascript.
2. Good understanding of CSS.
3. Good understanding of Photoshop.
4. Good understanding of Database.
5. Good understanding of server-side programming like asp.net.
GISResearch

Friday, May 12, 2006

You cannot simply pass the reference to user control.

We have a program which will host multiple map controls, and each map control will have its own legend. It's fine to host muliple maps on different tabs, but it's a little bit tricky to host multiple legends. The end user will only want to see the legend associated with the current active map.

The first approach I tried is to create a form-level legend, and also create each legend inside each map control. And when the map becomes visible, I will do something like this:
frmMain.legend = currentMap.legend.
frmMain.Legend.Refresh().

I thought this will make the frmMain.legend point to the active map legend, and draw the active map legend.

Actually, this is not the case. Simple reference passing won't make the active map legend become the visible legend. And the OnPaint method of the active map won't be called. The paint message will still be sent to original legend.

This issue looks simple, but does take me a while to figure it out.
GISResearch

Thursday, April 27, 2006

Error Handling:

Error Handling:

There are two ways to hanlde the error, one is check the return code of each function, and based on the code returned, determine whether to continue or abort the program.

The other way is to throw an exception , and catch it in the central place, and then determine the appropriate behavior from there.

Thread consideration:
Exceptions should be handled in each sperate thread, if an exception is thrown in a different thread, and not catched in the same thread, it will disapper sliently, and will cause confusion in trouble shooting the issue.

GISResearch

Saturday, April 22, 2006

Status watching thread in windows services.

I have a windows service program which needs to integrate with another vendor's program. The thing troubling me is that i cannot set up a good test environment with them. The only thing I can do is logging every error my program encounters.

Since it's running as a windows service, so it won't stop even it finds some errors, and the loop just continues running. I put this service on a client's machine, and it generates 2 GB log data in one day. It's pretty embarassing.

So, what I ends up is to create another status watching thread monitoring the log file it generates, if it finds out the log file size is exceeding the certain size, it will send a stop message to the ServieMain() thread, which will stop the service.
GISResearch

How ATL supports windows service.

If you want to create a service based on the ATL library, you normally will inherit the service from CAtlServiceModuleT which is included in atlbase.h

template
class ATL_NO_VTABLE CAtlServiceModuleT : public CAtlExeModuleT
{
......
int WinMain(int nShowCmd) throw()
}

When the the service control manager (SCM) is asked to start a service, through the StartService function, it starts the process using the CreateProcess function, it will go into the int WinMain(int nShowCmd) throw() inside the class.

int WinMain(int nShowCmd) throw()
{
if (CAtlBaseModule::m_bInitFailed)
{
ATLASSERT(0);
return -1;
}

T* pT = static_cast(this);
HRESULT hr = S_OK;

LPTSTR lpCmdLine = GetCommandLine();
if (pT->ParseCommandLine(lpCmdLine, &hr) == true)
hr = pT->Start(nShowCmd);

#ifdef _DEBUG
// Prevent false memory leak reporting. ~CAtlWinModule may be too late.
_AtlWinModule.Term();
#endif // _DEBUG
return hr;
}


This function is called by the main thread in the process, no additional thread is created yet. This function will in turn call the Start() function.

Inside the start function, it starts to hook up the real windows service stuff here, by checking the registery,

TCHAR szValue[MAX_PATH];
DWORD dwLen = MAX_PATH;
lRes = key.QueryStringValue(_T("LocalService"), szValue, &dwLen);

It will decide whether this is a service. [ In debug build, this won't be compiled and registered as a service to make life easier to do the debug.] If this is registered as a service, then a service table is created and StartServiceCtrlDispatcher is called to connect this service to the SCM.

SERVICE_TABLE_ENTRY st[] =
{
{ m_szServiceName, _ServiceMain },
{ NULL, NULL }
};
if (::StartServiceCtrlDispatcher(st) == 0)
m_status.dwWin32ExitCode = GetLastError();


StartServiceCtrlDispatcher establishes a connection that the SCM can use to send control commands to the service. StartServiceCtrlDispatcher will not return until the service has indicated that it has stopped. Once the connection to the SCM is established, StartServiceCtrlDispatcher creates a secondary thread that is the real starting point for the service. The second thread in this case is a static function called _ServiceMain, which in turn forwards the call to real ServiceMain function.

[MSDN:

When the service control manager starts a service process, it waits for the process to call the StartServiceCtrlDispatcher function. The main thread of a service process should make this call as soon as possible after it starts up. If StartServiceCtrlDispatcher succeeds, it connects the calling thread to the service control manager and does not return until all running services in the process have terminated. The service control manager uses this connection to send control and service start requests to the main thread of the service process. The main thread acts as a dispatcher by invoking the appropriate HandlerEx function to handle control requests, or by creating a new thread to execute the appropriate ServiceMain function when a new service is started.

]

The thread ServiceMain run is NOT the main thread referred here, the main thread is the controlling thread.

static void WINAPI _ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv) throw()
{
((T*)_pAtlModule)->ServiceMain(dwArgc, lpszArgv);
}

The real ServiceMain is here:

void ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv) throw()
{
lpszArgv;
dwArgc;
// Register the control request handler
m_status.dwCurrentState = SERVICE_START_PENDING;
m_hServiceStatus = RegisterServiceCtrlHandler(m_szServiceName, _Handler);
if (m_hServiceStatus == NULL)
{
LogEvent(_T("Handler not installed"));
return;
}
SetServiceStatus(SERVICE_START_PENDING);

m_status.dwWin32ExitCode = S_OK;
m_status.dwCheckPoint = 0;
m_status.dwWaitHint = 0;

T* pT = static_cast(this);
#ifndef _ATL_NO_COM_SUPPORT

HRESULT hr = E_FAIL;
hr = T::InitializeCom();
if (FAILED(hr))
{
// Ignore RPC_E_CHANGED_MODE if CLR is loaded. Error is due to CLR initializing
// COM and InitializeCOM trying to initialize COM with different flags.
if (hr != RPC_E_CHANGED_MODE || GetModuleHandle(_T("Mscoree.dll")) == NULL)
{
return;
}
}
else
{
m_bComInitialized = true;
}

m_bDelayShutdown = false;
#endif //_ATL_NO_COM_SUPPORT
// When the Run function returns, the service has stopped.
m_status.dwWin32ExitCode = pT->Run(SW_HIDE);

#ifndef _ATL_NO_COM_SUPPORT
if (m_bService && m_bComInitialized)
T::UninitializeCom();
#endif

SetServiceStatus(SERVICE_STOPPED);
LogEvent(_T("Service stopped"));
}

The first thing in service is to call RegisterServiceCtrlHandler to register a callback function that the control dispatcher, inside StartServiceCtrlDispatcher, can use to pass control requests to the service. RegisterServiceCtrlHandler also returns a handle that is used in calls to the SetServiceStatus function to update the SCM’s status information about the service.
GISResearch

Sunday, April 16, 2006

Eclipse

Jon Skeet's Coding Blog : Visual Studio vs Eclipse

I started to use eclipse to view some open source geometry alrogrithm in JTS. I like it very much just after a couple of days of using it. Sometimes, I just feel an "open source" product is not any worse than those M$ products.

I am not saying I don't like VS.2005, yes, it's great. It has tons of features, and if know 50% of its feature, I will be very satisfied myself. But if there will be an open source editor which has those features the Eclipse has, a lot of people will probably use it just liking prefer FireFox to IE.

DPack is an wonderful addon for the visual studio 2005. It adds a lot features which Eclipse has and VS 2005 doesn't have.

The best two I like is Solution Browser (Alt + S) and Code Browser (Alt + G).
GISResearch

Thursday, April 06, 2006

Breaking on Exceptions.


By default, the vs debugger will break if an exception is unhandled, but we can configure it to break when the exceptions are thrown. It is very helpful in some situations if we want to know exactly where the exception throws.

Under Debug Menu, select exceptions, you’ll see a tree display of all possible exceptions alongside checkboxes to indicate if the debugger should break when an exception “is thrown”, or only break if the exception is “user-unhandled”.

If you have not determined under what condition the exception occurs, or where the exception occurs, it's better to choose break on exceptions.

Sunday, April 02, 2006

Polygon intersection.

1> We need to decompose the two polygons into nodes and edge which make up the graph.
2> Combine the nodes and edges from those two polygons into one big graph, which is the initial graph we need to deal with.
3> Applies the sweep line intersection algorithm to get all the intersection points between the egdes from two polygons. The invariant is that the part of the overlay above the sweep line has been computed correctly.
4> If the event involves only edges from one of the two subdivsions, that is all; The event point is a vertex that can be re-used. If the event involves the edges from both subdivisions, we must link the doubly-connected edge lists of the two original subdivisions at the intersection point.
5> When an edge e passes through another polygon at point v, the edeg e must be replaced by two edges e1 and e2. The two half-edges become four half-edges. We create two new half-edge records whith v as the origin. The new edge e1 is represented by one new (with v as its origin) and one existing half-edge (with e's end point as its origin), and the same holds for e2.
6>
6-a> Link the edges at the end node of original edge e.
The most important part is that we have to link those edges with Prev() and Next() pointers. The Next() pointers of the two new half-edges each copy the Next() pointers of the old half-edge that is not its twin. The half-edges to which these pointers point must also update their Prev() pointer and set it to the new half edges().
6-b> Link the edge at the point v.
Consider the half edge for e1 that has v as its destiantion, it must be linked to the first half-edge, seen clockwise from e1, with v as its origin. The half edge for e1 with v as its origin must be linked to the first counterclockwise half-edge with v as its destination.
GISResearch

Thursday, March 23, 2006

Scroll in .Net user control.

Scroll in a user control is a pretty tricky. I used to have to override the WndProc procedure and call OnVScroll and OnHScroll there. It is not bad. But the whole idea of .Net is RAD,if you have to put a lots of P/Invoke methods, that defeats the whole idea.

I spent some time to do it in managed way. A couple of steps I have to follow is :

1> I have to set the AutoScroll = true.
2> I have to set the AutoScollMinSize to the drawing bitmap size. That way, if the client rectangle is smaller than this one. The scroll bar will show up.
3> Another feature I requested is programmatically scroll, when the mouse is moving out the client area, it should scroll the control. For this, I have to manually set the AutoScrollPosition property.

Friday, March 10, 2006

8 hours to figure out a DCOM call.

I spent quite a lot of time in last two days try to figure out a DCOM calls from the Windows 2003 machine to the Windows 2000 machine.

I had written a component to generate the sketch image for the property card. The actual component is sitting on windows 2000 server, and the proxy is exported and installed on windows 2000 server (the web server) too.

WebServer running the COM+ proxy(windows 2000) - > Component Server (also Database Server) (windows 2003)

Since the webserver is not very stable, and we exported the websites to the new 2003 server.

Suddently, the asp page gave out the following error.

Server object error 'ASP 0178 : 80070005'
Server.CreateObject Access Error

It is not a rare error, and googling will find tons of posts on this issue. Most of posts are misleading until i found this
link

Basically, when the anonymous user (IUSR_WEBSERVERNAME) makes a request on 2000, the identity used is NTAUTHORITY\IUSR_WEBSERVERNAME . On the 2003 server, the indentity used is WEBSERVERNAME\IUSR_WEBSERVERNAME, which is rejected by the component server.

The link suggested a couple of workaround, but I don't want to change anything on the new webserver, so I just added IUSR_WEBSERVERNAME to the Component Server, and it worked very beatifully.

Categories

Tuesday, March 07, 2006

Sweep line algorithm to computing the intersecting points.

The naive approach to compute the intersection points between line segments is use two for loops
for(int i = 0; i< count ; i++)
for( int j=i+1, j< count; j++)
{
compute the intersection between line[i] and line[j]
}

This is O(n*n) , not very efficient.

A better approach is to use the sweep-line approach. The sweep line will sweep from downwards. It will do some update at some event points.

Three types of event points:

1> The first type: the upper point of a line segment, we need to add that line segment into the set, and compute the intersection between this line segment and its immediate left and right neighbor.

2> The second type: the intersection point. The two line segments exchange position there, so we need to compute the intersection between those two line segments and thier new neighbors.

3> The third type: the end point of a line segment, this line segment will be deleted from the set. Its lef and right neighbor become immediate neighbor, we need to compute the intersections between them.

Thursday, March 02, 2006

CSS styles.

Three types of CSS styles:

1> Classes:
1-a> .ClassName
Classes with . at the beginning are applied to different html controls.
1-b> ElmentName.ClassName
Classes prefixed with the element name are applied only to the certain element.

2> Elements:
Elements are applied to certain elements, the following elements are applied to h1, h2.. h6 elements.

h1, h2, h3, h4, h5, h6
{
margin: 2px 0 2px 0;
}

.ClassName Element

.PageNumbers span
{
padding-left: 3px;
}

#ElementId Element

#poster h2
{
font-size: 13px;
font-weight: bold;
color: #50700E;
}


Those should be applied to certain element under the specific class name and the element Ids.

3> Element IDs:
Element IDs starts with the special symbol "#", and it only applies to element with those IDs applied. Those are normally used to position the different web parts.

Sunday, February 26, 2006

Visual Studio .NET plugin for Workspaces source control

A good practive to organize the solution and projects when working with VS.Net is you should always locate the solution file at a level higher in the directory hierarchy than any of the projects in contains. If we create proj1 in c:\temp\test1, we should always put the solution file one level higher, such as c:\temp.

This is very important, otherwise, the OK button will be disabled and you won't be able to add the projects into the workspace. This takes me a while to figure it out.

A good resources for Visual Studio .Net plugin.

Visual Studio .NET plugin for Workspaces source control

Saturday, February 25, 2006

Control the look and feel in Asp.Net.

1> Add a folder called "App_Themes" under the website.
2> Create a different folder under the App_Themes, and each one is a different theme name.
something like this
App_Themes
---- Default
-----Summer
-----Winter
3> In the web configuration file,
, this will associate a theme with the webpage.
4> Add the css files and skin files under the different folder.

Thursday, February 23, 2006

Dispose pattern in C#.

I reviewed some chapters on the dispose pattern on Jeff's book. I really enjoyed reading this book, everytime I read it, it gave me some new thoughts.

A couple of points :

1. If you class has unmanaged resources, you have to implement IDispose pattern to ensure that resources are cleaned up properly. The GC only takes care of the memory, not the other nasty resources issues.

2. The way to implement it:
2-a. Implement a private/protecte methods like Dispose(bool disposing), if the disposing is true, you can access both managed resources which are not collected by GC yet and unmanaged resources. If it's set to false, you cannot access other managed resources since they have the possiblity to have been collected by GC already.
2-b. Implement a Dispose() method, and call Disposing(true), since we are sure it's an explicitly cleaning up.
2-c. Implement a Dispose() method optianlly,and call Disposing(true), since we are sure it's an explicitly cleaning up.
2-d. Implement the finalize() method, and call Disposing(false) . In C#, this finalize method is implemented as a destructor format, though it's not a destructor by any means.

Unraveling Delegates & Events - The Code Project - .NET

Nice explanation about the difference between delegates and events.



Some properties that Events exhibit:

1) Events can only be invoked by the class that defined it.

2) Events can be included in interfaces whereas interfaces cannot contain fields of type delegate.

3) Events cannot reset the delegate invocation list by using “=” outside its class definitions. Events can only add/remove to the handler by using “+=” and “-=” respectively.
Conclusion:

Including Event modifier to the delegate declaration only lets the adding/removing the target to the invocation list and constraints its invocation from outside the class that defines it.

Unraveling
Delegates & Events - The Code Project - .NET

Monday, February 20, 2006

Page.IsPostBack Property

I have to admit I am pretty new to the Asp.Net since most of my work are server-side service programming, or components programming. I get exposed to the Asp.Net since a couple of our freinds want to design a restaurant webiste where people can search enough information before going to a restaurant.

One thing which confused me a bit is when I designed a dropdownlist control to let people select the item, it appears to me that the selection is always get reset when I click on the button. The symptom is that the first item is selected everytime.

It seems that when the page is posted back, the drop down list is always get reset, so the simple trick is to check this :
if (!Page.IsPostBack)
{
//do the actual data binding.
}

Interface implementation in C#.

I read a chapter about interface implemenation in "Applied Microsoft .Net framework programming" and gain some more understanding on this interface topic.

There are basic two types of interface implementation, one is the implicit implementation, in which case, the public/private/protected modifier have to be specified on the implementation. It is the recommended way to implement the interface. Another type of implementation is explicit implementation, in which case, the modifier cannot be added, but the method has to be preceded with the interface name. This will sometimes hide the implementation details, and IS NOT recommended in most cases.

To call the methods in the "explicit implementation", the object has to be casted to the interface type before calling the actual method.

A good example is the Int32 type in the .Net framework, it implements an interface called IConvertible , but you cannot call the ToDouble(), ToByte().. methods until you have to cast the integer to IConvertible.

Thursday, February 16, 2006

DisplayIndex trick.

I spent a couple of hours try to figure out a trick in DisplayIndex of the DataGridView. The trick is that I put the datagridview on a tab page of the tab control, however, when I selected the tab, the display index I set was invalidated. That means, it still shows the original display index, not the index I have set.

I have to put the display index set code in the Tab_SelectedIndexChanged event handler, and set it every time whne the tab is selected. It was not very efficient, but at leat it takes care of the issue.

Quite confusing.

Tuesday, February 14, 2006

Data Mapping in SQL Server Data in C# with ADO.NET

Accessing SQL Server Data in C# with ADO.NET: "SQLServer Type SQL-92 Compliant Type C# Type CLS-Compliant Type
binary + * binary byte[] Byte[]
bigint bigint long Int64
bit bit bool Boolean
char * character char Char
datetime ** datetime DateTime DateTime
decimal dec decimal Decimal
float double precision float Float
image *** varchar Image Image
int integer int Int32
money ++++ SqlMoney SqlMoney
nchar +++ * national character char Char
ntext +++ national text string String
nvarchar +++ **** national character varying char ArrayList Char ArrayList
numeric dec decimal Decimal
real double precision float Float
smalldatetime ** smalldatetime DateTime DateTime
smallint smallint short Int16
smallmoney ++++ SqlMoney SqlMoney
sql_variant sql_variant object Object
text text string String
timestamp ++ rowversion byte ArrayList Byte ArrayList
tinyint tinyint byte Byte
varbinary + **** binary varying byte ArrayList Byte ArrayList
varchar **** character varying char ArrayList Char ArrayList
uniqueidentifier uniqueidentifier byte[16] or Guid Byte[16] or Guid"

Copied from mitbbs, not mine.

Just back from Google on-site. I am a fresh minted Ph.D. in computer science.
It was a long dreadful 5 hour interview by 4 Google enginners, plus the fifth
guy asked my thesis.

A little heads up: be prepare for writing error-free C/C++ code on board given
30 minutes or so. The code has to be generic enough to handle different
platforms and data. Sorry, I can not give out the question in detail here. (as
you know why, please don't ask me) Basically , you must understand from
inside out the memory layout, algorithm and recursion. I prepared for the
interview for about two months, reading algorithm book from cover to cover.
But honestly, none of the interview questions I encountered was what I had
seen before. I wound up digging deep in my old bag of tricks to figure out the
solution. Each interviewer would only ask you one question or two, but hard
enough for you to figure out the solution and possible improvements in 45
minutes. If you screwed, you were done with that Engineer

I don't think I can get the offer. As one of the interviewer said to me, they
turned down a lot of ph.d.s who were not good programmer. The acceptance ratio
is about 1 out of 6, even lower than the best conference in my field.

So take it easy if you are about fly to Google, and enjoy the stay.

Monday, February 13, 2006

NUnit MSBuild Task

A very good resource to include NUnit in MSBuild.

Michael F. Collins, III : NUnit MSBuild Task

My easy work around is like this:

Exec Command="nunit-console.exe $(DeploymentPath)\DDTI.Utilities.UnitTest.dll"
WorkingDirectory="$(PROGRAMEPATH)\NUnit-Net-2.0 2.2.6\bin"

I spent quite a few time to work on the MsBuild today. Honestly, I think I gain more understanding on that. One issue which confused me is that when you embed resource file into the assembly. In Vs.2005, it will append the prefix (such as assemblyname.foldername) before the resource name. But in MsBuild, it won't , so it cause some trouble when trying to reference the resource.

One workaround I figured out is to use "Defined Constants" in the CSC command to control the compiling process. It's kind of like this:

#if MSBUILD
set resourcename= "File.xml"
#else
set resourcename= "AssemblyName.FolderName.File.xml"
#endif

Also, always use $ in front of property name and @ in front of item name.

Friday, February 10, 2006

Edit command file for SSEUtil

SSEUtil is vey powerful, but I have to pay attention when editing those command text file, if you add some extra space , character, or tab... it may cause the SSEUtil unable to parse the command and execute it.

So, please pay attention to edit those command files.

Thursday, February 09, 2006

Good sample to create xml using MSXML in Visual C++

PerfectXML.com - MSXML for C++ Developers :: Creating XML Document Using DOM    

But it’s always painful to check all the HRESULT values in C++ programs, so I end up using the XML class for processing and building simple XML documents.

Std debugging in VS2005

The nice thing about std debugging in vs2005. In previous version of vs2003, the std debugging is not very pleasant, when you define a map object, it’s not very easier to see what it contains in the debugger. Sometimes, I have to write some custom code to loop through the contents to check what it contains. With this new feature in vs 2005, I can see all the contents by just mouse over it. It was so cool….

MSDN

Visual C# Application Development
How to: Use Code Snippets (C#)

The following procedures describe how to use code snippets. Code snippets are available in five ways: through a keyboard shortcut, through IntelliSense auto-completion, through the IntelliSense complete word list, through the Edit menu, and through the context menu.
To use code snippets through keyboard shortcut

1.

In the Visual Studio IDE, open the file that you intend to edit.
2.

In the Code Editor, place the cursor where you would like to insert the code snippet.
3.

Type CTRL+K, CTRL+X.
4.

Select the code snippet from the code snippet inserter and then press TAB or ENTER.

Alternatively, you can type the name of the code snippet, and then press TAB or ENTER.

To use code snippets through IntelliSense auto-completion

1.

In the Visual Studio IDE, open the file that you intend to edit.
2.

In the Code Editor, place the cursor where you would like to insert the code snippet.
3.

Type the shortcut for the code snippet that you want to add to your code.
4.

Type TAB, TAB to invoke the code snippet.

To use code snippets through the IntelliSense Complete Word list

1.

In the Visual Studio IDE, open the file that you intend to edit.
2.

In the Code Editor, place the cursor where you would like to insert the code snippet.
3.

Begin typing the shortcut for the code snippet that you want to add to your code. If automatic completion is turned on, then the IntelliSense complete word list will be displayed. If it does not appear, then press CTRL+SPACE to activate it.
4.

Select the code snippet from the complete word list.
5.

Type TAB, TAB to invoke the code snippet.

To use code snippets through the Edit menu

1.

In the Visual Studio IDE, open the file that you intend to edit.
2.

In the Code Editor, place the cursor where you would like to insert the code snippet.
3.

From the Edit menu, select IntelliSense and then select the Insert Snippet command.
4.

Select the code snippet from the code snippet inserter and then press TAB or ENTER.

Alternatively, you can type the name of the code snippet, and then press TAB or ENTER.

To use code snippets through the context menu

1.

In the Visual Studio IDE, open the file that you intend to edit.
2.

In the Code Editor, place the cursor where you would like to insert the code snippet.
3.

Right-click the cursor and then select the Insert Snippet command from the context menu.
4.

Select the code snippet from the code snippet inserter and then press TAB or ENTER.

Alternatively, you can type the name of the code snippet, and then press TAB or ENTER.

Saturday, February 04, 2006

Method Resolution

Method Resolution

When the Select method is called, the data fields from the data-bound control, the parameters that were created declaratively in the SelectParameters element, and the parameters that were added in the Selecting event handler are all merged. (For more information, see the preceding section.) The ObjectDataSource control then attempts to find a method to call. First, it looks for one or more methods with the name that is specified in the SelectMethod property. If no match is found, an InvalidOperationException exception is thrown. If a match is found, it then looks for matching parameter names. For example, suppose a type that is specified by the TypeName property has two methods named SelectARecord. One SelectARecord has one parameter, ID, and the other SelectARecord has two parameters, Name and Number. If the SelectParameters collection has only one parameter named ID, the SelectARecord method with just the ID parameter is called. The type of the parameter is not checked in resolving the methods. The order of the parameters does not matter.

If the DataObjectTypeName property is set, the method is resolved in a different way. The ObjectDataSource looks for a method with the name that is specified in the SelectMethod property that takes one parameter of the type that is specified in the DataObjectTypeName property. In this case, the name of the parameter does not matter.
this page

MSBuild frustration.

MSBuild frustration.

I spent a lot of time trying to figure out a way to edit the MSBuild project file in the VS 2005. When I referred to the xml schema file, I cannot add the custom properties in the property group, VS kept giving me the annoying warnings. I searched online, not many posts, but there are some people who experienced the same issue with me. But I am sure it’s probably not a common issue. I submitted the post to the MSDN newsgroup, and hopefully, I can get an answer from there.

I am not surprised when I opened the .xsd file, because I know if I add those elements in the schema definition. It was OK. But that just cannot be the issue, and it contradicts with the MSDN documentation.

I ended up editting those xsd file, and hopefully, I can find a satisfactory answer from somewhere.

Friday, February 03, 2006

Projection Concepts

Projection Concepts
1. Ellipsoid: WGS84 (Wordl Geodetic System 1984) and GRS80 () are ellipsoid names.
2. Datum: A paticular datum (like NAD 27 and NAD 83) will use the relevant ellipsoid.
3. Coordiante System: The datum will be used as a base to do the coordinate transfer, the following concepts are coordiantes.
* US State Plane 1927 (both original and exact solutions)
* US State Plane 1983
* UTM (Universal Transverse Mercator) North and South zones
* Gauss-Kruger Modified, 3TM, and 6TM
* XYZ Cartesian ECEF
* XYZ Cartesian Eath-Centered Earth Fixed (ECEF)
* New Zealand Map Grid
* Grids for Argentina, Australia, Austria, Bahrain, Belgium, Borneo, Columbia, Cuba, Egypt, England, France, Ghana, Greece, India, Iraq, Ireland, Italy, Japan, Minnesota, Netherlands, New Brunswick, New Zealand, Nigeria, Peru, Phillipines, Qatar, Quebec, Rumania, Veracruz, and many more. More are being added all the time!
4. Map Projections: formulas used to do the projection
* Albers Equal-Area Conic
* Azimuthal Equal Area
* Azimuthal Equidistant
* Bonne
* Cassini
* Double Stereographic
* Equal-Area Cylindrical
* Equidistant Conic
* Equidistant Cylindrical
* European Stereographic
* Gnomic
* Hotine Oblique Mercator (Rectified Skew Orthomorphic - with the Skew Angle parameter)
* IMW Polyconic
* Lambert Conformal Conic (1 parallel)
* Lambert Conformal Conic (2 parallel)
* Mercator
* Miller Cylindrical
* Mollweide
* Orthographic
* Polar Azimuthal
* Equal Area
* Polar Azimuthal Equidistant
* Polar Stereographic
* Polyconic
* Robinson
* Sinusiodal
* Space Oblique Mercator
* Stereographic
* Stereographic 70
* Transverse Mercator (Gauss-Kruger)
* Two-Point Fit (a special polynomial projection)
* Van der Grinten

Wednesday, February 01, 2006

Bootstrapper for the VC++ 2005 Redists (with MSI 3.1) - The Code Project - C++ / MFC

Bootstrapper for the VC++ 2005 Redists (with MSI 3.1) - The Code Project - C++ / MFC: "including "

I had some difficulty to register my dll on a co-worker's machine until I found this vcredist_x86.exe under C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\vcredist_x86

Sunday, January 29, 2006

SQL notes

TSQL reference On MSDN

I am reading some code snippts in Transactional SQL and found this interesting.

1>uniqueidentifier type and NEWID() function.


The NEWID() function in stored procedure will return a unique identifier type, which is essentially a old COM concept GUID.

2>Sql command to display all the tables.
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

3> Data types


Data Types Description
bigint Integer data from -2^63 through 2^63-1
int Integer data from -2^31 through 2^31 - 1
smallint Integer data from -2^15 through 2^15 - 1
tinyint Integer data from 0 through 255
bit Integer data with either a 1 or 0 value
decimal Fixed precision and scale numeric data from -10^38 +1 through 10^38 -1
numeric Fixed precision and scale numeric data from -10^38 +1 through 10^38 -1
money Monetary data values from -2^63 through 2^63 - 1
smallmoney Monetary data values from -214,748.3648 through +214,748.3647
float Floating precision number data from -1.79E + 308 through 1.79E + 308
real Floating precision number data from -3.40E + 38 through 3.40E + 38
datetime Date and time data from January 1, 1753, through December 31, 9999,
with an accuracy of 3.33 milliseconds
smalldatetime Date and time data from January 1, 1900, through June 6, 2079,
with an accuracy of one minute
char Fixed-length character data with a maximum length of 8,000 characters
varchar Variable-length data with a maximum of 8,000 characters
text Variable-length data with a maximum length of 2^31 - 1 characters
nchar Fixed-length Unicode data with a maximum length of 4,000 characters
nvarchar Variable-length Unicode data with a maximum length of 4,000 characters
ntext Variable-length Unicode data with a maximum length of 2^30 - 1 characters
binary Fixed-length binary data with a maximum length of 8,000 bytes
varbinary Variable-length binary data with a maximum length of 8,000 bytes
image Variable-length binary data with a maximum length of 2^31 - 1 bytes
cursor A reference to a cursor
sql_variant A data type that stores values of various data types,
except text, ntext, timestamp, and sql_variant
table A special data type used to store a result set for later processing
timestamp A database-wide unique number that gets updated every time
a row gets updated
uniqueidentifier A globally unique identifier.

4> Alter Table and Create Table.
Alter Table apply to a table which has already has some data and you want to keep the data.

0x8DDD0004

I think I probably spent about 3 hours trying to fix this issue. When I go to the microsoft update website, it always returns the "0x8DDD0004" error. I tried a lot of differetn solutions until I found the following one.

Be honest, I don't know what is going on underneath, but it turns out the only fixing solution for me.

Windows update doesn't work on my computer until I found the following solution.

corrupted keys.

Import registry key.
=====================
1. Click Start, Click Run, type in "notepad C:\fix.reg" (without quotation
marks) and press Enter. Choose Yes when you are prompted.
2. Copy the following commands and then paste them into the opened Notepad
window.

Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\CLSID\{0000031A-0000-0000-C000-000000000046}]
@="ClassMoniker"

[HKEY_CLASSES_ROOT\CLSID\{0000031A-0000-0000-C000-000000000046}\InprocServer32]
@="ole32.dll"

[HKEY_CLASSES_ROOT\CLSID\{0000031A-0000-0000-C000-000000000046}\ProgID]
@="clsid"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\CLSID]
@="{0000031A-0000-0000-C000-000000000046}"

3. After you paste the above commands, please close the Notepad window.
Choose Yes when you are prompted to save the file.
4. Click Start and Click Run, type in "C:\fix.reg" (without quotation marks)
and press Enter to run the commands we have pasted.
5. A dialog box will pop-up saying "Are you sure you want to add the
information in C:\fix.reg to the registry?". Click Yes on this dialog box
6. Reboot the machine.
7. After the machine reboots use Windows Update and see if the problem has
gone away.

Saturday, January 28, 2006

#2120 : How do I page through a recordset?

A common issue in displaying large recordset in a database.

#2120 : How do I page through a recordset?

SELECT @local_variable=NULL

ransact-SQL Reference
SELECT @local_variable

Specifies that the given local variable (created using DECLARE @local_variable) should be set to the specified expression.

It is recommended that SET @local_variable be used for variable assignment rather than SELECT @local_variable. For more information, see SET @local_variable.
Syntax

SELECT { @local_variable = expression } [ ,...n ]
Arguments

@local_variable

Is a declared variable for which a value is to be assigned.

expression

Is any valid Microsoft® SQL Server™ expression, including a scalar subquery.
Remarks

SELECT @local_variable is usually used to return a single value into the variable. It can return multiple values if, for example, expression is the name of a column. If the SELECT statement returns more than one value, the variable is assigned the last value returned.

If the SELECT statement returns no rows, the variable retains its present value. If expression is a scalar subquery that returns no value, the variable is set to NULL.

In the first example, a variable @var1 is assigned Generic Name as its value. The query against the Customers table returns no rows because the value specified for CustomerID does not exist in the table. The variable retains the Generic Name value.

USE Northwind
DECLARE @var1 nvarchar(30)
SELECT @var1 = 'Generic Name'

SELECT @var1 = CompanyName
FROM Customers
WHERE CustomerID = 'ALFKA'

SELECT @var1 AS 'Company Name'

This is the result:

Company Name
----------------------------------------
Generic Name

In this example, a subquery is used to assign a value to @var1. Because the value requested for CustomerID does not exist, the subquery returns no value and the variable is set to NULL.

USE Northwind
DECLARE @var1 nvarchar(30)
SELECT @var1 = 'Generic Name'

SELECT @var1 =
(SELECT CompanyName
FROM Customers
WHERE CustomerID = 'ALFKA')

SELECT @var1 AS 'Company Name'

This is the result:

Company Name
----------------------------
NULL

One SELECT statement can initialize multiple local variables.

Note A SELECT statement that contains a variable assignment cannot also be used to perform normal result set retrieval operations.

See Also

DECLARE @local_variable

Expressions

SELECT

Friday, January 27, 2006

Found an interesting question.

given the following code:

p is not NUL terminated char array
int foo(char *p, char c, int length)
{
for(int i = 0 ; i <= length ; i++)
{
if(p[i] == c) return i;
}
return -1;
}

question:
1. what does above code do?
2. how many comparison for each iteration?
3. can you modify the function to have less comparison for each iteration?
(hint: p is not pointer to a const char)

Thursday, January 26, 2006

Binding Data to a datagrid.

Binding Data to a datagrid.

1 Declare a datagrid object.
2 Declare a data grid table style.
a. Set the mapping name to the collection name.
b. Add the DataGridTextBoxColumn to the GridColumnStyles of the datagrid.
3 Add the data grid table style to the table styles of the datagrid.
4. Very important, in order to let the datagrid notified the data change and do the proper update of the interface. The collection object which binds to the interface must support the following:

4-a. bool SupportsChangeNotification {get;} must return true.
4-b.event ListChangedEventHandler ListChanged must be implemented.

public event ListChangedEventHandler ListChanged
{
add
{
m_oOnListChanged += value;
}
remove
{
m_oOnListChanged -= value;
}
}
4-c. Expose the OnListChanged method
protected virtual void OnListChanged(ListChangedEventArgs ev)
{
if (m_oOnListChanged != null)
{
m_oOnListChanged(this, ev);
}
}


protected override void OnInsertComplete(int index, object value)
{
//raise the event on ListChanged
//raise event
OnListChanged( new ListChangedEventArgs(ListChangedType.ItemAdded, index ) );
//base.OnInsertComplete (index, value);
}




protected override void OnSetComplete(int index, object oldValue, object newValue)
{
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, index));
}

protected override void OnRemoveComplete(int index, object value)
{

OnListChanged(new ListChangedEventArgs(ListChangedType.ItemDeleted, index));
}

The datagrid which binds to the collection class will register the ListChanged event and will be notified if an item is added.

If those properties, methods, events are not properly registered, the datagrid will behave stupid and never responds to any event.

Tuesday, January 24, 2006

ASP.Net Web Application Administration


Membership management in Asp.Net 2.

ASP.Net Web Application Administration

I was following the membership tutorials on the Asp.Net website, and it mentioned to use "ASPNETDB" database, however, I couldn't find that database on my machine. But on the Asp.Net administration page, I found the aspnet_regsql feature. It was so cool that it could install and uninstall ASP.Net features on a SQL Server. Essentially, it will add all the necessary tables, views, and stored procedures to database, so the website could take full advantage of all the membership service Asp.Net could provide.

Sunday, January 22, 2006

近10年最强的50本计算机图书

I found it from here

NO.1
设计模式:可复用面向对象软件的基础
Design Patterns: Elements of Reusable Object-Oriented Software
NO.2
人月神话
The Mythical Man-Month: Anniversary Edition
NO.3
TCP/IP详解卷1:协议
TCP/IP Illustrated, Volume 1: The Protocols
NO.4
编写安全的代码
Writing Secure Code, Second Edition
NO.5
UNIX环境高级编程
Advanced Programming in the UNIX Environment, 2nd Edition
NO.6
代码大全
Code Complete, 2nd Edition
NO.7
C程序设计语言
The C Programming Language, 2nd Edition
NO.8
计算机程序设计艺术
Art of Computer Programming Volumes 1-3 Boxed Set
NO.9
Effective C++
Effective C++: 55 Specific Ways to Improve Your Programs and Designs, 3rd Edition
NO.10
Transact-sql权威指南
The Guru's Guide to Transact-SQL
NO.11
Perl语言编程
Programming Perl, 3rd Edition
NO.12
编程珠玑
Programming Pearls, 2nd Edition
NO.13
程序员修炼之道
Pragmatic Programmer: From Journeyman to Master
NO.14
解析极限编程
Extreme Programming Explained: Embrace Change, 2nd Edition
NO.15
Don't Make Me Think
Don't Make Me Think: A Common Sense Approach to Web Usability, 2nd Edition
NO.16
ASP.NET服务器空间与组件开发
Developing Microsoft ASP.NET Server Controls and Components
NO.17
信息安全工程
Security Engineering: A Guide to Building Dependable Distributed Systems
NO.18
TCP/IP路由技术(第一卷)
Routing TCP/IP, Volume 1
NO.19
The Design of Everyday Things
NO.20
Joel说软件
Joel on Software
NO.21
Internet路由结构
Internet Routing Architectures, 2nd Edition
NO.22
网络信息安全的真相
Secrets & Lies: Digital Security in a Networked World
NO.23
程序设计实践
The Practice of Programming
NO.24
网站重构
Designing with Web Standards
NO.25
人件
Peopleware: Productive Projects and Teams, 2nd Edition
NO.26
The Code Book: The Science of Secrecy from Ancient Egypt to Quantum Cryptography
NO.27
WINDOWS程序设计
Programming Windows, 5th Edition
NO.28
Mac OS X: The Missing Manual, Panther Edition
NO.29
The Elements of Style, 4th Edition
NO.30
IT大败局
In Search of Stupidity: Over 20 Years of High-Tech Marketing Disasters
NO.31
Godel, Escher, Bach: An Eternal Golden Braid
NO.32
Service-Oriented Architecture: A Field Guide to Integrating XML and Web Services
NO.33
Head First Java, 2nd Edition
NO.34
算法导论
Introduction to Algorithms, 2nd Edition
NO.35
A First Look at SQL Server 2005 for Developers
NO.36
Core Java 2, Volume 1: Fundamentals, 7th Edition
NO.37
UML精粹:标准对象建模语言简明教程
UML Distilled: A Brief Guide to the Standard Object Modeling Language, 3rd Edition
NO.38
Expert Oracle, Signature Edition (One-on-One)
NO.39
黑客大曝光
Hacking Exposed: Network Security Secrets & Solutions, 5th Edition
NO.40
Microsoft SharePoint: Building Office 2003 Solutions
NO.41
EFFECTIVE JAVA中文版
Effective Java Programming Language Guide
NO.42
Joe Celko's SQL for Smarties : Advanced SQL Programming, 3rd Edition
NO.43
企业应用架构模式
Patterns of Enterprise Application Architecture
NO.44
Group Policy, Profiles, and IntelliMirror for Windows 2003, Windows XP, and Windows 2000
NO.45
应用密码学
Applied Cryptography: Protocols, Algorithms, and Source Code in C, 2nd Edition
NO.46
重构--改善既有代码的设计
Refactoring: Improving the Design of Existing Code (The Addison-Wesley Object Technology Series)
NO.47
C#编程语言详解
The C# Programming Language
NO.48
ADO.NET实用指南
Pragmatic ADO.NET: Data Access for the Internet World
NO.49
计算机网络(第四版)
Computer Networks, 4th Edition
NO.50
DNS与BIND

近10年最强的50本计算机图书,您读过几本?

美国著名图书频道Book Pool集结最权威的62位作者评选出了最近10年计算机专业图书中的50强[原文]

光这62位作者阵营就非常强大,我们熟悉的就有:

* Francesco Balena(Microsoft.NET框架程序设计,Visual Basic.NET语言描述作者)
* Bert Bates(Head First Design Patterns作者)
* Joshua Bloch(Effective Java作者)
* Kalen Delaney(Microsoft SQL Server 2000技术内幕作者)
* Stephen C. Dewhurst(C++ Gotchas作者)
* Bill Evjen(Visual Basic.NET宝典作者)
* Dino Esposito(构建Web解决方案—应用ASP.NET和ADO.NET、Microsoft .NET XML程序设计作者)
* Andy Hunt(Pragmatic Programmer系列图书作者)
* Gary McGraw(Exploiting Software: How to Break Code作者)
* Steve McConnell(Code Complete作者)
* Christian Nagel(Enterprise Services with the .NET Framework作者)
* Arnold Robbins(Linux程序设计作者)
* Tim O'Reilly(O'Reilly媒体集团创始人)
* Chris Sells(Windows Forms程序设计、.NET本质论作者)
* Stephen Walther(设计模式--可复用面向对象软件的基础作者)
* John Vlissides(ASP.NET揭秘作者)

由此可见,这次评选的权威性,还是让我们来看看这50本书的分布吧:

软件工程类

按照现代计算机技术的发展,人月神话应该称得骨灰级图书了,计算机图书能够流行30年,Frederick Brooks确实让人刮目相看。这种现象往往出现在软件工程类和算法类的图书上,这些理论和技术往往经久不衰。比如:
# 设计模式:可复用面向对象软件的基础 -- 1994年出版(多位大师创作)
# 人件 -- 1987年出版(Tom DeMarco、Timothy Lister)

Martin Fowler和Kent Beck是软件工程领域最有名的技术作家,剩下的4本上榜图书全部是他们所写:
# 企业应用架构模式(Martin Fowler)
# 重构--改善既有代码的设计(Martin Fowler)
# 解析极限编程(Kent Beck)
# UML精粹:标准对象建模语言简明教程(Martin Fowler)

看看这个领域还漏掉哪些经典:
Robert C. Martin的敏捷软件开发:原则、模式与实践或者是其他?

C/C++类

C语言的设计者Brian W.Kernighan的C程序设计语言确实经典,超过C++之父Bjarne Stroustrup的C++程序设计语言进入名单榜中。

此外,Scott Meyers的Effective C++众望所归,作者的More Effective C++、Effective STL也同样精彩。

Stan Lippman的C++ Primer不在榜单,有点可惜。

Java类

不知道什么原因,Java类图书的排名比较靠后,Head First Java是一本不错的教材,不过国内好像还未引进,Java 2核心技术 卷I: 基础知识已经出第7版了,可见受欢迎的程度。Sun的Joshua Bloch在Effective Java采用Scott Meyers的风格,使本书成为真正的Effective Java Book。

不过Java编程思想、J2EE核心模式、Contributing to Eclipse、 Expert One-on-One J2EE Development without EJB落榜有点意外。

Windows/.NET类

Charles Petzold的Windows程序设计是尽人皆知的Win32 API编程经典,也称为“Petzold Book”。由 Anders Hejlsberg来写C#编程语言详解 ,谁说不是经典?不过ADO.NET实用指南上榜有点出乎我的意料,为什么不是 Jeffrey Richter的Microsoft .NET框架程序设计?

Linux/Unix类

这类只有一本UNIX环境高级编程,漏掉了UNIX 编程艺术是否可惜?

Web开发类

有3本书上榜,Perl之父Larry Wall的Perl语言编程 是经典的教程,网站重构上榜在情理之中,Jeffrey Zeldman一直走在Web标准制定的最前沿。

ASP.NET Page Framework负责人Nikhil Kothari的ASP.NET服务器空间与组件开发讲解ASP.NET模式非常清晰,不过,如果是ASP.NET入门的话,我倒是推荐另外一本--ASP.NET揭秘。

还有没有漏掉什么啦?JavaScript权威指南是不是也很好?

网络通讯类

这类图书上榜比较多,TCP/IP如此的重要,TCP/IP详解卷1:协议和 TCP/IP路由技术(第一卷)同时上榜。其他的还有Internet路由结构、计算机网络(第四版)、DNS与BIND

数据库类

数据库类评选结果不太好评点,Transact-sql权威指南是一本标准的T-SQL教材,进一步实践,还是建议看邹建最新出版的中文版 SQL Server 2000 开发与管理应用实例。

其他上榜的都没有中文版:A First Look at SQL Server 2005 for Developers (FirstLook系列过时太快,基本上没有引进)、Expert Oracle, Signature Edition (One-on-One)(2005年的新书,作者 Thomas Kyte是Oracle的VP)、Joe Celko's SQL for Smarties : Advanced SQL Programming(作者Joe Celko是ANSI SQL标准委员会成员)

安全类

网络社会没有比安全更重要的了,这类图书上榜就有5本,分别是: 编写安全的代码、 黑客大曝光、 信息安全工程、 网络信息安全的真相、 应用密码学。 后2本都是国际公认密码和信息安全专家Bruce Schneier的大作。

算法和代码类

提到算法,没有人不想到Donald E.Knuth的计算机程序设计艺术,据说Bill Gates曾放言,做对该书所有习题就能到微软来报到上班,可见此书探讨算法的深度。相比Donald的巨著,算法导论更适合做为算法教材。

代码大全上榜在预料之中,这本书曾经有过中文版,不过现在已经绝版了,有点可惜。

综合类

不好归类的都叫综合类吧,程序员修炼之道书名翻译不太恰当,Pragmatic Programmer代表注重实效的程序员,程序员如何注重实效?全书就围绕这个话题在谈。不过,因为这本书出版时间较早(1999年),我更愿意看Joel说软件,这种Blog的写作风格更加通俗易懂。

编程珠玑和程序设计实践是2本讲解编程技巧的图书,如果说软件是工艺的话,你对这门手艺掌握的如何了?

Merrill R. Chapman作为老资格的程序员、销售主管,在IT大败局中以事件亲历的方式来剖析Ashton-Tate等公司的失败案例的时候显得特别具有说服力。前车之鉴、后车之师,何必自己花钱买教训呢?

综合类还有很多好书,比如,Gerald M.Weinberg的你的灯亮着吗?、David Kushner的DOOM启世录都值得一读。国内的读者还不应该放过李维的Borland传奇、蔡学镛的爪哇夜未眠

其他一些上榜图书没有中文版,不太好点评,分别是:
# Microsoft SharePoint: Building Office 2003 Solutions
# Group Policy, Profiles, and IntelliMirror for Windows 2003, Windows XP, and Windows 2000
# Don't Make Me Think
# The Design of Everyday Things
# The Code Book: The Science of Secrecy from Ancient Egypt to Quantum Cryptography
# Mac OS X: The Missing Manual, Panther Edition
# The Elements of Style, 4th Edition
# Godel, Escher, Bach: An Eternal Golden Braid

Why does StartingNodeOffset make my SiteMap dissappear?

Why does StartingNodeOffset make my SiteMap dissappear?

Very useful information on explaining how the sitemap works.

Saturday, January 21, 2006

Exception Handling Process.


Windows can handle user-mode errors in a variety of ways. The following sequence shows the precedence used for error handling:
  1. If a user-mode debugger is currently attached to the faulting process, all errors will cause the target to break into this debugger.
As long as the user-mode debugger is attached, no other error-handling methods will be used — even if the gn (Go With Exception Not Handled) command is used.
  1. If no user-mode debugger is attached and the executing code has its own exception handling routines (for example, try - except), this exception handling routine will attempt to deal with the error.

  2. If no user-mode debugger is attached, and Windows has an open kernel-debugging connection, and the error is a breakpoint interrupt, Windows will attempt to contact the kernel debugger.
Kernel debugging connections must be opened during Windows' boot process. If you are using Windows Server 2003 or a later version of Windows and wish to prevent a user-mode interrupt from breaking into the kernel debugger, you can use the KDbgCtrl utility with the -du parameter. For details on how to configure kernel-debugging connections and how to use KDbgCtrl, see Configuring Software on the Target Computer.
If Windows does attempt to contact a kernel debugger but there is no debugger running at the other end of the connection, Windows will freeze until kernel debugger is activated.
In the kernel debugger, you can use gh (Go With Exception Handled) to disregard the error and continue running the target. You can use gn (Go With Exception Not Handled) to bypass the kernel debugger and go on to step 4.
  1. If the conditions in steps 1, 2, and 3 do not apply, Windows will activate a debugging tool. Any program can be selected in advance as the tool to use in this situation. The chosen program is referred to as the postmortem debugger. This is also known as the just-in-time debugger or the JIT debugger.
If the postmortem debugger is a standard user-mode debugger (such as CDB, WinDbg, or Microsoft Visual Studio®), this debugger will start up and break into your application.
If the postmortem debugger is a tool for writing dump files (such as Dr. Watson), a memory dump file will be created, and then the application will be terminated.
Note If Dr. Watson is activated on Windows XP or a later version of Windows, a message box will appear. This window gives you the option of sending an error report to Microsoft. If you choose Don't Send, a dump file will created and stored on your hard disk. If you choose Send Error Report, a dump file will be created and stored on your hard disk, and will also be transmitted to Microsoft over the internet.
If you have not reconfigured Windows' postmortem settings, Dr. Watson is used as the default postmortem debugger. This setting can be changed programmatically or through the registry; any changes take effect immediately

Testing Applications with Microsoft Windows XP AppVerifier

I found this tool while reading John Robbin's debugging book, except it seemed that it does not support the integration with the VS.Net 2003 anymore as the author has said in his book.

Nevertheless, it is still a very useful tool.

Testing Applications with Microsoft Windows XP AppVerifier

Using Application Verifier to Troubleshoot Programs in Windows XP

Friday, January 20, 2006

How projection works


How projection works.

Projection is the way to project the points on the earth (globe) to the plane.  For different projection systems, like NAD27 and NAD83, they use the same mathematical formula to do the projection, but use the differnt referece system. The NAD 1927 use the Ellipsoid 7008 (Clarke 1866), and the NAD 1983 use the Ellipsoid 7019 (GRS 1980).

The other difference between NAD 1927 and NAD 1983 are the defining constants like the false northing, false easting, etc..

Rules of Thumb to put into StdAfx.h

Rules of Thumb to put into StdAfx.h

  1. All CRT/compiler supplied library included headers.

  2. If you are suing brackets around the name in the include statements, the header files you develop should be in quotes.

  3. Any third-party library header files, like boost.

  4. You own library files.

The inline function in debug/release build.

The inline function in debug and release build.

Page 673 of “Debugging Applications For Microsft.Net and Microsoft Windows”.

In release builds, inline indicates to the complier that it’s supposed to take the code inside the function and pop it directly into where it is being used instead of making a function call. However, in a debug build inline-specified functions don’t get expanded and are treated as normal functions.

Sunday, January 15, 2006

SEH exception and C++ exception.

SEH exception and C++ exception.

SEH doesn’t mix well with C++ programming because C++ exceptions are implemented internally with SEH and the compiler complains when you try to combine them indiscriminately. The reason for the conflict is that when straight SHE unwinds out of a function, it doesn’t call any of the C++ object destructors for objects created on the stack. Because C++ objects can do all sorts of initialization in their constructors, such as allocating memory for internal data structures, skipping the destructors can lead to memory leaks and other problems.

Friday, January 13, 2006

PostgreSQL: The world's most advanced open source database

PostgreSQL: The world's most advanced open source database

I was working on the project to read and write in the WKB format, and was not able to do a good testing. As always , I went to sourceforge to find some information. The WKB4J I found there suggested using the PostgreSQL database. But it seemed to me it's pretty difficult to plug in the postGIS into the engine. I am not a guru of the make file, though I knew it's an essential part to become a good C++ programmer.

It turned out that in the installation package, there was an choice to let you choose whether you want to include the PostGIS part or not, if you choose yes, everything will be ready to go after you finish the installation. It was a beauty.

The PostgreSQL engine also gets strong command support (much like the SSEUtil.exe I played with the SQL server express) and nice GUI.

Open-source projects sometimes are much better than most shity proprietary work.

Tuesday, January 10, 2006

SQL Server Express Utility

SQL Server Express Utility

Version 1.0.2130
Overview
SQL Server Express Utility is a tool for interacting with SQL Server. It provides many features including:
- Connect to the main instance or user-instance of SQL Server.

- Create/Attach/Detach/List databases on the server.

- Upgrade database files to match the version of the server.

- Execute SQL statements via the console (similar to SQLCMD) or the console window (UI).

- Retrieve the version of SQL Server running.

- Enable/Disable trace flags (e.g. to trace SQL statements sent to the server by any client app)

- List the instances of SQL Server on the local machine or on remote machines.

- Checkpoint and shrink a database

- Measure the performance of executing specific queries using the timer function (console mode).

- Create and playback lists of SQL commands to be executed by the server.

- Log all input/output.



Even though the tool was built with focus on SQL Server Express (by default, it tries to connect to the SQLEXPRESS instance on the local machine), the tool can also be used to connect to other versions of SQL Server, including SQL Server 2000 and earlier (see the –main option for more information).
Important note
Microsoft Corporation does not provide any technical or customer support services for SQL Server Express Utility
Major changes from the Beta2 version



- All help is now build into SSEUtil.exe. For help on a specific command type SSEUtil help .

- Create new databases (-create command)

- List the child instances running (-childlist command)

- Interactive console window (-consolewnd command)

- History commands in the SQL console (!history show/clear/save)

- Set the connection timeout (-timeout option)

- Set the command timeout (-commandtimeout) command



- Script files can contain variables that will be expanded before sending to the server.

- You can specify the name of the database when attaching (see -attach command)

e.g. SSEUtil -attach c:\northwind.mdf NW

- Most commands can now work with a file path (.mdf) or a database name.

- Detach command syntax changed. You can provide either a path or name of DB to detach

Monday, January 09, 2006

TortoiseCVS: About

TortoiseCVS: About

I was trying to get the latest code from the sourceforge, and it seemed to me this was the mostly recommended CVS client. I had installed, and configured, but everytime, I couldn't get the latest code from the sourceforge. It made me think I configure something wrong.

Finally, it turned out that the source code was at the other cvs hoster website, but I finally get the JTS 1.7 code. It was a very nice software.

Sunday, January 08, 2006

Update database in OLE DB.

I had a project which will parse the address in one field, and write the parsed out data to the different fields. Today, it seems not working fine. I was quite confused for a while, the return value E_UNEXPECTED didn't return much information even with Dr. MSDN.

To write values into the fields in ATL OLEDB, the SetData() function has be to called firstly, and then the Update() function. The SetData() returns DB_S_ERRORSOCCURRED

According to MSDN:


An error occurred while setting data for one or more columns, but data was successfully set for at least one column. To determine the columns for which data was returned, the consumer checks the status values. For a list of status values that can be returned by this method, see "Status Values Used When Setting Data" in "Status" in Chapter 6: Getting and Setting Data.

So I had to check which field returned the bad value, so I called CDynamicAccessor::GetStatus(), and a memo field returned value (8). I ended up deleting this field out of database, it succeeded.

Friday, January 06, 2006

Finally fixed my computer.

I was very frustrated on the old Soyo case because of the loud noise of the battery fan. I went to the local microcenter store to check some possible good deals. Fortunately, I found a Xion case with battery which is 60 dollars. Not bad, and I like one side of the case is transparent, it let me see through the case.

But the process of moving all the parts from one computer to another was not that fun to me. Initially, I thought it should be easy. But the motherboard wouldn't boot after I changed it. I thought it is possible loose memory issue, so I took both memory off, and put them on. It still wouldn't work. I even took the CPU off and put it on again.

I took the computer to the company to ask some help form Dave, who is much more experienced than me on that side. He thought the same issue with me, took one memory off, it booted. Then he took another memory off and put the first memory back on, it worked. It proved both memory were fine. He put both on, and the motherboard booted. Well, I still don't know what I did wrong at home.

Then I took the computer back and put the hard drive and DVD on, the system booted, but the OS wouldn't run. And the BIOS won't recognize any of the drives. I thought the DVD has some issue, so I connected it to the other Dell computer at home. Apparently, it worked. Then I replaced the IDE cable, the OS started. It seemed to me that OS has to boot the IDE devices in the right order. My DVD is on the primary IDE , and two hard drives are on the second IDE. If the OS couldn't find the DVD, it won't go to the next.

It took me three days to get the computer back, after all, I still likes the experiences.

Reverse Method in array.

Reverse Method

I am implementing an revese method of a line in our geometry engine, and I am thinking of how to do the reverse efficiently by avoiding creating extra space.

After I search online, it seems the reverse method already comes with Array class in .Net, and all I need to do is simply calling it.

Easy :-)