MindManager 7 ToDoList AddIn development Part 6: the Mysteries of COM interop

Sometimes there are inevitable mysteries uncovered when writing code.  Well, I’ve bumped into quite a rich source of mysteries in trying to use an aspect of the MindManager object model that thunks through a brittle COM interop module, known as CmjDocumentCollectionComObject.  Here’s just a couple of examples that have come up recently:

“unable to create document”

Here is the ‘offending’ code:

public static MMInterop.Document GetMap(string filename)
{
    MMInterop.Document toDoListMap;
    MMInterop.Documents maps;
    string toDoListMapFullPath = Connect.applicationObject.get_Path(MMInterop.MmDirectory.mmDirectoryMyMaps) + filename;
    maps = Connect.applicationObject.get_Documents(true);
    try // open a ToDoList map
    {
        toDoListMap = maps.Open(toDoListMapFullPath, String.Empty, true); // here's where the COMException is raised
    }
}

Here is the exception raised:

System.Runtime.InteropServices.COMException occurred
  Message=”Object ‘CmjDocumentCollectionComObject’ reports an error: ‘unable to create document'”
  Source=”MindManager.Application.7″
  ErrorCode=-2147220992
  StackTrace:
       at Mindjet.MindManager.Interop.DocumentsClass.Open(String pFileName, String pPassword, Boolean Visible)
       at ParanoidMike.MindManager.ToDoList.ToDoListMap.GetMap(String filename) in C:\personal\VS Projects\MM7TODOList\ToDoList.cs:line 187
  InnerException:

And do you want to know what that exception really means?  “The specified file does not exist” would be my interpretation.  If I understand the MindManager function maps.Open() correctly, this is meant to open an existing document.  I’ve just asked it to open a non-existent document, so I’d expect “can’t find it”, but I’m puzzled by “unable to create document”.  It’s like whoever wrote the error strings for the CmjDocumentCollectionComObject is interpreting the name of the Win32 CreateFile() API literally.

I am attempting to use a Try…Catch approach to testing whether the requested file exists. If the file exists, then maps.Open() would succeed; if it didn’t exist, then I’d use the Catch block to instead create the named file.  I didn’t expect to have to catch a System.Runtime.InteropServices.COMException, nor in figuring out how to catch only the exception with a specific ErrorCode/HRESULT returned by the COM object.

But then again, “Nobody expects the Spanish Inquisition”

{“Retrieving the COM class factory for component with CLSID {5B9EA9CE-76A3-4878-9A6B-22D0A3042774} failed due to the following error: 80040154.”}

Here’s the code:

MMInterop.Document toDoListMap;
try
{
    toDoListMap = new MMInterop.Document();
}
catch (System.Runtime.InteropServices.COMException e)
{
    throw;
}

Here’s the .NET exception that gets thrown:

{“Retrieving the COM class factory for component with CLSID {5B9EA9CE-76A3-4878-9A6B-22D0A3042774} failed due to the following error: 80040154.”}

And here’s the HRESULT that is being thrown by the COM object: -2147220992

In various posts, the common theme seems to be that the “component with the noted CLSID” needs to be re-registered.  Searching for this CLSID on my system (predictably) leads to Mindjet.MindManager.Interop, Version=7.0.323.0, Culture=neutral, PublicKeyToken=19247b5ea06b230f and Mindjet.MindManager.Interop, Version=7.1.388.0, Culture=neutral, PublicKeyToken=19247b5ea06b230f.  [However, there’s no ProgID registered for Mindjet.MindManager.Interop.  Is that bad — I know it’s not good for typical apps, but is a COM interop assembly a “typical” COM app?]

I remember reading somewhere that the MindManager 7 Primary Interop Assemblies were installed by default when installing MM7, so I thought perhaps and Add/Remove Programs “Repair” operation would suffice.

Unfortunately no — damned MindManager, I ran the full Repair, and it even reinstalled all the 41 default templates (so I know it did completely successfully), but my code is still throwing this same error.  So I went looking for the file path, which meant examining the Properties of the “MindManager” Reference, and it reports that this “ActiveX” file is stored here: C:\WINDOWS\assembly\GAC_MSIL\Mindjet.MindManager.Interop\7.1.388.0__19247b5ea06b230f\Mindjet.MindManager.Interop.dll.  Fire up a Command Prompt in that directory, run “REGSVR32.EXE Mindjet.MindManager.Interop.dll”, and I end up with this error:

image

REGASM.EXE

Here’s a riddle: how does one initialize a variable that cannot be initialized?

When I try to create a new mindmap document using a .NET AddIn, I’m finding that the variable I declare to hold a reference to the new mindmap is not usable: (a) it won’t work until it’s initialized, but (b) when it’s initialized it throws the error documented here:
http://tech.groups.yahoo.com/group/MindManagerDev/message/447

I’ve tried to dig up any hints that would help me figure out what to do to resolve this error, but so far nothing has worked (including trying to Register the Interop DLL, and Repairing the installation of MindManager).

There are plenty of people asking about this kind of issue — some related to straight COM objects, others talking about COM Interop assemblies:
http://www.thescripts.com/forum/thread731361.html
http://forums.cnet.com/5208-6141_102-0.html?forumID=8&threadID=216925&messageID=2313201
http://channel9.msdn.com/ShowPost.aspx?PostID=333247
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=765439&SiteID=1
http://groups.google.com/group/microsoft.public.dotnet.framework.interop/browse_thread/thread/e8d8ccb58221f843/2263fa2b3db5895b

(1) I tried loading up the Interop DLL in DEPENDS.EXE, but there appear to be no missing dependencies.
(2) I tried registering the assembly using REGASM.EXE, according to the article here: http://www.simple-talk.com/dotnet/visual-studio/build-and-deploy-a-.net-com-assembly/
using the following command:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>regasm C:\WINDOWS\assembly\GAC_MSIL\Mindjet.MindManager.Interop\7.1.388.0__19247b5ea06b230f\mindjet.mindmanager.interop.dll
Microsoft (R) .NET Framework Assembly Registration Utility 2.0.50727.1433
Copyright (C) Microsoft Corporation 1998-2004.  All rights reserved.

Types registered successfully

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>

Now I’m getting the same .NET exception, with a different HRESULT: -2147221164.  That HRESULT appears to be associated with needing to re-register Atl.dll, so I gave that a shot.  Unfortunately, it gave me the same error and the same HRESULT.  I also tried re-running the above REGASM.EXE command, with no change — still throwing the same exception.

Cheap Hack: avoid init issues with dummy calls

I’m almost embarrassed to even discuss how I’m getting around this intractable problem…but not embarrassed enough not to do it, so I might as well own up to it.  Who knows?  Maybe one of you will know what I’m overlooking.  Maybe I’ll find this article in six months’ time and remember why I put this hack in place.  Maybe this will just be my own personal legacy to the world. 🙂

Let’s recap: my design for this AddIn is to use a separate map to list copies of all Tasks found in the searched maps. If the named map already existed, just open it; if not, a new map should be created.  However, I kept getting blocked by not “initializing” the local variable to hold the new/opened Document handle before returning it to the calling function.  However, initializing the local variable with a “new MMInterop.Document()” call just caused other problems.

I was thinking that because Visual Studio was throwing the CS0165 error “Use of unassigned local variable ‘toDoListMap” on the final line of code “return toDoListMap”, and not on any of the preceding where the toDoListMap variable was being assigned, what Visual Studio might be reacting to is that toDoListMap wouldn’t have a non-null value on all code paths through the function.  I’d ignored this thought because (a) the code paths where it wouldn’t get a value were intentional, and (b) the documentation on CS0165 kept indicating that I needed to initialize the variable.

However, after exhausting all the “right way” options, I finally just dropped some initializations (assignments?) into the code paths where toDoListMap wasn’t previously being touched:

public static MMInterop.Document GetMap(string filename)
{
    MMInterop.Document toDoListMap;
    MMInterop.Documents maps;
    string toDoListMapFullPath = Connect.applicationObject.get_Path(MMInterop.MmDirectory.mmDirectoryMyMaps) + filename; // TODO: remove this hard-coded pathing to the ToDoList map
    maps = Connect.applicationObject.get_Documents(true); // assign/initialize the maps variable so the array can be searched by maps.Open().  "Connect" is the Class that implements a static variable "applicationObject" which is assigned to the "application" object that's captured during AddIn initialization.

    try // open the existing ToDoList map
    {
        toDoListMap = maps.Open(toDoListMapFullPath, String.Empty, false);
    }
    catch (System.Runtime.InteropServices.COMException e) // if a ToDoList map by that name does not exist, create one
    {
        if (e.ErrorCode == -2147220992) // "Object 'CmjDocumentCollectionComObject' reports an error: 'unable to create document'"
        {
            System.Windows.Forms.MessageBox.Show("Exception opening map: " + e.Message); // TODO: remove once initial debugging is complete
            string templateFullPath = Connect.applicationObject.get_Path(MMInterop.MmDirectory.mmDirectoryTemplates) + templateFileName; //construct reference to the template that's required when creating a new Document

            toDoListMap = maps.AddFromTemplate(templateFullPath, String.Empty, false);
        }
        else // this is never intended to be run - it's just here to convince the compiler that the toDoListMap variable has been initialized on all code paths, as it otherwise throws an exception "Use of unassigned local variable 'toDoListMap'.
        {
            System.Windows.Forms.MessageBox.Show("If you see this message, record the error and report it to the developer - this should never be seen: error code = " + e.ErrorCode.ToString());
            toDoListMap = new MMInterop.Document();
        }
    }
    catch (Exception e) // this is never intended to be run - it's just here to convince the compiler that the toDoListMap variable has been initialized on all code paths, as it otherwise throws an exception "Use of unassigned local variable 'toDoListMap'.
    {
        System.Windows.Forms.MessageBox.Show("If you see this message, record the error and report it to the developer - this should never be seen: error code = " + e.ErrorCode.ToString());
        toDoListMap = new MMInterop.Document();
    }

    return toDoListMap;
}

And now, miraculously this damned code compiles and runs correctly.  I really wish I had some better ideas than these “new” calls, ’cause I’ve got a feeling they’ll come back to bite me far down the line.  I’ve added some MessageBox “please let me know if you see this” dialogs, but that won’t really solve the problem — just make me look a little more like an amateur code-jockey.

[I’m still not sure why in this case, I was able to assign the toDoListMap variable without first initializing it — it’s not one of the simple datatypes, so I don’t think it’s being implicitly initialized by the compiler, and I thought I’d just re-learned that a complex Object always needs to be declared, initialized and then assigned.  Once again there’s something I don’t get about this, but I’ll leave that to dig up in the future, as yet another great surprise. :)]

Advertisements

MindManager 7 ToDoList AddIn development Part 5: minimizing Object overhead between classes

I’ve created quite a puzzle for myself.  In writing an AddIn that calls functions from custom Classes, I am forcing the AddIn to pass in all the data that would be needed in the custom code.  I’ve added a few helper functions to the ToDoListBuilder class including GetAllTasks(), IsTaskCompleted() and IsTopicATask().  These are easy because I’m passing simple variables into each function.

However, I haven’t yet wired up the primary function that will be called from the AddIn’s mmCommand_Click() event, and I haven’t decided what I need to pass down from the button_Click() to the cascade of encapsulated functions, nor how far down to pass any object like a baton.

It seems like it’d be correct to pass the MMInterop.Application object into the ToDoListBuilder code, but in passing the Application object to a GenerateToDoListItems() method, I’ll have to pass the Application object to at least one further layer of called functions such as GetAllToDoListMaps().  Or will I?

Now that I’m looking around, the Connect class has a private applicationObject variable.  While it seems unlikely I’d be able to make reference to that Class’ private variable from a called Class, there should be no reason why I couldn’t create another private variable in the ToDoListBuilder class as soon as the GenerateToDoListItems() method is called, and then call on that Class-wide variable from then on.

Reducing Memory Footprint of Application Object(s) without Passing References Everywhere

Here’s how the code around the Application object comes out from the Visual Studio AddIn Template wizard by default:

    public class Connect : Object, Extensibility.IDTExtensibility2
{
private Mindjet.MindManager.Interop.Application applicationObject; private Mindjet.MindManager.Interop.Command mmCommand;
... }

Changing the first declaration to public from private makes that applicationObject object available outside of the assembly as well as within it, so that pointers (references) to the object don’t have to be explicitly passed around the code.

Assuming that nothing can affect the state of the applicationObject, there should be no reason not to declare it as “public”.  I’m not entirely naive though — I assume there’s reasons why you’d want to do one and not the other, but I have to believe that any code running in the MindManager application should necessarily want/try to use a single application object anyway.

Solution: Static/Shared modifier

After bashing my skull into the wall of my ineptitude for a few days, I finally dislodged a bone fragment of useful info: the “static” modifier.  Somehow this does what I had expected the “public” keyword to accomplish — makes it possible to access the variable from outside the class, without having to instantiate another copy of the object.

Open Questions

Now I’m left wondering two things:

  1. What’s the lowest level of accessibility that the object needs?  Does it still need to be public, or would protected or less be acceptable?
  2. Under what circumstances would it be inadvisable to use the static modifier?  I can imagine that in theory, anything that is supposed to represent multiple objects should not be marked “static”, but that still leaves a ton of room for interpretation (and for subtle mistakes in code that will bite me only later).

Aside: Registry entries in Setup project Aren’t Automatically Installed

Idiot assumption of the day: just because I entered the correct Registry settings in the Setup project, doesn’t mean that when I Debug the Solution those settings will be automatically added to the computer’s Registry.  (Sigh, sometimes I surprise myself with how dense I can be.)

So which “hack” would be better — should I hand-enter the Registry settings I need (which seems pretty lame) or should I build the Setup project and actually install this AddIn (which might end up leaving behind stuff that I’ll need to rip out later after I’ve rev’d the AddIn a few times)?

I guess I’m going down the path of hand-entering the Registry settings.  I don’t like doing this, and I really wish debugging MindManager AddIns didn’t require this lame step, but it looks like I’ve got no better option.

NullReferenceException: When will I ever learn?

I can’t believe the number of times I get caught by this seemingly predictable error:

        private System.Collections.ArrayList toDoListItems; // building list of all Tasks to be emitted as the items for the ToDoList
        private Mindjet.MindManager.Interop.Application applicationObject; // local instance of the Application object

        public System.Collections.ArrayList GenerateToDoListItems(MMInterop.Application application)
        {
            System.Collections.ArrayList toDoListMaps; // collection of all maps to be searched for Task topics
            applicationObject = application; // sets the local variable equal to the value of the passed-in parameter
            toDoListMaps = GetAllToDoListMaps(); // generate the collection of maps to be enumerated and searched
            toDoListItems = new System.Collections.ArrayList(); // declare this to avoid a NullReferenceException when it's assigned below
            
            foreach (MMInterop.Document map in toDoListMaps)
            {
                    toDoListItems.AddRange(GetAllTasks(map));
            }
            return toDoListItems;
        }

I really don’t get why I don’t have to declare the “new toDoListMaps” object, but I have to declare the “new toDoListItems”.  Is there something about creating the object inside the method that implicitly initializes it, but this implicit initialization doesn’t occur for objects that are created outside of the method?

And why does creating an int object not require initialization, but creating an ArrayList object does?  This might make sense to veteran coders, but my god it’s confusing for those of us just trying to get their first few apps out the door…

MindManager 7 ToDoList AddIn development Part 4: Fixing the Registry Settings in the Setup Project

The MM VS2005 AddIn wizard created a set of Registry settings for my project, and the friendly folks at Mindjet’s Dev Support team helped me fix a problem with my project (and in the process had to remove most of those Registry settings). Well, now we’re taking it back [anyone else remember Bono’s intro to Helter Skelter?].

It took me a bit of time to track down the hidden place where Visual Studio “hides” the Registry settings for a Setup project: right-click the Setup Project (“AddInSetup_en” in this case), choose View, Registry. There’s a stub for each hive, but not all of them contain actual Registry Keys or Values.

For my project, the only Key with any entries was HKLM\Software\Mindjet\MindManager\7\AddIns, with the Values (though different settings) that I’d noted earlier. The ProgID that it’s setting is ParanoidMike.ToDoListBuilder.AddIn which isn’t really representative of what I’m intending to release – ToDoListBuilder is just one portion of the functionality I want to provide (i.e. I’ve also spec’d out a ToDoListManager class that’ll be a peer to ToDoListBuilder).

Also, if I’m going to define a namespace rooted in ParanoidMike, I figure I should use the application name as the next-level-down, and then describe the actual code/app/add-in as the third-level-down. That gives me the namespace ParanoidMike.MindManager.ToDoListAddIn, so I’ve replaced the existing ProgID with this as the new ProgID (and .NET namespace for my source code). I deleted the old Registry entries that reference this ProgID, added the new ProgID and its entries, and also added the HKCR settings that were still missing when I published this article.

That results in the following Registry entries populated in the AddInSetup_en project:

Complete Set of Registry Entries for MM7 Add-in

HKLM\Software\Mindjet\MindManager\7\AddIns

Value

Data type

Setting

Description REG_SZ MindManager ToDoList AddIn for MM7 – Built by ParanoidMike
FriendlyName REG_SZ MM7ToDoList
LoadBehavior REG_DWORD 2

HKCR\ParanoidMike.MindManager.ToDoListAddIn

Value

Data type

Setting

(Default) REG_SZ ParanoidMike.MindManager.ToDoListAddIn

HKCR\ParanoidMike.MindManager.ToDoListAddIn\CLSID

Value

Data type

Setting

(Default) REG_SZ {33B60353-E8F3-4F38-98B6-41C7E5C6D32B}

Note: this little tip (HowTo: Create a Default Registry Value in Registry Editor) saved me a lot of trouble futzing around with these infrequently-created values.

Note: if you’ve used the MM7 AddIn template for Visual Studio, the CLSID above can be found in the Connect.cs file just under the ///

comment, like so:

GuidAttribute("33B60353-E8F3-4F38-98B6-41C7E5C6D32B")

Open Issue: ProgID versioning

There’s conflicting evidence on whether it’s best to create the ProgID using the “.1” suffix notation, so that the ProgID can be rev’d, or whether it’s just as good to leave it without the “.1” suffix and replace it upon every install (upgrade?). For the moment, until I stumble across anything better, I’m just going to leave it without.

Open Issue: ProgId in AddIn’s source code

After cleaning out the old entries from my computer’s Registry and testing this new set of code, I noticed that there was still the old ProgId referenced in the Connect.cs code:

    /// 
    ///   The object for implementing an Add-in.
    /// 
    ///    
    [
     CLSCompliant(false),
     ComVisible(true),
     GuidAttribute("33B60353-E8F3-4F38-98B6-41C7E5C6D32B"), ProgId("ParanoidMike.ToDoListBuilder.AddIn")
   ]

Since the add-in loaded and executed successfully, I’m now left to wonder what effect this ProgId entry is really supposed to have. Clearly it doesn’t affect the operations of debugging the code (i.e. hitting F5 from within Visual Studio 2008 and waiting for MindManager to launch), but I can’t imagine it’s just there for decoration either. It’s possible that, because I haven’t rebooted since I cleaned out the Registry and updated the AddInSetup_en project settings, there’s still enough of this information cached to allow the Add-in (with the same CLSID) to still work.

I’m taking no chances of a vaguely-specified error down the line, so I’ve updated this ProgId entry to the current value, but if anyone knows how these entries are related, I’d sure love to hear it.

MindManager 7 "ToDo List" Add-in development: Notes to Self

Notes to Self: Object Model stuff I Might Use in my Add-in

  • Application.ActiveDocument: the currently-displayed Map
  • Application.Visible: enables/disables the MM UI
  • DocumentObject.Guid, DocumentObject.ResetDirty: this seems like a generic object type within the MM object model — might be useful for manipulating a whole collection of different objects at once
  • Document.Attributes: collection of document’s custom attributes
  • Document.CentralTopic
  • Document.Guid
  • Document.IsModified
  • Document.Properties
  • Document.AssignMapMarkers(): assigns a map markers template to the document
  • Document.GetAttributes()
  • Document.Range(): returns a new Range collection of all the specified objects (topics, boundaries, relationships) in the document
  • Topic.AllSubTopics: subtopics connected to the topic
  • Topic.Attributes
  • Topic.Document: the document in which the Topic is found
  • Topic.Guid
  • Topic.Icons, Topic.UserIcons
  • Topic.IsFirstSibling: TRUE if the topic is the first in a set of siblings
  • Topic.IsMainTopic: TRUE if the topic is a child of the Central topic
  • Topic.IsSubTopic: TRUE if the topic is a child of another topic
  • Topic.Level
  • Topic.NextSibling
  • Topic.ParentRelationship
  • Topic.ParentTopic
  • Topic.SubTopics, Topic.UnfilteredSubTopics
  • Topic.Synchronization: ????
  • Topic.Task
  • Topic.Text
  • Topic.TopicLabel
  • Topic.TopicPrefix: sets the prefix for the topic — something to do with “numbering”
  • Topic.Type
  • Topic.AddControlStripType()
  • Topic.AddSubTopic()
  • Topic.CreateHyperlinkToTopicByGuid(): Cool! This could be used to hyperlink topics in ToDoList back to their original Topics. Might be useful to sync properties, attributes automatically.
  • Topic.GetAttributes()
  • Topic.NewTopicFinder(): helpful for traversing sub-topics from the current topic.
  • Topic.ResetDirty(): resets dirty bit of this and all subsequent objects. [Could be used to determine if a Topic has been changed since last “sync”.]
  • Topics.Add()
  • Topics.AddWithGuid(): creates new Topic with a given Guid
  • CustomProperty.Value
  • CustomAttributes.GetAttributeValue(), CustomAttributes.SetAttributeValue()
  • Task.IsDone
  • Task.IsValid
  • Task.Priority
  • Task.Topic: the parent Topic for this object
  • TextLabels.AddTextLabel()
  • Icons.AddStockIcon(), Icons.AddCustomIcon()
  • Icon.Delete()
  • Utilities.Execute

Notes to Self: Questions to Research

  1. What’s the difference between a CustomProperty and a CustomAttribute?
    • Attributes are persistent
    • Nick Duffill has more info here
  2. Is a TextLabel the same thing as a Text Marker?
  3. What’s the difference between a CategoryMarker, a CustomIconMarker and a CustomIcon?
  4. What Events are available to which to respond (such as Topic.Moved)?
    • Nick Duffill alludes to “topic-delete” and “topic-add” here
  5. Is there a way to find the current position among siblings for a Topic? Could there be a Property that indicates the Topic’s position?
    • There is the Topics.Item property…
  6. Can you get a handle to a Topic when you know its Guid? Do you need to be attached to its Document, or can you search all open Documents (e.g. searching through the AllDocuments or Documents collections)?
  7. Is there some way (e.g. derive a class from the Topic class) that would allow me to define a Property whose Value was equal to its 1-index position among its siblings?
  8. Does the Dirty flag get toggled automatically as soon as any change is made to the object? Or is this a flag that must be explicitly set?
  9. Does the Dirty flag inherit up the tree — i.e. if any Object in a Document has the Dirty flag set, does that implicitly “set” the Dirty flag on the Document as well?
  10. Can you reset the Dirty flag on a Document, and would that reset the Dirty flag on every Object in the Document all at once?
  11. Could the InsertCustomProperties event be used to automatically propagate a Property to another attribute on the Topic object (e.g. taking the Index of a Topic next to its ToDoList siblings and convert that to a custom ToDoListPriority property, or to use the Priority icon’s value as a ToDoListPriority value)?
  12. Is the SetCustomPropertyValue event the one that’ll let me trigger when the user changes the Topic’s ToDoListPriority value (either automatically, by moving the Topic to a different position among its List siblings, or manually, by typing the value in or selecting it from a pre-populated list) to propagate that value back to the source Topic?
    • If so, could I reset the Dirty flag on the Topic in the ToDoList, but leave open the possibility that the ToDoList overall is still “Dirty” and prompt the user to save unsaved changes?

Notes to Self: MM-specific Objects to Manipulate

There’s all these new Object types defined in the MM object model:

  • BusinessTypeRegistry/Business Topics (see Nick Duffill’s expert explanation of these Object classes here)
  • External Topics
  • Map Parts
  • MapShortcutCollections
  • Baselines
  • DocumentBars
  • Filter
  • Control Strips

Notes to Self: Code Tidbits

“use the Document.Range() method to iterate over all Objects” (Create and Use Custom Attributes)

Add Topics

Iterate over Topics (includes sample code for using the TopicFinder, an iterator)

Work with the Object ID (includes reference to FindByGuid() method that finds DocumentObjects by GUID in any Range, such as Document.Range)

Get an Object’s Type (which refers to an enumeration of DocumentObject that includes mmDocumentObjectTypeTopic)

MindManager 7 "ToDo List" Add-in development Part 3: Initial Working Code

Successful running of the add-in!  Once I added the required Registry settings, the add-in finally made itself known (through the MessageBox’es).  I learned that the HKCR settings are also necessary for other calls to succeed, but the essential behaviour of being recognized and loaded by MindManager was entirely dependent on having those Registry settings populated in the \Addins key.

At first I just used a .REG file to populate the Registry settings, following the model of the MM7 Sample Addin.  I had to do this as a side-effect of the work the helpful folks on the Mindjet “Dev Support” team did to rip out a bunch of “custom actions” stuff from my MM7 add-in solution, and this appears to have included all the Registry settings as well.  [Note: the Mindjet dev support folks are really helpful, and I’m not blaming them for this — the MM7 VS project template was (a) developed under Visual Studio 2005 not 2008 (which I’m using), and (b) was last updated last summer (and is no currently under active development I’d guess because the person who originally created it has since left the company — at least, that’s the usual way these things occur).

However, it’s not quite perfectly operating yet — just before the OnStartupComplete dialog box comes up, the following error is thrown by MM7:

image

According to this thread, this means that Addin ID must match the first parameter to applicationObject.Commands.Add().  In my code that parameter is “ParanoidMike.ToDoListBuilder.AddIn”, and my first guess is that the key under HKLM\Software\Mindjet\MindManager\7\AddIns needs to have the same name (which it currently doesn’t).  Upon changing it to match, I finally saw the Add-Ins Ribbon tab that I hadn’t been able to expose until now.

On to a little code…

First stage: Ribbon Button That Counts Tasks in Current Map

I wanted to use as much of the code from the MindManager7 Sample Add-in as possible… however somehow I ended up not using much or any of that.  This was my original plan:

  1. Create variable for MM application
    • Sample\MmxUtility\Helper.cs: MmxUtility.Helper.GetMmxMap()
  2. Beg/borrow/steal ribbon button code from existing add-in
    • Sample\MmxUtility\RibbonTabBase.cs (base class for creating a new Ribbon tab)
    • Sample\MmxUtility\ControlStripBase.cs
  3. Attach function to Ribbon button
  4. Create variable for Current Map
    • Application.ActiveDocument
  5. Find the Base Topic and enumerate
    • Sample\MmxUtility\Helper.cs: Helper.BaseTopicFinder()
  6. Create variable for Count
  7. Create For Each loop of Task objects, and count ’em
    • Sample\MmxUtility\Helper.cs (Topic attributes)

Instead, though, I ended up trying to separate out the UI from the data manipulation code, and leveraging the code I’d written from the MindManager DevZone article “How to Create a MindManager 7 Add-in Using C#“. 

This is what resulted:

        private void mmCommand_Click()
        {
            // Process the MindManager command and say hello
            MessageBox.Show("Hello world! (C#)", addInDisplayName);

            // Get the current Map
            Mindjet.MindManager.Interop.Document currentMap;
            currentMap = applicationObject.ActiveDocument;

            // Count the current Map's Tasks and display for the user:
            int count;
            ToDoListBuilder taskCounter = new ToDoListBuilder();
            count = taskCounter.countTasks(currentMap);
            MessageBox.Show("There are " + count.ToString() + " Tasks in this Map");
        }
    class ToDoListBuilder
    {
        public int countTasks(MMInterop.Document mindMap)
        {
            int tasksCount; // count of the number of Topics that are Tasks
            MMInterop.Range range; // just a collection of whatever we can find in the Document 🙂
            range = mindMap.Range(MMInterop.MmRange.mmRangeAllTopics, true);
            tasksCount = 0; // initialize to avoid error CS1065
            foreach (MMInterop.Topic topic in range)
            {
                if (topic.Task.Complete >= 0)  // this is intended to test whether the "topic" has Task attributes attached to it, and is how ResultsManager characterizes a Task
                {
                    tasksCount++; // increment this counter variable
                }
            }
            return tasksCount;
        }
    } 

The key magic in this code was the test for whether a Topic is a Task or not:

if (topic.Task.Complete >= 0) 

I’d spotted this approach in a macro that was published on ActivityOwner, but it seemed more complicated and indirect than should be necessary.  I wondered whether something like topic.Task.IsValid() would identify whether a topic had “valid” Task characteristics.  I looked into what documentation for this method was available, but the available info is pretty sparse.  If not for the generous help from the MindManager development community like Nick Duffill, I would’ve been forced to work through this by trial & error.

MindManager 7 "ToDo List" Add-in development Part 2: Adventures in Add-in Installation

MindManager 7 provides the ability (through the MindManager options menu) to inspect and enable/disable already-installed add-ins.  However, it’s not clear from the UI nor Help file how to install an add-in for MindManager.  The DevZone article indicates that once I’ve built the assembly it should be installed in MM7 automatically, but I’ve built it many times and it definitely doesn’t show up in the listed add-ins in MindManager:

If the code compiled successfully, your add-in DLL was created and registered with MindManager. At this point, you are ready to test your new add-in.

I’d posted a couple of requests to the MM7 developer user forum and that’ll probably give me some clues, but in the meantime I happened to find this blog article (Creating a MindManager 7 Add-in Sample) from last summer, and spotted this gem:

“Probably the most useful thing the wizard does is create a Setup project that carries the Windows Registry settings needed to let the MindManager application locate the Add-in component at load-time.  These settings are used by MindManager to discover and load selected Add-in components.  If they are wrong, your Add-in never makes  it onto the available Add-ins list.”

[That sharp sound you heard was my hand hitting my forehead]  Duh, indeed.

Registry Settings Are the “Key”

It appears that the critical piece of info I hadn’t found in the documentation (MM7 Help file, DevZone walkthrough) was the existence of the Registry Key HKLM\Software\Mindjet\MindManager\7\Addins\.  The add-in downloadable from the “Sample” blog article creates the following in that Addins key:

  • Key = MmxSample.Connect [i.e. the ProgID for the add-in]
    • Value: FriendlyName (REG_SZ) = Pandimonium[sic] Productions Mmx Sample Add-in
    • Value: LoadBehavior (REG_DWORD) = 2
    • Value: Description (REG_SZ) = A sample MindManager Add-In to dump map contents

As well (though I wonder if this is optional — at least while developing the add-in), the Setup project creates the following entries under HKCR (HKEY_Classes_Root):

  • Key = MmxSample.Connect
    • Key = CLSID
      • Value: (Default) (REG_SZ) = {925b5786-bf6f-4ac5-9df1-61ee50a815ca}
    • Value: (Default) (REG_SZ) = MmxSample.Connect

Since these Registry values are static, it appears that MindManager enumerates the keys under \Addins at each startup.  Therefore, I believe that just building the add-in assembly does not magically make MindManager aware of the add-in you’re developing.

So perhaps I can just populate my Registry settings by hand?  The AddInSetupen.vdproj file for my add-in’s setup project intends to set these values:

  • [\Addins] Key = ParanoidMike.ToDoList.AddIn.1
    • Value: FriendlyName (REG_SZ) = MM7TODOList
    • Value: LoadBehavior (REG_DWORD) = 2
    • Value: Description (REG_SZ) = MM7TODOList|Built by ParanoidMike|Version 1.0.0

Grrr

Oh hell.  I just went back to the DevZone walkthrough article, and the next thing (just beyond the point at which I abandoned the walkthrough) is this page that documents exactly the Registry settings I just unearthed.  Man, this is truly time to let it go for the evening…

One Open Question

My project’s Setup does not currently populate any HKCR settings!  Is this the cause of the “unrecoverable error” when building the Setup project?

MindManager developer resources

These are the various sources of information I’ve stumbled across so far that are useful for me (a budding MindManager add-in developer):

Resources related to Custom Properties

I anticipate leveraging custom Properties in my add-in, so I’ll want to dig into these articles when I get to that point:

Developing a MindManager Add-in for Staying On Top of my ToDo Lists

I’ve made a few attempts at staying “on top of” my workload using tools like the Getting Things Done add-in for Outlook, MindManager, and even tried the ResultsManager add-in for MindManager. Each of them help, but somehow they all seemed a bit too “high maintenance” for my needs — they required a great deal of management of metadata about each project and task, and yet I always found it hard to get a simple “to do list” summary of stuff I need to do.

It wasn’t that I couldn’t get some subset list or grouping of my tasks. I just couldn’t quite make it work for me in a way that made it easy to see what I really needed to work on.

My Woes with the Commercial Alternatives

With the GTD tool, I could see my tasks grouped by Project or by “context” (a GTD-ism for “if I’m near a phone, I should knock off all my calls; if I’m by my computer, I should knock off a bunch of computer-needing tasks all at once”). However, while I was really good about collecting all my tasks, I wasn’t so good about understanding which of them was most urgent — it all just became one big pile and I could never get a “meta-view”. I also could never get the hang of using the Prioritization field that should’ve allowed me to order & re-order all the tasks without regard for their project/context grouping.

Ages ago I’d even tried Taskline, which adds even more metadata to the Tasks in Outlook, but even with the combination of Taskline and GTD, I wasn’t able to make any more sense out of the 200+ tasks that I’d be able to collect, each time I gave these things a try.

With MindManager, I’m able to pull together a random set of ideas, tasks, steps, requirements and issues, and re-group them in ways that make sense once I’ve got them all in the same “place”. However, while it has some integration with Outlook, and I should be able to sync Tasks bidirectionally, I can’t say I’ve ever committed to the notion of marrying the incredible number of Tasks I’ve already got in Outlook to the scattered (and possibly overlapping or conflicting) musings I’ve got in MindManager.

When I added ResultsManager to MindManager, I was blown away by the UI, the great number of useful metadata I could assign to my “project planning” items (though such efforts on my part are a great insult to those skilled/sick individuals who actually know how to manage projects), and the really well-thought-out introduction process they used to familiarize customers and get them up and running quickly. However, I found that once I got all my projects, deliverables and tasks into the environment, I was still struggling to (a) find a ResultsManager template that would give me that “holy crap” daily/weekly view of my critical tasks, and (b) prioritize all my tasks relative to each other when they’re gathered together in one mind map. I’ve even tried discussing this with some of their technical evangelist types, but for all the work they did in trying to explain how to customize the ResultsManager environment, something about it didn’t click for me.

I really like the concepts behind ResultsManager — tagging items that are in multiple maps and gathering them into one “meta-map”, organizing projects into sub-deliverables and tasks, using icons and other visual elements to help annotate the information. I liked the flexibility in the design, and the implicit promise that it’ll help you see the patterns and overall workflow.

However, it doesn’t quite live up to that — at least not for me, with only a moderate amount of time invested in the training they provide for newbies (and poking around their forums and discussions). And frankly, I didn’t like what I saw when I looked under the hood — it’s all written in VBA, and becomes a real hog at any sort of scale. They’re interested in developing in .NET (or VSTA?), but between that and the effort to simplify the usability, I can’t imagine it would be really ready in time to keep me from getting fired. (I’m kidding, mostly.)

Build My Own MindManager add-in

So I’ve decided to explore the effort it would take to do something similar, but aimed at one single goal: produce a ToDo List from the task items scattered throughout my MindManager maps, and be able to prioritize (i.e. re-order) them in a persistent manner.

I know that Mindjet has produced some resources for developers who wish to add functionality to MindManager:

  • a Visual Studio template for C#/VB development
  • a Primary Interop Assembly (PIA) that installs by default with MindManager Pro 7
  • a free community portal where documentation and resources are available for registered developers

Once I downloaded the VS template, installed it, and created a new project from it, I was surprised at how many different files were generated by the wizard: there’s AssemblyInfo.cs, Connect.cs and Utility.cs in the Addin project, then a Common project and an AddinSetup_en project. This made me think there’s probably a tour of the different components in the MindManager add-in project somewhere on the Mindjet developer site, and that I’d probably earn a few shortcuts in my development time if I read up on this first.

Browse over to the Mindjet Devzone. That’s where folks like me (as well as professional development organizations) can get at the really cool developer resources. Once you’re registered, you’ll be able to access resources aimed at MindManager version 6 or version 7 such as “How to Create a MindManager 7 Add-in Using C#” and the “MindManager 7 Object Model Reference“. They even provide a downloadable archive of all their online documentation if you’d rather just dig through the info without having to login each time.

Now, it’s not well-documented where a guy like me should start, but it’s a pretty good guess that “How to Create a MM7 Add-in using C#” is a likely walkthrough for newbie developers. And as it turns out, this is definitely targeted at a C# developer who’s just starting into MindManager development.

You will need to read the guidance with a grain of salt, however; there’s a lot of steps specified in the first few sections that don’t apply if you’re using Visual Studio 2005 + the MM7 addin template (i.e. MM7AddInTemplateSetup2005.msi found in Mm7AddInTemplateSetup.zip).

[Also note: if you’ve got the same setup that I happen to have — which is to say, Visual Studio 2005 and Visual Studio 2008 installed side-by-side — then you’ll probably have to create your MM7 add-in project in VS2005 and then open it in VS2008. I couldn’t find a way to install the MM7 add-in template so that it showed up in the VS2008 “New Project” selection, but that’s probably because I haven’t uninstalled VS2005 yet.]

Brewing Problem

I don’t know why, but I decided to try building the Solution before I spent too much time writing code. It turns out that there are three errors with this Solution, and I don’t think the minor changes I’ve made could possibly have caused all this damage:

General failure building custom actions C:\personal\VS Projects\MM7TODOList\MM7TODOList\Common\Common.vdproj (Project=)Common

Unrecoverable build error C:\personal\VS Projects\MM7TODOList\MM7TODOList\Common\Common.vdproj (Project=)Common

Unable to import merge module ‘C:\personal\VS Projects\MM7TODOList\MM7TODOList\Common\Debug\Common.msm’ C:\personal\VS Projects\MM7TODOList\MM7TODOList\AddInSetUp\AddInSetupen.vdproj (Project=)AddInSetup_en

I figure I better get these problems resolved before too long, or else I won’t be able to debug this project and even bigger issues will go unnoticed. I’ve posted this issue to the MindManager developer forum, and I hope it gets answered soon. 🙂

Update: For the benefit of everyone who’s waited with baited breath…

Well, even if you just want to know how to deal with this, here’s what Mindjet Developer Support told me:

“The solution on the DevZone is based of VS 2005 that’s why (I am assuming) that you could not get it to compile on VS2008. I have modified your project a little bit (removed custom actions) and it is working fine.”

Couple of Open Questions

  1. What’s the difference between adding a Reference in the References section of the Solution Explorer, and adding the “using CLASSNAME” statement in each source file?
  2. If I wanted to rename a namespace after I created the project, can I just right-click on the name of the namespace (e.g. MM7TODOList) and choose Rename? Or do I need to find other dependent code fragments that don’t get updated automatically?