Com Exception: Word was unable to read this document. It may be corrupt - asp.net

I have a web app that takes some client info and produces a letter for each client. Everything works good in my test environment, but on the production server I get an error that says the file is corrupt. I can open the .dotx file in word just fine on the server but not via code. Please help. Here is my code:
Object oMissing = System.Reflection.Missing.Value;
Object oTrue = true;
Object oFalse = false;
Word.Application oWord = new Word.Application();
Word.Document oWordDoc = new Word.Document();
oWord.Visible = false;
Object oTemplatePath = Request.PhysicalApplicationPath + "letters\\" + letter.letter_data; //samplehollisletter.dotx";
oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
foreach (Word.Field myMergeField in oWordDoc.Fields)
{
iTotalFields++;
Word.Range rngFieldCode = myMergeField.Code;
String fieldText = rngFieldCode.Text;
if (fieldText.StartsWith(" MERGEFIELD"))
{
Int32 endMerge = fieldText.IndexOf("\\");
Int32 fieldNameLength = fieldText.Length - endMerge;
String fieldName = fieldText.Substring(11, endMerge - 11);
fieldName = fieldName.Trim();
if (fieldName == "letter_title")
{
myMergeField.Select();
oWord.Selection.TypeText(acct.letter_title);
}
if (fieldName == "account_id")
{
myMergeField.Select();
oWord.Selection.TypeText(acct.account_id);
}
if (fieldName == "address")
{
myMergeField.Select();
oWord.Selection.TypeText(acct.PEOPLE.home_address + "\r\n" + acct.PEOPLE.home_city + ", " + acct.PEOPLE.home_state + " " + acct.PEOPLE.home_zip);
}
if (fieldName == "greeting_title")
{
myMergeField.Select();
oWord.Selection.TypeText(acct.greeting_title);
}
if (fieldName == "service_name")
{
myMergeField.Select();
oWord.Selection.TypeText((acct.SERVICEs.FirstOrDefault()).service_name);
}
if (fieldName == "service_date")
{
myMergeField.Select();
oWord.Selection.TypeText((acct.SERVICEs.FirstOrDefault()).service_date.ToString());
}
}
}
oWordDoc.PrintOut();
oWordDoc.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges);
Thread.Sleep(2000);
oWord.Quit();
The Error is:
Server Error in '/Tracker2' Application.
Word was unable to read this document. It may be corrupt.
Try one or more of the following:
* Open and Repair the file.
* Open the file with the Text Recovery converter.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.InteropServices.COMException: Word was unable to read this document. It may be corrupt.
Try one or more of the following:
* Open and Repair the file.
* Open the file with the Text Recovery converter.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[COMException (0x800a141f): Word was unable to read this document. It may be corrupt.
Try one or more of the following:
* Open and Repair the file.
* Open the file with the Text Recovery converter.]
Microsoft.Office.Interop.Word.Documents.Add(Object& Template, Object& NewTemplate, Object& DocumentType, Object& Visible) +0
Tracker.RunLetter2.Button1_Click(Object sender, EventArgs e) in C:\Users\Ethan\Documents\Visual Studio 2010\Projects\EstateTracker\Tracker\RunLetter2.aspx.cs:52
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +154
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3691

I know it is time that this item has been opened, but as I had not found the answer anywhere, following solution for those who need it.
1 - In IIS, the application pool used by the application, change the Identity attribute to LocalSystem
2 - Create a folder called Desktop within the following directories on the server:
C:\Windows\System32\config\systemprofile
and
C:\Windows\SysWOW64\config\systemprofile
After that, give full permission for these two folders to the user group IIS: IIS_IUSRS
This will cause this user to have a "desktop" to work, thereby achieving the IIS Word use the library.
I rough it helps someone.

I have discovered that the issue stems from permissions of a WCF call using BasicHTTPBinding endpoints. When a call is made using this type of endpoint, the service assumes the use of an IIS account which does not have a desktop to open word. This is a requirement of the account to automate word. Even when you have a service, that launches a windows application, that launches word, the entire set of events will be given the privilage of the original WCF call and will result in this error.
My solution, while not great, nor what I really want, does work for the time being. I created a Queue table in the database. I then have the web app insert a request for a task to be completed. then on the server I have a standalone application that checks the queue for requests every 60 seconds and processes the request. Its not the best method boe like I said, it does work.

Related

Access denied error using asymmetric binding in web host server - .NET

I'm getting an Access denied error when I attempt to make a web service request. The web service requires an asymmetric security binding. The call is made via a webpage that references a .NET dll that references the web service. All of this works fine on our server but we loaded it up at a web hosting company we got hit with this error.
My theory is that whatever the GetKeyPairHelper method does it requires the ability to write a file to do it while we don't have access to the location it tries to write to. The support people at this company ran a trace for us and these were the last two lines:
06:03.1 w3wp.exe 5860 CreateFile C:\ProgramData NAME COLLISION >Desired Access: Read Data/List Directory, Synchronize, Disposition: Create, Options: >Directory, Synchronous IO Non-Alert, Open Reparse Point, Attributes: N, ShareMode: Read, >Write, AllocationSize: 0
06:03.1 w3wp.exe 5860 CreateFile C:\ProgramData ACCESS DENIED >Desired Access: Read Attributes, Disposition: Open, Options: Open Reparse Point, >Attributes: n/a, ShareMode: Read, Write, Delete, AllocationSize: n/a
Looks like something trying to write to C:\ProgramData but what? And why? And how do I get around it? I'm hoping there is some way to configure this so it doesn't have to write a file. Perhaps this job can be performed in memory or directed to an area we have access to.
Stacktrace:
Error: Access is denied. : Server stack trace:
at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)
at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
at System.IdentityModel.Tokens.X509AsymmetricSecurityKey.get_PrivateKey()
at System.IdentityModel.Tokens.X509AsymmetricSecurityKey.GetSignatureFormatter(String algorithm)
at System.IdentityModel.SignedXml.ComputeSignature(SecurityKey signingKey)
at System.ServiceModel.Security.WSSecurityOneDotZeroSendSecurityHeader.CompletePrimarySignatureCore(SendSecurityHeaderElement[] signatureConfirmations, SecurityToken[] signedEndorsingTokens, SecurityToken[] signedTokens, SendSecurityHeaderElement[] basicTokens)
at System.ServiceModel.Security.SendSecurityHeader.CompleteSignature() at System.ServiceModel.Security.SendSecurityHeader.CompleteSecurityApplication()
at System.ServiceModel.Security.SecurityAppliedMessage.OnWriteMessage(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.Message.WriteMessage(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.Message.WriteMessage(XmlWriter writer)
at CustomMessageEncoder.CustomTextMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
in C:\xxxxx\CustomEncoders\CustomTextMessageEncoder.cs:line 86
Code:
public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
{
MemoryStream stream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(stream, this.writerSettings);
message.WriteMessage(writer); //'line 86' in stacktrace.
writer.Close();
byte[] messageBytes = stream.GetBuffer();
int messageLength = (int)stream.Position;
stream.Close();
int totalLength = messageLength + messageOffset;
byte[] totalBytes = bufferManager.TakeBuffer(totalLength);
Array.Copy(messageBytes, 0, totalBytes, messageOffset, messageLength);
//maybe parse message around here...
ArraySegment<byte> byteArray = new ArraySegment<byte>(totalBytes, messageOffset, messageLength);
return byteArray;
}
What happened here is that the hosting company was hosting our site on a shared server and so rightfully denied access to the C:\ProgramData folder which, further down the directory contains C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys which is the folder you need access to in order to use certificates based security. Their solution for us was to allow access to this folder for our app pool only. Works like a charm.

Thread aborting issue with Sharp Svn with C#.Net 4.0

I have developed ASP.net application using VS-2010, C#.Net 4.0 with SharpSvn dll. When I'm working with dev server(don't have 3-Tier Architecture), it works fine. But when we are working with QA environment(have 3-Tier Architecture) it gives thread abort exception most of the time.Following shows the code and error log I have. Any help on this really appreciate.
public bool Checkout(string svnurl, string target)
{
try
{
using (_client = new SharpSvn.SvnClient())
{
_client.LoadConfiguration(Path.Combine(Path.GetTempPath(), "Svn"), true);
_client.Authentication.DefaultCredentials = new TNetworkCredential(_username, _password);
_client.Authentication.SslServerTrustHandlers += SvnSslOveride;
var targetsvn = new SvnUriTarget(svnurl);
if (_client.CheckOut(targetsvn, target))
{
Log.Info("Successfully checked out to following location : " );
Log.Info(target);
return true;
}
}
Log.Info("Unable to checkout "+ svnurl +" Svn location to target location : ");
Log.Info(target);
return false;
}
catch (Exception ee)
{
Log.Error("Error:SvnClient checkout....");
Log.Error(ee);
throw ee;
return false;
}
}
private static void SvnSslOveride(object sender, SvnSslServerTrustEventArgs e)
{
e.AcceptedFailures = e.Failures;
e.Save = true;
}
error log
ERROR 2013-08-12 12:13:37,714 3223821ms SvnClient Checkout -
Error:SvnClient checkout.... ERROR 2013-08-12 12:13:37,730 3223837ms
SvnClient Checkout - System.Threading.ThreadAbortException: Thread was
being aborted. at svn_client_checkout3(Int32* , SByte* , SByte* ,
svn_opt_revision_t* , svn_opt_revision_t* , svn_depth_t , Int32 ,
Int32 , svn_client_ctx_t* , apr_pool_t* ) at
SharpSvn.SvnClient.CheckOut(SvnUriTarget url, String path,
SvnCheckOutArgs args, SvnUpdateResult& result) at
SharpSvn.SvnClient.CheckOut(SvnUriTarget url, String path)
I missed <httpRuntime executionTimeout="(time in seconds)">
tag in web config and it automatically set by IIS server. The default is 110 seconds.
Note :In the .NET Framework 1.0 and 1.1, the default is 90 seconds.
After I added following line to web.config and it works fine.
<httpRuntime executionTimeout="600">
Previously it works sometimes because the time taken to SVN checkout in DEV server is less than in other environment because of the size of the repositories and network connections. Thanks all for your answers
As per my comment above, I've seen this issue. It appears to be related to plink authentication.
I resolved it by upgrading to the latest build of SharpSVN v1.7, at which point the error changed from a null-ref exception in the C++, to an SVN exception with the message "Can't create tunnel: The parameter is incorrect".
There are a few articles which explain how to resolve this, the best of which I've found here:
SVN+SSH and Sourceforge
In my case, changing the backslashes to forwardslashes in the SVN_SSH env var resolved the problem. Worth giving a shot.

The remote host closed the connection. The error code is 0x800704CD

I receive error emails from my website whenever an exception occurs. I am getting this error:
The remote host closed the connection. The error code is 0x800704CD
and don't know why. I get about 30 a day. I can't reproduce the error either so can't track down the issue.
Website is ASP.NET 2 running on IIS7.
Stack trace:
at
System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationError(Int32
result, Boolean throwOnDisconnect) at
System.Web.Hosting.IIS7WorkerRequest.ExplicitFlush()
at
System.Web.HttpResponse.Flush(Boolean
finalFlush) at
System.Web.HttpResponse.Flush() at
System.Web.HttpResponse.End() at
System.Web.UI.HttpResponseWrapper.System.Web.UI.IHttpResponse.End()
at
System.Web.UI.PageRequestManager.OnPageError(Object
sender, EventArgs e) at
System.Web.UI.TemplateControl.OnError(EventArgs
e) at
System.Web.UI.Page.HandleError(Exception
e) at
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) at
System.Web.UI.Page.ProcessRequest(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) at
System.Web.UI.Page.ProcessRequest() at
System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext
context) at
System.Web.UI.Page.ProcessRequest(HttpContext
context) at
ASP.default_aspx.ProcessRequest(HttpContext
context) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at
System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
I get this one all the time. It means that the user started to download a file, and then it either failed, or they cancelled it.
To reproduce the exception try do this yourself - however I'm unaware of any ways to prevent it (except for handling this specific exception only).
You need to decide what the best way forward is depending on your app.
As m.edmondson mentioned, "The remote host closed the connection." occurs when a user or browser cancels something, or the network connection drops etc. It doesn't necessarily have to be a file download however, just any request for any resource that results in a response to the client. Basically the error means that the response could not be sent because the server can no longer talk to the client(browser).
There are a number of steps that you can take in order to stop it happening. If you are manually sending something in the response with a Response.Write, Response.Flush, returning data from a web servivce/page method or something similar, then you should consider checking Response.IsClientConnected before sending the response. Also, if the response is likely to take a long time or a lot of server-side processing is required, you should check this periodically until the response.end if called. See the following for details on this property:
http://msdn.microsoft.com/en-us/library/system.web.httpresponse.isclientconnected.aspx
Alternatively, which I believe is most likely in your case, the error is being caused by something inside the framework. The following link may by of use:
http://blog.whitesites.com/fixing-The-remote-host-closed-the-connection-The-error-code-is-0x80070057__633882307305519259_blog.htm
The following stack-overflow post might also be of interest:
"The remote host closed the connection" in Response.OutputStream.Write
One can reproduce the error with the code below:
public ActionResult ClosingTheConnectionAction(){
try
{
//we need to set buffer to false to
//make sure data is written in chunks
Response.Buffer = false;
var someText = "Some text here to make things happen ;-)";
var content = GetBytes( someText );
for(var i=0; i < 100; i++)
{
Response.OutputStream.Write(content, 0, content.Length);
}
return View();
}
catch(HttpException hex)
{
if (hex.Message.StartsWith("The remote host closed the connection. The error code is 0x800704CD."))
{
//react on remote host closed the connection exception.
var msg = hex.Message;
}
}
catch(Exception somethingElseHappened)
{
//handle it with some other code
}
return View();
}
Now run the website in debug mode. Put a breakpoint in the loop that writes to the output stream. Go to that action method and after the first iteration passed close the tab of the browser. Hit F10 to continue the loop. After it hit the next iteration you will see the exception. Enjoy your exception :-)
I was getting this on an asp.net 2.0 iis7 Windows2008 site. Same code on iis6 worked fine. It was causing an issue for me because it was messing up the login process. User would login and get a 302 to default.asxp, which would get through page_load, but not as far as pre-render before iis7 would send a 302 back to login.aspx without the auth cookie. I started playing with app pool settings, and for some reason 'enable 32 bit applications' seems to have fixed it. No idea why, since this site isn't doing anything special that should require any 32 bit drivers. We have some sites that still use Access that require 32bit, but not our straight SQL sites like this one.
I got this error when I dynamically read data from a WebRequest and never closed the Response.
protected System.IO.Stream GetStream(string url)
{
try
{
System.IO.Stream stream = null;
var request = System.Net.WebRequest.Create(url);
var response = request.GetResponse();
if (response != null) {
stream = response.GetResponseStream();
// I never closed the response thus resulting in the error
response.Close();
}
response = null;
request = null;
return stream;
}
catch (Exception) { }
return null;
}
I too got this same error on my image handler that I wrote. I got it like 30 times a day on site with heavy traffic, managed to reproduce it also. You get this when a user cancels the request (closes the page or his internet connection is interrupted for example), in my case in the following row:
myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
I can’t think of any way to prevent it but maybe you can properly handle this. Ex:
try
{
…
myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
…
}catch (HttpException ex)
{
if (ex.Message.StartsWith("The remote host closed the connection."))
;//do nothing
else
//handle other errors
}
catch (Exception e)
{
//handle other errors
}
finally
{//close streams etc..
}

Silverlight error while calling a service

I am trying to call a service from a silverlight application, but I am getting the following error.
Uncaught Error: Unhandled Error in Silverlight Application An exception occurred during the operation, making the result invalid. Check InnerException for exception details.
This works fine locally. I don't know if it make any sense, but locally if I add the url of the webservice on a browser, I am getting the details page of the service. In the other hand, on production server, it prompts me to download it.
Does anyone know something about this?
Thanks
public MainPage() {
InitializeComponent();
Loaded += new System.Windows.RoutedEventHandler(MainPage_Loaded);
}
private void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e) {
var newsFeedWcfClient = new NewsFeedWCFClient();
newsFeedWcfClient.GetNewsFeedItemsCompleted += newsFeedWcfClient_GetNewsFeedItemsCompleted;
newsFeedWcfClient.GetNewsFeedItemsAsync();
}
void newsFeedWcfClient_GetNewsFeedItemsCompleted(object sender, GetNewsFeedItemsCompletedEventArgs e) {
var source = (IList<NewsFeed>)e.Result;
IList<CustomNewsFeed> customNewsFeeds = new List<CustomNewsFeed>();
foreach (var item in source) {
customNewsFeeds.Add(new CustomNewsFeed() {
ProductID = item.Products.ProductID,
ProductTitle = item.Products.Title,
Status = item.Text,
Thumb = string.Format("{0}/{1}", item.Products.Product_Photos.Select(pp => pp.PhotoPath).FirstOrDefault(), item.Products.Product_Photos.Select(pp => pp.PhotoName).FirstOrDefault()),
UserID = item.User.Id,
UserName = item.User.Username
});
}
NewsFeedLB.ItemsSource = customNewsFeeds;
}
The fact that on the production server it "prompts you to download" would suggest that the production web server doesn't know what to do with your .svc or .asmx file. It is treating it like a normal file (.txt, .pdf etc).
Have you got all of the required items installed in production. For instance, you need the correct .NET runtime to be installed. Also, ASP.NET needs to be installed and then enabled.
To determine exactly what is happening I would recommend installing Fiddler and using it to trace what is happening when the Silverlight app calls the server. I have found this approach to be invaluable when troubleshooting Silverlight to Web Service communication problems.

ASP.Net Page for file upload stops processing in middle of log statement

We have a very simple ASP.Net page for uploading a file to our webserver. The page has no controls - a client uses it to automatically send us a file each night.
On occasion, the file seems to not get to us, but the client reports that they have sent it.
We added some logging statements to the page, and discovered something quite odd. The page ceases to execute right in the middle of a log statement. No exceptions, just up and dies.
Here is the code-behind:
protected void Page_Load(object sender, EventArgs e) {
try {
// record that request came in at all
log.Debug("Update Inventory page requested through HTTP {2} on {0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString(), IsPostBack ? "POST" : "GET");
// make sure directory exists
string basePath = Server.MapPath("~/admin/uploads/");
log.Debug("Saving to folder {0}", basePath);
if (!Directory.Exists(basePath)) {
log.Debug("Creating folder {0}", basePath);
Directory.CreateDirectory(basePath);
}
// generate a unique file name
string fileName = DateTime.Now.Ticks.ToString() + ".dat";
string path = basePath + fileName;
log.Debug("Filename to save is {0}", fileName);
// record initial bytes of stream/file
StreamReader reader = new StreamReader(stream);
string fileContents = reader.ReadToEnd();
log.Debug("File received by GET is " + fileContents.Length + " characters long and begins with: "
+ Environment.NewLine + fileContents.Substring(0, Math.Min(fileContents.Length, 1000)));
// write out file
File.WriteAllText(path, fileContents);
log.Debug("Update Inventory page processing finished.");
// trap for and record any and all exceptions
}
catch (Exception ex) {
log.Debug(ex);
}
}
The processing seems to die in the middle of the log statement that outputs the length and first portion of the fileContents variable. The logging that occurs when the process fails looks like this:
2010-08-02 02:46:01.7342|DEBUG|UpdateInventory|Update Inventory page requested through HTTP GET on 8/2/2010 2:46:01 AM
2010-08-02 02:46:01.7655|DEBUG|UpdateInventory|Saving to folder c:\hosting\sites\musicgoround.com\wwwroot\admin\uploads\
2010-08-02 02:46:01.7811|DEBUG|UpdateInventory|Filename to save is 634163139617811250.dat
2010-08-02 02:48:02.3905|DEBUG|UpdateInventory|
I really don't understand what to make of this.
I assume if there was a error in the transmission of the file that either an exception would be thrown from the reader.ReadToEnd() line. And if not an exception, I would expect the page processing to continue but that I may only receive part of the file (in which case it should log something).
The logging statement is only accessing a string variable, and it's inside a try-catch. NLog is the logging component we use, and we access that through the facade provided by the Simple Logging Facade project on Codeplex. So, we trust the logging component to be more or less bulletproof - we certainly don't see anything in our usage of it here that should be causing problems.
So, what's the deal? Why on earth could this page just up and stop processing like this?
The fact that we get a half-finished logging statement seems to point towards an error being swallowed in the logging system - but that just seems so unlikely - and we have NLog's internal logging on and it is not reporting any problems.
The most likely candidate is that this line:
2010-08-02 02:48:02.3905|DEBUG|UpdateInventory|
Is caused by this:
log.Debug(ex);
I.e. it is throwing an exception, but the logger is not recording anything useful. Why don't you try switching about the log levels a bit, e.g. change the exception logging level to error:
log.Error(ex);
That way you can see if it is actually throwing an exception and it is just the logger not recording the exception string properly.

Resources