Friday, December 29, 2006

Windows XP dialog default font changed automatically!

Recently, we had a customer running chinese on his machine have a problem with the way in which fonts were being choosen for the dialog. On all our machines the dialog would default to MS Sans Serif. But on this one machine it would switch to a serif based font. We tried changing fonts via the Appearance dialog under Display Properties, but that would not do it. We even tried changing the DPI to recreate the issue, tried installing foreign language packs, but we just could not recreate the proble. Then we found the following registry item : "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontSubstitutes" Under that key are two entries MS Shell Dlg and MS Shell Dlg 2. These are set to Microsoft Sans Serif and Tahoma respectively on my machine. If you change these, then, VOILA!, the font used in the dialog started to change. More info about this key is available at http://support.microsoft.com/kb/282187 Once we had a way to recreate the problem, we were able to provide a fix to the customer, as well as fix the code so that it would better scaled dialogs to handle different fonts. Lesson here: never resize dialogs by hard-coded values. Either use the automatic scaling functionality provided by .NET 2.0, or resize to a location that is offset from a control on the dialog. That way, when fonts change and the position of the controls change, your dialog will resize to the new location without a problem. This probably is my last post for 2006 - So HAPPY NEW YEAR!

Are ATMs safe

According to an article from MSNBC, ATMs could be hacked to divulge your account number and pin to a hacker. (Its not the ATM itself, but the method in which the information is sent to the bank, that makes the process insecure). Here is an illustration of the points of vulnerability. And read it in full at http://redtape.msnbc.com/2006/11/researchers_who.html#posts

Introduction to the Make Controller Kit in C#

From Coding for Fun: Introduction to the Make Controller Kit in C# The Make Controller Kit was developed by MakingThings in collaboration with Make Magazine to provide an open hardware platform that encourages experimentation, learning, and - most importantly - the creation of fun, interesting, and practical projects. This article talks about using C# to control this controller.

A GPS device that plugs into the SD memory slot!

This is the first time I have come across a device like this: A GPS that plugs into the SD memory slot. Gosh the possibilities are endless: from the immediate - frees up a slot, to the future - cameras, pocket pc's could become location aware. And it also contains memory: which means a map maker could release the maps and the GPS device on a single package - very cool! http://www.spectec.com.tw/sdg810.htm SDG-810 Special Features: SiRF Star III with low signal levels and high sensitivity acquisition Built-in GPS omni directional Antenna Supports 20-Channel GPS all-in-view tracking accuracy Real time navigation for location based services Colored LED shows GPS signal fixed or searching This company makes other devices that plug into the SD memory slot (like a camera). Physical Characteristics Dimension 62 mm * 24 mm * 2.1 mm Weight Approximately 30 grams Memory: Expansion Slot Micro SD card (TransFlash Card) memory Size : 512MB, up to 2GB

Monday, November 27, 2006

Trouble with the Large Object Heap

I have always had trouble understanding why at times .NET will allow you to allocate a block of memory and then a couple of minutes later it will refuse to do so, even though there is enough free memory available. In my case I know its because of .NET not compacting the large object heap. And this article explains it very well with a code example and also typical work arounds - good read! http://www.codeproject.com/useritems/Large_Objects____Trouble.asp

Wednesday, November 22, 2006

Creating an object just from its name in .NET

Recently one of my co-workers was looking for a method of creating an instance of an object just from its name. The Activator class has methods to do just that, but those methods need a full name. So to create an object just from its name (excluding version number, public key and assembly name), I came up with the following steps. Type type = Type.GetType("name of object"); //where name of object is System.String or namespace.object Object theObj = Activator.CreateInstance(type); Thats it!

Tuesday, November 21, 2006

Disabling the CTRL + TAB functionality in Visual Studio 2005

Hated the new way in which Ctrl + Tab worked within the new Visual Studio 2005 IDE. From day 1, I have been trying to disable it and make it work in the old way. Finally I found the answer. The simple answer : one can use CTRL + F6, to tab through the windows as one would do in previous versions of VS. But I prefer reassigning the shortcuts, so that I can use the good old CTRL+TAB (CTRL+F6, somehow doesnt cut it for me and is harder for single hand access!) So here is how you do that: Goto Tools->Customize. Click on Keyboard... This will bring up the Options dialog with the tree item Keyboard under Environment open. Type in the "Show commands containing" text box the following "Window.NextD". This should bring up two commands Window.NextDocumentWindow and Window.NextDocumentWindowNav. If you look, CTRL+Tab has been assigned to Window.NextDocumentWindowNav and CTRL+F6 to Window.NextDocumentWindow. Just reassign the shortcuts and you are in business.

What is ReadyBoost?

A new feature in the Windows Vista operating system is where it can automatically take advantage of a USB flash drive to improve system performance. Read more about this cool new feature at : http://windowsvistablog.com/blogs/windowsvista/archive/2006/11/20/windows-readyboost.aspx Here is the main excerpt from that page : "Windows ReadyBoost isn’t really using that memory to increase the main system RAM in your computer. Instead, ReadyBoost uses the flash drive to store information that is being used by the memory manager. If you are running a lot of applications on a system that has limited memory, Windows ReadyBoost will use the flash drive to create a copy of virtual memory that is not quite as fast as RAM, but a whole lot faster than going to the hard disk. What is very cool here is that there is nothing stored on this flash disk that isn’t also on the hard disk, so if you remove the flash drive, the memory manager sees the change and automatically goes to the hard disk. While the performance gain from ReadyBoost is gone, you don’t lose any data and there is no interruption. And because the Windows Readyboost cache on the flash drive is encrypted using AES-128, you don’t need to worry about exposing sensitive data if the flash drive is stolen or lost. Also, the memory manager compresses the pages before writing them into the cache on the flash disk, which means you’ll get more mileage from each MB. "So, if you just want your PC to run faster with Windows Vista -- it's pretty simple -- connect your flash drive through any USB 2.0 socket or PCI interface and when the autoplay interface comes up, choose 'Speed up my system using ReadyBoost.' "

Generalization of a Simple Genetic Algorithm (GA)

Taking a simple genetic algorithm and constructing a framework to allow easy creation of similar algorithms. http://www.codeproject.com/useritems/GA_Generalization.asp

Monday, September 11, 2006

MDB Browser and Editor

MDB Browser and Editor - Download.com This application can be used to work with tables from databases created in Access 97 or 2000 in a manner similar to FoxPro 2.6. You can open tables or SQLs from a view window, browse, set, create or delete indexes, set relations, copy to text or another table, append from text or another table and delete records. And its FREE!

Sunday, September 10, 2006

Wednesday, September 06, 2006

Practical .NET 2 and C#2 Chapter: Collections

Practical .NET 2 and C#2 Chapter: Collections While looking for articles/books on the new features of C#2.0 and .Net2.0, I came across this book. Some of the samples on the site are useful starting points.

Practical .NET 2 and C#2 Chapter: Collections

Practical .NET 2 and C#2 Chapter: Collections While looking for articles/books on the new features of C#2.0 and .Net2.0, I came across this book. Some of the samples on the site are useful starting points.

Preparing for emergencies

Scott Hanselman's Computer Zen - 2006 Resolution - Prepare This article talks about what one should have to deal with emergencies. This article is different from others as it talks about the types of documents that one should keep copies of as well as how one can carry them on a USB stick. The tools that he recommends Keith Brown's Password Minder for keeping track of all your passwords. and TrueCrypt to encrypt all your important electronic data (especially what you may carry on a USB stick)

Finding Great Developers - Joel on Software

Finding Great Developers - Joel on Software Another good article on looking for great developers to hire into your team.

Finding Great Developers - Joel on Software

Finding Great Developers - Joel on Software Another good article on looking for great developers to hire into your team.

XML Notepad 2006

I am always looking for tools that I can use to view and edit XML files.

Came across XML Notepad 2006 a Microsoft tool.

And its my new favorite XML editor/viewer.

My favorite feature, the deal clincher, is the fact that it understands SOAP xml files and its FREE.

I used to use XMLDocViewer, but that one only allows viewing of files. This new MS tool allows editing too.

I JUST LOVE IT!

Tuesday, September 05, 2006

Window's Live Writer

 

This post has been made using Window's new blog posting tool, Window's Live Writer.

And so were the previous two. And it is really good and easy to use. I am hooked.

Interop 101 in .NET

 

Previously, I had included links to BorisJ's article on interop.

Here is the 3rd installment in that series.
Interop 101 - Part 3 : http://blogs.msdn.com/borisj/archive/2006/09/02/73...

Also, for convenience, here are the links to the previous 2.
Part 1: http://blogs.msdn.com/borisj/archive/2006/07/29/683061.aspx
Part 2: http://blogs.msdn.com/borisj/archive/2006/08/21/711530.aspx

Unresolved external symbol ?.ccto@@$$FYMXXZ

 

Using Visual Studio 2005 and getting the following error LNK2001: unresolved external symbol ?.cctor@@$$FYMXXZ" (?.cctor@@$$FYMXXZ)

Well its most probably because you have the /ZI flag enabled for the compiler settings. Remove it and then recompile. It most probably will go away.

To remove it go to your managed C++ project settings. Under C++ >> Command Line, remove the /ZI setting from "Additional Options".

Hanoi: A simple C# solution

Here is a simple towers of Hanoi solution in C# public static void SolveSubHanoi(int n, string start, string end, string intermediate) { System.Console.WriteLine(n + " " + start + " " + end + " " + intermediate); if (n <= 1) { //move topmost from start peg to end peg System.Console.WriteLine("c1:" + start + " --> " + end); } else { //move n-1 discs to intermediate position SolveSubHanoi(n - 1, start, intermediate, end); //now move the n(th) disc from start to end System.Console.WriteLine("c2:" + start + " --> " + end); //now move the n-1 discs from intermediate to end SolveSubHanoi(n - 1, intermediate, end, start); } } And all you do is call it so: SolveSubHanoi(n, "Peg A", "Peg B", "Peg C"); //where n is the number of discs. "Peg A" contains all the discs at start and "Peg B" will get all the discs at the end. Recursively, this solution solves the movement of (n-1) discs at each step. This is the basic idea for the solution of the 750 points problem in the practice room of Google CodeJam.

MSI Installer - Selecting the Everyone option in the Select Installation Folder dialog

When running an installer, the dialog "Select Installation Folder", has an option for installing the application for either "Everyone" or "Just for you". And "Just me" is the option selected by default. Recently for one of our applications, we wanted it to default to "Everyone". Turns out that changing the default option cannot be done through the Installer solution. You need Microsoft's MSI editor tool "ORCA". Here is what you need to do: Install ORCA. After which if you right click on an MSI file, you get the option: "Edit with Orca". Select it, to open the MSI in ORCA. The MSI file is basically a specialized database, and ORCA allows you to edit it. To change the default to everyone, navigate to the table "Property". Change the value for the entry FolderForm_AllUsers from "Me" to "ALL". And thats it. Fire up your installer, and it should automatically default to the "Everyone" option.

Monday, September 04, 2006

FileNotFoundException: The specified module could not be found. (Exception from HRESULT: 0x8007007E

System.IO.FileNotFoundException: The specified module could not be found. (Exception from HRESULT: 0x8007007E) This was the arcane error message I recently started getting when I tried running one of the C# projects I was trying to build. Obviously, it was some dependency that .NET was not finding.... but why couldn't it just tell me what dll it was looking for. Normally, for such problems, I fire up Fuslogvw.exe, to find the problem. But no.... FusLogvw.exe wouldnt register any error messages. After some thought, I started looking at all the dependencies my project had and found that the problem was one of the native DLLs that the project needed. Once, I put that in my output folder, voila the problem disappeared. So the solution for 0x8007007E, is search for a native DLL that your project relies on and see if its not in the application folder or the Windows\System32 folder: coz thats what is most probably causing the failuer.

Friday, September 01, 2006

Multi Monitor Software

Recently, I came across MaxiVista, an interesting software for using multiple monitor. Currently, at work I use UltraMon (http://www.realtimesoft.com/ultramon/overview/), to control the 2 monitors connected to my desktop developlment machine. What I love about UltraMon, is that it gives me a task bar for my other monitor, so applications shown in that screen, appear on the status bar for that screen. It runs fast, and in the two years I have been using it, I have had no problems or complaints. (It also has some cool tools for screensavers and wallpapers). So, what about MaxiVista. It doesnt seem to handle status bars for multiple monitors. But it can enable networked computers as multiple monitors. UltraMon, works only with multiple monitor display cards. MaxiVista, allows you to extend your screen using a second networked computer (so you could use your notebook as a second monitor). Their demo looks vast and impressive. (Havent had a chance to personally try it, but I have a computer at home that I would like to try it on). MaxiVista - Multi Monitor Software: "MaxiVista turns any spare PC into a second monitor for your main computer. No extra hardware required. You can seamlessly extend program windows across multiple screens like it would be a single big monitor. Increase your productivity by using multiple monitors " Here is another software : MultiMon, which is free:http://www.mediachance.com/free/multimon.htm Here is a UltraMon look a like : http://www.digitaltigers.com/zenview-manager.shtml

.NET Reflector Add-Ins

.NET Reflector Add-Ins This page lists all the greatest add-ins for the .NET Reflector tool.

Thursday, August 24, 2006

Sample book chapter on new features from C#2.0

In this sample chapter from the book "Visual C#2005 - A Developer's Notebook" learn about and use the new features in C# 2.0, including generics, iterators, anonymous methods, partial types, static classes, nullable types, and limiting access to properties, as well as delegate covariance and contravariance. http://www.oreilly.com/catalog/visualcadn/chapter/ch01.pdf

Free C# chapters from books

This guy regularly updates this page with links to freely downloadable chapters from books on C#. Great resource. PublicJoe's - C# Tutorial - Free EBook

A good paper on binary representation of floating point data

Here is a good article on binary representation of floating point values. The article use C# to explain the concepts. Herong's Tutorial Notes On C# - Part B - Binary Representation of 'float' and 'double' Values

Tuesday, August 22, 2006

A book on OpenSource licensing

A book on OpenSource licensing: Open Source LicensingSoftware Freedom and Intellectual Property Law http://www.rosenlaw.com/oslbook.htm This book is available online under the Academic Free License version 3.0. Links to the individual chapters are shown below. Front matter Preamble Chapter 1: Freedom and Open Source Chapter 2: Intellectual Property Chapter 3: Distribution of Software Chapter 4: Taxonomy of Licenses Chapter 5: Academic Licenses Chapter 6: Reciprocity and the GPL Chapter 7: The Mozilla Public License (MPL) Chapter 8: The Common Public License (CPL) Chapter 9: The OSL and the AFL Chapter 10: Choosing an Open Source License Chapter 11: Shared Source, Eventual Source, and Other Licensing Models Chapter 12: Open Source Litigation Chapter 13: Open Standards The Open Source Paradigm Appendices

CoolCommands 3.0 for Visual Studio 2005

Here is another really useful Visual Studion 2005 PowerToy:

CoolCommands 3.0 for Visual Studio 2005

In short, the tool provides access to some everyday tasks that you might do within VS, such as collapse all projects. Great time saver. Check it out at: http://weblogs.asp.net/gmilano/archive/2006/05/10/446010.aspx or directly download it from : http://downloads.deklarit.com/files/gmilano/CoolCommands30.msi

Visual Studio 2005 PowerTools

Here is a great tool for debugging .NET20 apps. From:http://www.codeplex.com/Wiki/View.aspx?ProjectName=MSE Do you ever need to get stack traces for your .NET 2.0 applications? Want a quick and easy way to monitor managed processes and threads? Need a way to view a thread's stack trace to investigate an application hang? If so, Managed Stack Explorer is for you.

Managed Stack Explorer is a lightweight tool that allows you to do just this. Simply copy the executable anywhere and start monitoring your stack traces today.

Check out all of the MSE Features for the 1.0 release. Learn more about the Managed Debugger Sample MDbg

Monday, August 21, 2006

VS2005 - Forms Designer exception: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for mo

Update : MS has a hotfix for this problem : Check out the following page: http://support.microsoft.com/kb/912019/en-us Kept having the following problem with the Windows Forms Designer in VS2005. Here is what the problem is: All my Forms that inherited from another base form that I had created would all of sudden stop displaying the designer. The error that I would get was: One or more errors encountered while loading the designer. The errors are listed below. Some errors can be fixed by rebuilding your project, while others may require code changes. Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. Hide at System.Reflection.Module.GetTypesInternal(StackCrawlMark& stackMark)at System.Reflection.Assembly.GetTypes()at Microsoft.VisualStudio.Shell.Design.AssemblyObsoleteEventArgs..ctor(Assembly assembly)at Microsoft.VisualStudio.Design.VSDynamicTypeService.ReloadAssemblyIfChanged(String codeBase) . . . It was the most annoying error and I found that it would happen most often when I performed a rebuild on my solution. The one method that I found that always worked was to close down the solution, and go to the project folder and clean out the obj and bin folders. (Performing a clean from within the solution did not always work, but shutting down VS and then cleaning the files worked always.) Some bloggers have pointed to this problem being caused by an indexing service that is run in the background, which causes file locking and hence the error. To work around this do the following: Select the projects folder in Windows File Explorer. On the Properties Tab, click the Advanced button and disable the checkbox to allow the indexing of the folder and subdirectories and files. But this was not the case on my machine. So there may be more than one reason for this error. (But if you want there is a hot fix for this file locking due to indexing issue and its : VS.NET 2005 Hotfix 265517_ENU_i386 - you will have to contact MS tech support for it though). Another reason that this can be caused is if the UserControl or base class form is in another DLL and its version has changed between builds. (To work around this, you can set the AssemblyVersion in the AssemblyInfo.Cs file of the DLL.

Sunday, August 20, 2006

jfo's coding

Here is a pretty good MSDN blog on Windows Forms. Lots of interesting discussion. jfo's coding

jfo's coding

Here is a pretty good MSDN blog on Windows Forms. Lots of interesting discussion. jfo's coding

FTPOnline - .NET Blogosphere

FTPOnline - .NET Blogosphere These guys constantly read .Net blogs and post those that are most interesting for that day. A great time saver, as I find these guys do my work of finding the latest interesting blogs. Most of the time, these guys find good ones. Check it out: http://www.ftponline.com/portals/blogosphere/net/

LogMeIn - Remote Access and Desktop Control Software for your PC

LogMeIn - Remote Access and Desktop Control Software for your PC: "Provide instant remote support in seconds, without pre-installing software. LogMeIn Rescue gives you temporary control of remote PCs over the web to accelerate problem resolution, reduce support times, and increase customer satisfaction."

Windows Live Ideas � Product Page

Windows Live Ideas � Product Page: "What it is Windows Live� Writer is a free, downloadable program that will help you lay out your blog posts just the way you want them." Compose posts for Windows Live Spaces as well as Blogger, LiveJournal, TypePad, WordPress, and many other services

Saturday, August 19, 2006

FTPOnline - Special Report: Visual Studio Team System

FTPOnline - Special Report: Visual Studio Team System: "Visual Studio 2005 Team System Microsoft Visual Studio 2005 Team System, an integrated software development platform to help your team build mission-critical applications, delivers new role-based tools for software architects, developers, testers, database professionals, and project managers. This Special Report shows how you can use VSTS and its Team Foundation Server to better manage application delivery and maintenance, as well as improve realtime communication across the enterprise. "

Wednesday, August 16, 2006

AutoStitch: Automatic photo/image stitcher, creates panoromas from a set of images

AutoStitch: "Autostitch� is the world's first fully automatic 2D image stitcher. Capable of stitching full view panoramas without any user input whatsoever, Autostitch is a breakthrough technology for panoramic photography, VR and visualisation applications. This is the first solution to stitch any panorama completely automatically, whether 1D (horizontal) or 2D (horizontal and vertical). Autostitch is built using cutting edge research from the AI lab at UBC, but it's incredibly simple to use! Just select a set of photos, and Autostitch does the rest: digital photos in, panoramas out. Try the free demo (for Windows):"

The Most Important Software Innovations

The Most Important Software Innovations An excellent list of the most important software innovations. Did you know that hypertext was invented in 1945! The last innovation of web-crawling search engines is from way back in 1994. None since then.

The Road to Know Where: Ultimate List of Free Windows Software from Microsoft

The Road to Know Where: Ultimate List of Free Windows Software from Microsoft Microsoft has over 150 FREE Windows Programs available for download -- but finding them all is extremely difficult. This page has a small description and links to these useful tools.

Three Sins of Authors in Computer Science and Math

Three Sins of Authors in Computer Science and Math: "Three Sins of Authors in Computer Science and Math " A concise article on some mistakes often found in technical papers (Not only those written on Math and CS subjects). A good read for anybody writting a paper.

Debugging MSI problems

 Feed: Microsoft WebBlogs
 Title: Diagnosing Installation Errors

Author: heaths 
0+ Comments 

 

 

When problems occur when installing, repairing or patching, or uninstalling a product using Windows Installer technology, you need to be able to figure out what happened and why it happened. Dialogs that occur when the user interface is displayed can be helpful sometimes, but many times you need to look at a log to determine the exact cause of the problem.

The first step in diagnosing a problem using the log is to, of course, enable logging. When performing any actions with an installation package or patch always be sure to pass /L*v filename.log on the command line. This enables verbose logging. You can also use /L*vx which outputs debugging information as well, but this isn't always helpful and can lead to much larger log file sizes than even verbose logs. This option is also only available on Windows Server 2003 and newer. You can also set logging options using the logging policy that will apply to all Windows Installer operations on the machine.

Now that verbose logging is enabled when an error occurs you can search for "value 3" and in most cases find the return code from a failed standard or custom action. Note that this is not the only indication that a standard or custom action did not run perhaps as expected. An installation that returned prematurely but that did not return an error code from the process would have returned IDIGNORE, so you would have to search for "value 5". In Return Values of JScript and VBScript Custom Actions you can find the return values that can be returned from actions and what they indicate. Of course, it is recommended that you write custom actions in native C++ but this page does list both the #define constants and their values. Another good source of return values for custom actions is Logging of Action Return Values that lists a few more possible return values, as well as what value is returned from the custom action server depending on what values you return from your custom action.

You should see a line like the following listing the action that returned the error value:

Action ended 12:00:00: MyCustomAction. Return value 3.

Now that you've located the error in the log you must determine what really happened since the return value isn't really adequate for determining the cause of the problem. If your custom action failed hopefully you've logged enough information to determine the cause right away. If you used the MsiProcessMessage function to log the error from the Error table, or a standard action failed, you will find the error number in field 1 of the log message a little above where you found "value 3":

MSI (s) (AC:14) [12:00:00:000]: Note: 1: 1601 2: C: 3: 4096 4: 1024
MSI (s) (AC:14) [12:00:00:0000]: Product: My Product -- Out of disk space -- Volume: 'C:'; required space: 4096 KB; available space: 1024 KB

The first line lists the error in field 1 as 1601. If you look up the error in Windows Installer Error Messages you will see Windows Installer error 1601 has the English text of "Out of disk space -- Volume: '[2]'; required space: [3] KB; available space: [4] KB". Plus the values of the fields in the first line into that message and you'll end up with the second line in the log. This will give you a much better indication of what error occurred. If the error value isn't in the Windows Installer Error Messages table, be sure to look in the Error table itself since this may be a custom error. Custom errors should be in the range from 25000 to 30000 according to the documentation for the Error table, but this isn't always the case.

In Logging of Action Return Values return codes from msiexec.exe are paired with error codes returned from custom actions, but msiexec.exe may return other error codes as documented in Error Codes, such as ERROR_UNKNOWN_PRODUCT (1605) if you try uninstalling a product by its ProductCode that is not installed, or ERROR_PATCH_TARGET_NOT_FOUND (1642) if you try applying a patch to a product that is not installed.

 

Debugging .NET Loading problems

Create a text file named fusionLog.reg
Edit it with notepad and add the following content:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion]
"ZapQuotaInKB"=dword:000f4240
"ViewerAttributes"=dword:50b00149
"LogFailures"=dword:00000001
"LogPath"="c:\\log\\Fusion"
"ForceLog"=dword:00000000
"LogResourceBind"=dword:00000001

 

create a folder c:\log\fusion

 

double click the fusionLog.reg file and accept adding info in the registry

Each time an assembly fails to load, a log file is created in c:\log\fusion folder

In order to also see successes, change ForceLog to 1

Sunday, August 13, 2006

Open source Licenses

Recently, I was looking into the different kinds of licenses available for open source software. Specifically I was looking into the Lesser GNU Public License (LGPL). Most of the main pages such as the GNU site (http://www.gnu.org/licenses/lgpl.html) is so full of legalize that I just could not figure out what I had to do to comply with the license. The best that I found was this page for the CGAL library, that tells me what I have to do with the LGPL license. http://cgal.org/license_frame.html The Lesser General Public License gives you the right to use and copy the code freely. It is also possible to modify the code under the condition that the resulting modification is released as source code under the LGPL with any binary distribution that you may do of a resulting application using these LGPL parts. And these are some other links that I found along the way: Here is a page on different kinds of Open Source licenses. Open Source Initiative OSI - Licensing And this one is for all GNU Licenses : http://www.gnu.org/licenses/

Saturday, August 12, 2006

Reflection in .NET

Recenty I was doing some research on reflection in .NET. Questions I was looking at were: When is it to be used? What costs are there to using reflection? What alternatives are there to reflection? Here are some websites that I found to answer these questions: Reflection (A chapter from the book Programming C#) http://www.oreilly.com/catalog/progcsharp/chapter/ch18.html Reflection Demystified http://www.dotnetdevs.com/articles/ReflectionDemystified.aspx Dodge Common Performance Pitfalls to Craft Speedy Applications http://msdn.microsoft.com/msdnmag/issues/05/07/Reflection/ This article compares CodeDOM to Emit (The major difference is that Emit, emits IL code, whereas CodeDOM can generates code in .NET languages like C#, VB....) http://www.fawcette.com/reports/vslivesf/2004/holmes/ In .NET 2.0, there is an alternative to Reflection called Dynamic Code Generation (sort of a light weight Emit) This article from CodeProject talks about it with some good examples: http://www.codeproject.com/useritems/Dynamic_Code_Generation.asp Here is a code project article on using this method to work around the issue of calling properties in a loop using reflection (which is very slow). Fast Dynamic Property/Field Accessors http://www.codeproject.com/csharp/DynamicCodeVsReflection.asp In VS2005, one can use visualizer and here is one for use with Reflection Debugger Visualizer for MethodInfo, DynamicMethod, and MethodBase http://weblogs.asp.net/rosherove/archive/2006/04/25/MethodsVisualizer.aspx ---------------------------------------------------------------------------- One major use of Reflection is for the loading of plugin dlls, using the mechanism of loading a DLL and then using reflection to query and find those types that implement a certain interface. Here is some information regarding this use of Reflection. Remember to scroll down to the "Oops a small problem" part of the article (which talks about doing this querying in a different appdomain). http://weblogs.asp.net/rosherove/pages/8048.aspx

Cool Dev Tools

Often times I have XML files that I have written out in my code and I want to view quickly such that the view is formatted and nice and pretty with color. Here is a great tool that does just that: XMLDocViewer. Its free and all it does is view XML files. I need to see if it will work with SOAP XML, cause if it does, then its like gold to me. http://www.sliver.com/dotnet/XmlDocViewer/ There are many other tools and snippets on this guys website worth checking out : http://www.sliver.com/dotnet/index.aspx Snippet Compiler: This is Jeff's best tool. An easy way to test C# code, without having to create a solution and a project in VisualStudio. A must have : http://www.sliver.com/dotnet/SnippetCompiler/

Tuning your XP machine for best performance during recording of Audio

Here is a site that has a list of tips for making an XP machine faster for recording of auido. http://www.musicxp.net/tuning_tips.php

Replacing Start Run

Feed: ComputerZen.com - Scott Hanselman's Weblog Title: Replacing Start Run - The Quest Continues

So many ways to launch programs. A good launcher doesn't just launch, it also auto-completes paths for you, starts your search engine or browser and generally saves you 15 minutes a day. No need to learn all the hotkeys like those Keyboard wonks who try to guilt you. Just learn ONE and make it do everything.

Given these offerings, if you open your Start Menu at all, at any point in the day, you're doing something wrong. Try them all, pick one, and save 15 min * 5 days * 52 weeks = 65 hours a year you'd have spent futzing around in your Start Menu*. * These numbers came straight out of my butt.

  • Slickrun - still the sexy favorite, this little floating magic bar keeps me moving fast, launching programs, macros and explorer with it's shiny simplicity. Tell them I sent you. ;)

  • SmartStartMenu - Shaun Harrington has created this elegant little application that lives in the task bar and automatically indexes the list of items in your Start Menu for quick access with the speed of AutoComplete. It will take system commands, paths to launch explorer, even UNC paths. Launch anything on your system with less than 4 keystrokes. It also adds new context menus to Explorer like CopyPath and Open in DOS box to Explorer.

  • Martin Plante, hot off his gig at Xceed has created slimKEYS, a "universal hotkey manager" with a simple .NET plugin architecture. If you've got ideas or thoughts, visit the slimCODE Forums. Have you ever wanted to bind something to Shift-Ctrl-Alt-Window-Q but didn't know how to grab a global hotkey? This will launch programs, watch folders, and find files. It has great potential as more and more plugins appear. The current version already comes with the following built-in plug-ins:
    • slimSIZE: Change the current window's position, size or monitor location to any area of your choice.
    • slimLAUNCH: Open applications, documents or folders by typing a few letters from their name.
    • slimVOLUME: Display the volume level when you use your keyboard's volume control.

  • Colibri - The closest thing so far, IMHO, to Quicksilver on Windows, although this little gem has a slow startup time, it runs fast! It's being actively developed and promises integration with a dozen third party programs. It also formally supports "Portable Mode" for those of you who like to carry your apps around on a USB key.
  • Launchy - Another do it all application, this one Open Source and written entirely in .NET, Launchy binds to Alt-Space by default. This app also has the potential to be Quicksilver like if it start including support for stringing together verb-noun combos. It's pretty as hell and totally skinnable (there's TWO Quicksilver skins included!)
  • AppRocket -this little bar sits at the top of your screen, popping down an active list of Bookmarks, Programs, Music, Web Queries and more. It's unclear if this tool is being enhanced for future versions as folks have reported not hearing from the company in a while.
  • ActiveWords - Arguably the most minimal of these launchers (as it can have no UI at all if you like!), but the most configurable. ActiveWords watches everything you type, in every application, so anything you've just typed could potentially be used by you to launch a program, a macro, send email, or give you Auto-Correct in any application. Check out their screencast/demos and their scripting language. It also is the only launcher (I've seen) with explicit support for the Tablet PC and allows ink to trigger an "Active Word."
  • Dave's Quick Search Bar - Written orignally in JavaScript and now written in magic and ensconced in voodoo, this little Toolbar sits in your Windows Task bar (or wherever you choose to drag it) and supports a huge community of macro writers who've enabled it as a Calculator, Web Searcher, People Finder, Currency Converter and literally hundreds of other tasks via simple to write plugins. Very actively developed and on the web for over 5 years (that's like 100 people years).It even has a Search Wizard to create your own web searches by example.

UPDATE: I forgot a few that were totally worth mentioning. My bad.

  • Google Desktop - Google Desktop has an option that let's you use it as a quick program launcher along with fantastic search abilities by tapping Ctrl-Ctrl.
  • Find and Run Robot - Lightweight, small, quiet until you need it. This little application allows for tuneable heuristics to make it work like you think. Demo Screencast here.

Tuesday, August 01, 2006

Getting the relative path to a file, given its absolute path and a source folder (C#)

Here is some code that will get the relative path to a file, given its absolute path and the source folder from which the relative path should be computed. Code is in C# private static string GetRelativePath(string mainDirPath, string absoluteFilePath) { mainDirPath = mainDirPath.Substring(0,mainDirPath.LastIndexOf(Path.DirectorySeparatorChar)); string[] firstPathParts=mainDirPath.Trim(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar); string[] secondPathParts=absoluteFilePath.Trim(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar); int sameCounter=0; for(int i=0; isameCounter ) { newPath+=Path.DirectorySeparatorChar; } newPath+=".."; } if( newPath.Length==0 ) { newPath="."; } for(int i=sameCounter; i { newPath+=Path.DirectorySeparatorChar; newPath+=secondPathParts[i]; } return newPath; }

Thursday, July 13, 2006

C# programs/source code

Found this page to be useful as it has links to useful C# projects that include source code. http://www.manbu.net/Lib/En/Class3/Sub1/index.asp and http://www.manbu.net/Lib/En/Class3/Sub1/index.asp Most of the projects have implementation of popular algorithms used in computational geometry as well as searching, etc.

void * __cdecl operator new(unsigned int) error during linking

Recently while trying to create a DLL in managed C++, i came across an error about : error "void * __cdecl >operator new(unsigned int)" (??2@YAPAXI@Z) being undefined!

This occured when I tried to create a dynamic unmanaged array in a managed class.

That is : within a gc class, I could not do the following int __nogc* buffer = new __nogc[100];

but in a non-gc class I could do it!

After much searching I found the resolution to be this:

Add msvcrt.lib to the input section of the linker property pages of your project settings. Thats all!

Monday, July 03, 2006

Memory corruption in Managed C++ .NET in Release Mode

Recently we were working with some .NET Managed C++ code, that would work in debug mode but not in Release mode. What was weirder was that on most machines, it would work in Release mode. Except when it got built by the build machine. Further probing made us realize that the biggest difference between the developer machines and the build machine was it had the Professional version of Visual Studio - which meant that it had a different set of optimizations enabled. Looking closer - the optimization we were using on the compiler was /O2 : Optimize for speed. which used a couple of underlying switches (/Og /Oi /Ot /Oy /Ob2 /Gs /GF /Gy). If we turned of Optimization the code would run properly and turning it out would give us garbage output. Further investigation lead us to pinpoint /Og switch as the culprit. /Og uses global optimizations. Looking at the documentation, I figured the issue is most probably because we were pinning some arrays and using both the original array and the pinned pointer to access the data. I believe the problem is most probably to do with aliasing, where the optimizer gets confused when aliasing is used in code. So our solution: We could have just disabled optimizations on the project. But we wanted to have access to the speed. So we left the optimization swith /O2 in. Instead what we did was use the pragma directive "#pragma optimize" to turn off the "Og" optimization only for those methods that used pinning and aliasing. And voila - the problem is all gone and the code still runs nice and fast.

Tuesday, June 27, 2006

Creating a shell extension with C#

This article demonstrates a Windows Shell hook/extension in C#, demonstrating how easy it is to consume COM interfaces and to deploy the final code as though it is a bona-fida COM object. http://www.codeproject.com/csharp/dateparser.asp

Wednesday, June 14, 2006

WHOS-IN Pro 2006 (a who's in and who's out office board)

http://www.hudsoft.com/products/whosin/index.html WHOS-IN Pro 2006 is THE multi-award winning, easy-to-use, in-out board for businesses and organizations that would like to know who's in and who's out of the office.

Thursday, May 11, 2006

Eric Gunnerson's C# Compendium : Using GC Efficiently

Eric Gunnerson's C# Compendium : Using GC Efficiently Using GC Efficiently Spending lots of time on C++ means I haven't been paying as much attention to managed code as I did in the past, and I missed an excellent series of articles by Maoni about the GC. They are: Using GC Efficiently – Part 1 Using GC Efficiently – Part 2 Using GC Efficiently – Part 3 Using GC Efficiently – Part 4 Go read Maoni's blog for lots of other useful information (Large object heap, etc.) Published Thursday, May 11, 2006 12:35 PM by ericgu Filed Under: ,

NMEA Parser Design

NMEA Parser Design Other interesting GPS coding links: edjez's WebLog http://blogs.msdn.com/edjez/archive/2005/02/20/377187.aspx Where the Heck am I? Connecting .NET 2.0 to a GPS Scott Hanselman (Coding4Fun) http://msdn.microsoft.com/coding4fun/someassemblyrequired/whereami/default.aspx

Tuesday, May 09, 2006

Adding Merriam Webster to the Internet Explorer 7's Toolbar search box

Did not find a link to add M-W to the search box of IE7 from Microsoft's site : http://www.microsoft.com/windows/ie/searchguide/default_new.mspx Found out that its based on the OpenSearch description standard. So created one for use with Merriam Webster and here it is for your use. Click on the following link to: Add Merriam Webster Search to the Internet Explorer 7 Toolbar Search Box

Thursday, May 04, 2006

Type Changes between ArcGIS 8.3 and ArcGIS 9.0

Type Changes between ArcGIS 8.3 and ArcGIS 9.0 This page documents the changes in namespaces as well as assembly names between ArcGIS 8.3 and ArcGIS 9.0. A required resource, when you are trying to port code from Arc83 to Arc90.

Monday, May 01, 2006

Overwatch Systems Purchases Visual Learning Systems - Official press release

From : http://www.geospatial.overwatch.com/ow_news_pressreleases/VLS_acquired.html The official press release: Overwatch Systems Purchases Visual Learning Systems MORRISTOWN, N.J., USA, 1 May 2006 – Overwatch Systems today announced that it has acquired Visual Learning Systems (VLS) of Missoula, MT. The purchase became effective on April 28, 2006.Founded in 1999 by Dr. David Opitz and Stuart Blundell, VLS is the worldwide leader in automated feature extraction solutions (AFE) for geographic information systems (GIS). The company's innovative software applications provide assisted and automated tools for extracting geospatial features of interest from imagery with the highest measure of speed and accuracy. VLS’ tools provide a key bridging technology between the raster based world of imaging and the vector based world of mapping. VLS's flagship product, Feature Analyst®, debuted in 2001 and quickly garnered industry-wide attention. Feature Analyst earned "Most Innovative Solution" in the 2002 ArcGIS Challenge Contest sponsored by ESRI, the world's leading provider of GIS software. In 2005, VLS introduced LIDAR Analyst™ to automate the extraction of 3D terrain surfaces, buildings, trees, and forest areas from LIDAR.The VLS product line is an outstanding extension of the current Overwatch Systems product offerings. Overwatch Systems was formed from the combined the resources of five companies – Sensor Systems, Paragon Imaging, Austin Info Systems, ITSpatial and Federal IT – to provide a suite of integrated geospatial and intelligence fusion software tools for the defense/intelligence community. This toolset, known as the Overwatch Intelligence Center (OIC), focuses on providing situational awareness by enabling analysts to generate relevant, actionable intelligence faster and more effectively for the warfighter, first reponder and decision maker. The Overwatch OIC will contribute to transforming the Intelligence Community with low-cost collaboration tools. The addition of VLS to the Overwatch OIC family will enhance analysts’ productivity by streamlining the way they examine, evaluate, learn and record geospatial information. The senior management of VLS has chosen to use a portion of its transaction proceeds to invest back into Overwatch Systems and will continue to manage the company. VLS will report to Kirk Brown, President of Overwatch Geospatial Operations, formerly Sensor Systems, based in Sterling, Va. Brown was a key advocate for acquiring VLS and expressed his enthusiasm for the transaction.“Visual Learning Systems enables us to offer our customers market-leading feature extraction tools that fit well within our historical engineering design philosophy. VLS enhances analysts’ productivity with feature extraction tools that are fast, accurate, and require only a minimum of user interaction and guidance. Their market offering will also deepen our customer relations with the growing cadre of geospatial analysts in the military and intelligence community both here in the US as well as in the international community. VLS helps Overwatch fulfill our mission to deliver collaborative analysis systems across the Intelligence Community that speed actionable intelligence to the warfighter,” said Brown. “The VLS team is a strong addition to our Geospatial Operations. While VLS will continue to service their existing customer base, we are eager to offer our combined customers the synergy of VLS technology within our exiting Geospatial Operations product offerings.” Dr. David Opitz and Stuart Blundell the principal shareholders of VLS said at the time of the closing, “We’re very pleased to become part of the Overwatch team. We could have taken VLS in any number of directions, but felt the Overwatch strategy of linking intelligence sources together with easy-to-use data extraction and analysis tools provides the greatest benefit for our customers and our employees.”

Saturday, April 29, 2006

Overwatch Systems

Wondering why the name "Overwatch" Systems.... I did too. Seems to me, the most likely reason for the company's name is the way the word "Overwatch" is used by the U.S Military. Overwatch is the term used when one unit provides support for another unit. Usually the support is of covering fire and looking out for enemy movement. Guess, in that context, Overwatch is an appropriate name for a company that is into providing tools for intelligence gathering as well as use in the field for the war-fighter. According to Wikipedia: In modern warfare, overwatch is the state of one small unit supporting another, while they are executing fire and movement tactics. An overwatching, or supporting unit has taken a position where it can observe the terrain ahead, especially likely enemy positions. This allows it to provide effective covering fire for advancing friendly units. The term overwatch originates in U.S. military doctrine.

Visual Learning Systems (VLS) gets acquired by Overwatch

On friday, April 28, 2006, Visual Learning Systems (VLS), the company that I work for got acquired by a New Jersey based intelligence company called "Overwatch Systems". Overwatch Systems has been on a buying spree for some of the best tools used by intelligence agencies all around the world. It has tools such as RemoteView, used for analysing satellite imagery, as well as tools used for monitoring communications. VLS having been acquired, I guess is a testimony to all the great work that we have been doing here and also to the quality of our products FeatureAnalyst and LidarAnalyst. Most importantly, I think that this acquistion will have the following meaning for our customers: "nothing". We will continue to work and operate just as VLS did for the past 6 years. VLS even gets to keep its name and r&d will stay here in Missoula. I guess a formal announcement will be made on May 1, 2006. Here is a summary about Overwatch from their website. (www.OverWatch.com) "Overwatch Systems provides a suite of integrated software tools that enable analysts to generate relevant, actionable intelligence faster and more effectively for the warfighter, first responder and policy maker. Using capabilities from the Overwatch Intelligence Center to counter current threats, we deliver fieldable collection and analysis capabilities in months where the traditional approach is measured in years." Overwatch Systems develops and markets intelligence analysis products and develops custom intelligence systems as specified by our Government customers. Overwatch Systems develops multi-band single feed SATCOM systems for DOD/HLS customers and have significant communications experience directly related to satisfying intelligence systems communications requirements.

Thursday, April 20, 2006

RSAC conference 2006

I am heading to Salt Lake City on April 24th, to attend the Remote Sensing Applications Center 2006 conference. I am presenting a paper on LIDAR Analyst. Find me, let me know if there are features you would like to see in the next version or tell me how you like (or dont like) the current version http://www.fs.fed.us/eng/rsac/RS2006/ I also presented a paper on terrestrial LIDAR at the International Lidar Mapping Forum 2006 at Denver. This one was on the current research we are doing with side-sweep lidar data http://www.lidarmap.org/program.html

Thursday, April 13, 2006

C# converting bytes (byte arrays) to other data types

C# converting bytes (byte arrays) to other data types There are basically two ways to do this: 1. Use the BitConvertor class. To use this class, you need to keep track of where you want to read in the byte array 2. Use BinaryReader This is the method I prefer, though it might be just a little bit slower than using the BitConvertor class (I am not sure of that though!) Basically you can load your byte into a MemoryStream object. Then feed the memory stream to a BinaryReader object. After that you just need to call the appropriate methods for conversion. Best of all the BinaryReader object keeps track of where in the stream you currently are reading from. Makes for some nice clean code. Just the way I like it!

25 Top Jobs for 2005-2009

25 Top Jobs for 2005-2009: A survey of what will be the top jobs for the next four years. Software engineers, software analysts and geo-scientist are in there, a combination of which is what I consider my job to be!

Tuesday, April 11, 2006

Center for LIDAR Information Coordination and Knowledge - CLICK

http://lidar.cr.usgs.gov/ The goal of CLICK is to facilitate data access, user coordination and education of lidar remote sensing for scientific needs. A national repository for LIDAR data.

Saturday, April 08, 2006

SUPER - A video convertor

SUPER � .: " A GUI to ffmpeg, mencoder, mplayer, x264, ffmpeg2theora & the theora/vorbis RealProducer plugIn. If you need a simple, yet very efficient tool to convert (encode) or play any Multimedia file, without reading manuals or spending long hours training, then SUPER � is all you need. It is a Multimedia Encoder and a Multimedia Player, easy-to-use with 1 simple click. SUPER � is totally FREE to download and to use. It plays & converts very fast full length movies to any other format with NO time limitation."

Friday, April 07, 2006

Debugging .NET Assembly loading problems

from Benjamin Guineberti�re : debug .NET Assembly loading: Create a text file named fusionLog.reg Edit it with notepad and add the following content: Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion] 'ZapQuotaInKB'=dword:000f4240 'ViewerAttributes'=dword:50b00149 'LogFailures'=dword:00000001 'LogPath'='c:\\log\\Fusion' 'ForceLog'=dword:00000000 'LogResourceBind'=dword:00000001 create a folder c:\log\fusion double click the fusionLog.reg file and accept adding info in the registry Each time an assembly fails to load, a log file is created in c:\log\fusion folder In order to also see successes, change ForceLog to 1"

ArcSketch, A Sample Extension for ArcGIS

ArcSketch, A Sample Extension for ArcGIS: "ArcSketch is a free sample extension for ArcGIS that allows you to quickly create features in ArcMap using easy-to-use sketch tools. You simply select a sketch tool and an associated symbol, and then draw the feature. ArcSketch automatically manages the drawing environment, allowing you to conceptualize what to draw, as opposed to how to draw it."

Wednesday, April 05, 2006

Writing C# 2.0 Unsafe Code

This article is extracted from Practical .NET2 and C#2 by Patrick Smacchia. http://www.practicaldot.net/en2/Resources/PracticalDotNet2_Ch14.pdf Introduction We will see that C# allows suspending the verification of code by the CLR to allow developers to directly access memory using pointers. Hence with C#, you can complete, in a standard way, certain optimizations which were only possible within unmanaged development environments such as C++. These optimizations concern, for example, the processing of large amounts of data in memory such as bitmaps. Pointers and unsafe code C++ does not know the notion of code management. This is one of the advantages of C++ as it allows the use of pointers and thus allows developers to write optimized code which is closer to the target machine. This is also a disadvantage of C++ since the use of pointers is cumbersome and potentially dangerous, significantly increasing the development effort and maintenance required. Before the .NET platform, 100% of the code executed on the Windows operating system was unmanaged. This means the executable contains the code directly in machine instructions which are compatible with the type of processor (i.e. machine language code). The introduction of the managed execution mode with the .NET platform is revolutionary. The main sources of hard to track bugs are detected and resolved by the CLR. Amongst these: Array access overflows (Now dynamically managed by the CLR). Memory leaks (Now mostly managed by the garbage collector). The use of an invalid pointer. This problem is solved in a radical way as the manipulation of pointers if forbidden in managed mode. The CLR knows how to manipulate three kinds of pointers: Managed pointers. These pointers can point to data contained in the object heap managed by the garbage collector. These pointers are not used explicitly by the C# code. They are thus used implicitly by the C# compiler when it compiles methods with out and ref arguments. Unmanaged function pointers. The pointers are conceptually close to the notion of delegate. We will discuss them at the end of this article. Unmanaged pointers. These pointers can point to any data contained in the user addressing space of the process. The C# language allows to use this type of pointers in zones of code considered unsafe. The IL code emitted by the C# compiler corresponding to the zones of code which use these unmanaged pointers make use of specialized IL instructions. Their effect on the memory of the process cannot be verified by the JIT compiler of the CLR. Consequently, a malicious user can take advantage of unsafe code regions to accomplish malicious actions. To counter this weakness, the CLR will only allow the execution of this code at run-time if the code has the SkipVerification CAS meta-permission. Since it allows to directly manipulating the memory of a process through the use of an unmanaged pointer, unsafe code is particularly useful to optimize certain processes on large amounts of data stored in structures. Compilation options to allow unsafe code Unsafe code must be used on purpose and you must also provide the /unsafe option to the csc.exe compiler to tell it that you are aware that the code you wish to compile contains zones which will be seen as unverifiable by the JIT compiler. Visual Studio offers the Build Allow unsafe code project property to indicate that you wish to use this compiler option. Declaring unsafe code in C# In C#, the unsafe keyword lets the compiler know when you will use unsafe code. It can be used in three situations: Before the declaration of a class or structure. In this case, all the methods of the type can use pointers. Before the declaration of a method. In this case, the pointers can be used within the body of this method and in its signature. Within the body of a method (static or not). In this case, pointers are only allowed within the marked block of code. For example: unsafe{...} Let us mention that if a method accepts at least one pointer as an argument or as a return value, the method (or its class) must be marked as unsafe, but also all regions of code calling this method must also be marked as unsafe. Using pointers in C# Each object, whether it is a value or reference type instance, has a memory address at which it is physically located in the process. This address is not necessarily constant during the lifetime of the object as the garbage collector can physically move objects store in the heap..NET types that support pointers For certain types, there is a dual type, the unmanaged pointer type which corresponds to the managed type. A pointer variable is in fact the address of an instance of the concerned type. The set of types which authorizes the use of pointers limits itself to all value types, with the exception of structures with at least one reference type field. Consequently, only instances of the following types can be used through pointers: primitive types; enumerations; structures with no reference type fields; pointers.Declaring pointers A pointer might point to nothing. In this case, it is extremely important that its value should be set to null (0). In fact, the majority of bugs due to pointers come from pointers which are not null but which point to invalid data. The declaration of a pointer on the FooType is done as follows: FooType * pointeur; For example: long * pAnInteger = 0; Note that the declaration... int * p1,p2; ... makes it so that p1 is a pointer on an integer and p2 is a pointer.Indirection and dereferencing operators In C#, we can obtain a pointer on a variable by using the address of operator &. For example: long anInteger = 98;long * pAnInteger = &anInteger; We can access to the object through the indirection operator *. For example: long anInteger = 98;long * pAnInteger = &anInteger;long anAnotherInteger = *pAnInteger;// Here, the value of 'anAnotherInteger' is 98. The sizeof operator The sizeof operator allows obtaining the size in bytes of instances of a value type. This operator can only be used in unsafe mode. For example: int i = sizeof(int) // i is equal to 4int j = sizeof(double) // j is equal to 8 Pointer arithmetic A pointer on a type T can be modified through the use of the '++' and '--' unary operator. The '-' operator can also be used with pointers. The '++' operator increments the pointer by sizeof(T) bytes. The '--' operator decrements the pointer by sizeof(T) bytes. The '-' operator used between two pointers of same type T, returns a value of type long. This value is equal to the byte offset between the two pointers divided by sizeof(T). The comparison can also be used on two pointers of a same or different type. The supported comparison operators are:== != < > <= >=Pointer casting Pointers in C# do not derive from the Object class and thus the boxing and unboxing does not exist on pointers. However, pointers support both implicit and explicit casting. Implicit casts are done from any type of pointer to a pointer of type void*. Explicit casts are done from: Any pointer type to any other pointer type. Any pointer type to the sbyte, byte, short, ushort, int, uint, long, ulong types (caution, we are not talking about the sbyte*, byte*, short*... types). One of sbyte, byte, short, ushort, int, uint, long, ulong types to any pointer type. Double pointers Let us mention the possibility of using a pointer on a pointer (although somewhat useless in C#). Here, we talk of a double pointer. For example: long aLong = 98;long * pALong = &aLong;long ** ppALong = &pALong ; It is important to have a naming convention for pointers and double pointers. In general the name of a pointer is prefixed with 'p' while the name of a double pointer is prefixed with 'pp'. Pinned object The garbage collector has the possibility of physically moving the objects for which it is responsible. Objects managed by the garbage collector are generally reference type's instances while pointed objects are value type's instances. If a pointer points to a value type field of an instance of a reference type, there will be a potential problem as the instance of the reference type can be moved at any time by the garbage collector. The compiler forces the developer to use the fixed keyword in order to tell the garbage collector not to move reference type instances which contain a value field pointed to by a pointer. The syntax of the fixed keyword is the following: class Article { public long Price = 0;}unsafe class Program { unsafe public static void Main() { Article article = new Article(); fixed ( long* pPrice = &article.Price ) { // Here, you can use the pointer 'pPrice' and the object // referenced by 'article' cannot be moved by the GC. } // Here, 'pPrice' is not available anymore and the object // referenced by 'article' is not pinned anymore. }} If we had not used the fixed keyword in this example, the compiler would have produced an error as it can detect that the object referenced by the article may be moved during execution. We can pin several objects of a same type in the same fixed block. If we need to pin objects of a several types, you will need to use nested fixed blocks. You must pin objects the least often as possible, for the shortest duration possible. When objects are pinned, the work of the garbage collector is impaired and less efficient. Variables of a value type declared as local variable in a method do not need to be pinned since they are not managed by the garbage collector.Pointers and arrays In C#, the elements of an array made from a type which can be pointed to can be accessed by using pointers. Let us precise that an array is an instance of the System.Array class and is stored on the managed heap by the garbage collector. Here is an example which both shows the syntax but also the overflow of the array (which is not detected at compilation or execution!) due to the use of pointers: using System;public class Program { unsafe public static void Main() { // Create an array of 4 integers. int [] array = new int[4]; for( int i=0; i < 4; i++ ) array[i] = i*i; Console.WriteLine( "Display 6 items (oops!):" ); fixed( int *ptr = array ) for( int j = 0; j< 6 ; j++ ) Console.WriteLine( *(ptr+j) ); Console.WriteLine( "Display all items:" ); foreach( int k in array ) Console.WriteLine(k); }} Here is the display: Display 6 items (oops!):014902042318948Display all items:0149 Note that it is necessary to only pin the array and not each element of the array. This confirms the fact that during execution, the value type elements of an array are store in contiguous memory.Fixed arrays C#2 allows the declaration of an array field composed of a fixed number of primitive elements within a structure. For this, you simply need to declare the array using the fixed keyword and the structure using the unsafe keyword. In this case, the field is not of type System.Array but of type a pointer to the primitive type (i.e. the FixedArray field is of type int* in the following example): Example: unsafe struct Foo{ public fixed int FixedArray[10]; public int Overflow;}unsafe class Program { unsafe public static void Main() { Foo foo = new Foo(); foo.Overflow = -1; System.Console.WriteLine( foo.Overflow ); foo.FixedArray[10] = 99999; System.Console.WriteLine( foo.Overflow ); }} This example displays: -199999 Understand that FixedArray[10] is a reference to the eleventh element of the array since the indexes are zero based. Hence, we assign the 99999 value to the Overflow integer.Allocating memory on the stack with the stackalloc keyword C# allows you to allocate on the stack an array of elements of a type which can by pointed to. The stackalloc keyword is used for this, with the following syntax: public class Program { unsafe public static void Main() { int * array = stackalloc int[100]; for( int i = 0; i< 100 ; i++ ) array[i] = i*i; }} None of the elements of the array are initialized, which means that it is the responsibility of the developer to initialize them. If there is insufficient memory on the stack, the System.StackOverflowException exception is raised. The size of the stack is relatively small and we can allocate arrays containing only a few thousand elements. This array is freed implicitly when the method returns.Strings and pointers The C# compiler allows you to obtain a pointer of type char from an instance of the System.String class. You can use this feature to circumvent managed string immutability. Let us remind that managed string immutability allows to considerably ease their use. However, this can have a negative impact on performance. The System.StringBuiler class is not always the proper solution and it can also be useful to directly modify the characters of a string. The following example shows how to use this feature to write a method which converts a string to uppercase: public class Program { static unsafe void ToUpper( string str ) { fixed ( char* pfixed = str ) for ( char* p = pfixed; *p != 0; p++ ) *p = char.ToUpper(*p); } static void Main() { string str = "Hello"; System.Console.WriteLine(str); ToUpper(str); System.Console.WriteLine(str); }} Delegates and unmanaged function pointers You can invoke a function defined in a native DLL by the intermediate of a delegate fabricated from an unmanaged function pointer. In fact, using the GetDelegateForFunctionPointer() and GetFunctionPointerForDelegate() static methods of the Marshal class, the notion of delegates and function pointers becomes interchangeable: using System;using System.Runtime.InteropServices;class Program { internal delegate bool DelegBeep(uint iFreq, uint iDuration); [DllImport("kernel32.dll")] internal static extern IntPtr LoadLibrary(String dllname); [DllImport("kernel32.dll")] internal static extern IntPtr GetProcAddress(IntPtr hModule,String procName); static void Main() { IntPtr kernel32 = LoadLibrary( "Kernel32.dll" ); IntPtr procBeep = GetProcAddress( kernel32, "Beep" ); DelegBeep delegBeep = Marshal.GetDelegateForFunctionPointer(procBeep , typeof( DelegBeep ) ) as DelegBeep; delegBeep(100,100); }}

Steve Miller's Applications Page

Steve Miller's Applications Page This guy has written some cool nifty tools for use by developers and some that are useful to ordinary computer users too. Best of all, they are all free!

Wednesday, March 29, 2006

The Great Robot Race - The DARPA Grand Challenge

Watched the program on the grand challenge on PBS. I found it immensely inspiring. Here is a link to the programs website http://www.pbs.org/wgbh/nova/darpa/ Also here is a link to Sebastin Thrun's website: http://robots.stanford.edu/index.html And here is a link to Whitaker's website: www.ri.cmu.edu And a link to the DARPA Grand Challenge website: http://www.darpa.mil/grandchallenge05/index.html