OdeToCode IC Logo

Office Needs A Better Managed API

Monday, July 5, 2004 by scott
A few days ago, I decided I wanted a new button on my Outlook toolbar. When I click the button I want highlighted items redirected to a web mail account with the ‘From’ address intact. I’m sure this already exists somewhere, but I wanted to learn how to do it myself.

With the Shared Add-In extensibility project wizard and code from “An Introduction to Programming Outlook 2003 Using C#”, I thought I was 90% of the way there, except it didn’t work. Specifically, the following line of code from the article would never return:

CommandBars commandBars = applicationObject.ActiveExplorer().CommandBars;

The call would literally disappear in the opaque goo of COM interop. No exceptions, no error dialogs, no abnormal behavior as Outlook continued to work. I thought I must have a configuration problem and began double-checking primary interop assembly versions and looking for updates. I happened to run across a knowledge base article using the following code:

activeExplorer = applicationObject.GetType().InvokeMember("ActiveExplorer",BindingFlags.GetProperty,null,applicationObject,null);
commandBars= (CommandBars)activeExplorer.GetType().InvokeMember("CommandBars",BindingFlags.GetProperty,null,activeExplorer,null);

The above code, using reflection, worked perfectly. I managed to finish the code for my button click event, but not without some irritation.

The base class library in .NET spoils developers, and I think if Microsoft wants people to develop for Office they should provide a higher level of abstraction on top of the runtime callable wrappers. The interface should be subject to the same design rules and usability testing as the rest of the .NET libraries. Let me give you a couple examples about why I am griping.

Selected items are kept in a Selection collection. Indexing into the collection gives me a plain object reference. It would be nice if there was a base class representing any type of item in Outlook which I could perform some operations on. As it stands, I had to dig through the documentation to find the types of Items I am interested in: MailItem and PostItem objects. I had to find these items in the object browser of the IDE as the documentation I used (VBAOF11.chm – the Microsoft Office Object Model) make no mention of them.

Without documentation I decided the best way to get to know these classes was by inspecting them in the debugger. Unfortunately, if I cast an object reference to type MailItem, all I see in the debugger quick watch is a System.__ComObject, which gives me nothing to go on. If, however, I cast the reference to the interface type of _MailItem (notice the underscore), then I can see all the properties and values I am interested in.

The fact that there are three types available to work with (MailItem, _MailItem, and MailItemClass) only adds to the confusion. My fading COM memories tell me these types probably exist because of the difference is dispatch and vtable binding, but when I just want to get something done in Outlook I don’t really care to learn the differences. I just wish it was easier, and with integrated documentation, like the rest of the .NET development experience. Whine, whine, whine.

P.S. I found the easiest way to debug an add-in which is loaded by Outlook when Outlook starts is to invoke System.Diagnostics.Debugger.Launch(), and let's not talk about the number of times you need to put in System.Reflection.Missing.Value as a parameter to a method. Complain, complain, complain.

Twisty Little Passages

Wednesday, June 30, 2004 by scott
Most of the healthcare facilities I’ve been to in traveling consultant mode require an employee to escort the me around. This is in large part due to the high percentage of locked doors in the admin and IT areas, but also in part due to the standard hospital floor plan. Fans of interactive fiction would describe the standard architecture as a “maze of twisty little passages, all alike”. One wrong turn and you could be lost for hours, or have your appendix removed.

It’s refreshing to be visiting a small, rural hospital, where I can walk in the back door without being fingerprinted, and go to the bathroom without leaving a trail of breadcrumbs.

A contrast arises because the IT department here has more security in place for the network than many of the places where physical security is much tighter. The use of the IIS Lockdown Tool, the Baseline Security Analyzer, group policy, and software to monitor the network for vulnerable machines on the LAN makes the deployment of a web application a little more challenging. Not that I’m complaining, it’s just the way it has to be.

Debugging HTTP

Tuesday, June 29, 2004 by scott

In debugging some web service wierdness I downloaded Fiddler. Fiddler is an excellent tool for viewing and experimenting with the HTTP headers and payload exchanged between client and server. I've never used a debugging proxy that is so easy and informative.

Any software using the WinINET API (like IE) will automatically send traffic through fiddler when the “Act as System Proxy” check box is checked.

For the .NET classes like HttpWebRequest and WebClient, I found the GlobalProxySelection class is pretty useful for setting the proxy programatically:

GlobalProxySelection.Select = new WebProxy("", 8888);

Before yesterday I didn't know this class existed. It's amazing what I can find when I venture outside of my “framework comfort zone”.


Thursday, June 24, 2004 by scott

Let’s see what adds up...

Scoble says there is a launch coming next week that requires Slashdot-compliant servers.

There is a party at TechEd 2004 Amsterdam Wednesday night. A certain product group from Microsoft will host the party. I see they were talking to the press in San Diego.

I’ve had a fresh Virtual PC machine ready for weeks in anticipation of a major event.

I’ve named the machine SQL2005B2...

Partial Success

Thursday, June 24, 2004 by scott

I have a problem when new keywords appear in a language. I consider the problem odd, because I am generally fond of new features. XAML? Super! One hundred new classes in the base class library? Excellent! Hosting the CLR inside of SQL Server? Positively orgasmic! Yet when a new keyword appears in my development language, I respond with complete indifference.

I first recognized this strange behavior when the mutable keyword appeared in C++. I’d be reading an article on C++ and suddenly mutable would be mentioned. My eyes would skip over the section, just like they do when I run across an advertisement for something I don’t really need, like a maternity dress.

Now today, I performed an experiment with the May CTP of VS 2005. Ever since the release of Visual Studio.NET people have been designing base classes for their Web forms to inherit from. In the first design iteration these classes will be marked as abstract (must inherit), but the VS.NET designer does not like this one bit, and will not let you edit the form in code mangling mode (also known as “design mode”). I just wanted to see if this was still the case.

After starting a new web project, I switched to the code view and came up with this:

public abstract class MyBase : System.Web.UI.Page
public partial class Default_aspx : MyBase 

To which the compiler gleefully responded:

"Build (web) : Partial declarations of 'Default_aspx' must not specify different base classes"

Partial? WTF is partial? I’d seen it mentioned in various blogs hither and thither, but to me it was still a maternity dress. All of a sudden, here it was on my screen. It was talking to me. It was saying:

I’ve got your attention now, loser.

So I did some reading. Obviously, the ASPX file had a different intention as to who it wants to inherit from. I prepared for a battle of wills. I remembered the Inherits attribute in the @Page declaration and tried this:


And the compiler responded with a laugh:

"Build (web) : Could not load type 'MyBase'." 

Partial: 2 Me: 0

For my next offensive I launched Google, and found Matt Bether’s blog. Matt had pulled this off without a problem, so I didn’t lose hope. I thought I just had to pay my penance for snubbing partial.

Matt's base class wasn't abstract, so I was beginning to wonder if the abstract base was causing more problems. I tried removing the abstract keyword from MyBase - but still no go. Next, I made a guess that something looks at the @Page directive, sees the Inherits tag, and tries to load the type to make sure it is a type compatible for a webform. I’m not sure why, but I think having the base class type defined in the same/almost same compilation unit as part of the webform class causes difficulty. Can anyone shine some light on this? I moved the MyBase class into a separate new file (MyBase.cs) in the magic Code directory. Voila! No errors. Even better news: I can load the form into design view without a designer error, which was all I had wanted to test in the first place.

At this point I’m not sure I like the fact that I have to specify the base class in the @Page directive. I’d be much more comfortable if the partial class in the code view would allow me to specify the base class. It feels much more natural and is easier to see. I hope it changes. I see Natty Gur has a similar request.

If I chalk up the experience as a partial success, that would sound partially lame. Ok, completely lame, but it’s late, and I’m about to hit the POST button.

Security Whodunit

Wednesday, June 23, 2004 by scott

I think one of the first steps in troubleshooting the dreaded “permission denied” exception in a server application is to ask the question: To whom did the system deny permission?

The knee jerk reaction to this exception is to wander off into the security dialog boxes and start giving the Everyone group permissions. Just to test it, you see. Really. When this doesn’t work, the next step is to start running everything as SYSTEM. Just as a test! Before long, you have an unholy mess of ACL modifications and config file tweaks to undo.

Just like a good murder mystery sometimes this question has a surprising answer. You might be assuming the answer is the NETWORK SERVICE or ASPNET account, or the impersonated user. As a server request makes its way across threads and through pipelines, to unmanaged code and back and hopping from machine to machine, there are a slew of reasons why the security context might not be who you think it is at that point in time when the exception occurs.

Consider these scenarios:

All three scenarios can result in a security context you didn’t expect trying to get to a protected resource. (Yep, I've hit them all).

I think the first step is to find out whodunit. I’ve generally answered this question by enabling security auditing at the right spots. Keith Brown discusses how to enable auditing, and how to audit access to files in his book: a .net developer’s guide to Windows security. As Keith points out, auditing can also help you track down other silly problems that cause exceptions and make you remove hair from your scalp, like expired passwords and locked out accounts.

Explicit Boundaries

Tuesday, June 22, 2004 by scott

I’ve been working with two web service APIs recently and pondering issues. The first issue is what I’ve been calling the “magic string” parameter. In both APIs I’ve had to dig through the documentation to find all the legal values for a “magic string” parameter. For instance:

string mode = “verbose”;
service.GetData(id, mode);


string mode=”concise”;
service.GetData(id, mode);

Magic strings are nothing new in the web service world, but in the APIs I’ve been working with the documentation hasn’t been helpful in identifying all the possibilities. How do I know “verbose” and “concise” are the only two options? Perhaps I’m just spoiled by intelli-sense and enumerations. When I need to pass a FileMode parameter to File.Open, the six available options are just a pick list away.

What bothers me is how primitive the approach feels. We’ve mostly abstracted away memory management, made web forms feel like windows forms, and write software 8 layers above the hardware. Still, I’m passing a carefully ordered collection of characters to an API in the name of interoperability.

The next step is to abstract away the primitiveness. Bury all these magic invocations inside of a framework and allow the application developer to invoke instance methods with enumerations. But wait, I think, soon the application developer will be willy nilly calling methods which involve network hops across trust boundaries and have no idea of the turmoil occurring underneath this thin layer. The boundaries, as the SO tenets say, should be explicit.

Many of the essays on explicit boundaries concentrate on the server side of the design. For instance, Clemens Vasters: “Forbidding foreign access or even knowledge about service internals allows radical changes inside and “underneath” services”.

Hiding service details is one-half of the design. I found a patterns and document addressing the second half: “The idea that you can take a local object interface and extend it across machine boundaries to create location transparency is flawed.”, and later: “From the client perspective, a remote implementation of the interface is subject to network latency, network failure, and distributed system failures, but a local implementation is not. A significant amount of error detection and correction logic must be written to anticipate the impacts of using remote object interfaces.“.

So the next question is: how do we make the boundary explicit in client code? How do we let the application programmer know that the code they just typed in might not be a stroll through the neighborhood app domain, but might just be a 747 trip across the oceans and back, complete with custom declarations and long lines at the security checkpoints?

In looking for more thoughts about the matter, I found a lot of theory. Ingo Rammer, however, addressed the topic head on with an example using an interface (IRemoteCustomerManager) and a helper class (RemotingHelper). As Ingo says: “Even when looking at this piece of code months after you’ve written it, it will be immediately obvious: you are accessing a remote component.”

So I’m following a similar pattern and I feel better about the design, but I now worry how the code will age. Methods and code are constantly refactored by developers. Eventually, someone will need to aggregate data from two services and end up pushing everything into another layer. Somehow, somewhere, a boundary will become implicit. Of all the SOA tenets, I think this one will be the toughest for architects to enforce.