Showing posts with label Office. Show all posts
Showing posts with label Office. Show all posts

Saturday, April 21, 2012

Safely accessing Named Properties in Outlook

Whenever you want to access properties in Outlook that are not exposed by the Outlook Object Model, there is the PropertyAccessor object.

Not only does this powerful class allow you to retrieve any of the standard MAPI properties, it also gives you access to any custom Named Properties using a convenient string notation.

This class does have one minor problem though: it doesn't offer any way to explicitly check for the existence of a property. So when one half of your applications marks certain emails with a certain named property, and the other half needs to read out that marker, you end up with code like this:

var
  mailItem: OleVariant;
  propertyName: String;
  marker: String;

begin
  ...

  propertyName := 'http://schemas.microsoft.com/mapi/string/someGuid/my.secret.marker';

  try
      marker := mailItem.propertyAccessor.getProperty( propertyName );

  except
      // Apparently, the marker isn't set.
      marker := '';
  end;

end;

Ouch. Not so much fun when doing this in a loop over a few thousand email. And turning off Break on OleException in the IDE is not the best of ideas when you are doing office automation, either.

Moving from late to early binding (and you should, anyway) makes this problem blatantly apparent; here is the interface definition of PropertyAccessor (renamed IPropertyAccessor for compliance with Delphi naming standards):

  IPropertyAccessor = interface(IDispatch)
    ['{0006302D-0000-0000-C000-000000000046}']
    ... snip ...
    function  GetProperty(const SchemaName: WideString): OleVariant; safecall;
    procedure SetProperty(const SchemaName: WideString; Value: OleVariant); safecall;
    ... snip ...
  end;

See those safecall markers? Those means that Delphi has wrapped the calls in a little check, raising an exception whenver the result is not ok. Which is nice and error proof, but brushes over the fact that there are several different results possible from the underlying call, and not all of them are crucial errors. In our case the returned result is MAPI_E_NOT_FOUND, which just tells us the mailItem at hand wasn't marked... not exactly an "exceptional" situation in this particular application.

The trick is that we can simply redefine this interface, using HResult stdcalls directly, as opposed to the magically wrapped safecalls. This conversion is easy enough to do by hand (everything needs to return a HResult, move all function results to out parameters). However, for even more convenience, we can use use tlibimp to do this. From a command line, execute:


tlibimp -P -Ps- "C:\Program Files\Microsoft Office\Office14\MSOUTL.OLB"


(make sure to correct that path if office is installed elsewhere). This will output a nice Outlook_TLB where we can copy the property from. I aptly (although perhaps slightly confusing) named my copy ISafePropertyAccessor.
ISafePropertyAccessor = interface(IDispatch)
    ['{0006302D-0000-0000-C000-000000000046}']
    ... snip ...
    function GetProperty(const SchemaName: WideString; out Value: OleVariant): HResult; stdcall;
    function SetProperty(const SchemaName: WideString; Value: OleVariant): HResult; stdcall;
    ... snip ...
  end;

Here is how we'd use it in the example above:
var
  mailItem: OleVariant;
  propertyName: String;
  propertyAccessor: ISafePropertyAccessor;
  value: OleVariant;
  marker: String;

begin
  ...

  propertyName := 'http://schemas.microsoft.com/mapi/string/someGuid/my.secret.marker';
  propertyAccessor := IUnknown(mailItem.propertyAccessor) as ISafePropertyAccessor;

  hr := mailItem.propertyAccessor.getProperty( propertyName, value );

  if hr = S_OK then
  begin
      marker := value;
  end
  else
      marker := '';

  ...
end;
Slightly more verbose, but that can always be wrapped away in some convenience functions... and it sure is nice to get rid of the exception!

Tuesday, October 27, 2009

Microsoft Word and default filenames

Have you noticed how, when you save a new document in a Microsoft Word, the save dialog comes up with a default filename suggestion? Ever wondered how it comes up with that suggestion, impractical as it may sometimes be?


No? Neither had I, but unfortunately we are developing an office add-in that actually replaces the file dialogs with our own, and to facilitate user acceptance, minor functional details like that have to be mimicked in detail. Users might not notice the behaviour when it's there, but they sure do notice it when its missing or, god forbid, ever so slightly different!

The filename generation is a three-step algorithm:

Step 1) First, and not many users are aware of this, Word looks at the document title. You can set this title by selecting Properties from the File menu, but it will show up in the document properties in Windows Explorer as well.

Programmatically, you can access the document title through the BuiltInDocumentProperties property of the Document object, by requesting the wdPropertyTitle property.

Step 2) If the document title is empty, Word looks at the very first sentence of your document. It will skip anything that is not a "valid" character (i.e. an alphanumeric or a space), and then simply return all characters until the next invalid character. Usually this comes down to simply returning the sentence up to the first punctuation mark. This very same sanitization algorithm is actually applied to the document title from step 1 as well.

Step 3) If both the title is empty and your document doesn't have any valid characters in it (i.e. it is mostly empty), things get a bit hairy. This is when Word falls back onto the doc1, doc2 etc naming convention. I am still not 100% sure how this convention works, but here is how we handle it: simply take the first three characters and the suffix number from the document Name property (which will be something like Document1), and lowercase the first character. This approach works properly with localization in the three languages (English, German and Dutch) we actively test here in our development lab, but I cannot give any guarantees yet on the 34 other languages supported by Microsoft Office.

As a funny sidenote, across Office applications things behave in slightly different ways. Excel simply suggests the name of the current Workbook (Book1, Book2, etc). PowerPoint uses a similar algorithm to Word, but only looks at the text in the presention, not at the presentation title. It does however automatically populate the title property with that first sentence, something Word doesn't do.

Ah well, it's those minute differences that keep office developers on their toes I guess. To the typical end user the office applications are similar enough to allow them to switch from one to the next without too much pain, and that's all that really counts in the end.