Saturday, January 28, 2006

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

Wednesday, December 28, 2005

MSTest.exe Command-Line Options


I designed a test program using the visual studio 2005 testing suites, but i will prefer doing some automated testing using the command line.

After some research online:
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\MSTest.exe is the right tool to launch the test.

Then , it will be easier to add this into the automatic testing in the IDE.

Monday, December 26, 2005

Using the Windows Headers - a good reference

Using the Windows Headers


Platform SDK: Windows API
Using the Windows Headers

The header files for the Windows API enable you to create 32- and 64-bit applications. They include declarations for both Unicode and ANSI versions of the API. For more information, see Unicode in the Windows API. They use data types that allow you to build both 32- and 64-bit versions of your application from a single source code base. For more information, see Getting Ready for 64-bit Windows. Additional features include Header Annotations and STRICT Type Checking.

Microsoft Visual C++ includes copies of the Windows header files that were current at the time Visual C++ was released. Therefore, if you install updated header files from an SDK, you may end up with multiple versions of the Windows header files on your computer. If you do not ensure that you are using the latest version of the SDK header files, you will receive the following error code when compiling code that uses features that were introduced after Visual C++ was released: error C2065: undeclared identifier.

Conditional Declarations

Certain functions that depend on a particular version of Windows are declared using conditional code. This enables you to use the compiler to detect whether your application uses functions that are not supported on its target version(s) of Windows. To compile an application that uses these functions, you must define the appropriate macros. Otherwise, you will receive the C2065 error message.

The Windows header files use macros to indicate which versions of Windows support many programming elements. Therefore, you must define these macros to use new functionality introduced in each major operating system release. (Individual header files may use different macros; therefore, if compilation problems occur, check the header file that contains the definition for conditional definitions.) For more information, see Sdkddkver.h.

The following table describes the preferred macros in use by the Windows header files.
Minimum system required Macros to define
Windows Vista and Windows Server "Longhorn" NTDDI_VERSION >=NTDDI_LONGHORN
Windows Server 2003 SP1 NTDDI_VERSION >=NTDDI_WS03SP1
Windows Server 2003 NTDDI_VERSION >=NTDDI_WS03
Windows XP SP2 NTDDI_VERSION >=NTDDI_WINXPSP2
Windows XP SP1 NTDDI_VERSION >=NTDDI_WINXPSP1
Windows XP NTDDI_VERSION >=NTDDI_WINXP
Windows 2000 SP4 NTDDI_VERSION >=NTDDI_WIN2KSP4
Windows 2000 SP3 NTDDI_VERSION >=NTDDI_WIN2KSP3
Windows 2000 SP2 NTDDI_VERSION >=NTDDI_WIN2KSP2
Windows 2000 SP1 NTDDI_VERSION >=NTDDI_WIN2KSP1
Windows 2000 NTDDI_VERSION >=NTDDI_WIN2K

The following table describes the legacy macros in use by the Windows header files.
Minimum system required Macros to define
Windows Vista and Windows Server "Longhorn" _WIN32_WINNT>=0x0600

WINVER>=0x0600
Windows Server 2003 _WIN32_WINNT>=0x0502

WINVER>=0x0502
Windows XP _WIN32_WINNT>=0x0501

WINVER>=0x0501
Windows 2000 _WIN32_WINNT>=0x0500

WINVER>=0x0500
Windows NT 4.0 _WIN32_WINNT>=0x0400

WINVER>=0x0400
Windows Me _WIN32_WINDOWS=0x0500

WINVER>=0x0500
Windows 98 _WIN32_WINDOWS>=0x0410

WINVER>=0x0410
Windows 95 _WIN32_WINDOWS>=0x0400

WINVER>=0x0400
Internet Explorer 7.0 _WIN32_IE>=0x0700
Internet Explorer 6.0 SP2 _WIN32_IE>=0x0603
Internet Explorer 6.0 SP1 _WIN32_IE>=0x0601
Internet Explorer 6.0 _WIN32_IE>=0x0600
Internet Explorer 5.5 _WIN32_IE>=0x0550
Internet Explorer 5.01 _WIN32_IE>=0x0501
Internet Explorer 5.0, 5.0a, 5.0b _WIN32_IE>=0x0500
Internet Explorer 4.01 _WIN32_IE>=0x0401
Internet Explorer 4.0 _WIN32_IE>=0x0400
Internet Explorer 3.0, 3.01, 3.02 _WIN32_IE>=0x0300

Note that some features introduced in the latest version of Windows may be added to a service pack for a previous version of Windows. Therefore, to target a service pack, you may need to define _WIN32_WINNT with the value for the next major operating system release. For example, the GetDllDirectory function was introduced in Windows Server 2003 and is conditionally defined if _WIN32_WINNT is 0x0502 or greater. This function was also added to Windows XP SP1. Therefore, if you were to define _WIN32_WINNT 0x0501 to target Windows XP, you would miss features that are defined in Windows XP SP1.

You can define these symbols by using the #define statement in each source file, or by specifying the /D compiler option supported by Visual C++. To specify compiler options, go to the Projects menu and click Properties. Go to Configuration Properties, then C++, then Command Line. Enter the option under Additional Options.

Faster Builds with Smaller Header Files

You can reduce the size of the Windows header files by excluding some of the less common API declarations as follows:

* Define WIN32_LEAN_AND_MEAN to exclude APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets.
* Define one or more of the NOapi symbols to exclude the API. For example, NOCOMM excludes the serial communication API. For a list of support NOapi symbols, see Windows.h.

Friday, December 23, 2005

Property settings to generate debug information in a release mode.





A couple of points from a book (Debugging applications fro MS.Net and MS Windows) I am currently read.

/OPT:REF tells the linker to bring in only functions that your program calls directly. OPT:ICF switch will combine identical data COMDAT recrods when ncessary so that you'll have only one constant data variable for all reference to that constant value.

Thursday, December 22, 2005

Walking the stack, pdb file location.

The service I programmed reports some winsock error message and I want to be able to trace the stack to see where the error comes out.

I keep getting meaningless stack :

Stack Testing
(0) : DDTIE911Attribute.exe at ?()
(0) : DDTIE911Attribute.exe at ?()
(0) : DDTIE911Attribute.exe at ?()
(0) : kernel32.dll at IsProcessorFeaturePresent()

I suspected everything, maybe, the version of the debug dll was not right, and I tried to use a sample small program from Several classes for exception handling, and it worked.

Finally, I found that I had to put the .pdb file in the system32 folder, since that was the directory where the service runs. Even the actual executable was in another directoy.

After I put the .pdb file in the system32 folder, yes, I can read the stack trace now.

The way of learning.

Tuesday, December 20, 2005

No pait for you in a single thread application.

If the application has a single thread of execution, so when the thread is doing something, it can't also draw the UI.

After the user puts the application into the background and then the foreground again, the main form must paint the entire client area, and that means processing the Paint event. Because the no other event until the the thread finished the executing, the user will se a white UGLY interface until all the processing finished.

Monday, December 19, 2005

Gunjan Doshi: Using Visual Studio.Net to edit NAnt build files

Gunjan Doshi: Using Visual Studio.Net to edit NAnt build files

Good reference.

IntelliSense for NAnt .build files

IntelliSense for NAnt .build files

Enterprise .NET Community: Managing .NET Development with NAnt

Enterprise .NET Community: Managing .NET Development with NAnt

A very good NAnt tutorial.

Database checking thread

Database checking thread.


One of the issues that E911 server faces is the database connection. Since the database is sitting on another box, so it’s possible that the server reboots, or network goes down.

I posted this question in the atl newsgroup since I know there are a couple of gurus there.

Here is the question I posted.
[
Hi, dear gurus in this group, I have a question about a design to check a valid database connection in my service application. My service is caching a database connection on another server. If for some reason, the database server is rebooted, then my connection become invalid, and any operations will cause an error. 1> Is there any way to get some event that the other database is available after rebooting? if that is the case, I can just simply catch that event and reopen my connection. 2> Another way is that I have to keep polling to check the database connection. Which I cannot run it in main thread since it may take long time, and I don't want to block other work. So I would think creating another thread just dedicated to check the database availability. Do you guys have any good suggestions. Thanks, Jianwei
]

Then , I got a couple of answers from Brian Muth and one answer from Alexander Nickolov, who are both gurus on the group.

[Brain]
Often the simplest solution is the best. If any of your database operations
returns an error indicating the the server is unavailable, then handle the
problem right there (presumably by closing and reopening the connection).

Why wouldn't that work?

[Me]
Hi, Brain, The issue is that the database is sitting on another box,and if I do that way, it may take long time to get some result back (like the connection error), and it will block other work. [Brian]
Ok, first tell me what you anticipate would be the cause of the database to
be offline? Maybe the remote machine has been rebooted, or the disk drive
has overflowed. Perhaps the janitor has tripped over the network cable. Is
pinging the target computer every second going to help your program to
recover any sooner? Of course not.

I'm having trouble seeing how you can make the program more "responsive"
when dealing with a physical connection problem.

Brian

[Alexander]

For example a caching proxy will be affected, e.g. a server that
caches some information and only goes to the database for
cache misses.

The real problem, however, is that the server is single-threaded.

[Brian]

I think it is worth pointing out to the original poster, than connection
pooling comes for free if you package any DB layer as a COM+ object
(assuming OLEDB is being used). One can open the connection object only when
one needs it, and then close it immediately after, and Component Services is
clever enough to look after the connection pooling for you. This "open-late
close-early" strategy is counter-intuitive, but actually scales better in
the long run. I don't know enough of the inner workings to comment on what
CS does when there is a blip in the database server, but I suspect it might
be wiser in the long run to leave the details to CS rather than
"over-engineer" the solution. It probably depends a lot on the requirements,
of which we have heard very little.

Friday, December 16, 2005

How to properly terminate a thread.

The terminating of a thread is a pretty tricky issue, basically, you should never call terminating thread explicitly.

The spawned thread normally runs in Run() method, where it will wait for some shutdown event. In the main thread, when it determeines that the main thread should be terminated, it should set that event, and then wait on the thread handle for it to complete.

void CMainClass::InitiateShutdown()
{
//do some cleaning work.
m_shutdownEvent.Set();
}

After the thread catches that event, it should exits the loop.

And in another Wait() function, the main thread should waits on the Run() to finishe by waiting on that thread object like this:

DWORD result = ::WaitForSingleObject(m_hThread, timeoutMillis);

Then the main thread will be able to exit.

Wednesday, December 14, 2005

Several classes for exception handling - The Code Project - C++ / MFC

When C++ programs crashes, sometimes, it's really hard to figure out where it goes wrong exactly. .Net improved a lot on this aspect, you can find out where it crashes by pritinting out the stack trace.

Konstantin Boukreev's approach allows you to print out the stack trace in the exception hanlder, which is very useful to diagonose the problem.

There is a very similar article also on code project called Walking the callstack , which is also helps you to find out the stack trace in VC++.

Monday, December 12, 2005

/* Rambling comments... */: Testing Windows Services

Len always have some cool idea on how to program effectively. The atl framework my service based on has some good design to debug the OnStart method. In the debug mode, it will be registed as "Local Service", this will make it easier to run it in debug mode.

However, the only way I can stop the servcie is press "shift-F5" , and this cannot help me much in debugging the right clean code.

Inside RunMessageLoop, my service is waiting for the ShutdownEvent , if running as a service, that event will be sent throgh the SCM (The SCM registered the handler function like this:

void Handler(DWORD dwOpcode) throw()
{
T* pT = static_cast(this);

switch (dwOpcode)
{
case SERVICE_CONTROL_STOP:
pT->OnStop();
break;
case SERVICE_CONTROL_PAUSE:
pT->OnPause();
break;
case SERVICE_CONTROL_CONTINUE:
pT->OnContinue();
break;
case SERVICE_CONTROL_INTERROGATE:
pT->OnInterrogate();
break;
case SERVICE_CONTROL_SHUTDOWN:
pT->OnShutdown();
break;
default:
pT->OnUnknownRequest(dwOpcode);
}
}

But in debugging mode, the event can be simulated from a different process. This will rely on a named event, which can communicate between different processes.

Tuesday, October 25, 2005

Return a string in COM methods.

In a typical com function which returns a string, people could make an error easily like the following one:

STDMETHODIMP MyClass::MyFunction(BSTR* pRet)
{
// This is how I return a string - is this incorrect?
std::string myString;
CComBSTR bstr (A2W (myString.c_str()));
*pRet = bstr;
return S_OK;
}

Issue with this is : while pRet points to the bstr , but bstr is defined inside the function scope, so when it goes out of the scope, the CComBSTR destructor will be called like this:

~CComBSTR() throw()
{
::SysFreeString(m_str);
}
which now makes pRet point to a dangling pointer.

An appropriate way is detach the m_str from the CComBSTR , so even when the destructor is called, the m_str won't be destroyed.

BSTR Detach() throw()
{
BSTR s = m_str;
m_str = NULL;
return s;
}

Monday, October 10, 2005

Forward declaration of a template class.

Forward declaration of a template class.

This issue confused me a little bit when I try to declare a template-based class as a friend class of another class.

The issue is like this:

<template class T>
Class A
{
Public:
Private:
}

Class B
{
Public:
Private:
     int m_b;
}

And Class A wants to access the private member m_b in Class B, the forward declaration of A will be like this:
template <class T>  class A

Friday, October 07, 2005

Exception Handling Model

Exception Handling Model /Ehs and /Eha

The exception handling model specifies the model of exception handler used by the computer.

Eha : The exception handler catches the asynchronous structured exceptions and tells the compiler to assume that extern C function do throw an exception.

Ehs: The exception handler doesn’t catch the asynchronous exceptions and tells the compiler to assume that extern C functions do throw an exception.

Ehc: It can be used either with the Eha or Ehs, but it assumes that extern C functions never throw an exception.


XmlDocument.Load and XmlDocument.LoadXml

I was playing around the xml tree view control which I found from the codeproject, but keeping getting "The data at the root level is invalid".

Later on, I find I am confused between XmlDocument.Load and XmlDocument.LoadXml, the former always load an xml file based on the file name, while the later will accept the actual xml document.

JST Robust issue

JTS union may *not* be commutative or associative in the strict sense. In other words, different ordering of the operands may produce slightly different results. This is an unavoidable result of using finite-precision arithmetic to compute operations which inherently require higher precision.

The difference should normally be *very* minor, however. The one time this is not the case is when the first operation produces a robustness error. In this case obviously the two results can be very different (e.g. an exception, versus an actual return value).

> Is this simply a bug that has been fixed?

Yes, this probably reflects an improvement that was made in the intersection calculation.

> Should a union of two valid Geometry's always yield a valid Geometry?

Yes, if the operation completes successfully, the result will always be a valid Geometry. Unfortunately, in the current implementation, sometimes overlay operations can also result in robustness errors. (This is something I'm hoping to fix in a future release).

I notice that your data seems to be fairly limited in precision. You might try using a fixed precision model - this can sometimes alleviate robustness problems.

Martin Davis, Senior Technical Architect
Vivid Solutions Inc. www.vividsolutions.com
Suite #1A-2328 Government Street Victoria, B.C. V8T 5G5
Phone: (250) 385 6040 - Local 308 Fax: (250) 385 6046

Monday, August 08, 2005

BeginInvoke Method

BeginInvoke Method

BeginInvoke is a method of Control, and it executes a delegate asynchronously on the thread that the control's underlying handle was created on.

Sunday, August 07, 2005

How virtual Memory works?

The virtual memory system allows only part of the memory required by the process to be resident in physical memory. Say, if a process requires 500 mb memory, but it may only have 20% memory sitting in physical memory, the other 80% may actually stay on the disk.

Demand Paging

1>When a process requests a block of memory, it check the internal page table for this process to determine whether the reference was a valid or invalid memory access.
2>If the reference is invalid, we terminate the process. If it was valid, but we have not yet brought in that page, we now page it in.
3>We find a free frame by taking one from the free-frame list.
4>We schedule a disk operation to read the desired page into the new allocated frame.
5>When the disk operation is complete, we modify the internal table kept with the process and the page table to indicate that the page is now in memory.
6>We restart the instruction that was interrupted by the illegal address trap.

Paging

1>Paging allows the logically continuous memory to be scattered through the physical memory out of order.
2>Suppose the logical address space is 2**m, and the page size is 2**n, then the high order m-n bits are designated as page number, while the lower n bits are designated as offset after the particular physical page has been found.
3>The TLB is the quick look up to speed up the page table translation, it will quickly find the entry for the logical address. If the TLB is missing, then we need to look up the page table to find the right entry.
4>If the logical address space is very large, and the page size is relatively small, it will lead to a very large page table. We have to use a couple of techniques such as "multi level page table", "inverted page table" to reduce the size.

Finalizer and Disposer

Finalizer is an implict cleanup, which relies on the GC to clean up the resources, while the disposer is explicit cleanup, which allows to clean up the resources explictly. The .Net supports both patterns, so it is very important to distinguish them. In general, explicit cleanup should be used favorably over the implict cleanup, since the resources are generally more precious than memory, we shouldn't really rely on the GC to hold it for long time and clean it after an unspecified time.

Annotation (Brian Grunkemeyer): There are two different concepts that are somewhat intertwined around object tear-down. The first is the end of the lifetime of a resource (such as a Win32 file handle), and the second is the end of the lifetime of the object holding the resource (such as an instance of FileStream). Unmanaged C++ provided destructors which ran deterministically when an object left scope, or when the programmer called delete on a pointer to an object. This would end the resource’s lifetime, and at least in the case of delete, end the lifetime of the object holding onto the resource. The CLR’s finalization support only allows you to run code at the end of the lifetime of the object holding a resource. Relying on finalization as the sole mechanism for cleaning up resources extends the resource’s lifetime to be equal to the lifetime of the object holding the resource, which can lead to problems if you need exclusive access to that resource or there are a finite number of them, and can hurt performance. Hence, witness the Dispose pattern for managed code, allowing you to define a method to explicitly mimic the determinism & eagerness of destructors in C++. This relegates finalization to a backstop against users of a type who do not call Dispose, which is a good thing considering the additional restrictions on finalizers.

In the Dispose(bool disposing) method, if the diposing passed in is true, it means that we can explicitely use other reference types that refer to other objects knowing for sure that those other objects have not been finalized or disposed yet. If it's false, we cannot refer to other resources since those objects may have already been freed.

When we inherit a class which has already correctly implemented "IDispose" pattern, we need only override the Dispose (bool disposing) class, we don't need to override the Finalize and Dipose class.

Saturday, August 06, 2005

Internal Fragmentation and External Fragmentation.

In the memory allocation model, if the memory is partitioned into the fixed size blocks[M bytes a block], then when a process(N bytes) is allocated into the memory, it will fit the first N/M blocks, and occupy the part of the last block, and this is called "internal fragmentation", since the fragment is internal to a block.

The other model is called "external fragmentation", the memory is NOT partitioned into the fixed size. It will maintain a free list of "available" memory blocks and select the best fit for the waiting process. The fragment is external to any occupied blocks so it is called external fragmentation.

Wednesday, August 03, 2005

What is delegate in C#

Delegate is a class, NOT a method. It is a class inherited from System.Delegate or System.MulticastDelegate, which has two properties called "Target" and "Method". The target is the class instance on which the current delegate invokes the instance method, if it is null, it means it's a "Static" calling. MethodInvoker or EventHander are two special delegates treated in a fast manner by Invoke and BeginInvoke. MethodInvoker takes no parameters and returns no value, and EventHandler takes two parameters and returns no value.

Notifications

Notifications

It takes me a while to figure out why the legend control is not updated correctly until I found this sentence.

The applications that rely solely on WM_VSCROLL (and WM_HSCROLL) for scroll position data have a practical maximum position value of 65,535.


The GetScrollInfo function enables applications to use 32-bit scroll positions. Although the messages that indicate scroll-bar position, WM_HSCROLL and WM_VSCROLL, provide only 16 bits of position data, the functions SetScrollInfo and GetScrollInfo provide 32 bits of scroll-bar position data. Thus, an application can call GetScrollInfo while processing either the WM_HSCROLL or WM_VSCROLL messages to obtain 32-bit scroll-bar position data.

To get the 32-bit position of the scroll box (thumb) during a SB_THUMBTRACK message in a WM_HSCROLL or WM_VSCROLL message, call GetScrollInfo with the SIF_TRACKPOS value in the fMask member of the SCROLLINFO structure. The function returns the tracking position of the scroll box in the nTrackPos member of the SCROLLINFO structure. This allows you to get the position of the scroll box as the user moves it. The following sample code illustrates the technique.

SCROLLINFO si;
case WM_HSCROLL:
switch(LOWORD(wparam)) {
case SB_THUMBTRACK:
// Initialize SCROLLINFO structure

ZeroMemory(&si, sizeof(SCROLLINFO));
si.cbSize = sizeof(SCROLLINFO);
si.fMask = SIF_TRACKPOS;

// Call GetScrollInfo to get current tracking
// position in si.nTrackPos

if (!GetScrollInfo(hwnd, SB_HORZ, &si) )
return 1; // GetScrollInfo failed
break;
.
.
.
}

Wednesday, July 27, 2005

Test the E9-1-1 Server.

It has been pretty stressful for me to write the testing code for the E9-1-1 server these days. Multithreading programming is always challenging, it's hard to debug, the code is flowing all around, and it's easy to make mistakes with those locks, monitors, wait handles. But it's also enjoyful to dig into those codes.

After finishing the test codes, the server part also needs extensively refactoring, the I/O completion port should be used to replace the polling, the so called "virtual multithreading" should be replaced by true multi-threading.

Tuesday, July 26, 2005

Bing will go to Hospitality and Tourism Management Program - College of Charleston

Hospitality and Tourism Management Program - College of Charleston

This blog is a little bit late, but still, I am very proud of him when I heard that he will head to College of Charleston to become a faculty.

Bing inspired me a lot in my life. When I was still at Nanjing University, I saw him get very high score in GRE, go abroad successfully, all of those things have a very good impact on my life.

After coming to states, we have choosing different roads. He is finishing his PH.D. and then go to Cornell , firstly in the CS master program, then transfer to a PostDoc in the Info Lab. I know his road is not smooth, but he goes through this step by step.

I hope he will do well in the future as a faculty, which he could be even 7 years ago in Nanjing University.

Wednesday, July 20, 2005

中文博客.

写写中文试试看.

keyboard shortcut assignment in textbox

keyboard shortcut assignment in textbox
All 2 messages in topic - view as tree


I'm building a form to allow the user to assign a keyboard shortcut.
Basically I have a textbox that I want to work like the "Press shortcut
key(s)" in the Visual Studio keyboard options, the user does the key
combination and it shows up in the textbox. It looks like it works on the
KeyDown event. The KeyDown event has an argument of KeyEventArgs. The docs
say "You can use constants from Keys to extract information from the KeyData
property. Use the bitwise AND operator to compare data returned by KeyData
with constants in Keys to obtain information about which keys the user
pressed. To determine whether a specific modifier key was pressed, use the
Control, Shift, and Alt properties." Unfortunately there is no example and
I don't know how to do bitwise compares in c#. Can someone help me out
here?

thanks
Paul




first, set Form1.KeyPreview value to "true"

then, on Form's KeyDown Event

private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs
e)
{
//Note: "T" is a sample designated shortcut key for textbox
if (e.Modifiers.ToString().ToUpper() == "ALT" &
e.KeyCode.ToString().ToUpper() == "T")
this.textBox1.Select();

}

gani

How Static Method works.

[Question:]
What if two users call the static method at the same time? Since the
method is static, is any data within this method (parameters passed in and
local variables declared within the method) also considered static and shared for all users of the class?

[Answer:]
If the method is not accessing other static variables,
and is only working with references/values that are stored on the stack (in
other words, declared in the function), then you should have nothng to worry
about. The only thing you have to worry about at this point is other
resources you might be accessing (for example, the same file, if you are
working with files).

Tuesday, July 19, 2005

Can you find YY on this page?



This picture is supposed to taken by a professional photographer, well, can you tell how professional it is. If you cannot, then you have the same idea as mine, the so-called professional photographer is totally bullshit.

Monday, July 18, 2005

The priorty date issue.

[Email from my attorney:
Jianwei

You are going to create a serious problem for yourself if you continue to try and use multiple avenues to push this along. The DOL and USCIS are going to start to push back. Up to now, I think your calls and actions have been just a question of impatience, but you are about to cross the line to a problem. I have seen cases where the agencies get calls from several sources, dig in their heels, and do nothing just to spite the individual because they feel there is too much pressure.

Please, I am serious. If you want me to work on this, you are going to have to back off and be patient. If you are convinced that you need to call dozens of people and push hard, I will be happy to submit a withdrawal letter, and you can handle it on your own. However, I can't do both. You need to make a decision whether you are going to handle your case on your own, or whether you want me to continue to work on it.

I called John today and left a voice mail. I will talk to him when he calls, and see what I can do to find out where in the process the information is stuck, if in fact it is stuck at all. But if you are going to make calls through Congressional offices, have the lawyer call, have the manager call, and check back a few days later for all, you are going to sabotage the process. I know that the government agencies will ignore the file if they think that is what is going on.
]

Well, I feel a little bit frustrating. I think Rob did a pretty good job on my case, and I don't have any issues with him. After all, the whole thing is not his responsbilty. But it still frustrates me, I have been waiting for this for the last three years, and every step seems to have a lot of pains. I adimit it is an issue because I have limited ability. If I am truley outstanding, I may not have to go through this painful process.

Life is life, you just have to live with it. If you spend more time improve yourself, there will be less pain ahead.

Sunday, July 17, 2005

Columbus, Ohio: Dentist Reviews, Dentist Ratings, Dentist Recommendations and Dentist Help.

Columbus, Ohio: Dentist Reviews, Dentist Ratings, Dentist Recommendations and Dentist Help.

Well, I was suggested by my dentist to get my wisdom teeth out. Since xiaoyi had very bad experiences when she did it two year ago, and I am a little bit worried. I don't want to lie on the bed for two weeks after doing the surgery.

This seems a pretty good place to see other people's reviews about a particular dentist. Unfortunately, it is not very complete.

Tactus Touch Typing Keyboard - Keyboard Posture - Correct Posture

Tactus Touch Typing Keyboard - Keyboard Posture - Correct Posture

I feel a little bit hurt on my back of arms, and I think it is caused by incorrect posture of typing posture. It is very important to keep it right.

Friday, July 15, 2005

A regular expression help from C# newsgroup

: I am trying to parse out the apratment number in a regular expression :
:
: If I use
:
: Regex regex = new
: Regex(@"[...](?\bAPT|#|UNIT\b)[...]",
: RegexOptions.ExplicitCapture);
:
: I will be able to parse out "100 main ST # C)
:
: But if I move "#" position in regular expression, I won't be able to
: parse out the same address anymore.
:
: Regex regex = new
: Regex(@"[...](?\bAPT|UNIT|#\b)[...]",
: RegexOptions.ExplicitCapture);

The latter fails to match because there's no word boundary (\b) between
an octothorpe and a space. Remember, a word boundard occurs between a
\w and a \W or vice versa, but '#' and ' ' both match \W.

A start in the right direction is (line breaks inserted):

(?.+)
(?\b(APT|UNIT)\b|#(?=\s+))
(?.+)

Hope this helps,
Greg

Thursday, July 14, 2005

The powerful unit testing.

The whole idea of unit testing is to ensure that you won't break already-working codes when you refactoring. Address Parsing is a very good example, there are a lot of different situations, and it's very easily that you break some codes when you modify the regular expression rules.

The better way is to put everything into an XML file, and run the parsing through the XML file every time when modifying something. That way, you will always ensure that something already working well won't be broken when regular expression rules are added, modified, or delete.

Another way to learn from JTS, the great library.

Wednesday, July 13, 2005

How JTS cropping works.

JTS is very cool, the algorithm is complex but really powerful. All the intersection/union/difference/symmetry difference operations in all kinds of geometry types could be done in a very generic algorithm.

How the cropping works, here is what I understood:

1> The first step is to get all the intersection points between two geometries. The algorithm used here is the sweep-line algorithm.

2> Then it will need to create the split edges based on those intersection points. The split edge is the edge between two intersection points on the same geometry.

3> For each split edge, we have two directed edge end generated from it. One is starting from the beginning, and the other one is starting from the end. For the labelling, if it starts from the beginning, it will use the parent edge label, if it starts from the end, it will filp the parent edge label.

4> Based on those directed edges, we can create a planar graph, and all the vertices in the graph are made from the starting point of the directed edge end.

5> We need compute the labels (topological relationship) of the directed edge and vertice relative to the two different geometries.
a> Each edge end in the edge end map has a label.
b> The edge end star map has its own label, which will be used to update the label of the node.
c> Get the starting edge in the edge end star map, loop through each edge in the edge end map, and compute the labelling location.
d> We also need to merge the label from one directed edge with its symmentric directed edge.
e> Merge the label of the node with the label of the edge end star map.


6> We can determine whether each edge is in result or not based on the topological relationship with two geometries. For each different operation like intersection / union / difference, the criteria to determine whether it is in result is different.

7> We sort each vertice in the planar graph firstly by X coordinate, then by Y coordinate. By looping each vertice in the graph, we will determine how the edges in each vertice link together.

8>For the polygon building, we must determine which edge will actually qualify for the result polygon. There are generally three conditions which will make it qualify for the polygon edge:
8-a. The label of the edge has to show that it is an area edge to both geometries.
8-b. The edge is not an interior area edge. The interior area ege means that the label is an area label for both geometries and for each geometry, both sides are interior.
8-c. The right sides of the edge to both geometries should be inside.


9>We build the maximal edge ring and minimum edge ring based on linking results.
The maximal edge rings will be built firstly, and then we loop through each node. If there are more than one outgoing directed edge which is in result, we must consider the minimal edge ring too. Because if we have one more outgoing edge in one particular vertice, it means that we cannot simply link the edge to form a polygon, we must do another step to form the minimum edge ring, which is based on the maximum edge ring.

10> The actual geometries are built based on the linking results. If there are only maximum edge rings, then build polygons based on that. If there are minimum edge rings, then we need build polygon based on it instead of maximum edge rings.

11> We will collect the geometries in the following order: polygons firstly, lines second, and points last. The lines could be generated by an input geometry of line, or
two touching polygons.
GISResearch

Monday, July 11, 2005

Very good regular expression site.

Very good regular expression site.

The world of regular expression is very exciting, but it is also very error prone when you try to build those complex rules. A good rule is very helpful to understand and build the rules. Regular Expression Workbench at goddotnet.com is very powerful tool to build the expression rules dynamically.

I mainly use the regular expression rule for the address parsing. The previous method I used is brute-force parsing, it's not very pleasant though it does the work. In the newer version, I hope I can build a much powerful tool to parse the address, and hopefully, publish it to the codeproject.com

Thursday, July 07, 2005

UML Diagrams

UML Diagrams

A simple introduction to UML diagrams.

Obfuscation and Decompilation

Obfuscation and Decompilation

Good Article about Obfuscation and Decompilation.

Thursday, June 16, 2005

Finally get a way out.

The dead hard drive has made me in a disaster in the last three days, thanks for Dave's help, without his help, I may spend much more time to recover the data.

The hard drive we ordered from CompUSA finally came this morning, but it is not what we had hoped. We hoped that there is an internal SATA that we can swap my bad disk in, but it's not the case. Another way dead.

Then Dave suggested that I can try another SATA - IDE bridge card, I went to microcenter to get it, tried it again on his computer. The computer cannot recogize the drive. Another way dead.

The only way left is to run the system on WinPE from CD-ROM based on suggestions from http://www.runtime.org./peb.htm before putting it into the freezer. Dave helped me burn a CD again. You know what, it worked!!!!!

Wednesday, June 15, 2005

Dead hard drive.

I have tried to run the Maxtor Hard Drive Self -checking utility (with Chris's suggestion) , and the drive is not good.

We have tried to put the hard drive in another computer yesterday, it is not even starting.

I also checked the order you made yesterday, and that hard drive is supposed to come tomorrow, I am going to swap my drive into that USB box, and I hope this at least will make the main computer with good drive boot.

I am suggesting the following steps:

1> If the drive is readable , we can simply copy the data out. ( I seriously doubt on that).
2> If the drive is not readable, we can try the GetDataBack, the good thing about this is that you can check how much files you can recover before buying the license code. (Scan is free, and copying needs license).
3> If 2> doesn't work, I read some posts that some people successfully get the data out by freezing the hard drive overnight, I will give it a try.
4> If nono of them work, then I probably have to rewrite some codes. As I told you guys, most of my codes are in source safe, especially important ones, but there are still quite a few recent updates not in source safe , and some utility programs I wrote. I will spend some extra hours to do some code recovering from my brain.

But I think Dave and you have much more experiences on that, so give me hints if you guys have.

I will take this afternoon off, and work on Saturday morning.

Monday, June 06, 2005

Roland Weigelt's GhostDoc

Roland Weigelt's GhostDoc

I have been looking for this plug-in for the whole day. I firstly heard about that in the Day of .Net Columbus meeting, but really didn't pay attention to that. Suddenly today, I find I desperately need this tool to help me write some comments.

It is good that I find it finally.

Microsoft AntiSpyware blocks tests from running.

I had tried using Team System Test in VS2005 to develop test projects, but everytime when I started the test, the result shows "aborted", and Microsoft AntiSpyware pops up a box quickly.

This issuue has driven me nuts for a while until I found a known issue here:

Issue: Microsoft AntiSpyware blocks tests from running.

Details: If Microsoft AntiSpyware's real-time protection is enabled with the default configuration, the running of unit tests will be blocked and all tests will end in Aborted.

Workaround: Deactivate the Script Blocking Checkpoint in Microsoft AntiSpyware.

1. Open Microsoft AntiSpyware.
2. Select Real-time Protection.
3. Click the "Application Agents" link in the Security Agents Status panel.
4. A list of Application Agent Checkpoints will be displayed. Scroll down to find "Script Blocking."
5. Click on the "Script Blocking" checkpoint.
6. From the "Checkpoint Details" pane, choose "Deactivate Checkpoint."

Sunday, May 08, 2005

Instance Constructor vs. The Class Constructor

Instance Constructor vs. The Class Constructor

A good explanation of difference between the instance constructors and the class constructors.

Class constructors are used for static field initialization. Only one class constructor per type is permitted, and it cannot use the vararg (variable argument) calling convention. Normally, class constructors are never called from the IL code. If a type has a class constructor, this constructor is executed automatically after the type is loaded. However, a class constructor, like any other static method, can be called explicitly. As a result of such a call, the global fields of the type are reset to their initial values. Calling class constructor explicitly does not lead to type reloading.

MS Access Application With C#

MS Access Application With C#


I encountered this problem when I wrote the map projection function for the DTMap, since I need to get some data from the EPSG_v66.mdb and write it to the xml file. I think this is a good start.

Thursday, May 05, 2005

Waiting for the I-140 aproval.

Waiting for the I-140 approval is one of the most painful thing in my life, the response to the RFE has been submitted last week, and USCIS records shows that they have received the response on Apr 26. Then in the following three days, 27, 28, 29, the LUD keeps change, so I guess that somebody is working on my case. However, after that, nothing happens. Well, this is also normal, accoridng to the pattern observerd on the immigration.com, a lot of people have the similar experience.

Hopefully, I will have it approved by next week.

God bless me!

Monday, May 02, 2005

Split a string by double pipe.

How to split a string like "TEST1||TEST2".

I raised this question in C# MS newsgroup, and Tim Wilson answered my question that I should use

string[] asTest = Regex.Split(sTest, @"\|\|");

Well, this works beautifully. But it takes ome time for me to fully understand it. Fristly of all, "|" is considered one of the special characters (. $ ^ { [ ( | ) * + ? \) in the regular expression , so \ signals to the regular expression parser that the character following the backslash is not an operator. Then, how about string[] asTest = Regex.Split(sTest, "\|\|"), The compiler complains error CS1009: Unrecognized escape sequence. Will it make sense? According to MSDN , it means that "An unexpected character followed a backslash (\) in a string. The compiler expects one of the valid escape characters", then what is valid escape characters, | is a NOT a valid character following \, by using @ , we mean \| Unicode character 007C, do you understand, I am NOT.

Friday, April 29, 2005

Programming C#: Working with Arrays

Programming C#: Working with Arrays

C# makes working with arrays much easier and enjoyful.

Saturday, April 23, 2005

Finally the response to my I-140 RFE is filed.

The RFE was issued on Feb 25, 2005, so it was almost two months ago. Firstly, it took some time to get the supporting letter from CHINA, then the attorney started to look at my case after two weeks. Then after that, we found that ODJFS screwed up the priority date, so we waited another two weeks to deal with issue.

Finally, the package was sent out on Thursday night, hopefully, I can get it approved next week.

It will be such a relief.

Friday, April 22, 2005

Good example in XML Serialization in C#

XML Serialization in C#

Best examples to demonstrate the xml serialization.

Sunday, April 10, 2005

Too many things to do.

Always feel too many things to do everyday. Working is the most important, but also a lot of reading. I am always exciting to get a new book, but rarely get enough time to go through. Well, maybe, just try my best.

Browsing web has been the worst thing I can ever do to waste the time, sometimes, I just cannot control myself, reading those stupid news.

Answering other people's questions in newsgroup seems a better way to relaxing.

Wait for the pictures of Albany trip from Lingling and Dawei.

Tuesday, March 22, 2005

Excited trip to Albany, NY

I am excited to visit my freind, Lingling and Dawei. They just bought a new house , and we are excited to check it out.

One house, two cars, and a dog is a typical American life which I have seen in movies and imagined in my head. I still have one house, one car, and a dog left. Maybe, I need to work harder on this.

TDD: Testing Internal classes

TDD: Testing Internal classes

Nice trick to test the internal class, plus another trick to test private methods( http://www.codeproject.com/csharp/TestNonPublicMembers.asp). I should be able to test whatever I want to test.

Sunday, March 20, 2005

Essential .Net by Don Box.

Like all other books written by Don Box, I can always learn something which I cannot learn by day to day programming. Though I still insist the best way to learn programming is still through coding.

The chapter 7 "Advanced Methods" has a lot of similarities with the ideas expressed in "Transactional COM+". All objects are living in context, and context decides the behavior of the objects.

Good book, recommend for reading.

Tuesday, March 08, 2005

C# and .NET articles and links

C# and .NET articles and links

A very good C# resources. I read about this person from MS C# newsgroup, and then find this out. Really easy understanding tutorial. Compared to a lot of C# books, this one has a lot of practical approaches. Strong recommended , A++.

Sunday, March 06, 2005

The best online Computer Science resources I have ever found.

CS Classes

I start to read this when I prepare the CS GRE subject test, this is by far the best online resources I have ever found on Internet. Though I didn't do well on Nov, 2004 test, but I think I learned a lot in the process of preparing it. I got a lot of trouble in ansewring those questions related to virtual memory, cache, pipeline, and also computation theory. Well, I won't say the questions are too difficult, it's just all about myself. I don't have a solid understanding on those concepts , it's also understandable for a geography major. But I still think I am on the right track.