I am trying to save, modified changes in an existing powerpoint file loaded from disk. i was successfully able to open the file.
While tried to save edited (already existing) powerpoint file using saveas method, exception is observed.
private void adxPowerPointAppEvents1_PresentationBeforeSave(object sender, ADXHostBeforeActionEventArgs e)
{
try
{
PowerPoint.Presentation pre = e.HostObject as
PowerPoint.Presentation;
// cancel this operation
e.Cancel = true;
//save
pre.SaveAs(pre.Name,
PowerPoint.PpSaveAsFileType.ppSaveAsDefault,Office.MsoTriState.msoTrue);
MessageBox.Show("you will not see me due to exception");
}
catch(Exception e){}
}
When code is executed, enter image description here
The approach used in msword and msexcel were not working.
If there would be either approach to save the edited file, kindly help me ..
Got solution for this problem...
Like in word, excel we can't make save() operation... Powerpoint throws an exception if we call save or saveas from the same event handler(function).Accordingly, you must call SaveAs outside of that event handler, after PowerPoint invokes it.
private void adxPowerPointAppEvents_PresentationBeforeSave(object sender, ADXHostBeforeActionEventArgs e)
{
PowerPoint.Presentation pre = e.HostObject as PowerPoint.Presentation;
try
{
if (pre.Saved == Microsoft.Office.Core.MsoTriState.msoFalse)
{
e.Cancel = true;
GCHandle handle = GCHandle.Alloc(pre.FullName);
IntPtr parameter = (IntPtr)handle;
this.SendMessage(MESSAGE_SAVE_PPT, parameter, IntPtr.Zero);
pre.Saved = Microsoft.Office.Core.MsoTriState.msoTrue;
}
}
catch(Exception ex)
{
Log.Info("Exception while saving powerpoint : " + ex.StackTrace);
MessageBox.Show(ex.Message);
}
return;
}
private void AddinModule_OnSavePowerPointMessage(object sender, AddinExpress.MSO.ADXSendMessageEventArgs e)
{
if (e.Message == MESSAGE_SAVE_PPT)
{
PowerPoint.Presentation ppPre = null;
try
{
GCHandle handle = (GCHandle)e.WParam;
String fullName = (handle.Target as String);
ppPre = PowerPointApp.Presentations[fullName];
if (ppPre != null)
{
ppPre.Saved = Microsoft.Office.Core.MsoTriState.msoTrue;
//ppPre.SaveAs(ppPre.FullName, PowerPoint.PpSaveAsFileType.ppSaveAsDefault, Microsoft.Office.Core.MsoTriState.msoTrue);
ppPre.Save();
Log.Info("Value of pre.name " + ppPre.Name);
}
}
catch (Exception exSavePpt)
{
Log.Info("Exception while saving powerpoint : " + exSavePpt.StackTrace);
}
}
}
Actually, in AddinModule_OnSavePowerPointMessage(), We should not pass COM objects which would create com exception. So instead that we should pass presentation name(ppt.fullname) and create com reference pointing to same object in the second method. So, without any trouble now i could save ppt files...
Related
I have added a CEF control into a WinForm. And I have added an invokeCapture method that is expected to capture the screen shot of the entire page of the CEF. It works fine when first invoking. But errors are encountered since second invoking and more, which the message is "Generated MessageID 100002 doesn't match returned Message Id 100001". How can I capture screen shot more than once?
I have copied the screenshot function code from https://github.com/cefsharp/CefSharp/blob/master/CefSharp.Example/DevTools/DevToolsExtensions.cs to my project and renamed the namespace of it to winformcefdemo.CefSharp.Example.
The variable lastMessageId of the class DevToolsClient, in which class CaptureScreenshot executes ExecuteDevToolsMethodAsync in order to run command "Page.CaptureScreenshot", is private and there are either no getter nor setter to it. It seems to be annoying. The method ExecuteDevToolsMethodAsync would want to compare the message ID of what the method ExecuteDevToolsMethod returns to the automatically increased message ID of the DevToolsClient itself. The DevtoolsClient in the method CaptureScreenShotAsPng is what browser.GetDevToolsClient() returns (in the line 36 of the link above). And I have also checked the implementation of the method GetDevToolsClient. It is also using DevToolsClient devToolsClient = new DevToolsClient(browser); in CefSharp.DevToolsExtensions.
private async void invokeCapture()
{
try
{
byte[] result = await winformcefdemo.CefSharp.Example.DevTools.DevToolsExtensions.CaptureScreenShotAsPng(browser);
// task.Start();
// byte[] result = task.Result;
SaveFileDialog dialog = new SaveFileDialog();
DialogResult dresult = dialog.ShowDialog();
if (dresult == DialogResult.OK)
{
string path = dialog.FileName;
try
{
File.WriteAllBytes(path, result);
MessageBox.Show(path + " saved success");
} catch (Exception e)
{
MessageBox.Show(path + "Unknown error occurred when saving to file: " + e.Message);
}
}
}
catch (Exception ee)
{
MessageBox.Show("Unknown error occurred when capturing: " + ee.Message);
}
}
Solved in Chinese community of CSDN
Use no DevToolsExtensions. Use PageClient Instead. DevToolsExtensions does have issues that are not solved.
And PageClient should be defined globally. Do not define it in the method.
# Source: https://bbs.csdn.net/topics/398544662
CefSharp.DevTools.Page.PageClient pageClien= null;
private async void invokeCapture()
{
if(pageClien==null)
{
pageClien = webBrowser.GetBrowser().GetDevToolsClient().Page;
}
var result = await pageClien.CaptureScreenshotAsync();
if (result.Data != null)
{
MemoryStream ms = new MemoryStream(result.Data);
ms.Write(result.Data, 0, result.Data.Length);
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "PNG Picture (*.PNG)|*.PNG";
DialogResult dresult = dialog.ShowDialog();
if (dresult == DialogResult.OK)
{
string path = dialog.FileName;
try
{
File.WriteAllBytes(path, result);
MessageBox.Show(path + " saved success");
} catch (Exception e)
{
MessageBox.Show(path + "Unknown error occurred when saving to file: " + e.Message);
}
}
}
}
I'm writing a program which copies an excel file to another location and removes the sheets except for the visible sheets and saving the copied file. I have used the BackgroundWorker class in order to achieve this.
First, I initialized the Background Worker methods.
private void InitializeBackgroundWorker()
{
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
}
"BackgroundWorker.DoWork()" method is as follows.
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
GenerateReports(worker);
// Cancel the asynchronous operation.
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
worker.ReportProgress(100);
if(backgroundWorker.IsBusy)
{
this.backgroundWorker.CancelAsync();
}
}
The "GenerateReports()" method contains the "ExtractVisibleSheets()" method which extracts the visible sheets, which then calls the "CopyVisibleSheets()" method.
private void ExtractVisibleSheets(String originalDirectory, String convertedDirectory)
{
//Get the .xlsx files of the original reports and the converted reports
visibleSheetsOriginal = Directory.GetFiles(originalDirectory, "*.xlsx");
visibleSheetsConverted = Directory.GetFiles(convertedDirectory, "*.xlsx");
//Copy the visible sheets to the defined workbooks
//Sample Reports
CopyVisibleSheets(originalDirectory, visibleSheetsOriginal, visibleSheetsBasePath);
//Converted Reports
CopyVisibleSheets(convertedDirectory, visibleSheetsOriginal, visibleSheetsConvertedPath);
}
private void CopyVisibleSheets(String directory, String[] excelFiles, String path)
{
excelApplication = null;
workbook = null;
Excel.Worksheet sheet = null;
String copiedReport = "";
try
{
foreach(String report in excelFiles)
{
copiedReport = path + "\\" + report.Substring(report.LastIndexOf('\\') + 1);
excelApplication = GetExcelApplication();
File.Copy(report, copiedReport);
OpenXmlFileProcessor.RemoveCustomProperty(copiedReport, FileProcessor.BaClientVerParam);
workbook = excelApplication.Workbooks.Open(copiedReport);
EnableDisableAlertsAndEvents(false);
for (int i = workbook.Worksheets.Count; i > 0; i--)
{
sheet = excelApplication.ActiveWorkbook.Worksheets[i];
if(sheet.Visible != XlSheetVisibility.xlSheetVisible)
{
sheet.Visible = XlSheetVisibility.xlSheetVisible;
sheet.Delete();
}
}
workbook.Save();
EnableDisableAlertsAndEvents(true);
workbook.Close();
Marshal.ReleaseComObject(workbook);
}
}
finally
{
QuitAndReleaseExcelApplication(false);
}
}
"BackgroundWorker.RunWorkerCompleted()" method is given below
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// First, handle the case where an exception was thrown.
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
// Next, handle the case where the user cancelled
// the operation.
}
else
{
// Finally, handle the case where the operation
// succeeded.
MessageBox.Show("Directory Generation Successful!");
}
EnableControls();
}
But an error occurs during the line "File.Copy(report, copiedReport)" as follows and is fired up from the "BackgroundWorker.RunWorkerCompleted()" method.
Error
Do let me know if someone knows the reason for this error.
As a rule, the system C: drive requires admin privileges for writing. I'd suggest choosing another drive or folder (application data).
path + "\\" + report.Substring(report.LastIndexOf('\\') + 1);
try to use double qute "" (report.LastIndexOf('\\') + 1);
its a type of strings
try to use path + "//" + report.Substring(report.LastIndexOf("//") + 1);
correct me if im wrong :)
How to keep the savefilediallog open when you write to a file which is in use by an other program so that you can change the file name and try to save again?
private void button1_Click_2(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
CsvExport = Class_ExportData.DataTableToCSV(datatabelControle, csvSCheidingteken);
Cursor.Current = Cursors.Default;
saveFileDialog1.OverwritePrompt = true;
saveFileDialog1.Filter = "Komma gescheiden waarden (*.csv)|*.csv|Tekst bestanden (*.txt)|*.txt|Alle formaten (*.*)|*.*";
saveFileDialog1.DefaultExt = "csv";
saveFileDialog1.AddExtension = true;
saveFileDialog1.ShowDialog();
}
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
try
{
string name = saveFileDialog1.FileName; // Get file name.
File.WriteAllText(name, CsvExport); // Write to the file name selected.
}
catch (Exception ex)
{
//file is locked, how to get back to the open save file dialog ???
}
}
Try this. Move the code associated with opening the saveFileDialog1 into its own function and invoke that function from button1_Click:
private void button1_Click_2(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
CsvExport = Class_ExportData.DataTableToCSV(datatabelControle, csvSCheidingteken);
Cursor.Current = Cursors.Default;
ShowSaveFileDialog();
}
private void ShowSaveFileDialog()
{
saveFileDialog1.OverwritePrompt = true;
saveFileDialog1.Filter = "Komma gescheiden waarden (*.csv)|*.csv|Tekst bestanden (*.txt)|*.txt|Alle formaten (*.*)|*.*";
saveFileDialog1.DefaultExt = "csv";
saveFileDialog1.AddExtension = true;
saveFileDialog1.ShowDialog();
}
EDIT: On further consideration, I don't think you want/need the loop here, so I've removed it. You still want to invoke the ShowSaveFileDialog method here in case of exceptions, though:
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
try
{
string name = saveFileDialog1.FileName; // Get file name.
File.WriteAllText(name, CsvExport); // Write to the file name selected.
return;
}
catch (Exception ex)
{
//file is locked, how to get back to the open save file dialog ???
// maybe display an error message here so that the user knows why they're about to see the dialog again.
}
ShowSaveFileDialog();
}
Technically, this can probably lead to a StackOverflowException if the user tries repeatedly (and I mean thousands of times) to retry the save after an exception, but that's pretty unlikely.
This is really short question. I don't understand try-catch mechanism completely.
This is my current code:
public static void WriteText(string filename, string text)
{
try
{
System.IO.StreamWriter file = new System.IO.StreamWriter(filename);
file.Write(text);
file.Close();
}
catch(Exception exc)
{
MessageBox.Show("File is probably locked by another process.");
}
}
Background:
Im writing application that shares configuration files with another application.
I need some dialog messagebox with "retry" and "abort" buttons, when that file is used by other application. When that message will appear - I will close that other application and I will try to rewrite that file again by pressing "Retry" button.
Whatr we have is using a counter for re-tries and possibly a thread sleep.
So something like
int tries = 0;
bool completed = false;
while (!completed)
{
try
{
System.IO.StreamWriter file = new System.IO.StreamWriter(filename);
file.Write(text);
file.Close();
completed = true;
}
catch(Exception exc)
{
tries++;
//You could possibly put a thread sleep here
if (tries == 5)
throw;
}
}
Even though there's a good answer already I'll submit one that's more tuned towards the OP's question (let the user decide instead of using a counter).
public static void WriteText(string filename, string text)
{
bool retry = true;
while (retry)
{
try
{
System.IO.StreamWriter file = new System.IO.StreamWriter(filename);
file.Write(text);
file.Close();
retry=false;
}
catch(Exception exc)
{
MessageBox.Show("File is probably locked by another process.");
// change your message box to have a yes or no choice
// yes doesn't nothing, no sets retry to false
}
}
}
If you need more info on how to implement the messagebox check out the following links;
http://msdn.microsoft.com/en-us/library/0x49kd7z.aspx
MessageBox Buttons?
I would do it like that:
public static void WriteText(string filename, string text, int numberOfTry = 3, Exception ex = null)
{
if (numberOfTry <= 0)
throw new Exception("File Canot be copied", ex);
try
{
var file = new System.IO.StreamWriter(filename);
file.Write(text);
file.Close();
}
catch (Exception exc)
{
WriteText(filename,text,--numberOfTry,ex);
}
}
I like it more like this (example tries to save a RichTextBox on close and allows retrying save or aborting close):
protected override void OnClosing(CancelEventArgs e)
{
if (richTextBox_Query.Modified)
{
DialogResult result;
do
try
{
richTextBox_Query.SaveFile(
Path.ChangeExtension(Application.ExecutablePath, "sql"),
RichTextBoxStreamType.UnicodePlainText);
result = DialogResult.OK;
richTextBox_Query.Modified = false;
}
catch (Exception ex)
{
result = MessageBox.Show(ex.ToString(), "Exception while saving sql query",
MessageBoxButtons.AbortRetryIgnore);
e.Cancel = result == DialogResult.Abort;
}
while (result == DialogResult.Retry);
}
base.OnClosing(e);
}
I am using Live api to download SkyDrive files.
My code has a download click event which triggers the OnDownloadedCompleted function.
OnDownloadedCompleted function copies the file to "filename".
and calls the DefaultLaunch(), which takes in the "filename" and tries to launch it by the default program in windows phone 8.
When i execute this code (The file downloaded is a OneNote file) OneNote opens and says that the file can't be open.
Can anyone please help me validate this code?
Thanks a lot!
private void btnDownload_Click(object sender, RoutedEventArgs e)
{
if (App.Current.LiveSession == null)
{
infoTextBlock.Text = "You must sign in first.";
}
else
{
LiveConnectClient client = new LiveConnectClient(App.Current.LiveSession);
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompleted);
client.DownloadAsync("file_id");
}
}
The code for OnDownloadCompleted is
void OnDownloadCompleted(object sender, LiveDownloadCompletedEventArgs e)
{
if (e.Result != null)
{
var filestream = File.Create(#"filename");
e.Result.Seek(0, SeekOrigin.Begin);
e.Result.CopyTo(filestream);
filestream.Close();
DefaultLaunch();
e.Result.Close();
}
else
{
infoTextBlock.Text = "Error downloading image: " + e.Error.ToString();
}
}
The code for Default launch function is
async void DefaultLaunch()
{
try
{
string imageFile = #"File.one";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
var success = await Windows.System.Launcher.LaunchFileAsync(file);
if (success)
{}
else
{}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
Console.WriteLine(e.ToString());
}
}
try this tutorial.. http://msdn.microsoft.com/en-us/live/ff519582.aspx.. it is given there how to use live sdk in windows 8 platform