Browsers: QGIS vs MapInfo 11


Warning: This post contains small rants! You have been warned.

PBBI have recently released MapInfo 11, the new version has brought one change that I think deserves some attention – even if for the wrong reasons.

MapInfo’s browser window was in need of a very good make over; it didn’t follow normal keyboard conventions, eg holding shift to select rather than ctrl; couldn’t sort via the headers; keyboard navigation was poor; and it looked ugly. PBBI then announced that MapInfo 11 would have a new “improved” browser. I thought “Sweet! About time” and then we got a copy. /sigh

So what’s the problem?

First off it’s slow to resize, this would be due to them using .NET WPF for the new browser (I have never seen a good fast .NET WPF datagrid).

Then we have sorting, which is meant to be the cool new feature. This is not the normal just click on the header to sort the column, no because that would be too easy, you have to right click in the browser, click sort and select the options which then opens a new browser window. um what?

Yes this is a pretty handy feature but no it shouldn’t be the only way to sort, you should have a click on the header kind of sort. This seems to be what people wanted.

Next. No visible scroll progress. When you move the little scroll box on the side the browser waits until you have finished to show you the data. I guess the old browser did this too so why change it!

And finally shift click to select a block of rows doesn’t work, I mean come on this is not a hard thing to do.

Surly you can dock it? Nope!

In the end we have a browser that is pretty much the same as the old one but slower……oh and has alternating row colors.

Overall reaction: Disappointed

Enter QGIS

Now if you are reading this blog you are well aware that I am a huge fan of QGIS, I don’t really make that a secret. So I guess the overall point of this post is to compare the QGIS attribute table (browser) and the new MapInfo 11 one.

Lets run though the same list as MapInfo.

Slow to resize? Nope. Even with a large table open the resize speed doesn’t change.

Header based sorting? Yep. Just click the header and it will sort that column. Multi column sorting is on the to-do list.

Live scrolling (results update as you scroll)? Yep + no lag.

Shift click to select blocks of rows? Sure why not. Or you can hold ctrl to select rows all over the grid.

Docking? Yep and floating so you can put it on a different monitor if you need.

Bonus

The QGIS attribute table has a built-in search/filter box, saves having to run a query and have a new window like in MapInfo if you just want to filter the browser.

The QGIS attribute table (browser)

Extra Bonus
The QGIS browser can even have other UI objects inside the cells. Very bloody handy.

Combo box in browser table.

You can even have a calendar date picker if you want.

Lets review

Feature MapInfo 11 QGIS
Good resize speed. No Yes
Header sorting. Yes [See update] Yes
Multi column sorting. Yes [1] No [2]
Live scrolling. No Yes
Shift click for blocks of rows No Yes
Docking. No[3] Yes

[1] Why does it need to open a new browser window? At least make it an option.
[2] On the to-do list

[3] Yes you can use http://www.pbinsight.com/support/product-downloads/item/windowhelper for this support. It’s a good tool go and download it. I just think it should be built in.

Doesn’t look too good for MapInfo at the moment. QGIS is even accessing the TAB data though ogr. Quick tip: if a free program can access and manage your data faster than you, you are failing.

My work place spends a good deal of money on our annual MapInfo “maintenance” licence, money I would happily send to the QGIS project if I had the choice. Or at least part of it,

Data

Both programs opened a 27000 row .TAB file.

Just for the record I’m not anti-MapInfo. It still has some features that I really like. I just wish they would pick up the game.

Update for 11.03 patch

As promised in my comments this is an update to reflect the new header click sorting in MapInfo Professional 11.03.

The 11.03 patch has added header based sorting, and while the sorting works as expected which is good, there is something a little odd.

What is the typical sort pattern? Left click header, table sorts ascending click again and table sorts descending or vice versa.  Then you normally have any extra sorting stuff in the right-click menu e.g Sort Ascending, Sort Desending, Clear Sort etc.

Go into MapInfo 11.03 left click header, context menu appears 0_o…  I’m not aware of any program that  has ever done that.  A menu on left click is not normal, even crappy ol’ Lotus Notes doesn’t have a menu on left click and Lotus Notes is one really crappy program.

Nuff said.

P.S Don’t talk about your new feature i.e the browser, following normal conventions for browser style windows then do something no one has ever done….and still no shift click block select.

P.P.S I know it may sound like a constant bashing but really something like this should never got passed review. I know UI is hard but come, on a context menu on left click…

Creating an instance of a MapInfo COM object in .NET – Speed Tests


A while ago I posted about how to create an instance of MapInfo in .Net, If you missed those posts then they can be found here.  In these posts I outlined how you can create a instance using three different methods, in the reflection based post I said that one of the disadvantages of doing it this way was that it was slower.   I said this due to just my observations but I thought it would be a good idea to put it to the test and show the speed difference.

I created a simple project to test and show me the results of three different things: Speed of complied MBX, calling a MapBasic function though the Do and via the interface (see posts 1 & 3) and calling Do and Eval via reflection (see post 2)

The code is simple, and is posted at the bottom of this post, the command “Fetch Next From {Table}” is called a number of times: 100;200;300;500;1000;2000;5000 and each block is timed.

After running each iteration set 3 times, these are the results :

SpeedTests

Behold my fancy graph making skills….or lack there of.  The time is in seconds, so the 0.032 in the Interface pass 1 is 0.032 seconds for 200 iterations which is still pretty quick.  You’ll notice that using the reflection based method starts to really take its toll when you are doing 5000 iterations, mind you ~1 second is still pretty quick.

The Mapbasic code I used:

Declare Sub Main
Declare Function Time(count as Integer) as Float
Declare Function GetTickCount Lib "kernel32" () As Integer

Sub Main
   Dim pass as Integer
   pass = 0
	Dim a,b,c,d,e,f,g as Integer
   a = 100
   b = 200
   c = 300
   d = 500
   e = 1000
   f = 2000
   g = 5000

	Do While pass <= 2
       Print "====PASS " + pass + "========="
       Print Time(a)
       Print Time(b)
       Print Time(c)
       Print Time(d)
       Print Time(e)
       Print Time(f)
       Print Time(g)
		pass = pass + 1
   Loop
End Sub

Function Time(count as Integer) as Float
    Dim a as Integer
    Dim b as Integer
	Dim i as Integer
	a = GetTickCount()
	For i = 0 to count
       Fetch Next From Untitled
    Next
	b = GetTickCount()
	Time = (b - a) / 1000
End Function

and the C# code:

class ReflectionMapInfo
    {
        private readonly object mapinfo;

        public ReflectionMapInfo(object mapinfo)
        {
            this.mapinfo = mapinfo;
        }

        public void Do(string commandstring)
        {
            this.mapinfo.GetType().InvokeMember("Do", BindingFlags.InvokeMethod,
                                                                null, this.mapinfo,
                                                                new[] {commandstring});
        }
    }

    class Program
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern int GetTickCount();
        static MapInfoApplication mapinfo = new MapInfoApplication();
        static ReflectionMapInfo reflectionmapinfo = new ReflectionMapInfo(mapinfo);

        static void Main(string[] args)
        {
            mapinfo.Do(@"Open Table ""C:\Users\Woo\Documents\Untitled.TAB""");

            int pass = 0;
            while (pass <= 2)
            {
                Console.WriteLine("Interface Test, Pass " + pass + "Count 100 " + Time(100));
                Console.WriteLine("Interface Test, Pass " + pass + "Count 200 " + Time(200));
                Console.WriteLine("Interface Test, Pass " + pass + "Count 300 " + Time(300));
                Console.WriteLine("Interface Test, Pass " + pass + "Count 500 " + Time(500));
                Console.WriteLine("Interface Test, Pass " + pass + "Count 1000 " + Time(1000));
                Console.WriteLine("Interface Test, Pass " + pass + "Count 2000 " + Time(2000));
                Console.WriteLine("Interface Test, Pass " + pass + "Count 5000 " + Time(5000));
                pass++;
            }

            pass = 0;
            while (pass <= 4)
            {
                Console.WriteLine("Reflection Test, Pass " + pass + "Count 100 " + ReflectionTime(100));
                Console.WriteLine("Reflection Test, Pass " + pass + "Count 200 " + ReflectionTime(200));
                Console.WriteLine("Reflection Test, Pass " + pass + "Count 300 " + ReflectionTime(300));
                Console.WriteLine("Reflection Test, Pass " + pass + "Count 500 " + ReflectionTime(500));
                Console.WriteLine("Reflection Test, Pass " + pass + "Count 1000 " + ReflectionTime(1000));
                Console.WriteLine("Reflection Test, Pass " + pass + "Count 2000 " + ReflectionTime(2000));
                Console.WriteLine("Reflection Test, Pass " + pass + "Count 5000 " + ReflectionTime(5000));
                pass++;
            }
            Console.ReadLine();
        }

        public static double Time(int count)
        {
            int start = GetTickCount();
            for (int i = 0; i < count; i++)
            {
                mapinfo.Do("Fetch Next From Untitled");
            }
            int end = GetTickCount();
            mapinfo.Do("Fetch First From Untitled");
            return (end - start) / 1000d;
        }

        public static double ReflectionTime(int count)
        {
            int start = GetTickCount();
            for (int i = 0; i < count; i++)
            {
                reflectionmapinfo.Do("Fetch Next From Untitled");
            }
            int end = GetTickCount();
            reflectionmapinfo.Do("Fetch First From Untitled");
            return (end - start) / 1000d;
        }
    }

Creating an instance of a MapInfo COM object in .NET – Speed Tests


Blog has now moved to <a href="http://nathanw.net&quot;A while ago I posted about how to create an instance of MapInfo in .Net, If you missed those posts then they can be found here.  In these posts I outlined how you can create a instance using three different methods, in the reflection based post I said that one of the disadvantages of doing it this way was that it was slower.   I said this due to just my observations but I thought it would be a good idea to put it to the test and show the speed difference.

I created a simple project to test and show me the results of three different things: Speed of complied MBX, calling a MapBasic function though the Do and via the interface (see posts 1 & 3) and calling Do and Eval via reflection (see post 2)

The code is simple, and is posted at the bottom of this post, the command “Fetch Next From {Table}” is called a number of times: 100;200;300;500;1000;2000;5000 and each block is timed.

After running each iteration set 3 times, these are the results :

SpeedTests

Behold my fancy graph making skills….or lack there of.  The time is in seconds, so the 0.032 in the Interface pass 1 is 0.032 seconds for 200 iterations which is still pretty quick.  You’ll notice that using the reflection based method starts to really take its toll when you are doing 5000 iterations, mind you ~1 second is still pretty quick.

The Mapbasic code I used:

Declare Sub Main
Declare Function Time(count as Integer) as Float
Declare Function GetTickCount Lib "kernel32" () As Integer

Sub Main
   Dim pass as Integer
   pass = 0
	Dim a,b,c,d,e,f,g as Integer
   a = 100
   b = 200
   c = 300
   d = 500
   e = 1000
   f = 2000
   g = 5000

	Do While pass <= 2
       Print "====PASS " + pass + "========="
       Print Time(a)
       Print Time(b)
       Print Time(c)
       Print Time(d)
       Print Time(e)
       Print Time(f)
       Print Time(g)
		pass = pass + 1
   Loop
End Sub

Function Time(count as Integer) as Float
    Dim a as Integer
    Dim b as Integer
	Dim i as Integer
	a = GetTickCount()
	For i = 0 to count
       Fetch Next From Untitled
    Next
	b = GetTickCount()
	Time = (b - a) / 1000
End Function

and the C# code:

class ReflectionMapInfo
    {
        private readonly object mapinfo;

        public ReflectionMapInfo(object mapinfo)
        {
            this.mapinfo = mapinfo;
        }

        public void Do(string commandstring)
        {
            this.mapinfo.GetType().InvokeMember("Do", BindingFlags.InvokeMethod,
                                                                null, this.mapinfo,
                                                                new[] {commandstring});
        }
    }

    class Program
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern int GetTickCount();
        static MapInfoApplication mapinfo = new MapInfoApplication();
        static ReflectionMapInfo reflectionmapinfo = new ReflectionMapInfo(mapinfo);

        static void Main(string[] args)
        {
            mapinfo.Do(@"Open Table ""C:UsersWooDocumentsUntitled.TAB""");

            int pass = 0;
            while (pass <= 2)
            {
                Console.WriteLine("Interface Test, Pass " + pass + "Count 100 " + Time(100));
                Console.WriteLine("Interface Test, Pass " + pass + "Count 200 " + Time(200));
                Console.WriteLine("Interface Test, Pass " + pass + "Count 300 " + Time(300));
                Console.WriteLine("Interface Test, Pass " + pass + "Count 500 " + Time(500));
                Console.WriteLine("Interface Test, Pass " + pass + "Count 1000 " + Time(1000));
                Console.WriteLine("Interface Test, Pass " + pass + "Count 2000 " + Time(2000));
                Console.WriteLine("Interface Test, Pass " + pass + "Count 5000 " + Time(5000));
                pass++;
            }

            pass = 0;
            while (pass <= 4)
            {
                Console.WriteLine("Reflection Test, Pass " + pass + "Count 100 " + ReflectionTime(100));
                Console.WriteLine("Reflection Test, Pass " + pass + "Count 200 " + ReflectionTime(200));
                Console.WriteLine("Reflection Test, Pass " + pass + "Count 300 " + ReflectionTime(300));
                Console.WriteLine("Reflection Test, Pass " + pass + "Count 500 " + ReflectionTime(500));
                Console.WriteLine("Reflection Test, Pass " + pass + "Count 1000 " + ReflectionTime(1000));
                Console.WriteLine("Reflection Test, Pass " + pass + "Count 2000 " + ReflectionTime(2000));
                Console.WriteLine("Reflection Test, Pass " + pass + "Count 5000 " + ReflectionTime(5000));
                pass++;
            }
            Console.ReadLine();
        }

        public static double Time(int count)
        {
            int start = GetTickCount();
            for (int i = 0; i < count; i++)
            {
                mapinfo.Do("Fetch Next From Untitled");
            }
            int end = GetTickCount();
            mapinfo.Do("Fetch First From Untitled");
            return (end - start) / 1000d;
        }

        public static double ReflectionTime(int count)
        {
            int start = GetTickCount();
            for (int i = 0; i < count; i++)
            {
                reflectionmapinfo.Do("Fetch Next From Untitled");
            }
            int end = GetTickCount();
            reflectionmapinfo.Do("Fetch First From Untitled");
            return (end - start) / 1000d;
        }
    }

MapInfo Window Manager Version 1 – Coming Soon!


Since the release of version 0.5 of my MapInfo Window Manager I have been working on the new version which will be Version 1.0 and to be released soon. It has some new features, bug fixes and a improved UI.

Some Screenshots and feature run down:

Windows Tab: (Shows Open Windows)

Features:

  • Double click to bring window to the front.
  • F2 turns on rename function for the selected window.
  • Supports all windows types, even info and stat windows. (Version 0.5 just supported Maps and Layouts)
  • Groups can be sorted alphabetically in ascending or descending order.  (A and D buttons)
  • Groups can be sorted individually.
  • All windows can be cloned except for Special windows.
  • Shows count of windows open in each group.
  • Windows can be locked to stop accidental closing.
  • Fancy icons :)

Closed Windows Tab: (shows closed windows allows them to be reopened)

Credit to Peter Horsboll Moller of PBBI MapInfo for this idea, which came from his MapBasic Window Helper tool.

Features:

  • Records all windows as they are closed, letting you restore the window later. (Handy for accidentally closing a legend window)
  • Double click to reopen window.

Settings tab: (Pretty boring just lets you change some settings)

Features:

  • Allows the program to be auto loaded and the tool to be shown when MapInfo loads.
  • Allows the program to store the position of itself.

About Tab: (Pretty boring also, just some info about the app and where to contact me)

Features:

  • It’s an about page, what features can it have!? :)

I have been testing my Window Manager at home and at work, I use it almost everyday, and with some people that I know.

However I would like to get some more testing done by some other people to make sure that Version 1.0 is good and stable.  I am also still look out for anymore ideas that I could throw into Version 1.0.

If you would like to give the beta a test and do some bug hunting for me, or likewise if you have a feature you would like to see rolled into Version 1.0, please contact me on here or by email (which you can see in the about tab page screenshot above)

Just for fun:

Here is a comparison screenshot of the old and new one:

New MapInfo Pro Tool – Window Manager


Over the last couple of weeks I have been working on a new MapInfo Professional tool called Window Manager, it is nothing big but I find it very handy.  The window manager shows all the open map and layout windows in a visual WPF tree view control and gives the users quick access to basic functions when dealing with windows in MapInfo eg Rename and Clone etc.

Screenshot

The current version (0.5) is only really a preview version and still has a little bit of work to make it a bit more polished looking, however I have tested the clone, close,rename and bring to front commands a lot as I use this tool all the time and it feels stable.  I am releasing it early rather than waiting for a couple of more weeks for a couple of reasons 1) Fear of forgetting to release it due to being busy 2) Would like to see what other people would like to do with a tool like this.

The wiki page with more details, download link and how to install instructions can be found here: http://code.google.com/p/nathansmapinfoprojects/wiki/WindowManager

This tool uses WPF and in doing so needs .Net 3.5, must people should have this so it shouldn’t be a big deal.

If you find any bugs or would like to see something added please let me know by commenting on this blog post, on the wiki page or on the issue tracker on my Google code page.

True floating and top most Mapbasic window.


<Rant>One thing that has always annoyed me with MapInfo is the Mapbasic window.</Rant>

That last statement is a bit bold so let me break it down, functionality wise it is great and I couldn’t use MapInfo without it, however it is part of the MDI Client (the gray bit in MapInfo  that the map windows belong to) this means that when you have a map or browser window and the Mapbasic window open they both have the same z-order in the MDI Client, meaning you can end up with this problem.

Not Cool

This is not cool, and I wonder how this even passed the user interface testing phase but I digress.

One of the problems that this can bring is that you can’t have a maximized map/browser window and just have a small Mapbasic window in the corner.  This may not seem like a big deal however due to the z-ordering issue it forces you to micro manage your windows in the MDI client, move the map a little bit now you have to move the Mapbasic window so that it doesn’t sit behind you map and so on, all in all wasting time you could be making your map.

Get on with it

So what is the point of this post, well a little while ago I was sitting writing some unrelated C# code and it hit me.  If I can call and show a .Net form from Mapbasic, parent it to MapInfo and embed the normal Mapbasic window in my new .Net form I could make a true top most floating Mapbasic window that lives above any other window in MapInfo and remove that z-ordering issue.

After doing some playing around in test projects I discovered what I wanted to do was possible and without to much effort, there was a few little things that caused problems but what software adventure doesn’t have those.

I complied all the code into a set of tools called the “Floating Windows Tools”, this set of tools also does a few other things but they will be covered in other blog posts.

The main thing the set of tools does is float the Mapbasic window above all the other window, here is an example of the result of using the tool.

The above image shows a maximized map window and the Mapbasic window sitting on top of the map, it will always be on top and never move behind the map or any other window in MapInfo for that matter.

More Information & Downloads

More information, downloads and examples can be found on my google code project page for the project:

Demo Video

Sorry about the low quality.

Contact me

I have spent a fair fews hours developing and testing this tool, however as with all software there are always things that could be improved or  bug to be squished.  So if you find anything or have a improvment idea don’t hesitate to contact me via here or on the google code page for this project.

Sneak Peek

And because software is never finished here is a sneak peek at the new version I am working on, this version will have syntax highlighting and code completion so that it will make it easier to type Mapbasic.

Since making the first release my time to work on this project has decrease a lot, so I can’t see me making a release of the new version anytime soon however I may have a  “all I do is code” weekend and may get it done faster then I think so stay tuned if your interested.

Embedding the whole Mapinfo application in a .Net form.


Not sure if I’ll ever have a need for this, but someone else may so I thought I would throw this up here, just in case.

A couple of days ago there was a question on MapInfo-l about embedding MapInfo into a .Net application(http://groups.google.com/group/mapinfo-l/browse_thread/thread/15dfc23ceff8ceef).
Embedding a map window into .Net is something that is covered in the Mapbasic manual however this is not what was needed, what was interesting was the person wanted to be able to embed the whole Mapinfo application menus and all into a .Net contol.

As I had not done this before or seen anyone else do it I thought it might be interesting to have a look into it, knowing also that by using Win32 libraries from .Net(eg User32.dll) you could do some cool stuff I figured why not?

The following code is what I managed to write that lets me embed the whole application into a .Net control(I let the code comments explain what is going on):

For this code to work you will need to create a .Net form with a picture box somewhere on it and a button that calls button1_click for it’s click handler, you will also need to reference Mapinfow.exe/Mapinfo COM server see https://woostuff.wordpress.com/2009/04/01/com-instance-mapinfo-main/ for details.

    public partial class Form1 : Form
    {
        // Sets the parent of a window.
        [DllImport("User32", CharSet = CharSet.Auto, ExactSpelling = true)]
        internal static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndParent);

        //Sets window attributes
        [DllImport("USER32.DLL")]
        public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

        //Gets window attributes
        [DllImport("USER32.DLL")]
        public static extern int GetWindowLong(IntPtr hWnd, int nIndex);

        //assorted constants needed
        public static int GWL_STYLE = -16;
        public static int WS_CHILD = 0x40000000; //child window
        public static int WS_BORDER = 0x00800000; //window with border
        public static int WS_DLGFRAME = 0x00400000; //window with double border but no title
        public static int WS_CAPTION= WS_BORDER | WS_DLGFRAME; //window with a title bar
        public static int WS_MAXIMIZE = 0x1000000;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Create a new instance of MapInfo.
            MapInfoApplication mapinfo = new MapInfoApplication();

            // Get the handle to the whole MapInfo application.
            // 9 = SYS_INFO_MAPINFOWND.
            string handle = mapinfo.Eval("SystemInfo(9)");

            // Convert the handle to an IntPtr type.
            IntPtr oldhandle = new IntPtr(Convert.ToInt32(handle));

            //Make mapinfo visible otherwise it won't show up in our control.
            mapinfo.Visible = true;

            //Set the parent of MapInfo to a picture box on the form.
            SetParent(oldhandle, this.pictureBox1.Handle);

            //Get current window style of MapInfo window
            int style = GetWindowLong(oldhandle, GWL_STYLE);

            //Take current window style and remove WS_CAPTION(title bar) from it
            SetWindowLong(oldhandle, GWL_STYLE, (style & ~WS_CAPTION));

            //Maximize MapInfo so that it fits into our control.
            mapinfo.Do("Set Window 1011 Max");
        }
    }

After the code is complied and run you should end up with a screen like this:
(Once the whole MapInfo application is embedded into our C# application, we can still do all the Do and Eval methods that we normally would when doing integrated Mapping)

Debugging MapInfo .Net Programs with Visual Studio 2008 or Visual Studio 2008 Express Editions


I was looking through some of the folders on my PC and found an article that I wrote about debugging Mapbasic and .NET programs in Visual Studio, so I thought it might be handy to post it here.

I was going to copy and paste everything in the article into a new blog post but instead I have just uploaded the pdf to the blog so it’s easy for people to download. The article can be found at Debugging .NET Mapbasic Applications with Visual Studio

MapInfo version detection.


I thought I would just write a follow up post for my creating an instance of MapInfo COM object series about being able to detect which version of MapInfo the user has installed.

In this blog post I’m going to show some sample code that you can use to find which version/s of MapInfo the user has installed, to allow you to notify which version of MapInfo your application is compatible with.

When you install MapInfo, it creates a key in the registry which stores information for MapInfo like MI version,COM GUID, Access code etc. The key that contains this information is located in:

HKEY_LOCAL_MACHINE\SOFTWARE\MapInfo\MapInfo\Professional

if we open up the registry and have a look at that key we should be able to see something that looks like this:

image

 

 

 

 

 

In the above picture you can see that professional subkey shows a folder for each version of MapInfo that you have installed, as you can see on my PC I have version 9.5 and 10 installed.  Each one of these keys holds the information for that installed version of MapInfo, if we have a look at the information of version 10 it looks something like this:

image

 

 

 

 

 

 

 

 

As you can see the key has all the information about the installed version 10 of MapInfo including Access Code(000000 for demo version),the COM GUID for MapInfo and install path.

Enough talk lets see some code:

This is a little bit of C#3.0 sample code that you can use to detect and display which version of MapInfo the version has installed.

   1: string registryKey = @"SOFTWARE\MapInfo\MapInfo\Professional";
   2:  
   3: using (Microsoft.Win32.RegistryKey prokey = Registry.LocalMachine.OpenSubKey(registryKey))
   4: {
   5:     var versions = from a in prokey.GetSubKeyNames()
   6:                    let r = prokey.OpenSubKey(a)
   7:                    let name = r.Name
   8:                    let slashindex = name.LastIndexOf(@"\")
   9:                    select new
  10:                    {
  11:                       MapinfoVersion = Convert.ToInt32(name.Substring(slashindex + 1,
  12:                                                                        name.Length - slashindex -1))
  13:                    };
  14:  
  15:     Console.WriteLine("Installed Mapinfo Version");
  16:     foreach (var item in versions)
  17:     {
  18:         Console.WriteLine("Mapinfo Version: {0}", item.MapinfoVersion);
  19:     }
  20: }

If you don’t want to use LINQ you could use something like this:

   1: string registryKey = @"SOFTWARE\MapInfo\MapInfo\Professional";
   2:  
   3: using (Microsoft.Win32.RegistryKey prokey = Registry.LocalMachine.OpenSubKey(registryKey))
   4: {
   5:     List<int> versions = new List<int>();
   6:     foreach (string key in prokey.GetSubKeyNames())
   7:     {
   8:         RegistryKey subkey = prokey.OpenSubKey(key);
   9:         string name = subkey.Name;
  10:         int slashindex = name.LastIndexOf(@"\");
  11:         int version = Convert.ToInt32(name.Substring(slashindex + 1,
  12:                                                      name.Length - slashindex - 1));
  13:         versions.Add(version);
  14:     }
  15:  
  16:     Console.WriteLine("Installed Mapinfo Version");
  17:     foreach (int mapinfoversion in versions)
  18:     {
  19:         Console.WriteLine("Mapinfo Version: {0}", mapinfoversion);

20: }

Both will output the installed versions to the console:

image

Now detecting the version is all well and good but you really need to tell the user if they won’t be able to use your application if they are running a version lower then your application was built with.

Something like this would do it:

   1: const int NeededMapinfoVersion = 1000;
   2:  
   3: Console.WriteLine("Checking Mapinfo Version");
   4: foreach (var item in versions)
   5: {
   6:     if (item.MapinfoVersion < NeededMapinfoVersion)
   7:     {
   8:         Console.WriteLine("Sorry I need Mapinfo Version {0} but you have {1}",
   9:                           NeededMapinfoVersion,item.MapinfoVersion);
  10:        // Exit the app.
  11:     }
  12:     else
  13:     {
  14:         Console.WriteLine("Your good to go");
  15:         break;
  16:     }
  17: }

Of course the above code is pretty rough but it should do the trick.

Hope this helps.

Creating an instance of a Mapinfo COM object in .NET – Part Three


In part three of the series Creating a instance of a Mapinfo COM object in .NET, I’m going to be talking about creating an instance of Mapinfo’s COM object using Activator.CreateInstace but also allowing you to have strong typed access to Mapinfo’s members. This approach unlike the approach outlined in part two, will allow for your application to be Mapinfo version independent without having to use reflection to get access to Do and Eval

If you haven’t read part one and two I would recommend reading them first as it will give you an understanding of where this post is heading.

Step 1: Adding a referance to Mapinfo.

As this method requires us to get access to some of the interfaces that Mapinfo provides, we will need to add a reference to Mapinfo like we did in first step in part one.

To save on re-explaining the whole process here again, I will wait while you head over to part one and follow the process outlined in step 1. Make sure that you come back here after you have completed step 1.

Step 2: Creating the instance

Now that you are back, we can continue.

The process in this step is similar to the process outlined in Part two step 1, however things will differ a little bit.

If you have a look at the Interop.Mapinfo.dll in the object browser of visual studio you will notice that the class called MapinfoApplicationClass, implments a interface called DMapinfo.
DMapinfo

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Does that MapinfoApplicationClass class look familiar? It should as it is what we used to create the Mapinfo instance in part one of this series, but we don’t need that class here so we will just forget about it. What we do need is that interface called DMapinfo as it provides all the methods that we need to interact with Mapinfo.

If we have the code that we used in part two step 1 for creating the instance of Mapinfo.

Type mapinfotype = Type.GetTypeFromProgID("Mapinfo.Application");
object instance = Activator.CreateInstance(mapinfotype);

now this code is great and all but we run into the problem that we had in part two where C# doesn’t support late binding so we have to use reflection which just feels dirty. There has to be a better way.

What object is Activator.CreateInstace returning in the above code anyway?

Turns out that the object that it returns also implements the interface DMapinfo, this is good for us as it allows us to cast the object returned from Activator.CreateInstance() to the type DMapinfo. If we go and add the right casting to the code it should now look like the following.

Type mapinfotype = Type.GetTypeFromProgID("Mapinfo.Application");
DMapInfo instance = (DMapInfo)Activator.CreateInstance(mapinfotype);

Cool, so we have created a instance of Mapinfo and casted it to the type DMapinfo now we should be able to do something useful with it.

Step 3: Using the object.

Because we have casted our object to the interface called DMapinfo, we can now get strongly typed access to Mapinfo’s Do and Eval method. No more reflection needed :).

Some sample code:

Type mapinfotype = Type.GetTypeFromProgID("Mapinfo.Application");
DMapInfo instance = (DMapInfo)Activator.CreateInstance(mapinfotype);

instance.Do("Print 1234567");
string value = instance.Eval("NumTables()");

More information on DMapinfo.

If we have a look at the GUID on the top of the DMapinfo interface you will notice that it looks something like this:

[Guid("1D42EC63-7B28-11CE-B83D-00AA002C4F58")]
public interface DMapInfo

This GUID for DMapinfo, which unlike the GUID for the MapinfoApplicationClass is the same for every Mapinfo version.
Because it is the same we can create Mapinfo using Activator.CreateInstance() which will return a COM object, cast it DMapinfo and by making calls against the interface we don’t have to worry about what version of Mapinfo the client is running.

Summing up: Pros and Cons

In this post I have outlined how you can create an instance of Mapinfo using Activator.CreateInstance() and cast the return object to the interface called DMapinfo. This technique allows us to have Mapinfo version independence while still maintaining our type safety and compiler support.

Pros

  • Allows Mapinfo version independence.
  • Strong Typed
  • Cleaner then having to use reflection.
  • Faster method calling then using reflection.

Cons

  • No real cons