I try open .doc file with interop, when I run in Visual studio result is a file but I publish web to IIS result is null.
I added folder Desktop to C:\Windows\SysWOW64\config\systemprofile, I run website, process Word run but still no return result.
I'm using Windows server 2012 64bit and Microsoft Office 2007. Why result in IIS return null and solution?
var wordApp = new Application { Visible = false };
var path = Request.PhysicalApplicationPath + "File\\TestFile.doc";
object srcPath = path;
var wordDoc = wordApp.Documents.Open(ref srcPath);
Refer Link
Sometimes with Office interop stuff it can be awkward.
If you use a single user to access the word application i.e. your asp.net service username.
Then what you can do is login to the computer using that username and open up word, this then adds all the registry and file system changes that the office applications seem to use. Note: if you are planning on using Excel as well then you need to open up excel also.
Another method is to create a new user account for accessing Word, then do the above and in your code behind impersonate that user so you're not giving the Web Application User access to word.
Hope this helps
p.s. When working with office interop it's important to watch for dirty references to objects. Leaving dirty references leaves ghost Word/Excel processes (visible only in task manager).
One thing I always do to help is to create a new AppDomain, this means there is no risk to the current process. Then I always release the objects as follows
if (item != null)
{
while (Marshal.ReleaseComObject(item) > 0);
item = null;
}
Where item is a document object, an application object etc. This code should go in a Finally block so that it always runs
Just in case you're new to office interop this one kept me busy for quite some time when I was just starting out.
Related
I have a Web Application that had been working for years on WindowsServer2012 with an Office automation implemented through microsoft.office.interop. I had to move the app to WindowsServer2019 and now the files can't be open. No error is thrown and the app is busy waiting for the server to proceed.
I perfectly know that this kind of automation is not recommended by Microsoft. It did a great job over the last 8 years and I'm using it only in our Intranet to convert Excel/Word documents to PDF and to bundle them in one PDF Binder using iTextSharp.
The fact that the browser keeps waiting all the time makes me think that Office popped up some (irrelevant) message or alert that need to be closed or accepted. The user that is supposed to run the application is set in Component Service. If I run Office under that identity no first-time-runtime message is displayed.
Comparing the old Server environment with the new one makes me think that the problem might be related to the behavior of Office. The documents I open are all ReadOnly. The new environment opens them in a restricted ReadOnly mode (where probably the "Save as" command isn't available?), while the old environment opens them in Edit mode. I couldn't manage to change that playing with the Office Options.
This is the code that works in the old environment:
public void Indexchanged_ConvertWordPDF(Object sender, EventArgs e)
{
Microsoft.Office.Interop.Word.Application xlApp = new Microsoft.Office.Interop.Word.Application();
object missing = System.Type.Missing;
xlApp.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable;
xlApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
xlApp.Visible = false;
string path = Gridview_SO.SelectedRow.Cells[0].Text;
string CertName = Gridview_SO.SelectedDataKey.Value.ToString().Replace("/", "-");
Microsoft.Office.Interop.Word._Document wordDocument = xlApp.Documents.Open(path, false, false, ref missing, ref missing);
wordDocument.ExportAsFixedFormat(#"C:\pdf\" + SALESID.Text + "_" + CertName + ".pdf", Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
wordDocument.Close(ref doNotSaveChanges, ref missing, ref missing);
xlApp.Quit();
DownloadSinglePDF(CertName);
GC.Collect();
GC.WaitForPendingFinalizers();
}
I perfectly know that this kind of automation is not recommended by Microsoft. It did a great job over the last 8 years
Nobody guarantees that your code will be working with new Office or Windows Server versions. You were lucky having automation running without issues on the server.
For other readers I'd like to remind that 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.
Consider using the Open XML SDK if you deal with open XML documents only, see Welcome to the Open XML SDK 2.5 for Office for more information.
Also you may consider using third-party components designed for the server-side execution.
I have a web API which simply
clone a .docx file
convert that cloned .docx to a .pdf format
using DocumentFormat.OpenXml.Packaging;
[HttpPost("clone")]
public IActionResult CloneBillFromTemplate()
{
var templateFilePath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Bill", "PaymentTempl.docx");
var clonedFilePath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Bill", "ClonedBill.docx");
var pdfFilePath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Bill", "FinalBill.pdf");
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(templateFilePath, true))
{
var clonedDoc = wordDoc.Clone(clonedFilePath);
System.Threading.Thread.Sleep(500);
clonedDoc.Save();
clonedDoc.Close();
}
using (var converter = new OfficeConverter.Converter())
{
converter.Convert(clonedFilePath, pdfFilePath);
}
return Ok();
}
Everything works fine when debugging (for sure :3) and also on IIS
But when I deploy to Azure App service, I got this type of error (stack trace + exception message).
Could not read registry to check Word version
Could not find registry key Word.Application\CurVer
at OfficeConverter.Word..ctor()
at OfficeConverter.Converter.get_Word()
at OfficeConverter.Converter.Convert(String inputFile, String outputFile, Stream logStream) at ....
Could you guys help me on this? Thanks all!!!
**feel free to ask for more information you need to detect this issue
Update
Looks like this is the issue with the pdf converter pacakge I'm using, not the OpenXML
It seems your application is relying on the Windows registry in a way that is not supported. If you are running on a Linux App Service, that would be the first thing to swap out, though my guess is that you are already running on Windows.
Apps have read-only access to much (though not all) of the registry of the virtual machine they are running on. In practice, this means registry keys that allow read-only access to the local Users group are accessible by apps. One area of the registry that is currently not supported for either read or write access is the HKEY_CURRENT_USER hive.
Write-access to the registry is blocked, including access to any per-user registry keys.
https://learn.microsoft.com/en-us/azure/app-service/operating-system-functionality#registry-access
If you can't refactor your code to not rely on such dependencies, I would suggest you put your application inside a Windows docker container. If you can run that locally, it should run on App Service as well.
Aim of the website is for a user to enter values into input fields and these values are used to find and replace text in word documents.
This works locally on my machine and replaces word documents and save them in the correct path.
I tried to publish the website using File System to a location on a web server. I created a new site on IIS manager and this is currently working fine, the website page loads. As soon I click on a button to generate the word documents I get the following error:
[NullReferenceException: Object reference not set to an instance of an
object.] src_PoA.OpenWordFile(String doc) +658
src_PoA.Submit_Click(Object sender, EventArgs e) +569
System.Web.UI.HtmlControls.HtmlButton.OnServerClick(EventArgs e) +133
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+1664
It seems to be failing when trying to define the word application, a word document and attempting to active the word document. I tried to debug it by opening the IIS website using visual studio on the web server, however I keep getting Unable to start debugging on the web server.:
private void OpenWordFile(string doc)
{
string caseno = casetextboxinput.Value;
string nameno = nametextbox.Value;
object fileName = Path.Combine(System.Windows.Forms.Application.StartupPath, doc);
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application { Visible = true };
Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(doc, ReadOnly: false, Visible: true);
aDoc.Activate();
}
I am using the UNC path in visual studio and this seems to find the path ok locally, but i dont know if it actually is able to access/read and write files back to this location which could be another place its also going wrong.
private static string directoryroot = #"\\testserver05\c$\inetpub\wwwroot\PoA\PoA Testing";
I have got .NET 4.5 and the bundle 4.0, 3 and 2 all installed on the web server. Also microsoft word is also installed.
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.
As a workaround you may consider using the Open XML SDK, see Welcome to the Open XML SDK 2.5 for Office for more information. Or just consider using any third-party components designed for the server-side execution.
In my ASP .Net application, I am using 'PDFTron 6.6.0.38591'.
We are using following code to convert Office documents to XOD:
string fileName = Path.GetFileName(pdfTronServiceRequest.FilePath);
fileName = ConstructConvertionFileName(fileName);
outFileName = Path.Combine(outputPath, fileName);
pdftron.PDF.Convert.ToXod(pdfTronServiceRequest.FilePath, outFileName);
response.Result = outFileName;
This code works well for filetypes like docx, xlsx, however for Powerpoint files, no response is returned(request timed out).
On checking the Task Manager window, we can see that a process for 'POWERPNT.exe' is started. However, this process never ends up itself(unlike that in case of word, excel upload).
Also, if I manually ends up this process, the conversion to XOD is successful and response is coming out correctly.
Also, please note that we are facing this issue only when we deploy the code on our test environments. Locally, PPT upload is working fine.
Let me know if you need any other information.
First, you should be running a licensed version of PowerPoint, not a trial/eval one. In particular, the account (including a Service/App Pool account) needs to have accepted the MS office licensing to make sure Office is a fully licensed product.
Also, is this happening with any ppt file or only certain ones? If certain ones, then try using one of the following two flags.
pdftron.PDF.Convert.Printer.SetMode(mode)
e_printer_only
e_interop_only
Finally, switch to the latest version. Which at the very least should provide a lot more debugging info in the exception message.
I am having an issue with opening a document using Microsoft Word from ASP.NET MVC.
This works perfectly on my developer machine, but not when deployed to IIS.
Dim word = New Microsoft.Office.Interop.Word.Application
'This line is failing to return a document object
Dim letter = word.Documents.Add(letter_doc_path)
'This line then fails due to [letter] being null
letter.MailMerge.OpenDataSource(csvPath)
I have added permissions in "Component Services" (dcomcnfg) to the NETWORK SERVICE user which allows the creation of the Word object in the first place, but I am completely stuck as what to do with this one.
I have also tried suppressing Word dialogs with the following line just in case
word.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone
The issue isn't helped by not having an error (apart from the null object reference obviously) - maybe there's a way to query Word for a specific error message?
Word requires the normal.dot template file when opening any document, the problem was occurring because the IIS user didn't have anywhere to create the normal.dot so it was failing in the background.
This was fixed by setting the UserTemplate path for the newly created word instance (immediately after creating it).
The path must be writeable by the IIS user (NETWORK SERVICE in my case).
word.Options.DefaultFilePath(Microsoft.Office.Interop.Word.WdDefaultFilePath.wdUserTemplatesPath) = working_folder
So just for completeness, here's the original example with the winning line included:
Dim word = New Microsoft.Office.Interop.Word.Application
'this line fixed it
word.Options.DefaultFilePath(Microsoft.Office.Interop.Word.WdDefaultFilePath.wdUserTemplatesPath) = working_folder
Dim letter = word.Documents.Add(letter_doc_path)
I was having the same problem, and the settings that wheelibin suggested weren't enough to create documents using the NETWORK SERVICE account.
What I ended up doing is:
Create a user account for this
process to run under.
Login as the user and run Word (this
does various setup tasks in Word so
the application doesn't try putting
up modal dialogs when running as a
service).
Create a new application pool and set
the pool to run as the user account.
If you're using Windows
Authentication, and your server is
Windows 2003 (or 2000, presumably),
then this issue applies, and you
need to either change the SPN of the
server, which will break Windows
Authentication for any application
running under a different user
account, or you have to switch the
authentication provider over to NTLM
instead of Kerberos.
IIS 7 can use Kernel Mode Authentication to avoid the issue.
I am not sure how are you catching the errors.
Please take a look at the following pages if you find some clue from that.
Error while using Microsoft Office 2003 in web application
Error while calling MS-Word from ASP.NET
"There is insufficient memory or disk space. Save the document now" - Opening MS Word from ASP.NET