error : word automation - c#

I have IIS7(Windows Server 2008) 64bit but my application is running in 32bit mode. Ms Office 2003 is installed on server. I cannot find {000209FF-0000-0000-C000-000000000046} in Component Services but I can see {00020906-0000-0000-C000-000000000046} and I assigned all permissions for it too.
If I apply impersonation then I see winword.exe*32 in task manager and page in progress for long long time just like stick, no response/ error. I noticed that page goes stick/always in progress with
'' Passed and no error with impersonation
Dim WordApp As Microsoft.Office.Interop.Word.Application = New Microsoft.Office.Interop.Word.Application
'' Passed and no error with impersonation
Dim objDoc As Microsoft.Office.Interop.Word.Document = New Microsoft.Office.Interop.Word.Document
'' With impersonation, this line of code stick page to long process - Documents.Open
objDoc = WordApp.Documents.Open(path)
What I am missing? Same code was working with Windows Server 2003 64 bit.

Office Interop is not designed for sever side use. Microsoft has a Knowledge Base article on the topic of server-side automation of Office, you may want to read though it.
Without knowing what you are trying to use the interop for, all I can recommend is switch to using Office OpenXML for your sever automation. If you are just doing document manipulation it should allow you to do that. For anything else I would recommend looking over the suggestions for alterintives in the KB article I linked.
If you really must there is a hack solution to your problem
if you create the folder C:\Windows\SysWOW64\config\systemprofile\Desktop and C:\Windows\System32\config\systemprofile\Desktop it may solve your problem, but if you can I would highly recommend using OpenXML instead.

Related

Opening WebDAV documents as read-only in MS Office with IT Hit WebDAV Server

I'm creating a solution for managing remote MS Office documents. I used library made by IT Hit WebDAV System (www.webdavsystem.com) as a prototype. It's doing pretty well actually, except I cannot open document in read-only mode using URIs for office (based on Office URI Schemes by Microsoft).
I want to open the document in read-only mode, so someone else can edit it in the same time. As it can be seen in B-3. URI Scheme Syntax part of mentioned documentation, there are three commands available:
ofe - open for edit
ofv - open for view
nft - new from template
It seems that server acts always as "ofe" commands was given, no matter which one was used. Actually, entering "whatever" also works, it can be literally everything. Using MS Word for example, I post request order below:
OPTIONS => HEAD => OPTIONS => OPTIONS => LOCK => GET => PROPFIND => OPTIONS
As I am understanding correctly, successful LOCK attempt results in opening the document in edit mode. That tells me, that somewhere before that point MS WORD should ask for permission to do it, but I analyzed previous requests and was unable to find any related data.
It is not my environment issue also. I checked it with SharePoint and it was ok. That's why I would blame the server.
As I read that sentence(below) in this question,
most WebDAV clients ignore this and pretend that the entire server is either read-write or read-only
I started to wonder. Maybe that's the case? Maybe the library skips that and treats every file as read-write? If yes, how can I check it to be sure?
I've checked also this topic. The author mentions, that he has Office URI command in his OPTIONS requests, but links are no longer valid. In the requests that are sent by MS Office 2016, I can't find it anywhere. Should it be anywhere? Where?
Last, but not least, I found this topic. It seems to be exactly my problem, but it don't have the solution mentioned, or at least anything that worked in my case.
I will appreciate any help.
We have recently retested ofv and ofe options with latest MS Office 2016 for Windows and for Mac OS X with all updates installed. Here is what we have found:
On Windows this option is being ignored. Regardless of this parameter
MS Office opens as read-write.
On Mac OS this option is required. MS
Office respects this option and opens depending on ofv/ofe as
read-only or read-write.
From our experience there is no reliable way to open a document as read-only. In SharePoint Online (SPS 2016) there is also no option to open a document as read-only in the desktop version of MS Office.
One workaround could be throwing DavException in IFileAsync.WriteAsync() method implementation when saving a file. Please note that MS Office will ignore the message text being returned and will just display a generic error.
Another workaround would be marking a document as read-only in IMsItemAsync.GetFileAttributesAsync() method implementation:
public async Task<FileAttributes> GetFileAttributesAsync()
{
return fileSystemInfo.Attributes | FileAttributes.ReadOnly;
}
MS Office will display a yellow ribbon "UPLOAD FAILED This file is locked for editing by another user".

Microsoft Office Interop Excel ExportAsFixedFormat - very slow, images not loaded

I want to export generated .xlsx spreadsheet as PDF.
I have two problems:
Exporting document is very slow for both method - SaveAs() ExportAsFixedFormat()
ExportAsFixedFormat do not export the images.
I am running the code in ASP.NET server with IIS.
Already configured permissions like it says here : https://support.comodo.com/index.php?/Knowledgebase/Article/View/1129/66/access-denied-exception-from-hresult-0x80070005-e_accessdenied
The code from this repository works without error: https://github.com/aardvarkss/ExcelPDFExport
Also I generate .xlsx file with EPPlus.
The code:
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbooks excelWorkbooks = app.Workbooks;
Microsoft.Office.Interop.Excel.Workbook wkb = excelWorkbooks.Open(this.tempExcelFilePath);
foreach (Microsoft.Office.Interop.Excel.Worksheet sheet in wkb.Sheets)
{
sheet.SaveAs(this.tempPdfFilePath); // Saves the PDF correct AS I want But it cannot finish the task (waiting around 3 mins)
sheet.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, this.tempPdfFilePath); // Export PDF without image (image currently cannot be displayed), Also slow
}
wkb.SaveAs(this.tempPdfFilePath); // Waiting too long and cannot be finished
wkb.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, "C:\\Users\\user222\\Desktop\\Sample.pdf"); // Waiting too long and cannot be finish the task
// Closes the EXCEL.exe process in windows. If it not closes it cause errors.
wkb.Close(SaveChanges: false);
excelWorkbooks.Close();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(wkb);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbooks);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
Any ideas why it is so slow? And how to fix my problems?
The slow loading started today. before that, it doesn't have this problems with slow loading.
I am running the code in ASP.NET server with IIS.
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, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.
I'd suggest using the Open XML SDK instead, see Welcome to the Open XML SDK 2.5 for Office. Also you may consider using third-party components designed for the server-side execution.

Excel automation in WCF

We have developed two projects WCF and ASP.net Website.The WCF service consists of code that performs excel generation
it has something like
Excel.Application xlapp=new Excel.Application();
xlapp.visible=true;
//get data from dataset and process it and then write it to excel
This WCF service is hosted in my ASP.net website on a click button in web page
However when I run this service and asp.net on IIS 7 whole lot of error's are generated
few of the errors are as follows
Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005."
Then after giving permissions
Application. Microsoft Office Excel cannot open or save any more documents because
there is not enough available memory or disk space. • To make more memory available,
close workbooks or programs you no longer need. • To free disk space, delete files
you no longer need from the disk you are saving to
because of all these errors I am not able to run excel on IIS 7
I have tried all the methods right from Permissions to Authentication but it generates error
I am running XP on my local machine and Win 7 on IIS machine (Is this the problem of WIN 7?)
also this link says Server side Office automation is not supported at all
Isnt there any simple approach to start excel in IIS 7 ?? Or may be I should call excel in my ASP.net website than the WCF service...
Thanks all
Automating Excel should be done with the OpenXML library if possible, since it does not require an instance of Excel to be running, which is questionable at best for server-side processing.
Bas Brekelmans is right. You should go for OpenXML. I spend something like 2-3 days looking for a solution. There are many work arounds. Creating a new path in System32/SysWOW64.
http://social.msdn.microsoft.com/Forums/en-US/b81a3c4e-62db-488b-af06-44421818ef91/excel-2007-automation-on-top-of-a-windows-server-2008-x64
Another solution is through dcomcnfg.exe -> Component Services->Computers->My Computer->DCOM Config->Microsoft Word->Right Click->Properties->Security&Identity.
You'll find a lot of questions about it, but might find 1-2 replies which work.
I've one server which works properly with the Automatisation of Office, on the other server it doesn't, can't tell you why. Been troubleshooting for weeks the issue.
Also server-side automatisation is a feature that isn't supported by Microsoft Servers(shouldn't be).
Also, look under which version you compile your project, if it's x64 or x86.
Bas Brekelmans and mike27015 are right.
You should never go for COM component in asp.net project.
Better to use OpenXml library or some third part library like NPOI
NPOI is free and supports both xls and xlsx(open xml) type.

Why would the Excel Interop remove an image after processing a file?

Excel Interop is removing images from processed files.
I’m using the Excel Interop, no third-party components are present (that I'm aware of).
The workflow is -- create a copy (target) of a file (template), populate cells, change radio-button state
Create copy (target) of a pre-existing .xslm file (template)
Open target via Excel Interop
Populate target cells, change radio-button state
The worksheet with an image is not modified
Close target
On my dev machine, the target file looks great -- everything is populated, the image is present. NB: on my dev machine, I'm running the code from the VS2010 IDE.
On the production machine -- everything is populated, but the image is not present.
Instead, the following error appears in its place:
NB: on the production machine, it's running as a service, with the Local Service account.
"The image part with relationship ID rId1 was not found in the file"
The entire workbook is opened via the following code:
var workbook = workbooks.Open(targetPath
0, false, 5, Type.Missing, Type.Missing, false, XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
Please note that the worksheet with the image is not manipulated in the code.
The worksbooks (and individual worksheets) are protected. However, the protected template is processed correctly in dev, but not in production. I don't think the protection has anything to do with it (but who knows, right? This is Interop. ugh).
The file was created by another party, and all components (ie, the image) reside within the .xslm structure, not as links to another server.
I have verified that the image is visible on the production machine in the template file, but not in a processed file.
To confirm that this was not an issue in opening the file within the production, I emailed myself a copy, and the image continued to be not present.
I have also confirmed that, on my development machine, processed files do have a visible image.
I unprotected the worksheet, and unzipped the file structure. The .jpg file is indeed not present in the processed target from the production machine.
One more note -- Office 2010 is installed on my development machine, but Office 2007 on the production machine. As a result, I'm using the Office 12 Interop. No runtime errors are generated in either environment.
I am using the Interop (instead of an OpenXml library) because there are ActiveX controls present that must be populated. Note however, that none of the ActiveX controls have any issues -- they are working fine. It's just image-files that are vanishing from processed files (they render fine in the template file).
UPDATE NOTE: There are four other image-files, all .emf on a different worksheet; they are all stripped as well.
As explained in comments (and eventually in an edit to the question), the code was running in production as a service, with the Local Service account.
I am now unsure why I picked this account -- something I found in passing during my research on getting the Interop to run correctly as a service?
However, once I switched from the Local Service account to the Local System account (and checked "Allow service to interact with desktop") it worked. Automagically.
services.msc
select the service
right-click, select "Properties"
select the "Log On" tab
select "Local System account" and check "Allow service to interact with desktop"
"Allow service to interact with desktop" might not be required; Other notes on automating the Interop suggest that other desktop settings are required, however I did an install where those pre-requisites were set but THIS value unchecked; app still worked...
Interop is not supported in sever-scenarios by MS.
There are many options to read/edit/create Excel files without Interop:
MS provides the free OpenXML SDK V 2.0 - see http://msdn.microsoft.com/en-us/library/bb448854%28office.14%29.aspx (XLSX only)
This can read+write MS Office files (including Excel).
Another free option see http://www.codeproject.com/KB/office/OpenXML.aspx (XLSX only)
IF you need more like handling older Excel versions (like XLS, not only XLSX), rendering, creating PDFs, formulas etc. then there are different free and commercial libraries like ClosedXML (free, XLSX only), EPPlus (free, XLSX only), Aspose.Cells, SpreadsheetGear, LibXL and Flexcel etc.
It is hard to say whether your specific case (ActiveX controls) is fully supported by any of the above... that is something you need to test...
Even if the ActiveX controls are supported by any of the libraries there is a chance that the ActiveX controls themselves don't work within a Windows Service (permissions etc.).
EDIT - as per comment:
I understand the ActiveX problem and I addressed it from 2 points:
Have you really tested all above mentioned libraries ?
Have you checked with the implementor(s) of the ActiveX controls whether the ActiveX controls could even theoretically work in a Windows Service scenario ?
EDIT 3 - after the UPDATE from the OP:
.emf is a vector file format... IIRC GDI+ is used to render it on current Windows versions... .emf has evolved a bit over time so older OS and/or Office versions can sometimes have problems rendering newer .emf files... which in turn means the problem is the "missing desktop" in the Windows Service AND/OR that your .emf files are "too new" for the production machine.
(a) Not supported, don't do it https://support.microsoft.com/en-gb/kb/257757
(b) Anyway, if you have to do it (and cannot give desktop access to your process, as suggested in the accepted answer), you can mess with the contents and permissions in C:\Windows\System32\config\systemprofile, as suggested by this answer.
I had to create and allow permissions to the Desktop and to the INetCache folders. Checking (and solving) failed access attempts in paths beginning with C:\Windows\System32\config\systemprofile with the help of Process Monitor was what got me out of the annoying problem and pointed out at INetCache permissions as the reason of the failed insertion of images.
You just have to add permisions to C:\Windows\SysWOW64\config\systemprofile\AppData\Local\Microsoft\Windows\INetCache or C:\Windows\System32\config\systemprofile\AppData\Local\Microsoft\Windows\INetCache(depends on your system version) folder and images will shown
You're probably on your own, since Excel isn't supported in a server environment as #Yahia correctly points out.
Your mention of ActiveX controls is a red flag - maybe some of your ActiveX controls require Excel to run under an account with a profile?
All you can do is debug this yourself, probably best to proceed by eliminating the possible sources of different behaviour in your dev and production environments.
Try using the same Office version in both environments
Are you using Cassini in your dev environment? (i.e. running under your own login) If so, perhaps try with IIS running under a service account with no profile
Try removing the ActiveX components one by one to see if one of those is having an impact
... etc ...
I'm facing the same issue with powerpoint on Desktop (not a service) by copying a slide with picture from a template. (when getting about 200 copy paste in 1 presentation, but 1300 slides with same picture works fine ???)
It is hard to get this issue, I think it is hardware related, like RAM errors, but not sure
only 1 client of hundred get this error, so i think it is hardware related.
Note that i have a website that provide an Excel automataion and it works PERFECTLY, even "it is not supported by MS blah blah...." !
Your excel file seems to be corrupted, you have to find how.

Creating and saving word doc on server

i have this web application in c# .net running on an external web server.In that i am trying to generate and save the word doc on the server ( without opening it) . It runs fines on my local machine as i am having word installed on my machine but on the server it is showing error on using MyApplication Class. I understand it is not possible to install word on the server . Right now i am referenceing word.interopp assembly in my application .
Is there any better way to solve the issue .
Thanks and regards
Vickey Y.
If you're trying to use Office Interop without installing office on the server, then it's clearly going to fail.
Could you install Word on a different server and expose some sort of web service to create the document for you and serve the file contents back to the original server to save?
You may be able to use some third party libraries which can generate the relevant Word format, but I don't know of any.
What format does it have to be? Is it a complicated document? Could you just use RTF?
We use a third party tool called Aspose.Word. This allows you to perform a whole bunch of Word releated stuff without the need to install Word itself on the server.
the word.interop uses an instance of word to generate and save the documents. Even though it doesnt display the UI, the process of WINWORD will be running. In short, you need word installed on the server to use word.interop. When we did this, we also encountered issues when the servers needed to be compatible with word 2007 documents too, so its not an easy venture working with Word. Hope you get through the issue ok :)
I think you can do something like this.
I should alow you to open a document from the server.
protected void btnCreateWordBulletin_Click(object sender, EventArgs e)
{
String a= Server.MapPath("/Solution/Templates/Sport/Sport.doc");
String b= Server.MapPath("/Solution/Templates/Sport/SportSave.doc");
CreateWordDocument(a, b);
}
protected void CreateWordDocument(object fileName, object saveAs)
{
//Set Missing Value parameter - used to represent
//a missing value when calling methods through interop
object missing = System.Reflection.Missing.Value;
//Setup the Word.App class
Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word.Document aDoc = null;
// Check to see that file exists
if (System.IO.File.Exists((string)fileName))
{... Activating doc etc...}}
Yes, you can have Word running on server. However, note that opening winword.exe process from web service will probably fire winword.exe as ASPNET user. Some versions of MS word displayed some customization modal form during first run, making it impossible to automate process of using Word in server environment. The solution was making ASPNET “login-enabled” user, logging to server as an ASPNET user, running Word manually, closing all first-time-configuration modal forms, and then setting ASPNET user to its normal state. Since those configuration windows appeared only during first run of winword (more precisely: until configuration was approved by user), this actually worked.
Note: using winword on server needs some legal investigation. As far as I know MS attitude towards such solutions is rather negative, while some legal systems find it perfectly ok. Also take into consideration need for managing winword processes, and … and in fact, this is a bit crude hack.
OfficeWriter is another potential solution for you if you need true DOC and DOCX (as opposed to RTF or some other format):
http://www.officewriter.com
Take a look at OpenXML which is the file format all word (and Office) documents are saved in by default. http://openxmldeveloper.org/

Categories