private static void AddDocumentContentPerformance(Excel.Worksheet sheet, IEnumerable <char> values) { using (var comHelper = new COMObjectsHelper()) { try { Excel.Range activeCell = null; var rowIndex = 0; var cells = comHelper.Register(() => sheet.Cells); do { ++rowIndex; activeCell = comHelper.Register(() => cells[rowIndex, 1]); } while (!string.IsNullOrEmpty((string)activeCell.Value2)); foreach (var value in values) { activeCell.Value2 = value; ++rowIndex; activeCell = comHelper.Register(() => cells[rowIndex, 1]); } } catch (COMException) { throw new InvalidInteropOperationException("Failed to add content to the worksheet, because of COMException."); } } }
private static PowerPoint.Shape CreateNewSlideWithEmptyShape(PowerPoint.Presentation presentation, COMObjectsHelper comHelper) { var slides = comHelper.Register(() => presentation.Slides); var slideMaster = comHelper.Register(() => presentation.SlideMaster); var layouts = comHelper.Register(() => slideMaster.CustomLayouts); var customLayout = layouts[PowerPoint.PpSlideLayout.ppLayoutChartAndText]; var newSlide = comHelper.Register(() => slides.AddSlide(slides.Count + 1, customLayout)); return(comHelper.Register(() => newSlide.Shapes[1])); }
private static void CreateNewDocument(COMObjectsHelper comHelper, PowerPoint.Application ppApp, string path, IEnumerable <char> content) { var presentations = comHelper.Register(() => ppApp.Presentations); object readOnly = false; var presentation = comHelper.Register(() => presentations.Add(MsoTriState.msoFalse)); AddDocumentContent(presentation, string.Concat(content)); presentation.SaveAs(path); presentation.Close(); }
private static void AddDocumentContent(PowerPoint.Presentation presentation, string content) { using (var comHelper = new COMObjectsHelper()) { var slides = comHelper.Register(() => presentation.Slides); PrepareDocument(presentation, slides, comHelper); var targetShape = FindEmptyShape(slides, comHelper) ?? CreateNewSlideWithEmptyShape(presentation, comHelper); var targetFrame = comHelper.Register(() => targetShape.TextFrame); var textRange = comHelper.Register(() => targetFrame.TextRange); textRange.Text = content; } }
/// <summary> /// Clears all content in document. /// </summary> public static void ClearDocumentContent() { using (var comHelper = new COMObjectsHelper()) { var powerpointApp = GetActivePowerPointApp(comHelper) ?? throw new InvalidInteropOperationException($"Could not find any {MSPOWERPOINT_INTEROP_APP_NAME} application with active window."); var presentation = comHelper.Register(() => powerpointApp.ActivePresentation); var slides = comHelper.Register(() => presentation.Slides); RemoveSlides(slides, comHelper, forceRemoveAll: true); CreateNewSlideWithEmptyShape(presentation, comHelper); } }
/// <summary> /// Adds passed string into an active word document. /// </summary> /// <param name="value">String to add to document.</param> /// <param name="title">Title in a correct format.</param> /// <exception cref="ArgumentNullException">Thrown when the content string is null.</exception> /// <exception cref="InvalidInteropOperationException">Thrown when content cannot be added.</exception> public static void AddDocumentContent(string value, string title) { if (value == null) { throw new ArgumentNullException("Content should not be null."); } using (var comHelper = new COMObjectsHelper()) { var wordApp = GetActiveWordApp(comHelper) ?? throw new InvalidInteropOperationException($"Could not find any {MSWORD_INTEROP_APP_NAME} application with active window."); // Note: This property controls the visibility of alert dialogs wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone; var windows = comHelper.Register(() => wordApp.Windows); // Note: It may happen when we have multiple processes of app and the object given by interop doesn't have windows. if (windows.Count == 0) { throw new InvalidInteropOperationException("MS Word application interop object doesn't contain windows."); } var document = FindDocument(windows, comHelper, title) ?? throw new InvalidInteropOperationException($"MS Word document with a given title: {title} wasn't found."); AddDocumentContent(document, value); } }
/// <summary> /// Adds passed string into an active excel workbook in the first free cell. /// </summary> /// <param name="value">String to add to workbook.</param> /// <param name="title">Title in a correct format.</param> /// <exception cref="ArgumentNullException">Thrown when the content string is null.</exception> /// <exception cref="InvalidInteropOperationException">Thrown when content cannot be added.</exception> public static void AddDocumentContent(string value, string title) { if (value == null) { throw new ArgumentNullException("Content should not be null."); } // Note: When add content happens in the same time with create new document it breaks excel tests. lock (interopProcessLockObject) { using (var comHelper = new COMObjectsHelper()) { var excelApp = GetActiveExcelApp(comHelper) ?? throw new InvalidInteropOperationException("Cannot obtain MS Excel application interop object from ROT table."); // Note: This property controls the visibility of alert dialogs excelApp.DisplayAlerts = false; var windows = comHelper.Register(() => excelApp.Windows); // Note: It may happen when we have multiple processes of app and the object given by interop doesn't have windows. if (windows.Count == 0) { throw new InvalidInteropOperationException("MS Excel application interop object doesn't contain windows."); } var activeSheet = FindActiveSheet(windows, comHelper, title) ?? throw new InvalidInteropOperationException($"MS Excel sheet with a given title: {title} wasn't found."); AddDocumentContent(activeSheet, value); } } }
private static Word.Application GetActiveWordApp(COMObjectsHelper comHelper) { var wordApplications = COMObjectsHelper.GetActiveInteropApp <Word.Application>(comHelper, MSWORD_INTEROP_APP_NAME) ?? throw new InvalidInteropOperationException($"Could not find any {MSWORD_INTEROP_APP_NAME} application."); return(wordApplications.Find(app => comHelper.Register(() => app?.ActiveWindow) != null)); }
private static PowerPoint.Application GetActivePowerPointApp(COMObjectsHelper comHelper) { var ppApplications = COMObjectsHelper.GetActiveInteropApp <PowerPoint.Application>(comHelper, MSPOWERPOINT_INTEROP_APP_NAME) ?? throw new InvalidInteropOperationException($"Could not find any {MSPOWERPOINT_INTEROP_APP_NAME} application."); return(ppApplications.Find(app => comHelper.Register(() => app.ActiveWindow) != null)); }
private static Excel.Worksheet FindActiveSheet(Excel.Windows windows, COMObjectsHelper comHelper, string title) { Excel.Window matchingWindow = null; for (var i = 1; i <= windows.Count; i++) { var window = comHelper.Register(() => windows[i]); if (title.Contains(window.Caption)) { matchingWindow = window; break; } } return(comHelper.Register(() => matchingWindow?.ActiveSheet)); }
private static Word.Document FindDocument(Word.Windows windows, COMObjectsHelper comHelper, string title) { Word.Window matchingWindow = null; for (var i = 1; i <= windows.Count; i++) { var window = comHelper.Register(() => windows[i]); if (title.Contains(window.Caption)) { matchingWindow = window; break; } } return(comHelper.Register(() => matchingWindow?.Document)); }
private static void RemoveShapesWithEmptyTextFrame(PowerPoint.Slides slides, COMObjectsHelper comHelper) { foreach (PowerPoint.Slide slide in slides) { comHelper.Register(() => slide); var shapes = comHelper.Register(() => slide.Shapes); for (int i = shapes.Count; i > 0; --i) { var shape = comHelper.Register(() => shapes[i]); if (shape.HasTextFrame == MsoTriState.msoTrue && comHelper.Register(() => shape.TextFrame2).HasText == MsoTriState.msoFalse) { shape.Delete(); } } } }
private static PowerPoint.Shape FindEmptyShape(PowerPoint.Slides slides, COMObjectsHelper comHelper) { foreach (PowerPoint.Slide slide in slides) { comHelper.Register(() => slide); foreach (PowerPoint.Shape shape in slide.Shapes) { comHelper.Register(() => shape); if (shape.HasTextFrame == MsoTriState.msoTrue && comHelper.Register(() => shape.TextFrame).HasText == MsoTriState.msoFalse) { return(shape); } } } return(null); }
/// <summary> /// Gets full file name that is currently opened in an active document. /// </summary> /// <returns>Full file name.</returns> public static string GetActiveDocumentFileName() { using (var comHelper = new COMObjectsHelper()) { var wordApp = GetActiveWordApp(comHelper); return(comHelper.Register(() => wordApp.ActiveDocument)?.FullName); } }
/// <summary> /// Gets a title of an active word document. /// </summary> /// <returns>Active document title.</returns> public static string GetActiveDocumentTitle() { using (var comHelper = new COMObjectsHelper()) { var wordApp = GetActiveWordApp(comHelper) ?? throw new InvalidInteropOperationException($"Could not find any {MSWORD_INTEROP_APP_NAME} application with active window."); return(comHelper.Register(() => wordApp.ActiveWindow)?.Caption); } }
/// <summary> /// Resolves extensibility COM object and creates new instance of ExtensibilityInformationHelper. /// </summary> /// <returns>ExtensibilityInformationHelper object instance.</returns> public ExtensibilityInformationHelper ResolveService() { comHelper = new COMObjectsHelper(); if (extensibilityInformation == null) { extensibilityInformation = comHelper.Register(() => (IExtensibilityInformation)TypeHelper.GetInstance(InterfacesIds.NETDOCUMENTS_EXTENSIBILITY_EXTENSIBILITYINFORMATION_PROG_ID)); } return(this); }
/// <summary> /// Gets full file name that is currently opened in an active workbook. /// </summary> /// <returns>Full file name.</returns> public static string GetActiveWorkbookFileName() { using (var comHelper = new COMObjectsHelper()) { var excelApp = GetActiveExcelApp(comHelper) ?? throw new InvalidInteropOperationException("Cannot obtain MS Excel application interop object from ROT table."); return(comHelper.Register(() => excelApp.ActiveWorkbook)?.FullName); } }
private static PowerPoint.Presentation FindPresentation(PowerPoint.DocumentWindows windows, COMObjectsHelper comHelper, string title) { PowerPoint.DocumentWindow matchingWindow = null; for (var i = 1; i <= windows.Count; i++) { var window = comHelper.Register(() => windows[i]); if (title.Contains(window.Caption)) { matchingWindow = window; break; } } return(comHelper.Register(() => matchingWindow?.Presentation)); }
/// <summary> /// Gets full file name that is currently opened in an active powerpoint presentation. /// </summary> /// <returns>Full file name.</returns> public static string GetActiveDocumentFileName() { using (var comHelper = new COMObjectsHelper()) { var powerpointApp = GetActivePowerPointApp(comHelper) ?? throw new InvalidInteropOperationException($"Could not find any {MSPOWERPOINT_INTEROP_APP_NAME} application with active window."); return(comHelper.Register(() => powerpointApp.ActivePresentation)?.FullName); } }
public static void CreateNewDocument(string path, string[] content) { lock (interopProcessLockObject) { using (var comHelper = new COMObjectsHelper()) { Word.Application wordApp = null; try { var isVisible = false; wordApp = comHelper.Register(() => new Word.Application()); wordApp.Visible = isVisible; var documents = comHelper.Register(() => wordApp.Documents); object readOnly = false; object isAppVisible = isVisible; object documentType = Word.WdNewDocumentType.wdNewBlankDocument; var document = comHelper.Register(() => documents.Add(DocumentType: ref documentType, Visible: ref isAppVisible)); var docContent = comHelper.Register(() => document.Content); docContent.Text = string.Join(Environment.NewLine, content); var paragraphs = comHelper.Register(() => document.Paragraphs); var lastParagraph = comHelper.Register(() => paragraphs.Last); var range = comHelper.Register(() => lastParagraph.Range); if (range.Text.Trim() == string.Empty) { range.Select(); var selection = comHelper.Register(() => wordApp.Selection); selection.Delete(); } object savePath = path.Clone(); document.SaveAs2(ref savePath); document.Close(); } catch (Exception ex) { Console.WriteLine($"Document creation failed with error: {ex.Message}. Exception: {ex}."); throw; } finally { // Note: We always should manually quit from application, // because Release() only decreases references counter. wordApp?.Quit(); } } } }
private static void RemoveSlides(PowerPoint.Slides slides, COMObjectsHelper comHelper, bool forceRemoveAll = false) { for (int i = slides.Count; i > 0; --i) { var slide = comHelper.Register(() => slides[i]); if (forceRemoveAll || IsSlideEmpty(slide, comHelper)) { slide.Delete(); } } }
private static void AddDocumnetContent(PowerPoint.Presentation presentation, string value) { using (var comHelper = new COMObjectsHelper()) { try { var slides = comHelper.Register(() => presentation.Slides); PrepareDocument(presentation, slides, comHelper); var targetShape = FindEmptyShape(slides, comHelper) ?? CreateNewSlideWithEmptyShape(presentation, comHelper); var targetFrame = comHelper.Register(() => targetShape.TextFrame); var textRange = comHelper.Register(() => targetFrame.TextRange); textRange.Text = value; } catch (COMException) { throw new InvalidInteropOperationException("Failed to add content to the presentation, because of COMException."); } } }
/// <summary> /// Resolves extensibility COM object and creates new instance of ExtensibilityService2Helper. /// </summary> /// <returns>ExtensibilityService2Helper object instance.</returns> /// <exception cref="System.InvalidOperationException">Thrown when login into extensibility failed with any error.</exception> public ExtensibilityService2Helper ResolveService(IAuthorizationContext authorizationContext) { comHelper = new COMObjectsHelper(); if (extensibilityService2 == null) { extensibilityService2 = comHelper.Register(() => (IExtensibilityService2)TypeHelper.GetInstance(InterfacesIds.NETDOCUMENTS_EXTENSIBILITY_SERVICE_2_PROG_ID)); extensibilityService2.SetAuthorizationContext(authorizationContext); } return(this); }
public static void CreateNewDocumentPerformance(string path, IEnumerable <char> content) { lock (interopProcessLockObject) { using (var comHelper = new COMObjectsHelper()) { Excel.Application excelApp = null; try { excelApp = comHelper.Register(() => new Excel.Application()); var books = comHelper.Register(() => excelApp.Workbooks); object readOnly = false; Excel.Workbook book = comHelper.Register(() => books.Add()); var sheet = comHelper.Register(() => book.ActiveSheet); AddDocumentContentPerformance(sheet, content); object savePath = path.Clone(); book.SaveAs(savePath); book.Close(); } catch (Exception ex) { Console.WriteLine($"Document creation failed with error: {ex.Message}. Exception: {ex}."); throw; } finally { // Note: We always should manually quit from application, // because Release() only decreases references counter. excelApp?.Quit(); } } } }
private static void AddDocumentContent(Word.Document document, string value) { using (var comHelper = new COMObjectsHelper()) { try { if (document == null) { throw new InvalidInteropOperationException("Could not update content for the document because document is null."); } var content = comHelper.Register(() => document.Content); if (content == null) { throw new InvalidInteropOperationException($"Could not obtain current content for document {document.Name}."); } var isDocumentEmpty = content.End == 1; if (isDocumentEmpty) { document.Content.Text = value; } else { var paragraphs = comHelper.Register(() => document.Paragraphs); var paragraph = comHelper.Register(() => paragraphs.Add()); var range = comHelper.Register(() => paragraph.Range); range.InsertAfter(value); } } catch (COMException ex) { throw new InvalidInteropOperationException("Failed to add content to the document, because of COMException.", ex); } } }
/// <summary> /// Adds passed string into an active word document. /// </summary> /// <param name="value">String to add to workbook.</param> /// <exception cref="ArgumentNullException">Thrown when the content string is null.</exception> /// <exception cref="InvalidInteropOperationException">Thrown when content cannot be added.</exception> public static void AddDocumentContent(string value) { using (var comHelper = new COMObjectsHelper()) { var wordApp = GetActiveWordApp(comHelper) ?? throw new InvalidInteropOperationException($"Could not get interop instance of {MSWORD_INTEROP_APP_NAME} with active window."); // Note: This property controls the visibility of alert dialogs wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone; var document = comHelper.Register(() => GetDocument(wordApp)) ?? throw new InvalidInteropOperationException($"MS Word active document wasn't found."); AddDocumentContent(document, value); } }
/// <summary> /// Adds passed string into presentation in the empty shape or in the newly created one. /// </summary> /// <param name="value">String to add to workbook.</param> /// <exception cref="ArgumentNullException">Thrown when the content string is null.</exception> /// <exception cref="InvalidInteropOperationException">Thrown when content cannot be added.</exception> public static void AddDocumentContent(string value) { if (value == null) { throw new ArgumentNullException("Content should not be null."); } using (var comHelper = new COMObjectsHelper()) { var powerpointApp = GetActivePowerPointApp(comHelper) ?? throw new InvalidInteropOperationException($"Could not find any {MSPOWERPOINT_INTEROP_APP_NAME} application with active window."); // Note: This property controls the visibility of alert dialogs powerpointApp.DisplayAlerts = PowerPoint.PpAlertLevel.ppAlertsNone; var presentation = comHelper.Register(() => powerpointApp.ActivePresentation); AddDocumnetContent(presentation, value); } }
public static void CreateNewDocument(string path, IEnumerable <char> content) { lock (interopProcessLockObject) { using (var comHelper = new COMObjectsHelper()) { PowerPoint.Application ppApp = null; try { Wait.ForResult(() => { try { ppApp = comHelper.Register(() => new PowerPoint.Application()); CreateNewDocument(comHelper, ppApp, path, content); } catch (COMException ex) { Console.WriteLine($"Document creation failed with error: {ex.Message}. Exception: {ex}."); } return(File.Exists(path)); }); } catch (Exception ex) { Console.WriteLine($"Document creation failed with error: {ex.Message}. Exception: {ex}."); throw; } finally { // Note: We always should manually quit from application, // because Release() only decreases references counter. ppApp?.Quit(); } } } }
/// <summary> /// Adds passed string into active excel workbook in the first free cell. /// </summary> /// <param name="value">String to add to workbook.</param> /// <exception cref="ArgumentNullException">Thrown when the content string is null.</exception> /// <exception cref="InvalidInteropOperationException">Thrown when content cannot be added.</exception> public static void AddDocumentContent(string value) { if (value == null) { throw new ArgumentNullException("Content should not be null."); } // Note: When add content happens in the same time with create new document it breaks excel tests. lock (interopProcessLockObject) { using (var comHelper = new COMObjectsHelper()) { var application = GetActiveExcelApp(comHelper) ?? throw new InvalidInteropOperationException("Could not get active excel application object."); // Note: This property controls the visibility of alert dialogs application.DisplayAlerts = false; var activeSheet = comHelper.Register(() => (Excel.Worksheet)application.ActiveSheet); AddDocumentContent(activeSheet, value); } } }
private static bool IsSlideEmpty(PowerPoint.Slide slide, COMObjectsHelper comHelper) => comHelper.Register(() => slide.Shapes).Count == 0;