Some C++, C#, .Net, windows service, GIS thoughts posted by me. 有度量去容忍那些不能改变的事,有勇气去改变那些可能改变的事,有智慧去区分上述两件事。
Sunday, April 08, 2007
This is what Rumsfeld said. I am sure this infamous saying also played a rule for his step down as Secretary of Defense. But I guess it also applies to a lot of developers like us. As a developer, you normally don't have the option to choose the best tools you have because you are the money maker, but NOT the money decision maker.
In the company worked before, we use visual studio professional to develop some performance sensitive application (GIS). The application involves a lot of graphics rendering, geometry processing, some real hard-core algorithm. We encounter some performance issue, and really would like some professional tools to profile it. But again, we cannot make the decision, because the visual studio team edition costs much more than the professional edition.
Now, I am working on Team Edition for software developer on my new job, but my current job uses so much database functionality, and I really hope I can have Team Suite, which contains the database piece of the Team edition. But again, I cannot make that decision.
Sometimes, as a developer, you just have to work the best with what you have. If you cannot make a decision or persuade the management to make a decision to offer sophisticated tools for you, just try to find some open source, or free tools.
Sometimes, you may have to go back to use some old fashion command way to finish your stuff.
I really hope I, as a developer, have more right in the company to decide what tools I want to use.
Monday, February 26, 2007
Visual studio 2005 Class Designer
I am not a big fan of UML, or any diagram in the development process. The biggest issue I found is the inconsistency between those nice diagrams and the actual codes. I just found it's too difficult to think over every possible situations at the beginning stage of the project, not just the developers. The clients also have the same issue, they are not very clear what they want too at the beginning. I find out unless you are a real guru in making those nice diagrams, and you can always make changes to those diagrams very fast ( I am NOT), it's so hard to keep those diagrams consistent with your code when the project requirements change.
The visual studio class design is a different story. The changes you made to the designer can be applied to the code instantly, on the other hand, the changes you made to the code can be applied to the designer instantly too. You don't have to worry about two pieces any more, you can just worry about one piece.
There is a power toy for the enhancement here too.
Sunday, January 21, 2007
check in the test project in Google code.
I have never tried to host my own project before. So, I want to give it a try.
The tools I am using TortoiseSVN, which also has a sibling called TortoiseSVN. Both are very handy tools.
Here are the steps I followed:
1. Create a project on google code.
2. Right Click the project folder , and select "Import " to check the source code into the google code repository. It will prompt for the url , use the http://**.**.**/trunck.
3. After the codes were imported into to the server, I tried to make some changes to the code, but it gave me an error (MKCOL405) when I tried to make some changes and commit the changes.
4. So, I deleted the original project, and tried to check out the project from the svn. It created a little folder (.svn) under the project folder. I believe it has all the information which the TortoiseSVN tool needed to communicate with the server.
5. Now, it seems that I can make the changes, update the server, and compare the changes.
Start to review some college stuff.
I guess many developers nowadays rely too much on libraries, without enough attention paid to how those libraries were actually develped.
I think I need some time to review some basic codes like how to write some basic data structure and their operations.
1. link list.
2. stack.
3. queue.
4. tree.
5. graph.
What is managed resources.
Something like this:
MyResource:IDispose
{
~MyResource()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{if(disposing)
{//clean up managed resources.
}
//clean up unmanaged resources.
}
So, my question is : what exactly is the unmanaged resources?
Are GDI+ objectes considered unmanged resources ? How about sockets, other windows resources ... ?
David Kline has a good example here :
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Snippet
{
///
/// Wrapper for the Win32 Device Context (DC)
///
public class DeviceContext : IDisposable
{
// the Win32 Device Context (DC) object
private IntPtr hDC;
// window handle associated with the DC
private IntPtr hWnd;
///
/// Constructor.
///
///
/// The window handle for which to retrieve the device context
///
public DeviceContext(IntPtr hwnd)
{
// call the p/invoke to get the device context for the specified window handle
IntPtr hdc = GetDC(hwnd);
// verify that the GetDC call succeeded
if(hdc == IntPtr.Zero)
{
throw new Exception("Failed to get the DeviceContext for the specified window handle");
}
// store the window handle and device context for future reference
this.hWnd = hwnd;
this.hDC = hdc;
}
///
/// Finalizer
///
~DeviceContext()
{
// dispose the object (unmanaged resources)
this.Dispose(false);
}
///
/// Cleanup the object (implementation if IDisposable::Dispose)
///
public void Dispose()
{
// clean up our resources (managed and unmanaged resources)
this.Dispose(true);
// suppress finalization
// the finalizer also calls our cleanup code
// cleanup need only occur once
GC.SuppressFinalize(this);
}
///
/// Cleanup resources used by the object
///
///
/// Are we fully disposing the object?
/// True will release all managed resources, unmanaged resources are always released
///
protected virtual void Dispose(Boolean disposing)
{
if(disposing)
{
//*** release any managed resources
}
// release unmanaged resources
if(this.hDC == IntPtr.Zero)
{
// we're already been disposed, nothing left to do
return;
}
Int32 ret = ReleaseDC(this.hWnd, this.hDC);
this.hDC = IntPtr.Zero;
this.hWnd = IntPtr.Zero;
// assert if the DC was not released.
Debug.Assert(ret != 0,
"Failed to release DeviceContext.");
}
//*** add desired p/invoke definitions
}
}
Based on my experiences, most of the unmanaged resources have been already wrapped inside .Net class, and those are really should be treated like managed resources. For example, those objects defined in System.Drawing like bitmaps, fonts, meshes and textures, they are managed objects containing reference to unmanged resources.
I have a windows service program which depends a sql database. Sometimes, when the machine starts and my program tries to connect the database, the da
I tried to a couple of solutions :
1> The first one I tried to is to set the recovery options of the service property, set it to restart the service if it fails. I actually misunderstand this property until I got an reply from a msdn newsgroup:
>2> Another solution I tried is to create a database watching thread. Instead of aborting from the startup procedure, the watching thread will keep checking the database connection, and notify the main thread when the database is available.
>> Recover options are only relevant if your service executable crashes, not
>> because of any HRESULTs which might lead to ending a process. If a
>> process is just ending by leaving all thread functions that is pretty OK
>> for the service control manager.
>>
>> You could try something like int *p = NULL; *p = 42; that should crash
>> your service and the restart should occur after the configured time
>> interval. Defaults to 1 minute IIRC.
This approach is working, but it's a little bit overkilling. Everybody knows that the thread should really be avoided unless it's absolutely needed. In my case, if the database is not connected, my program is not workable any way, since I need the information from database to perform a lot of things...
The final solution I come out is putting the database checking in a while loop, which will check the database connection a configurable times (10 times by default) at start up in every 10 seconds.
This solution has 2 advantages:
1> The start up procedure of my service won't abort immediately if the database is not available. And in my cases, most of times, the database is available, it's just a little bit slow to come back.
2> If it really failed after trying to connect to the database after certain attempts, it may need some attention anyway.
What makes a good programmer.
1>design patterns
I think it's the far most important one, the life of the software depends on how easy you can maintain the software, how easy you can add a new feature, how easy you can modify an existing feature. Every programmer can write some codes, but the difference is how they organize the codes. The seasoned programmer always bears in mind how s/he can maintain it when s/he implements some codes.
2>Language Features
Familiarity of the languages, including the libraries associated with the particular languages. There are a lot of languages available, C#, C++, Java..., and nobody could be very familiar with each of them, just as nobody could speak every language in the world. But a good programmer has to be very familiar with one or two languages s/he uses in day to day work. Efficiency also comes from this, if you know the language feature well, it's easier for you write clean code.
I often read code I wrote when I just started to work 5 years ago, and I feel it's ugly, and a lot of them are NOT very sophisticated. Sometimes, an experienced programmer can write two lines of codes which an inexperienced programmer may need write more than 10 lines of code.
3> Algorithms
That's the part I missed all. In day to day work, a lot of focuses are on RAD (Rapid Application Development). Most of time, you don't have to think about too much on the underlying algorithm, you'll just find some data structures in the library, rarely you'll have to write something really serious. This kind of work will make smart people dumb because they don't get chance to think deeply.
4> Resource Handling
Computer is a shared resource. The computer your program is running also includes a lot of other programs. It means, if you want to use certain resources , you are borrowing some resource from the computer, after using it, you want to give it back to the computer. If you don't , it means other people won't be able to use it.
The situation has been improved steadily with new technologies or research efforts underway. If you work in a managed world like C# or Java, you have less worry since GC did a lot of work for you. But still, there are a lot of resource the GC won't handle for you automatically, or in other word, you cannot rely on GC to take care for you.
5> Tools
Making good use of the tools. I know some geeks like to program in notepad, and open a command window to do everything. I admire those people since it reflects that those people really understand what's under the hood. And a lot of times, they can do thing more efficiency.
For me, like most other people, I like powerful IDEs like VS.Net and Eclipse, even though I don't have much experience in the latter one. Jon Skeet has a very good post about those two IDEs. I always try not to rely more on shortcuts instead of the mouse in developing. I feel it can improve efficiency much.
By meaning tools, I also mean those sdk tools, and a lot of third party add-ons. James Avery has a MSDN article about ten VS.Net essential tools. By making full use of those tools, you can really show a difference with those co-workers who don't use those tools.
The magic yield return , Tree enumerators.
Here is the sample code..
538 /// <summary>
539 /// Gets the depth first node enumerator.
540 /// </summary>
541 /// <value>The depth first node enumerator.</value>
542 public IEnumerable<DTreeNode<T>> DepthFirstNodeEnumerator
543 {
544 get
545 {
546 yield return this;
547 if (m_Nodes != null)
548 {
549 foreach (DTreeNode<T> child in m_Nodes)
550 {
551 IEnumerator<DTreeNode<T>> childEnum = child.DepthFirstNodeEnumerator.GetEnumerator();
552 while (childEnum.MoveNext())
553 yield return childEnum.Current;
554 }
555 }
556 }
557 }
558
559 /// <summary>
560 /// Gets the breadth first node enumerator.
561 /// </summary>
562 /// <value>The breadth first node enumerator.</value>
563 public IEnumerable<DTreeNode<T>> BreadthFirstNodeEnumerator
564 {
565 get
566 {
567 Queue<DTreeNode<T>> todo = new Queue<DTreeNode<T>>();
568 todo.Enqueue(this);
569 while (0 < todo.Count)
570 {
571 DTreeNode<T> node = todo.Dequeue();
572 if (node.m_Nodes != null)
573 {
574 foreach (DTreeNode<T> child in node.m_Nodes)
575 todo.Enqueue(child);
576 }
577 yield return node;
578 }
579 }
580 }
The point of iterators is to allow the easy implementation of enumerators. Where a method needs to return either an enumerator or an enumerable class for an ordered list of items, it is written so as to return each item in its correct order using the ‘yield’ statement.
The magic yield will keep a state information in the enumeration, so it always remembers where to start in the next loop.
Implement a queue using an array...
I have been reviewing some basic data structure lately. The queue is one of the basic data structure, just as other data structure, you can use the array or the link list to implement it.
When using an array to implement the the queue, there are two pointers, one points to the head, and the other points to the end. If we have array of size N to implement an list with N elements. We will have 0<=head<N, and 0<=tail<N, and the difference between head and tail satisfies 0<=(head-tail)mod N <N. There are only n distinct differences, with queue length 0, 1, 2, ... , N-1. But the queue could have N elements too, it means that the number of the enumerations(N+1) of the queue is larger than what the underlying array can offer.
Actually, when the array is empty (the queue has 0 element), the head and the tail points to the same position, and when the array is full, the head and the tail points to the same position too. So, we cannot tell whether the list is empty of full solely based on the head and tail position.
For example, when the queue is just created, the head points to 0 piston, and the tail points to the N-1 position in the array, and when we add the first element, the tail position will move to the first element. If we keep adding 10 elements, then we get to a point the tail position will point to the 10th element again. Then the head and tail position actually points to the exact same position as the empty queue.
There are two options for dealing with this problem. The first is to limit the number of elements in the queue to be at most n-1. The other is to use another member variable , count, to keep tract explicitly of the actual number of elements in the queue rather than to infer the number from the head and tail variables. Both are valid options.
In the first option, we let the tail point to the 0 element, and the head point to the N position. So, if we move the head right, then we'll reach the tail, that's the empty situation. On the other hand, if we have a full queue, we move the tail right, we'll reach the head.
The empty condition is happening when head/N==tail/N. And the full condition is happening tail+1==head.
The vm size on the task manager is confusing.
Everybody who has taken a course of Operating system knows the difference between the virtual memory and physical memory. There is a good definition here : Virtual (or logical) memory is a concept that, when implemented by a computer and its operating system, allows programmers to use a very large range of memory or storage addresses for stored data. The computing system maps the programmer's virtual addresses to real hardware storage addresses. Usually, the programmer is freed from having to be concerned about the availability of data storage.
And the physical memory is the memory actually used by the process right now. So normally, you would think that virtual memory used by one process should be larger than its physical memory.
But if you open the task manager,and compare the size of the virtual memory and physical memory, you will get a different answer.
The vm size is actually smaller than the physical memory size. The "VM size" used by the task manager is pretty misleading.
The VM is actually the "Private Bytes" used by the popular process explorer, which are part of the VM, but they exclude the memory allocated by the system. The process explorer depicts a much better picture of the system state.
Using FxCop
I have downloaded the FxCop long time ago, but really didn't use it too much until recently.
I think every .Net programmer really should run it on a routine basis. It's just too important to ignore. When I firstly ran it on my utilities project, it gave me over 3400 warnings, while the compiler even didn't give me a single warning.
I am not saying all those warnings are valid. One of my text file which is embedded in the resource is a soundex index file, and it has a lot of unrecognized words in that. So, it gives a lot of errors in the Microsoft.Naming. After I remove the files , the errors dropped about half. Still, it's quite a lot.
I spent about 10 hours go through those warnings, and a lot of those warnings are valid warnings, such as IDispose are not implement correctly, explicit interface implementations should be changed to conform to the standards.
After I go through those warnings line by line, it teaches me a lot what I should code according to the standard. A lot of stuff which I normally never pay attention to actually deserve a lot of attention.
Good stuff, strongly recommended.
Tuesday, May 30, 2006
C# Delegate.
The constructor takes an object and IntPtr value, in the constructor, these two arguments are saved in _target and _methodPtr private fields.