Microsoft KB Archive/257757

= Considerations for server-side Automation of Office =

Article ID: 257757

Article Last Modified on 5/14/2007

-

APPLIES TO


 * Microsoft Office Access 2007
 * Microsoft Office Access 2003
 * Microsoft Access 2002 Standard Edition
 * Microsoft Access 2000 Standard Edition
 * Microsoft Access 97 Standard Edition
 * Microsoft Office Excel 2007
 * Microsoft Office Excel 2003
 * Microsoft Excel 2002 Standard Edition
 * Microsoft Excel 2000 Standard Edition
 * Microsoft Excel 97 Standard Edition
 * Microsoft Office Outlook 2007
 * Microsoft Office Outlook 2003
 * Microsoft Outlook 2002 Standard Edition
 * Microsoft Outlook 2000 Standard Edition
 * Microsoft Outlook 97 Standard Edition
 * Microsoft Office PowerPoint 2007
 * Microsoft Office PowerPoint 2003
 * Microsoft PowerPoint 2002 Standard Edition
 * Microsoft PowerPoint 2000 Standard Edition
 * Microsoft PowerPoint 97 Standard Edition
 * Microsoft Office Word 2007
 * Microsoft Office Word 2003
 * Microsoft Word 2002 Standard Edition
 * Microsoft Word 2000 Standard Edition
 * Microsoft Word 97 Standard Edition
 * Microsoft Office Project Standard 2007
 * Microsoft Office Project Professional 2007
 * Microsoft Office Project Standard 2003
 * Microsoft Office Project Professional 2003
 * Microsoft Project 2002 Standard Edition
 * Microsoft Project 2000 Standard Edition
 * Microsoft Project 98 Standard Edition
 * Microsoft Office Visio Standard 2007
 * Microsoft Office Visio Professional 2007
 * Microsoft Office Visio Standard 2003
 * Microsoft Office Visio Professional 2003
 * Microsoft Visio 2002 Standard Edition
 * Microsoft Visio 2002 Professional Edition
 * Microsoft Visio 2000 Standard Edition
 * Microsoft Visio 2000 Professional Edition
 * Microsoft Visio 2000 Enterprise Edition
 * Microsoft Visio 2000 Technical Edition
 * Microsoft MapPoint 2006 Standard Edition
 * Microsoft MapPoint 2004 Standard Edition
 * Microsoft MapPoint 2002 Standard Edition
 * Microsoft MapPoint 2001 Standard Edition
 * Microsoft MapPoint 2000 Standard Edition
 * Microsoft AutoRoute 2006
 * Microsoft Office OneNote 2003
 * Microsoft Office OneNote 2007
 * Microsoft Office InfoPath 2003
 * Microsoft Office InfoPath 2007

-



This article was previously published under Q257757



SUMMARY
Developers can use Automation to Microsoft Office to build custom solutions that utilize the capabilities and features that are built into the Office product. While such programmatic development can be implemented on a client system with relative ease, there are a number of complications that can occur if Automation is to take place from server-side code such as Microsoft Active Server Pages (ASP), DCOM, or a Windows NT Service.

This article discusses the complications that developers may face, offers alternatives to Automation that can speed performance, and suggests ways to configure Office if server-side Automation is unavoidable. Developers should be aware, however, that the suggestions provided below are for informational purposes only. Microsoft does not recommend or support server-side Automation of Office.

Note In this context, the term "server-side" also applies to code that is running on a Microsoft Windows NT or Microsoft Windows 2000 workstation, provided that it is running from a WinStation other than the interactive station of the user that is logged on. For example, code that is started by Task Scheduler under the SYSTEM account runs in the same environment as "server-side" ASP or DCOM code, and therefore experiences many of the same issues. For more information on WinStations and COM, see the "More Information" and "References" sections.



MORE INFORMATION
All current versions of Microsoft Office were designed, tested, and configured to run as end-user products on a client workstation. They assume an interactive desktop and user profile, and do not provide the level of reentrancy or security that is necessary to meet the needs of server-side components that are designed to run unattended.

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when run in this environment.

If you are building a solution that runs in a server-side context, you should attempt wherever possible to use components that have been made safe for unattended execution, or find alternatives that allow at least a part of the code to run client-side. If you choose to use an Office application from a server-side solution, you will find that it lacks many of the necessary capabilities to run successfully, and you will be taking risks with the stability of your overall solution.

Problems using Automation of Office server-side
Developers who try to use Office in a server-side solution need to be aware of five major concerns in which Office behaves differently than anticipated because of the environment. If your code is to run successfully, these concerns need to be addressed and their effects minimized as much as possible. Consider these items carefully when you build your application because no one solution can address all of them, and different designs require you to prioritize the elements differently.
 * User Identity: Office Applications assume a user identity when they are run, even when they are started by Automation. They attempt to initialize toolbars, menus, options, printers, and some add-ins based on settings in the user registry hive for the user who launches the application. Many services run under accounts that have no user profiles (such as the SYSTEM or IWAM_[servername] accounts), and therefore Office may fail to initialize properly on startup, returning an error on CreateObject or CoCreateInstance. Even if the Office application can be started, without a user profile other functions may fail to work properly. If you plan to Automate Office from a service, you need to configure either your code or Office so that it will run with a loaded user profile.
 * Interactivity with the Desktop: Office Applications assume that they are being run under an interactive desktop, and may in some circumstances need to be made visible for certain Automation functions to work properly. If an unexpected error occurs, or an unspecified parameter is needed to complete a function, Office is designed to prompt the user with a modal dialog box that asks the user what they want to do. A modal dialog box on a non-interactive desktop cannot be dismissed, which causes that thread to stop responding (hang) indefinitely. Although certain coding practices can help reduce the likelihood of this occurring, they cannot prevent it entirely. This fact alone makes running Office Applications from a server-side environment risky and unsupported.
 * Reentrancy and Scalability: Server-side components need to be highly reentrant, multi-threaded COM components with minimum overhead and high throughput for multiple clients. Office Applications are in almost all respects the exact opposite. They are non-reentrant, STA-based Automation servers that are designed to provide diverse but resource-intensive functionality for a single client. They offer little scalability as a server-side solution, and have fixed limits to important elements, such as memory, which cannot be changed through configuration. More importantly, they use global resources (such as memory mapped files, global add-ins or templates, and shared Automation servers), which can limit the number of instances that can run concurrently and lead to race conditions if they are configured in a multi-client environment. Developers who plan to run more then one instance of any Office Application at the same time need to consider "pooling" or serializing access to the Office Application to avoid potential deadlocks or data corruption.
 * Resiliency and Stability: Office 2000, Office XP, Office 2003, and Office 2007 use Microsoft Windows Installer (MSI) technology to make installation and self-repair easier for an end user. MSI introduces the concept of "install on first use", which allows features to be dynamically installed or configured at runtime (for the system, or more often for a particular user). In a server-side environment this both slows down performance and increases the likelihood that a dialog box may appear that asks for the user to approve the install or provide an appropriate install disk. Although it is designed to increase the resiliency of Office as an end-user product, Office's implementation of MSI capabilities is counterproductive in a server-side environment. Furthermore, the stability of Office in general cannot be assured when run server-side because it has not been designed or tested for this type of use. Using Office as a service component on a network server may reduce the stability of that machine, and as a consequence your network as a whole. If you plan to automate Office server-side, attempt to isolate the program to a dedicated computer that cannot affect critical functions, and that can be restarted as needed.
 * Server-Side Security: Office Applications were never intended for use server-side, and therefore do not take into consideration the security problems that are faced by distributed components. Office does not authenticate incoming requests, and does not protect you from unintentionally running macros, or starting another server that might run macros, from your server-side code. Do not open files that are uploaded to the server from an anonymous Web! Based on the security settings that were last set, the server can run macros under an Administrator or System context with full privileges and compromise your network! In addition, Office uses many client-side components (such as Simple MAPI, WinInet, MSDAIPP) that can cache client authentication information in order to speed up processing. If Office is being automated server-side, one instance may service more than one client, and because authentication information has been cached for that session, it is possible that one client can use the cached credentials of another client, and thereby gain non-granted access permissions by impersonating other users.

Besides the technical problems, you must also consider the feasibility of such a design with respect to licensing. Current licensing guidelines prevent Office Applications from being used on a server to service client requests, unless those clients themselves have licensed copies of Office. Using server-side Automation to provide Office functionality to unlicensed workstations is not covered by the End User License Agreement (EULA).

In addition to these larger issues, many customers find that with no modification to their default installation of Office they may receive one of the following common errors when they try to automate server-side:  CreateObject/CoCreateInstance returns one of the following run-time error messages and cannot be started for Automation.

In Microsoft Visual Basic (VB) or ASP:  

Message 1

Run-time error '429': ActiveX component cannot create object

 

Message 2

Run-time error '70': Permission denied



In Microsoft Visual C or Visual C++:  

Message 1

CO_E_SERVER_EXEC_FAILURE (0x80080005): Server execution failed

 

Message 2

E_ACCESSDENIED (0x80070005): Access denied

</ul>

These errors appear because the server-side code is running without a user profile or the user identity that is specified for the launching context does not have proper DCOM permissions.</li> Opening an Office document results in one of the following errors:  

Message 1

Run-time error '5981' (0x800A175D): Could not open macro storage

</li> 

Message 2

Run-time error '1004': Method '~' of object '~' failed

</li></ul>

Typically, this is the result of failing to initialize VBA due to insufficient permissions or due to a lack of VBA component registration, both of which are typical when a user runs code from an account with no user profile (issue #1) and the user token does not contain the Interactive SID (issue #2).

</li> CreateObject/CoCreateInstance hangs and never completes, or takes a long time to return. On some servers, the creation is quick but 1004 errors appear in the Windows (NT) Event Log.

The issue is often a dialog box that is modal to the non-interactive desktop that is running the server-side code (issue #2). If the dialog box is due to an MSI component installation problem (a missing registry entry or corrupt file image), it prompts for the installation CD if it can't find the install point, and performs a re-install of one or more components (issue #4).</li> Certain functions fail unexpectedly or hang indefinitely.

When non-interactive (issue #2), certain resources such as printers, mapped drives, OLE embedded objects, and the clipboard may become unavailable or their state may become undefined. Likewise, without a user profile (issue #1), network resources are unavailable and permissions are minimal.</li> Running multiple requests or stress testing may cause the code to fail, hang, or crash on creation or termination of an Office application. Once this occurs, either the process is left running in memory and cannot be terminated, or all instances of the application that is being automated fail from that point on.

Because Office applications share global resources (issue #3), access to an Office application needs to be serialized on specific actions, including events like startup, shutdown, printing, exporting, and OLE link updating (including any DDE notifications).</li></ul>

Other problems or messages may appear in addition to those listed here, but they typically occur as a result of the five issues listed previously. To overcome these types of errors, developers should configure the operating environment of Office to simulate a client-side state, or remove the Office application from any server-side code and use more scalable components (or client-side Automation) instead.

Use alternatives to Automation when running server-side
Microsoft strongly recommends that developers find alternatives to Automation of Office if they need to develop server-side solutions. Because of the limitations to Office's design, changes to Office configuration are not enough to resolve all issues. Microsoft recommends a number of alternatives that do not require Office to be installed server-side, and that can perform most common tasks more efficiently and quickly than Automation. Before involving Office as a server-side component in your project, consider alternatives.

Most server-side Automation tasks involve document creation. Because Office 2000 and later support HTML as a native document format, most documents can be created in HTML, using Extensible Markup Language (XML) markup when needed, and streamed to a client by using a Multipurpose Internet Mail Extensions (MIME) type so that the resulting text is displayed in Office. The document can be edited, saved, and even returned to the server when needed, by using nothing more than ASP on the server. For earlier versions of Office, other easily manipulated text formats (like RTF) can be used to the same effect.

Some native binary formats can be edited by using the Office Web Components (OWC) or ActiveX Data Objects (ADO) with much greater speed and scalability. Document properties can be viewed or changed without Automation, and file management and versioning is possible by using FrontPage Server Extensions (FPSE) or Distributed Authoring and Versioning (DAV). When Automation is essential, most tasks can be offloaded to the client, providing better stability and scalability for the system because each user runs the task in their own context, with their own settings.

For more information about any of these topics, and for examples that show how to implement them, click the following article numbers to view the articles in the Microsoft Knowledge Base:

270906 How to use ASP to generate a Rich Text Format (RTF) document to stream to Microsoft Word

198703 How to automate Excel from a client-side VBScript

199841 How to display ASP results using Excel in IE with MIME types

224351 Dsofile.dll lets you edit Office document properties without Office in Visual Basic .NET 2003 and in Visual Basic .NET 2002

244049 How to use server-side charting to generate charts dynamically

258187 OWebComp.exe contains scripting samples for the Office 2000 Web Components

260239 How to format cell data when you are creating an Excel file with an Active Server Pages page

278973 ExcelADO demonstrates how to use ADO to read and write data in Excel workbooks

286023 How to use a VB ActiveX component for Word automation from Internet Explorer

288130 How to use ASP to build spreadsheet XML for client-side display

317316 Limitations of Office Web Components when used server-side

If your business requires the server-side creation of binary Office files, there are third-party vendors that offer components that can help you. The following is a list of some well-known vendors that offer such services. This list is provided for information purposes only. The list is not exclusive. Other vendors may offer similar services that work better for you. You should investigate all possible third-party solutions to best match the vendor to your business needs. The following vendors currently offer some solutions that allow the programmatic creation and editing of native Office file formats. For more information about the third-party vendors, visit the following Web sites:

Aia Software B.V.

http://www.aia-itp.com

Polar

http://www.polarsoftware.com

SoftArtisans

http://www.softartisans.com

SyncFusion

http://www.syncfusion.com

Keylogix

http://www.activedocs.com

The third-party products that this article discusses are manufactured by companies that are independent of Microsoft. Microsoft makes no warranty, implied or otherwise, regarding the performance or reliability of these products.

Configuring Office to run server-side
If no other solution is feasible, and you decide to proceed with Automation of Office server-side, you need to address many of the concerns listed previously in order to run successfully from that environment. Because the majority of issues are related to configuration, it is not possible to give one set of steps that will cause Office Automation to work server-side in all cases for all systems. Some configuration settings may conflict with other options, and there are advantages and disadvantages to each approach. You may need to experiment to find out what works best in your environment.

In order to Automate Office from server-side code, you generally need to accomplish the following:
 * Design your project to isolate and encapsulate Office.
 * Code your project to anticipate problems and seek to correct them dynamically.
 * Provide your project with a specific user identity and profile for Office to use.

Your project design should take into account the problems of server-side security and Office non-reentrancy when attempting to use Office Automation. Limit your use of Office to a specific instance that is controlled by a serialization object (mutex or custom-defined locking primitive), or "pool" a tightly controlled set of instances from a custom object handler (or broker) that can issue application objects when needed, but control those aspects that require serialization. Office assumes a certain amount of state, so multiple clients that perform certain actions simultaneously (such as startup, shutdown, printing, and so forth) can cause a conflict, and possibly deadlock one or more calling threads by displaying an error, prompting the user for more information, or refusing to free a global resource that is used by all instances.

The first step, therefore, is to limit the use of Office Automation in your server-side design, and isolate the process to a non-critical computer that can be restarted if needed. Isolate the calling context as well, so that a hung calling client does not diminish the performance of an essential system service. For example, do not automate directly from within IIS using a system thread; rather, isolate the code to run on its own thread so that if it fails it doesn't reduce IIS functionality in general. Also, consider how your design enforces security and authentication. Because Office does not enforce server-side security, your code needs to ensure that only "trusted" code modules such as ASP pages, script files, and so forth can create an Automation instance of an Office application and call its methods, and that all documents are safe before you ask Office to open them. Office applications on a server should run with High security at all times. If your design does not enforce security, you are putting your server at risk!

Once the design is in place, you should code defensively to try and prevent issues from arising and handle errors when they occur. Make sure your code passes values for optional parameters, because missing or conflicting values can sometimes require Office to prompt the user for more information. Use error trapping in all functions to gracefully handle error conditions, and log these errors by using logging code that can be turned on or off by a custom setting (in the registry or INI file). If you perform an action that can cause an error dialog box to be displayed independent of Office (for example, printing can cause the printer driver to display a dialog box if the printer runs out of paper), be prepared to handle possible deadlocks by using a timeout or second thread to monitor progress. For more information, see the following article in the Microsoft Knowledge Base:

259971 How to dismiss a dialog box displayed by an Office application with Visual Basic

Use your logging code to trace problems and debug your program. If you use a custom object pool, you can add performance and scalability tests to monitor usage and log problems that affect all clients. A central controller can also let you terminate errant instances of Office and re-create them when needed to strengthen overall stability.

After the program is ready to be deployed, ensure that Office is properly configured on the server to run a suitable user context. Office requires a user profile, and to automate it successfully you must ensure that it loads with one. There are three ways to do this when working in a server-side environment:
 * Configure all instances of the Office application that is started by Automation to run as the Interactive user.
 * Configure all instances of the Office application that is started by Automation to run as a specific user.
 * Configure your code to run as a specific user by using an MTS/COM+ package and allowing the Office application to inherit the identity of the user that launches the application.

The first option gives Office both identity and interactivity with a specific desktop, and is the preferred option when debugging (because Office can be made visible and any dialog boxes or GPF faults can be seen and recorded by the user who is logged on locally). It does require the Interactive user to remain logged on to run successfully, so it may not be suitable for some situations. For more information, see the following article in the Microsoft Knowledge Base:

288366 How to configure Office applications to run under the interactive user account

The second option assigns a specific user but does not allow for interactivity. Office starts as the assigned user in a new WinStation on an invisible desktop. This option requires some additional configuration to ensure that the user registry hive is loaded since COM/DCOM does not do this by default. The setting is global to the system, so it may conflict with other programs. For more information about configuring Office in this manner, see the following article in the Microsoft Knowledge Base:

288367 How to configure Office applications to run under a specific user account

The third option allows you to assign an identity to a specific Web site or code module and avoid setting a fixed identity for Office globally. Office runs as that identity and loads correctly as long as the identity has been configured for that computer previously and the registry hive has been loaded. This option is typically the most flexible and securable, but, like the previous option, it does not offer interactivity with a visible desktop and it requires some extra setup. For more information about configuring Office in this manner, please the following article in the Microsoft Knowledge Base:

288368 How to configure Office applications for automation from a COM+/MTS package

You need to evaluate which of the above options suits your needs, and how best to deploy your solution. The information provided here is not guaranteed to resolve all issues for all clients. You are encouraged to test thoroughly before you deploy.

<div class="references_section">