Creating and saving word doc on server - c#

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/

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".

Scripting Word doc from external app

I'm trying to automate a tedious process that currently involves launching Word, Creating a new document from a .dot, saving it, running one or two plug-ins that were written in C# using VSTO, saving it again, exiting the document, and exiting Word.
I want to write a C# commandline app that the user can launch with one or two args (conveying all the information that would normally require interaction with dialogs in Word), then walk away from as it runs without further interaction... suppressing any and all focus-stealing by Word while it's running if necessary and possible.
Is there some straightforward way to accomplish this? Here's a Java-like pseudocode example of what I have in mind:
// magic to non-interactively launch Word and expose it as an object
WordHost word = xx;
// create new Word document based on a specific template that isn't the default one.
WordDocument doc = MSWord.create("z:\path\to\arbitraryTemplate.dot");
// If we can avoid physically saving it at this point and just assign a concrete
// file path, it would be even better because the network is glacially slow.
doc.saveAs("z:\path\to\newDoc.docx");
// someZeroArgPlugin and aTwoArgPlugin are VSTO plugins written with C#
doc.someZeroArgPlugin();
doc.aTwoArgPlugin("first", "second");
// done!
doc.save();
doc=null;
word=null; // something like word.unload() first?
// now do more things that don't involve Word directly...
Assuming I'm on the right track...
I'm pretty sure I can find most of what I need to know by searching... once I figure out what I need to be searching for. What should I be searching for?
What kind of project do I want to be creating in Visual Studio? A .net 4.5 C# console application? A Word 2010 Add-In? Some other kind of project?
Details that might or might not make a difference:
my program will only be run on computers that have Word 2010 installed. Compatibility with older versions isn't necessary.
It would be nice if it can run under Vista, but it only has to work under Win7.
I have Visual Studio Ultimate 2012
Here's what you'll need to do:
Have Visual Studio and Office installed.
Create a C# console project using the .NET framework of your choice (recommend 4.0 or above).
Add a reference to the Word COM library (Project menu => Add Reference, COM tab, Microsoft Word XX.0 Object library -- Word 2010 is 14.0).
Set the Embed Interop Types setting to false for the references added above
Expand References in Solution Explorer
Select Microsoft.Office.Core, Microsoft.Office.Interop.Word and VBIDE
Right-click and select Properties to bring up the Properties panel for the references.
In the Properties panel, set Embed Interop Types to False
Code away.
Here's some sample code.
using System;
using Microsoft.Office.Interop.Word;
namespace CSharpConsole
{
static class Program
{
[STAThread]
static void Main()
{
var application = new ApplicationClass();
var document = application.Documents.Add();
document.SaveAs("D:\test.docx");
application.Quit();
}
}
}
For more information, see http://msdn.microsoft.com/en-us/library/office/ff601860(v=office.14).aspx

detecting when a user opens a word document and when he types in it (in c#)

i'd like to do the following :
whenever a word document is open i need to save it in a way, and then if a user starts typing in it i want to save the time the document is being edited.
i'm just on the first phase, and i can't seem to manage detecting when a user opens a document.
i tried using Microsoft.Office.Interop.Word, but, in this way i don't want to start word application unless the user opens a document. but, when i want to initialize a Microsoft.Office.Interop.Word.Application, it's the only way i saw possible.
is there a way, by using the Microsoft.Office.Interop.Word API to detect event of opening a file by a user ?
i tried the following (obviously it doesn't work, since it's just opens a word office application)
using Word = Microsoft.Office.Interop.Word;
Word.Application oWord = new Word.Application();
oWord.Visible = true;
oWord.DocumentChange += new Word.ApplicationEvents4_DocumentChangeEventHandler(oWord_DocumentChange);
...
private void oWord_DocumentChange()
{
Console.WriteLine("DocumentChange");
}
also, i wanted to maybe use Microsoft.Office.Interop.Word.Document, but couldn't.
i started developing a method of my own, but its just seems to be a waste since this api is already build.
any help will be great.. thanks.
Have you already tried creating an Application level Add-in. That add-in should have all the event handlers you need to detect the first and last change to the document.
Maybe you could keep checking for open instances of Word every so often, and if you find one, then you use interop to get that instance.
You could probably use something like FindWindow or EnumWindows to check for instances of Word (or there might be some built in way of doing that in .Net that I can't remember right now), and then perhaps use GetObject to get the instance. This link describes GetObject vs CreateObject.

error : word automation

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.

Better option for hosting MS Office documents in custom app?

I am currently hosting an IE Browser control in a .NET (2.0) Form and using it to load Office files such as Excel and Word thusly:
_ieCtrl.Navigate("C:\\test.xls", False);
The hosting and loading works well except whenever I navigate to a file I am presented with a dialog that asks whether I want to save or open the file. (This is standard IE file-download behavior.) I always want to open it of course and I do not want the dialog to show.
Another issue is that when I close the window that hosts the IE control and the Office doc the document does not close and remains open on disk. This means that subsequent attempts to open the same file via my app or the native office app will fail because of the sharing violation.
Is there a programmatic way of avoiding this dialog and cleaning up resources afterward? I am asking for a programmatic answer because web research has only yielded solutions that entail modifying OS-level settings.
Bounty NOTE:
I am open to any solution to this issue that will allow me to:
Host an Excel spreadsheet inside my application
Work rather transparently (avoid usability issues like the one described above)
Avoid having to make any OS-specific changes that may affect other applications (especially icluding IE)
Is zero additional cost (no licensed 3rd party libs please) Code Project and other open source resources are OK
Not mess around with the DSO Framer ActiveX control, unless a stable version is developed/discovered
Is your intention for the user to be able to work with the Excel file in an Excel-ish way (i.e. columns, rows, formulas, etc.), possibly saving it back? If this is the case, I can't see how you can solve this problem well without relying on COM Interop with the Excel object model or by integrating third-party libraries to work with the Excel sheet. I know you said no paid solutions, but there are some feature-rich 3rd-party controls out there just for working with Excel files within applications.
I noticed in your comment to SLaks that the final product is a "dashboard of sorts". If your intention is to design a a custom dashboard application, have you considered parsing the Excel file(s) to extract the data and then presenting it in a logical manner within your application. This removes the need to directly display and work with the Excel file while still allowing you to work with the data inside that file. If you are trying to get the data outside of the file, here are two approaches among many:
You might consider using the Excel object model and COM interop to read the data from the Excel file into your application. Granted, this includes a dependency on Excel being installed, but it is a possibility. This article has some great code for getting started with reading Excel files in this way.
A better way might be to use a library that doesn't have a dependency on Excel being installed on the local system. This answer suggests using the Excel Data Reader library, available on CodePlex.
I know this answer side-steps your original answer of "hosting MS Office documents in [a] custom app," but in case what you're really interested in is the data inside those Excel files, hopefully this answer will prove helpful.
This is a horrible hack and should only be considered as a last resort: SendKeys.Send("{O}");
http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys%28VS.71%29.aspx
Something similar to
_ieCtrl.Navigate("C:\\test.xls", False);
(code to sleep or wait may be needed here)
SendKeys.Send("{O}");
Basically, you send the "o" key to the dialog so it presses the "open" option. You are simulating a keyboard presses to click the "open" button. It is hackey because
1) you may need to wait in between
calls. If you send the o key before
the dialog is up it will be missed.
Hopefully the navigate call is finished when the dialog pops (dont know behavior of control in c#). You may need to experiment with the time since different computers will open faster\slower
2) If the dialog is not shown on a
computer, you will be inserting "o"s
into it. This may cause problems when
exiting because it may popup another dialog to try and save
the changes. May be able to prevent this by opening it in read-only mode
3) Different versions or windows may need different sendkeys commands. For example, you may need to send "o" and them the "{enter}" key
4) Probably more :)
If you want to open the file in a separate Excel instance (not embedded in the WebBrowser control), you can simply call
Process.Start(#"C:\Test.xls");
Office was never meant to run in embedded mode, not in a web page or in an ActiveX Document host. Microsoft had time and time again given us the warning. From pulling dsoframer from the knowledge base to skipping the BrowserFlags registry key in Office 2007.
Move to Office add-ins, Excel Web Access or Office Web Apps as quickly as you can.

Categories