I have created a taskpane addin for word that is using the Document.getFileAsync method to get the document contents in Compressed format (docx).
This works correctly for .docx files, but unsurprisingly fails if an old .doc file is used.
I get the following error:
code: 5001
message: "An internal error has occurred."
name: "Internal Error"
Is there a way to detect documents in invalid formats before calling getFileAsync?
I have tried reading the document properties format value using the following code:
return Word.run(function (context) {
var properties = context.document.properties;
context.load(properties, "format");
return context.sync()
.then(function () {
return properties.format;
});
});
But the returned value is always an empty string for both docx and doc files.
I would like to be able to detect old file formats so that I can display an appropriate error message to the users.
getFileAsync() method works for .docx file only. Just to detect the correct file you can simply check the extension of the file: fname.substr((~-fname.lastIndexOf('.') >>> 0) + 2) where fname is filename here. And prompt your message accordingly.
Related
I have proper .dotm template.
When I create a new file based on a template by double clicking in explorer it creates the correct file (based on this template). Created file size after save is 16Kb (without any content).
But if I want to use .CreateFromTemplate method in my code I cannot open a newly created .docx file in MS Word.
New file size is 207Kb (just like .dotm file). MS Word display "run-time error 5398" and not open the file.
I'm using nuget package DocumentFormat.OpenXml 2.19.0, Word 365 version 16.0.14931.20648 - 32bit and code like this:
using (WordprocessingDocument doc = WordprocessingDocument.CreateFromTemplate(templatePath))
{
doc.SaveAs(newFileName);
}
Google is silent about this error, ChatGPT says that:
The "Run-time Error 5398" error means that the file you are trying to open is corrupted or not a valid docx file. Possible reasons for this error may be the following:
The file was not saved correctly after making changes. Verify that the Save() method was called after making changes to the file.
The file was saved with the wrong extension, e.g. as DOTM instead of DOCX
The file was saved in an invalid format.
There may have been some unhandled exceptions in your code.
When I manually change the extension of a new file from docx to dotm, there is no error when opening, but the file does not open.
What am I doing wrong with CreateFromTemplate method?
I tried to reproduce the behavior you described, using the following unit tests:
public sealed class CreateFromTemplateTests
{
private readonly ITestOutputHelper _output;
public CreateFromTemplateTests(ITestOutputHelper output)
{
_output = output;
}
[Theory]
[InlineData("c:\\temp\\MacroEnabledTemplate.dotm", "c:\\temp\\MacroEnabledDocument.docm")]
[InlineData("c:\\temp\\Template.dotx", "c:\\temp\\Document.docx")]
public void CanCreateDocmFromDotm(string templatePath, string documentPath)
{
// Let's not attach the template, which is done by default. If a template is attached, the validator complains as follows:
// The element has unexpected child element 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:attachedTemplate'.
using (var wordDocument = WordprocessingDocument.CreateFromTemplate(templatePath, false))
{
// Validate the document as created with CreateFromTemplate.
ValidateOpenXmlPackage(wordDocument);
// Save that document to disk so we can open it with Word, for example.
wordDocument.SaveAs(documentPath).Dispose();
}
using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(documentPath, true))
{
// Validate the document that was opened from disk, just to see what Word would open.
ValidateOpenXmlPackage(wordDocument);
}
}
private void ValidateOpenXmlPackage(OpenXmlPackage openXmlPackage)
{
OpenXmlValidator validator = new(FileFormatVersions.Office2019);
List<ValidationErrorInfo> validationErrors = validator.Validate(openXmlPackage).ToList();
foreach (ValidationErrorInfo validationError in validationErrors)
{
_output.WriteLine(validationError.Description);
}
if (validationErrors.Any())
{
// Note that Word will most often be able to open the document even if there are validation errors.
throw new Exception("The validator found validation errors.");
}
}
}
In both tests, the documents are created without an issue. Looking at the Open XML markup, both documents look fine. However, while I don't get any runtime error, Word also does not open the macro-enabled document.
I am not sure why that happens. It might be related to your security settings.
Depending on whether or not you really need to use CreateFromTemplate(), you could create a .docm (rather than a .dotm) and create new macro-enabled documents by copying that .docm.
I opened an issue in the Open XML SDK project on GitHub.
I have a specialized WebView extension in VS Code that I use to generate .Net Classes. These files are generated through an external command line tool. One of the features that the command line tool provides is that it writes to a specific file, the location of the generated file in JSON format.
I setup a file watcher on this particular file so that anytime it is updated, I run an extension method that parses that json file, extracts the file path from within the json and then opens that file inside VS Code.
While this works, my intent is to open this file inside a split editor, such that on one side I have my WebView (html) showing, and the other to show the file that was just opened (aka, that who's path came from the JSON file as mentioned above).
How do I open a file to be opposite side of a split window, keeping my webview ext. view on one side and the other side showing the newly opened file?
I have this working such that it opens the file, but not in a split-view editor
// uri points to the file to read JSON from
let fileUri: vscode.Uri = vscode.Uri.file(uri.fsPath);
// read JSON from relative path of this file
fss.readFile(fileUri.fsPath, 'utf8', function (err, data)
{
if(!err) {
try{
// parse the data read from file as JSON
var jsonObj = JSON.parse(data);
try{
// create uri from path within json
let fileToOpenUri: vscode.Uri = vscode.Uri.file(jsonObj.path);
// open and show the file inside VS code editor
vscode.window.showTextDocument(fileToOpenUri);
}
catch(ex)
{
// handle file Open error
vscode.window.showErrorMessage(ex);
}
}
catch(ex)
{
// handle JSON Parse error
vscode.window.showErrorMessage(ex);
}
}
else
{
// handle file read error
vscode.window.showErrorMessage(err.message);
}
});
Looking to open the file into the opposite side of a splitview.
vscode.window.showTextDocument(document, {
viewColumn: vscode.ViewColumn.Beside
});
https://code.visualstudio.com/api/references/vscode-api#TextDocumentShowOptions
https://code.visualstudio.com/api/references/vscode-api#ViewColumn
I am trying to convert documents using the Bluemix Document Conversion service with a Node.js application. I am getting nothing but errors in my app, but the test document I'm using converts fine using the demo page. Below is a minimal app that demonstrates the problem (Note that, while this app is converting a PDF from disk, the "real" app can't do that, hence the Buffer object).
'use strict';
var fs = require('fs');
var DocumentConversionV1 = require('watson-developer-cloud/document-conversion/v1');
var bluemix=require('./my_bluemix');
var extend=require('util')._extend; //Node.js' built-in object extend function
var dcCredentials = extend({
url: '<url>',
version: 'v1',
username: '<username>',
password: '<password>'
}, bluemix.getServiceCreds('document_conversion')); // VCAP_SERVICES
var document_conversion = new DocumentConversionV1(dcCredentials);
var contents = fs.readFileSync('./testdoc.pdf', 'utf8');
var parms={
file: new Buffer(contents,'utf8'),
conversion_target: 'ANSWER_UNITS', // (JSON) ANSWER_UNITS, NORMALIZED_HTML, or NORMALIZED_TEXT
content_type:'application/pdf',
contentType:'application/pdf', //don't know which of these two works, seems to be inconsistent so I include both
html_to_answer_units: {selectors: [ 'h1', 'h2','h3', 'h4']},
};
console.log('First 100 chars of file:\n******************\n'+contents.substr(0,100)+'\n******************\n');
document_conversion.convert(parms, function(err,answerUnits)
{
if (!err)
console.log('Returned '+answerUnits.length);
else
console.log('Error: '+JSON.stringify(err));
});
The results from running this program against the test PDF (782K) is:
$ node test.js
[DocumentConversion] WARNING: No version_date specified. Using a (possibly old) default. e.g. watson.document_conversion({ version_date: "2015-12-15" })
[DocumentConversion] WARNING: No version_date specified. Using a (possibly old) default. e.g. watson.document_conversion({ version_date: "2015-12-15" })
First 100 chars of file:
******************
%PDF-1.5
%����
1 0 obj
<</Type/Catalog/Pages 2 0 R/Lang(en-US) /StructTreeRoot 105 0 R/MarkInfo<<
******************
Error: {"code":400,"error":"Could not push back 82801 bytes in order to reparse stream. Try increasing push back buffer using system property org.apache.pdfbox.baseParser.pushBackSize"}
$
Can someone tell me
How to get rid of the warning messages
Why the document is not getting converted
How do I "increase the push back buffer"
Other documents give different errors, but I'm hoping if I can make this one work then the other errors will go away too.
You can get rid of the warning message by specifying a version date in your configuration. See the tests for an example. 1
If the document converted through the demo but failed to convert when using your application, it is likely an error with how the binary data is passed to the service. (For example, it's getting corrupted or truncated.) You can see the Node.js source code for the demo here 2. It may help you figure out the mistake or give you a different approach to loading/sending the file.
That is an error from one of the underlying libraries used by the service. Unfortunately, it's not something that a caller can adjust at this point.
I have written a patcher for my game but I am stuck at the actual saving of the files part. I keep on getting the following error from unity:
System.ArgumentException: Name has invalid chars
at System.IO.FileStream..ctor....
Here is the code that is in charge of saving my files:
function downloadFile(file:String){
var download:WWW = WWW(rawDataFolder+""+file); //download file from platforms raw folder
yield download; // wait for download to finish
// var saveLoc = Application.persistentDataPath; //Location where the files will go
var saveLoc = "C:\\games";
try{
Debug.Log(saveLoc+"\\"+file);
File.WriteAllBytes (saveLoc+"\\"+file+".FILE", download.bytes); //<----PROBLEM HERE.
}
catch(error){
updateMsg ="Update Failed with error message:\n\n"+error.ToString();
errorOccured = true;
Debug.Log(error);
}
}
I am trying to download a file called "level0". It doesn't have a file extension... in windows explorer it says it is simply 'FILE'. So I was thinking it was a binary file. Am I wrong? What might be causing my null character problem? This missing extension? Any help on this would be amazing.
I found out that my problem originated in the text file that I was reading. The text file must have had spaces in it. Using the ".Trim()" command I was able to remove the invalid char error. Once that was removed it worked perfectly reading files without extensions (Binary Files).
This is a weird one... I have a CSV file on the server and make it available to users via the code below. Typically, the results set is correct, except that it always omits the last field of the last record:
Co Name,Process Date,Employee Id,Last Name,First Name,Cust Auth,ENTERED_HRS,Labor Type
Temp,2014-02-21,CONTRACTOR0001,Dahlenburg,Eric,131137057134,5,0
Temp,2014-02-21,CONTRACTOR0001,Dahlenburg,Eric,1411310002,8,0
Temp,2014-02-21,CONTRACTOR0001,Dahlenburg,Eric,1411320015,6.69,0
Temp,2014-02-21,CONTRACTOR0001,Dahlenburg,Eric,1413500001105,6
Notice there is no ",0" at the end of the last record? In Visual Studios, it works fine, but on my development server, it omits that last part.
I verified that the source CSV file has all the data fields. I tried different path locations for the CSV file, but no change. Can't understand why it works on Visual Studios and not on the server.
addendum: I don't know if it matters, but the source file is located on a virtual directory(not physical) on the server. Any Ideas???
// Causes Save As Dialog box to appear for user.
String FileName = fileName;
String FilePath = strFilePath;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/csv";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.WriteFile(FilePath + FileName);
response.Flush();
response.Close();
// response.End(); // Same as response.TransmitFile(), but causes an exception because it raises the EndRequest event.
After a lot of trial and error, I found that I can get it to work if I use the Content type:
response.ContentType = "application/csv";
Not sure why this is different from text/csv, but its working now.
Also, You could use
response.ContentType = "application/vnd.ms-excel";
As well, but its going to prompt the user that the file is not in the proper format, do you want
to open anyway.
Eric