DowngradeDocument() function not doing proper downgrade? - vsto

I am trying to downgrade a document using VSTO.
I have a webservice, that receive a byte array. This byte is from the current active document.
The webservice can only handle a 2007/2003 word doc file.
So I want to use the
document.DowngradeDocument();
But the webservice report an error, when sending the byte array.
If a do a SaveAs and force word to save as 2007/2003 doc format, then there is no problem.
So my question is:
1) Why is DowngradeDocument() function not working. Why is it not doing a proper downgrade.
2) Do I need to do something else when I have called DowngradeDocument()
This must be in memory, since the file a happen to be working on, is not saved on disk.
// Dennis
Thank you for taking the time to read this
--- edit d. 20120904 ---
I cant use the webservice error, since it does not make sense of the error.
It says that it can finde the file, and this is an error within and application at the other side.
So I have tryed, to save a document in the right format, and one that was downgraded.
Used the same code. One work and the other did not.
But here is how I save the file as a temp. Before I call this function I have done a document.DowngradeDocument();
So I need, when it save to also change the format, while calling the downgrade function.
In the documentation for this function, it is clear that all previous version of office can read it, if the function is called.
/// <summary>
/// Make a copy of ActiveDocument in current user temp folder, and get a byte[].
/// </summary>
/// <param name="filename"></param>
/// <param name="document"></param>
/// <param name="file"></param>
/// <returns></returns>
private byte[] MakeCopy(string filename, Document document, out FileInfo file)
{
// http://blogs.msdn.com/b/pranavwagh/archive/2008/04/03/how-to-do-a-save-copy-as-in-word.aspx
// http://stackoverflow.com/questions/12175273/serialize-current-activedocument-from-office-2007-add-in
Microsoft.Office.Interop.Word.Application wdApp = new Microsoft.Office.Interop.Word.Application();
wdApp.Visible = false;
{
// make a fil i Current user temp folder
// http://stackoverflow.com/questions/944483/how-to-get-temporary-folder-for-current-user
string tempPath = System.IO.Path.GetTempPath();
string fileName = Path.Combine(tempPath, GenerateValidFileName(filename)) + ".doc";
IPersistFile compoundDocument = document as IPersistFile;
compoundDocument.Save(fileName, false);
byte[] content = File.ReadAllBytes(fileName);
file = new FileInfo(fileName);
wdApp.Quit();
return content;
}
}

Related

Check if Seleniums chrome webbrowser is downloading

I've seen a few questions asking if it's possible to check if a specific download is completed, or if a specific download has been completed successfully. (to which the answer appears to be no.)
What I want to know: Is it possible to see if selenium is currently downloading any file? I.e. it doesn't matter if it's one file, or 20. Something like a small boolean check would be ideal.
When chrome is downloading a file you can check your downloads folder for the temp file (*.crdownload) that Chrome uses. When the download finishes that file is "replaced" by the actual filename/type.
/// <summary>
/// Looks for a file with the given extension (Example: "*.crdownload") in the current user's "Download" folder.
/// </summary>
public static string LocateDownloadedFile(string fileExtension)
{
// Get the default downloads folder for the current user
string downloadFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads";
DirectoryInfo di = new DirectoryInfo(downloadFolderPath);
FileInfo[] filesFound = di.GetFiles(fileExtension);
if (filesFound.Length == 0)
{
// do stuff
}
else
{
// do other stuff
}
}

Merging PDF and Compressing files .net

i am trying merge and compress PDF files using bitmiracle.docotic.pdf library(trial version) and for a merged file of size 700MB i am facing "out of memory exception", below is my code
/// <summary>
/// Open file for copy.
/// </summary>
/// <param name="file">File name.</param>
/// <param name="outputDocument">Output pdf document.</param>
private void OpenFileForCopy(string file, PdfDocument outputDocument)
{
if (isFirstFile)
{
outputDocument.Open(file);
}
else {
outputDocument.Append(file);
}
}
/// <summary>
/// Saves PDF merged pdf file to location specified.
/// </summary>
/// <param name="outputDocument">Merged pdf document.</param>
/// <param name="path">Path to be stored.</param>
/// <param name="source">Source of file.</param>
/// <param name="Number">Number.</param>
private string[] SavePDF(PdfDocument outputDocument, string path, string source, string Number)
{
string[] result = new string[2];
outputDocument.PageLayout = PdfPageLayout.SinglePage;
string newPath = path + "_" + "Merged";
string nor= Number.Substring(1);
Directory.CreateDirectory(newPath);
newPath += "\\Stmt" + source + nor+ ".pdf";
outputDocument.SaveOptions.Compression = BitMiracle.Docotic.Pdf.PdfCompression.Flate;
outputDocument.SaveOptions.UseObjectStreams = true;
outputDocument.SaveOptions.RemoveUnusedObjects = true;
outputDocument.SaveOptions.OptimizeIndirectObjects = false;
outputDocument.SaveOptions.WriteWithoutFormatting = true;
outputDocument.Save(newPath);
outputDocument.Dispose();
isFirstFile = true;
result[0] = source ;
result[1] = Convert.ToString(fileCount);
fileCount = 0;
return result;
}
The instance of PdfDocument happens to be used across methods
Kindly let me know if anything needs to modified
Thanks,
Kirankumar
Your code is ok. Jut please note that amount of memory the library consumes is proportional to total size and number of appended documents.
I would recommend you to save and re-open documents once in a while to reduce amount of memory consumed by the library. You can also use the following setting for intermediate saves.
outputDocument.SaveOptions.UseObjectStreams = false;
So, I propose you to try the following process:
Open document
Append no more than 10 (or other number) documents
Save document (intermediate save)
Open the document you just saved
Append next batch of documents
...
Please note that current version of the library can lead to out of memory exceptions even when the proposed process is used.

Catching and logging MVC4 message about "Minification failed. Returning unminified contents"

There are a number of questions on StackOverflow that talk about getting the Minification failed. Returning unminified contents error from the MVC4 minification.
I'd like to know if there is a way to be notified about this error when it happens and to be able to log it.
It is nice that when there is an error the bundler returns the original contents so my site doesn't break, but I would like to know about these errors automatically rather than having to visit each css/js bundle url to see if there is an error.
So that logic is actually in the implementation of the default transforms that Script/StyleBundle are using. If you want to catch those errors yourself, you can change the transforms on your bundles to something that surfaces those errors:
So to actually detect the errors, you would have to manually enumerate all of your bundles (to trigger them to get generated), and also be able to listen to errors that happened (so the GenerateErrorResponse equivalent below would need to report any errors to someplace that you would see)
Here's what JsMinify does in its process for reference:
/// <summary>
/// Transforms the bundle contents by applying javascript minification
/// </summary>
/// <param name="context">The <see cref="BundleContext"/> object that contains state for both the framework configuration and the HTTP request.</param>
/// <param name="response">A <see cref="BundleResponse"/> object containing the bundle contents.</param>
public virtual void Process(BundleContext context, BundleResponse response) {
if (!context.EnableInstrumentation) {
Minifier min = new Minifier();
// NOTE: Eval immediate treatment is needed for WebUIValidation.js to work properly after minification
// NOTE: CssMinify does not support important comments, so we are going to strip them in JS minification as well
string minifiedJs = min.MinifyJavaScript(response.Content, new CodeSettings() { EvalTreatment = EvalTreatment.MakeImmediateSafe, PreserveImportantComments = false });
if (min.ErrorList.Count > 0) {
GenerateErrorResponse(response, min.ErrorList);
}
else {
response.Content = minifiedJs;
}
}
response.ContentType = JsContentType;
}

How to save and open connect the SQLite database file in another location but the application temporary folder in windows 8 RT?

guys, now I have an issue, it really makes me wonder.
I'm currently developing a Windows 8 RT app, the app store data to local, so I choice to use the SQLite for WinRT(include the SQLite.cs SQLiteAsync.cs, SQLite3.dll) , the SQLite for WinRT store the database file in the application temporary folder by default
public SQLiteConnection (string databasePath, bool storeDateTimeAsTicks = false): this (databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks)
{
}
/// <summary>
/// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath.
/// </summary>
/// <param name="databasePath">
/// Specifies the path to the database file.
/// </param>
/// <param name="storeDateTimeAsTicks">
/// Specifies whether to store DateTime properties as ticks (true) or strings (false). You
/// absolutely do want to store them as Ticks in all new projects. The default of false is
/// only here for backwards compatibility. There is a *significant* speed advantage, with no
/// down sides, when setting storeDateTimeAsTicks = true.
/// </param>
public SQLiteConnection (string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = false)
{
DatabasePath = databasePath;
#if NETFX_CORE
SQLite3.SetDirectory(/*temp directory type*/2, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path);
#endif
Sqlite3DatabaseHandle handle;
#if SILVERLIGHT || USE_CSHARP_SQLITE
var r = SQLite3.Open (databasePath, out handle, (int)openFlags, IntPtr.Zero);
#else
// open using the byte[]
// in the case where the path may include Unicode
// force open to using UTF-8 using sqlite3_open_v2
var databasePathAsBytes = GetNullTerminatedUtf8 (DatabasePath);
var r = SQLite3.Open (databasePathAsBytes, out handle, (int) openFlags, IntPtr.Zero);
#endif
Handle = handle;
if (r != SQLite3.Result.OK) {
throw SQLiteException.New (r, String.Format ("Could not open database file: {0} ({1})", DatabasePath, r));
}
_open = true;
StoreDateTimeAsTicks = storeDateTimeAsTicks;
BusyTimeout = TimeSpan.FromSeconds (0.1);
}
assign to the app temporary folder path.
Now I want to save the database file to another folder, like document folder, in order to save the user data and behavior, import the data when user re-install the app. So I change the save folder, the code as follow
StorageFolder sourceFolder = await KnownFolders.DocumentsLibrary.GetFolderAsync(FolderName);
DatabasePath = Path.Combine(sourceFolder.Path, DBName);
SQLite3.SetDirectory(/*temp directory type*/2, storeFloderPath);
but it throw an excetion at:
var r = SQLite3.Open(databasePathAsBytes, out handle, (int)openFlags, IntPtr.Zero);
Handle = handle;
if (r != SQLite3.Result.OK)
{
throw SQLiteException.New(r, String.Format("Could not open database file: {0} ({1})", DatabasePath, r));
}
it says cannot open the file. I think maybe the problem is 'SQLite3.SetDirectory(/temp directory type/2, storeFloderPath)', the '2' is the stand temp directory type. These no official document, so I try the argument from 0 to 6, it did't work as well, the exception as same as original.
Anyone know how to do it, or it has some error in my codes.
Thanks in advance.
Thanks all you answers, I found a sick way to solve it, When I want to open the database connection in other folder, firstly copy the database file to the application local folder(Windows.Storage.ApplicationData.Current.LocalFolder), and then connect to the database file, and then it successed.
But I wish the developer of the SQLite for WinRT could remark the problem, and fix it

Out of memory exception while loading images

I am using the following piece of code to load images as thumbnails to a FlowLayoutPanel control. Unfortunately i get an OutOfMemory exception.
As you already guess the memory leak is found at line
Pedit.Image = System.Drawing.Image.FromStream(fs)
So how could i optimize the following code?
Private Sub LoadImagesCommon(ByVal FlowPanel As FlowLayoutPanel, ByVal fi As FileInfo)
Pedit = New DevExpress.XtraEditors.PictureEdit
Pedit.Width = txtIconsWidth.EditValue
Pedit.Height = Pedit.Width / (4 / 3)
Dim fs As System.IO.FileStream
fs = New System.IO.FileStream(fi.FullName, IO.FileMode.Open, IO.FileAccess.Read)
Pedit.Image = System.Drawing.Image.FromStream(fs)
fs.Close()
fs.Dispose()
Pedit.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom
If FlowPanel Is flowR Then
AddHandler Pedit.MouseClick, AddressOf Pedit_MouseClick
AddHandler Pedit.MouseEnter, AddressOf Pedit_MouseEnter
AddHandler Pedit.MouseLeave, AddressOf Pedit_MouseLeave
End If
FlowPanel.Controls.Add(Pedit)
End Sub
Update: The problem occurs while loading a number of images (3264x2448px at 300dpi - each image is about 3Mb's)
Documentation for Image.FromFile (which is related to your FromStream) says that it will throw OutOfMemoryException if the file is not a valid image format or if GDI+ doesn't support the pixel format. Is it possible you're trying to load an unsupported image type?
Also, documentation for Image.FromStream says that you have to keep the stream open for the lifetime of the image, so even if your code loaded the image you'd probably get an error because you're closing the file while the image is still active. See http://msdn.microsoft.com/en-us/library/93z9ee4x.aspx.
Couple of thoughts:
First off, as Jim has stated, when using Image.FromStream the stream should remain open for the lifetime of the Image as remarked on the MSDN page. As such, I would suggest to copy the contents of the file to a MemoryStream, and use the latter to create the Image instance. So you can release the file handle asap.
Secondly, the images you're using are rather big (uncompressed, as they would exist in memory, Width x Height x BytesPerPixel). Assuming the context you use them in might allow for them to be smaller, consider resizing them, and potentially caching the resized versions somewhere for later use.
Lastly, don't forget to Dispose the image and the Stream when they are no longer needed.
You can solve this in a few steps:
to get free from the File-dependency, you have to copy the images. By really drawing it to a new Bitmap, you can't just copy it.
since you want thumbnails, and your source-bitmaps are rather large, combine this with shrinking the images.
I had the same problem. Jim Mischel answer led me to discover loading an innocent .txt file was the culprit. Here's my method in case anyone is interested.
Here's my method:
/// <summary>
/// Loads every image from the folder specified as param.
/// </summary>
/// <param name="pDirectory">Path to the directory from which you want to load images.
/// NOTE: this method will throws exceptions if the argument causes
/// <code>Directory.GetFiles(path)</code> to throw an exception.</param>
/// <returns>An ImageList, if no files are found, it'll be empty (not null).</returns>
public static ImageList InitImageListFromDirectory(string pDirectory)
{
ImageList imageList = new ImageList();
foreach (string f in System.IO.Directory.GetFiles(pDirectory))
{
try
{
Image img = Image.FromFile(f);
imageList.Images.Add(img);
}
catch
{
// Out of Memory Exceptions are thrown in Image.FromFile if you pass in a non-image file.
}
}
return imageList;
}