Esempio n. 1
0
 ShouldRunTask
 (
     AutomationTasks eTasksToRun,
     AutomationTasks eTaskToTest
 )
 {
     return((eTasksToRun & eTaskToTest) != 0);
 }
Esempio n. 2
0
        DoDataExchange
        (
            Boolean bFromControls
        )
        {
            AssertValid();

            if (bFromControls)
            {
                AutomationTasks eTasksToRun = GetTasksToRun();

                if (eTasksToRun == AutomationTasks.None)
                {
                    this.ShowWarning("No tasks have been selected.");
                    return(false);
                }

                Boolean bAutomateThisWorkbookOnly =
                    radAutomateThisWorkbookOnly.Checked;

                if (
                    !bAutomateThisWorkbookOnly
                    &&
                    !usrFolderToAutomate.Validate()
                    )
                {
                    return(false);
                }

                m_oAutomateTasksUserSettings.TasksToRun = eTasksToRun;

                m_oAutomateTasksUserSettings.AutomateThisWorkbookOnly =
                    bAutomateThisWorkbookOnly;

                m_oAutomateTasksUserSettings.FolderToAutomate =
                    usrFolderToAutomate.FolderPath;
            }
            else
            {
                SetTasksToRun(m_oAutomateTasksUserSettings.TasksToRun);

                if (m_oAutomateTasksUserSettings.AutomateThisWorkbookOnly)
                {
                    radAutomateThisWorkbookOnly.Checked = true;
                }
                else
                {
                    radAutomateFolder.Checked = true;
                }

                usrFolderToAutomate.FolderPath =
                    m_oAutomateTasksUserSettings.FolderToAutomate;

                EnableControls();
            }

            return(true);
        }
Esempio n. 3
0
        clbTasksToRun_ItemCheck
        (
            object sender,
            ItemCheckEventArgs e
        )
        {
            // AssertValid();

            if (!m_bIgnoreItemCheckEvents)
            {
                // Some tasks are dependent on other tasks.  Automatically check or
                // uncheck tasks as appropriate.

                AutomationTasks eTasksToRun  = GetTasksToRun();
                Boolean         bItemChecked = (e.NewValue == CheckState.Checked);

                switch (ItemToAutomationTask(clbTasksToRun.Items[e.Index]))
                {
                case AutomationTasks.SaveGraphImageFile:
                case AutomationTasks.ExportToNodeXLGraphGallery:
                case AutomationTasks.ExportToEmail:

                    if (bItemChecked)
                    {
                        eTasksToRun |= (
                            AutomationTasks.ReadWorkbook
                            |
                            AutomationTasks.SaveWorkbookIfNeverSaved
                            );
                    }

                    break;

                case AutomationTasks.ReadWorkbook:
                case AutomationTasks.SaveWorkbookIfNeverSaved:

                    if (!bItemChecked)
                    {
                        eTasksToRun &= ~(
                            AutomationTasks.SaveGraphImageFile
                            |
                            AutomationTasks.ExportToNodeXLGraphGallery
                            |
                            AutomationTasks.ExportToEmail
                            );
                    }

                    break;

                default:

                    break;
                }

                SetTasksToRun(eTasksToRun);
            }
        }
Esempio n. 4
0
        AutomateOneWorkbook
        (
            ThisWorkbook thisWorkbook,
            NodeXLControl nodeXLControl,
            AutomationTasks tasksToRun,
            String folderToSaveWorkbookTo
        )
        {
            Debug.Assert(thisWorkbook != null);
            Debug.Assert(nodeXLControl != null);

            CheckTasksToRunArgument(ref tasksToRun);

            Microsoft.Office.Interop.Excel.Workbook oWorkbook =
                thisWorkbook.InnerObject;

            if
            (
                (
                    ShouldRunTask(tasksToRun, AutomationTasks.MergeDuplicateEdges)
                    &&
                    !TryMergeDuplicateEdges(thisWorkbook)
                )
                ||
                (
                    ShouldRunTask(tasksToRun, AutomationTasks.CalculateClusters)
                    &&
                    !TryCalculateClusters(thisWorkbook)
                )
                ||
                (
                    ShouldRunTask(tasksToRun,
                                  AutomationTasks.CalculateGraphMetrics)
                    &&
                    !TryCalculateGraphMetrics(oWorkbook)
                )
                ||
                (
                    ShouldRunTask(tasksToRun, AutomationTasks.AutoFillWorkbook)
                    &&
                    !TryAutoFillWorkbook(thisWorkbook)
                )
                ||
                (
                    ShouldRunTask(tasksToRun, AutomationTasks.CreateSubgraphImages)
                    &&
                    !TryCreateSubgraphImages(thisWorkbook)
                )
            )
            {
                return;
            }

            RunReadWorkbookTasks(thisWorkbook, nodeXLControl, tasksToRun,
                                 folderToSaveWorkbookTo);
        }
Esempio n. 5
0
        GetTasksToRun()
        {
            AssertValid();

            AutomationTasks eTasksToRun = AutomationTasks.None;

            foreach (Object oCheckedItem in clbTasksToRun.CheckedItems)
            {
                eTasksToRun |= ItemToAutomationTask(oCheckedItem);
            }

            return(eTasksToRun);
        }
Esempio n. 6
0
        CheckTasksToRunArgument
        (
            ref AutomationTasks eTasksToRun
        )
        {
            // Here are the various AutomationTasks flag dependencies:
            //
            // SaveGraphImageFile requires ReadWorkbook, because you can't save an
            // image of a graph that hasn't been shown yet.
            //
            // SaveGraphImageFile requires SaveWorkbookIfNeverSaved, because the
            // image is saved to a folder and the folder isn't determined until the
            // workbook is saved.
            //
            // ExportToNodeXLGraphGallery and ExportToEmail require ReadWorkbook,
            // because you can't export an image of a graph that hasn't been shown
            // yet.
            //
            // ExportToNodeXLGraphGallery and ExportToEmail require
            // SaveWorkbookIfNeverSaved, because the title or subject of the
            // exported graph is the workbook's file name.

            if (ShouldRunTask(eTasksToRun,

                              AutomationTasks.SaveGraphImageFile
                              |
                              AutomationTasks.ExportToNodeXLGraphGallery
                              |
                              AutomationTasks.ExportToEmail
                              ))
            {
                // The SaveWorkbookIfNeverSaved flag was introduced after the
                // SaveGraphImageFile flag, so it's possible to have an older
                // workbook that has SaveGraphImageFile set without the necessary
                // SaveWorkbookIfNeverSaved flag.  Fix this.
                //
                // The ExportToNodeXLGraphGallery and ExportToEmail flags were
                // introduced after all the others, so the dialogs that use this
                // class should ensure that ReadWorkbook and
                // SaveWorkbookIfNeverSaved are specified if
                // ExportToNodeXLGraphGallery is set.  Set it anyway, in case there
                // are any unforseen circumstances where this isn't done.

                eTasksToRun |=
                    (
                        AutomationTasks.ReadWorkbook
                        |
                        AutomationTasks.SaveWorkbookIfNeverSaved
                    );
            }
        }
        GetWorkbookSettings
        (
            Microsoft.Office.Interop.Excel.Workbook oWorkbook
        )
        {
            Debug.Assert(oWorkbook != null);
            AssertValid();

            // Temporarily change some settings.

            AutomateTasksUserSettings oAutomateTasksUserSettings =
                new AutomateTasksUserSettings();

            AutomationTasks eOriginalTasksToRun =
                oAutomateTasksUserSettings.TasksToRun;

            oAutomateTasksUserSettings.TasksToRun =
                AutomationTasks.CalculateGraphMetrics;

            oAutomateTasksUserSettings.Save();

            GraphMetricUserSettings oGraphMetricUserSettings =
                new GraphMetricUserSettings();

            GraphMetrics eOriginalGraphMetricsToCalculate =
                oGraphMetricUserSettings.GraphMetricsToCalculate;

            oGraphMetricUserSettings.GraphMetricsToCalculate =
                GraphMetrics.OverallMetrics;

            oGraphMetricUserSettings.Save();

            // Get the workbook settings that include the temporary changes.

            String sWorkbookSettings =
                (new PerWorkbookSettings(oWorkbook)).WorkbookSettings;

            // Restore the original settings.

            oAutomateTasksUserSettings.TasksToRun = eOriginalTasksToRun;

            oAutomateTasksUserSettings.Save();

            oGraphMetricUserSettings.GraphMetricsToCalculate =
                eOriginalGraphMetricsToCalculate;

            oGraphMetricUserSettings.Save();

            return(sWorkbookSettings);
        }
Esempio n. 8
0
        private void SetType(AutomationTasks requestTask)
        {
            switch (requestTask)
            {
            case AutomationTasks.Transport:
                Type = "Transport";
                break;

            case AutomationTasks.Insert:
                Type = "Insert";
                break;

            case AutomationTasks.Delete:
                Type = "Delete";
                break;
            }
        }
        public bool ParseAutomationTasks()
        {
            Logging.Info(Logfiles.AutomationRunner, LogOptions.MethodName, "Getting list and parsing of automation tasks");
            Logging.Debug("Getting xml node results of TaskDefinitions");
            XPathNavigator result = XmlUtils.GetXNodeFromXpath(TasksDocument, AutomationSequenceTaskDefinitionsXpath);

            if (result == null)
            {
                Logging.Error("The xml document was valid xml and loaded, but has incorrect task definition formatting for the application (missing the TaskDefinitions root?)");
                return(false);
            }

            XElement automationTaskHolder = XElement.Parse(result.OuterXml);

            Logging.Debug("Getting property of automationTasks and setting list entries");
            AutomationTasks.Clear();
            PropertyInfo listPropertyInfo = this.GetType().GetProperty(nameof(AutomationTasks));

            try
            {
                bool setListEntriesResult = CommonUtils.SetListEntries(this, listPropertyInfo, automationTaskHolder.Elements(), AutomationTask.AttributeNameForMapping, AutomationTask.TaskTypeMapper);
                if (!setListEntriesResult)
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Logging.AutomationRunner(ex.ToString(), LogLevel.Exception);
                return(false);
            }

            Logging.Debug(Logfiles.AutomationRunner, LogOptions.MethodName, "Configuration of any additional properties for each task");
            foreach (AutomationTask task in AutomationTasks)
            {
                task.AutomationSequence = this;
                task.PreProcessingHook();
                Logging.Info("Processed task {0}", task.ID);
            }

            Logging.Debug(Logfiles.AutomationRunner, LogOptions.MethodName, "Finish parsing of tasks");
            return(true);
        }
Esempio n. 10
0
        SetTasksToRun
        (
            AutomationTasks eTasksToRun
        )
        {
            AssertValid();

            CheckedListBox.ObjectCollection oItems = clbTasksToRun.Items;
            Int32 iItems = oItems.Count;

            m_bIgnoreItemCheckEvents = true;

            for (Int32 i = 0; i < iItems; i++)
            {
                clbTasksToRun.SetItemChecked(i,
                                             (eTasksToRun & ItemToAutomationTask(oItems[i])) != 0);
            }

            m_bIgnoreItemCheckEvents = false;
        }
Esempio n. 11
0
        AutomateThisWorkbook
        (
            ThisWorkbook thisWorkbook,
            AutomationTasks tasksToRun,
            Ribbon ribbon
        )
        {
            Debug.Assert(thisWorkbook != null);
            Debug.Assert(ribbon != null);

            Microsoft.Office.Interop.Excel.Workbook oWorkbook =
                thisWorkbook.InnerObject;

            if ((tasksToRun & AutomationTasks.MergeDuplicateEdges) != 0)
            {
                // In general, automation is best performed by simulating a click
                // of a Ribbon button, thus avoiding any duplicate code.

                if (!ribbon.OnMergeDuplicateEdgesClick(false))
                {
                    return;
                }
            }

            if ((tasksToRun & AutomationTasks.CalculateGraphMetrics) != 0)
            {
                // In this case, clicking the corresponding Ribbon button opens a
                // GraphMetricsDialog, which allows the user to edit the graph
                // metric settings before calculating the graph metrics.  The
                // actual calculations are done by CalculateGraphMetricsDialog, so
                // just use that dialog directly.

                CalculateGraphMetricsDialog oCalculateGraphMetricsDialog =
                    new CalculateGraphMetricsDialog(oWorkbook,
                                                    new GraphMetricUserSettings());

                if (oCalculateGraphMetricsDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
            }

            if ((tasksToRun & AutomationTasks.AutoFillWorkbook) != 0)
            {
                // In this case, clicking the corresponding Ribbon button opens an
                // AutoFillWorkbookDialog, which allows the user to edit the
                // autofill settings before autofilling the workbook.  The actual
                // autofilling is done by WorkbookAutoFiller, so just use that
                // class directly.

                try
                {
                    WorkbookAutoFiller.AutoFillWorkbook(
                        oWorkbook, new AutoFillUserSettings(oWorkbook));

                    ribbon.OnWorkbookAutoFilled(false);
                }
                catch (Exception oException)
                {
                    ErrorUtil.OnException(oException);
                    return;
                }
            }

            if ((tasksToRun & AutomationTasks.CreateSubgraphImages) != 0)
            {
                ribbon.OnCreateSubgraphImagesClick(
                    CreateSubgraphImagesDialog.DialogMode.Automate);
            }

            if ((tasksToRun & AutomationTasks.CalculateClusters) != 0)
            {
                if (!ribbon.OnCalculateClustersClick())
                {
                    return;
                }
            }

            if ((tasksToRun & AutomationTasks.ReadWorkbook) != 0)
            {
                // If the vertex X and Y columns were autofilled, the layout type
                // was set to LayoutType.Null.  This will cause
                // TaskPane.ReadWorkbook() to display a warning.  Temporarily turn
                // the warning off.

                NotificationUserSettings oNotificationUserSettings =
                    new NotificationUserSettings();

                Boolean bOldLayoutTypeIsNull =
                    oNotificationUserSettings.LayoutTypeIsNull;

                oNotificationUserSettings.LayoutTypeIsNull = false;
                oNotificationUserSettings.Save();

                if ((tasksToRun & AutomationTasks.SaveGraphImageFile) != 0)
                {
                    if (String.IsNullOrEmpty(thisWorkbook.Path))
                    {
                        throw new InvalidOperationException(
                                  WorkbookNotSavedMessage);
                    }

                    // After the workbook is read and the graph is laid out, save
                    // an image of the graph to a file.

                    GraphLaidOutEventHandler oGraphLaidOutEventHandler = null;

                    oGraphLaidOutEventHandler =
                        delegate(Object sender, GraphLaidOutEventArgs e)
                    {
                        // This delegate remains forever, even when the dialog
                        // class is destroyed.  Prevent it from being called again.

                        thisWorkbook.GraphLaidOut -= oGraphLaidOutEventHandler;

                        SaveGraphImageFile(e.NodeXLControl, thisWorkbook.FullName);
                    };

                    thisWorkbook.GraphLaidOut += oGraphLaidOutEventHandler;
                }

                ribbon.OnReadWorkbookClick();

                oNotificationUserSettings.LayoutTypeIsNull = bOldLayoutTypeIsNull;
                oNotificationUserSettings.Save();
            }
        }
        public async Task <bool> RunTasksAsync()
        {
            ExecutionTimeStopwatch.Restart();
            RunningTask = null;
            ExitCode    = SequencerExitCode.NotRun;
            if (Package == null || AutomationSequencer == null || AutomationRunnerSettings == null)
            {
                throw new NullReferenceException();
            }

            Logging.Debug(Logfiles.AutomationRunner, "Setting up macro list before task run");
            AllMacros.Clear();
            AllMacros.AddRange(ApplicationMacros);
            foreach (AutomationMacro macro in GlobalMacros)
            {
                AllMacros.Add(AutomationMacro.Copy(macro));
            }

            //process local macros in case they were added with macros inside them
            foreach (AutomationMacro macro in SequenceMacros)
            {
                macro.Value = AutomationTask.ProcessMacro(macro.Name, macro.Value, SequenceMacros);
                AllMacros.Add(AutomationMacro.Copy(macro));
            }

            Logging.Debug(Logfiles.AutomationRunner, "Setting up working directory");
            string workingDirectory = Path.Combine(ApplicationConstants.RelhaxTempFolderPath, Package.PackageName);

            if (Directory.Exists(workingDirectory))
            {
                Logging.Debug("Directory exits, delete");
                if (!await FileUtils.DirectoryDeleteAsync(workingDirectory, true, true))
                {
                    Logging.Error(LogOptions.ClassName, "Failed to clear the working directory");
                    return(false);
                }
            }
            Directory.CreateDirectory(workingDirectory);

            bool taskReturnGood = true;

            for (int index = 0; index < AutomationTasks.Count; index++)
            {
                AutomationTask task = AutomationTasks[index];
                RunningTask = task;
                bool breakLoop = false;
                Logging.Info(Logfiles.AutomationRunner, LogOptions.MethodName, "Running task: {0}", task.ID);
                try
                {
                    await task.Execute();
                }
                catch (Exception ex)
                {
                    if (task is ICancelOperation taskThatNeedsCancel)
                    {
                        taskThatNeedsCancel.Cancel();
                    }

                    if (!(ex is OperationCanceledException))
                    {
                        Logging.Exception(ex.ToString());
                    }
                }

                switch (task.ExitCode)
                {
                case AutomationExitCode.None:
                    breakLoop      = false;
                    taskReturnGood = true;
                    ExitCode       = SequencerExitCode.NoErrors;
                    break;

                case AutomationExitCode.Cancel:
                    breakLoop      = true;
                    taskReturnGood = true;
                    ExitCode       = SequencerExitCode.Cancel;
                    break;

                case AutomationExitCode.ComparisonNoFilesToUpdate:
                    breakLoop      = true;
                    taskReturnGood = true;
                    ExitCode       = SequencerExitCode.NoErrors;
                    break;

                case AutomationExitCode.ComparisonManualFilesToUpdate:
                    breakLoop      = true;
                    taskReturnGood = true;
                    ExitCode       = SequencerExitCode.NoErrors;
                    break;

                default:
                    Logging.Error(Logfiles.AutomationRunner, LogOptions.MethodName, "The task, '{0}', failed to execute. Check the task error output above for more details. You may want to enable verbose logging.", task.ID);
                    breakLoop      = true;
                    taskReturnGood = false;
                    ExitCode       = SequencerExitCode.Errors;
                    break;
                }

                if (CancellationToken.IsCancellationRequested)
                {
                    breakLoop      = true;
                    taskReturnGood = true;
                    ExitCode       = SequencerExitCode.Cancel;
                }

                if (breakLoop)
                {
                    break;
                }
            }

            //dispose/cleanup the tasks
            AutomationTasks.Clear();
            RunningTask = null;
            Logging.Info("Sequence {0} completed in {1} ms", PackageName, ExecutionTimeStopwatch.ElapsedMilliseconds);
            Dispose();
            return(taskReturnGood);
        }
    SetTasksToRun
    (
        AutomationTasks eTasksToRun
    )
    {
        AssertValid();

        CheckedListBox.ObjectCollection oItems = clbTasksToRun.Items;
        Int32 iItems = oItems.Count;
        m_bIgnoreItemCheckEvents = true;

        for (Int32 i = 0; i < iItems; i++)
        {
            clbTasksToRun.SetItemChecked(i, 
                ( eTasksToRun & ItemToAutomationTask( oItems[i] ) ) != 0);
        }

        m_bIgnoreItemCheckEvents = false;
    }
Esempio n. 14
0
        private bool PerformAutomationTask(IHTMLElementCollection col, AutomationTasks task, string elemname, string data)
        {
            bool bret = false;

            if (col == null) return bret;

            foreach (IHTMLElement elem in col)
            {
                if (elem != null)
                {
                    switch (task)
                    {
                        case AutomationTasks.ClickButton:
                            {
                                IHTMLInputElement btn = elem as IHTMLInputElement;
                                if ((btn != null) &&
                                    ((elem.id == elemname) ||(btn.name == elemname))
                                    )
                                {
                                    elem.click();
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.ClickLink:
                            {
                                IHTMLAnchorElement anchor = elem as IHTMLAnchorElement;
                                if( (anchor != null) &&
                                    ((elem.id == elemname) ||(anchor.name == elemname))
                                    )
                                {
                                    elem.click();
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.EnterData:
                            {
                                IHTMLInputElement inputelem = elem as IHTMLInputElement;
                                if( (inputelem != null) &&
                                    ((elem.id == elemname) ||(inputelem.name == elemname))
                                    )
                                {
                                    inputelem.value = data;
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.EnterDataTextArea:
                            {
                                IHTMLTextAreaElement txtarea = elem as IHTMLTextAreaElement;
                                if ((txtarea != null) &&
                                    ((elem.id == elemname) ||(txtarea.name == elemname))
                                    )
                                {
                                    txtarea.value = data;
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.SelectListItem:
                            {
                                IHTMLSelectElement selelem = elem as IHTMLSelectElement;
                                if( (selelem != null) &&
                                    ((elem.id == elemname) || (selelem.name == elemname))
                                    )
                                {
                                    //data can be value or text of the htmloptionelement
                                    // Obtain the number of option objects in the select object.
                                    int icount = selelem.length;
                                    IHTMLOptionElement optelem = null;
                                    for (int i = 0; i < icount; i++)
                                    {
                                        optelem = selelem.item(i, i) as IHTMLOptionElement;
                                        if (optelem != null)
                                        {
                                            if ((optelem.text == data) ||
                                                (optelem.value == data))
                                            {
                                                optelem.selected = true;
                                                return true;
                                            }
                                        }
                                    }
                                    return false;
                                }
                            }
                            break;
                        case AutomationTasks.SelectRadioButton:
                            {
                                IHTMLInputElement inputelem = elem as IHTMLInputElement;
                                if( (inputelem != null) && 
                                    ((elem.id == elemname) ||(inputelem.name == elemname))
                                    )
                                {
                                    inputelem.checkeda = true;
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.SubmitForm:
                            {
                                IHTMLFormElement form = elem as IHTMLFormElement;
                                if ((form != null) &&
                                   ((elem.id == elemname) ||(form.name == elemname))
                                    )
                                {
                                    form.submit();
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.SelectRadioButton2:
                            {
                                IHTMLInputElement inputelem = elem as IHTMLInputElement;
                                if ((inputelem != null) &&
                                   (((elem.id == elemname) || (inputelem.name == elemname)) &&
                                    (inputelem.value == data))
                                    )
                                {
                                    inputelem.checkeda = true;
                                    return true;
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } //End foreach

            return bret;
        }
Esempio n. 15
0
    AutomateOneWorkbook
    (
        ThisWorkbook thisWorkbook,
        NodeXLControl nodeXLControl,
        AutomationTasks tasksToRun,
        String folderToSaveWorkbookTo
    )
    {
        Debug.Assert(thisWorkbook != null);
        Debug.Assert(nodeXLControl != null);

        CheckTasksToRunArgument(ref tasksToRun);

        Microsoft.Office.Interop.Excel.Workbook oWorkbook =
            thisWorkbook.InnerObject;

        if
        (
            (
                ShouldRunTask(tasksToRun, AutomationTasks.MergeDuplicateEdges)
                &&
                !TryMergeDuplicateEdges(thisWorkbook)
            )
            ||
            (
                ShouldRunTask(tasksToRun, AutomationTasks.CalculateClusters)
                &&
                !TryCalculateClusters(thisWorkbook)
            )
            ||
            (
                ShouldRunTask(tasksToRun,
                    AutomationTasks.CalculateGraphMetrics)
                &&
                !TryCalculateGraphMetrics(oWorkbook)
            )
            ||
            (
                ShouldRunTask(tasksToRun, AutomationTasks.AutoFillWorkbook)
                &&
                !TryAutoFillWorkbook(thisWorkbook)
            )
            ||
            (
                ShouldRunTask(tasksToRun, AutomationTasks.CreateSubgraphImages)
                &&
                !TryCreateSubgraphImages(thisWorkbook)
            )
        )
        {
            return;
        }

        RunReadWorkbookTasks(thisWorkbook, nodeXLControl, tasksToRun,
            folderToSaveWorkbookTo);
    }
Esempio n. 16
0
    RunReadWorkbookTasks
    (
        ThisWorkbook oThisWorkbook,
        NodeXLControl oNodeXLControl,
        AutomationTasks eTasksToRun,
        String sFolderToSaveWorkbookTo
    )
    {
        Debug.Assert(oThisWorkbook != null);
        Debug.Assert(oNodeXLControl != null);

        Boolean bReadWorkbook = ShouldRunTask(
            eTasksToRun, AutomationTasks.ReadWorkbook);

        Boolean bSaveWorkbookIfNeverSaved = ShouldRunTask(
            eTasksToRun, AutomationTasks.SaveWorkbookIfNeverSaved);

        Boolean bSaveGraphImageFile = ShouldRunTask(
            eTasksToRun, AutomationTasks.SaveGraphImageFile);

        Boolean bExportToNodeXLGraphGallery = ShouldRunTask(
            eTasksToRun, AutomationTasks.ExportToNodeXLGraphGallery);

        Boolean bExportToEmail = ShouldRunTask(
            eTasksToRun, AutomationTasks.ExportToEmail);

        Microsoft.Office.Interop.Excel.Workbook oWorkbook =
            oThisWorkbook.InnerObject;

        if (bReadWorkbook)
        {
            // If the vertex X and Y columns were autofilled, the layout type
            // was set to LayoutType.Null.  This will cause
            // TaskPane.ReadWorkbook() to display a warning.  Temporarily turn
            // the warning off.

            Boolean bLayoutTypeIsNullNotificationsWereEnabled =
                EnableLayoutTypeIsNullNotifications(false);

            if (
                bSaveWorkbookIfNeverSaved
                ||
                bSaveGraphImageFile
                ||
                bExportToNodeXLGraphGallery
                ||
                bExportToEmail
                )
            {
                // These tasks need to wait until the workbook is read and the
                // graph is laid out.

                EventHandler<GraphLaidOutEventArgs> oGraphLaidOutEventHandler =
                    null;

                oGraphLaidOutEventHandler =
                    delegate(Object sender, GraphLaidOutEventArgs e)
                {
                    // This delegate remains forever, even when the dialog
                    // class is destroyed.  Prevent it from being called again.

                    oThisWorkbook.GraphLaidOut -= oGraphLaidOutEventHandler;

                    if (bSaveWorkbookIfNeverSaved)
                    {
                        if ( !TrySaveWorkbookIfNeverSaved(oWorkbook,
                            sFolderToSaveWorkbookTo) )
                        {
                            return;
                        }
                    }

                    if (bSaveGraphImageFile)
                    {
                        Debug.Assert( !String.IsNullOrEmpty(
                            oThisWorkbook.Path) );

                        SaveGraphImageFile(e.NodeXLControl, e.LegendControls,
                            oThisWorkbook.FullName);
                    }

                    if (bExportToNodeXLGraphGallery)
                    {
                        if ( !TryExportToNodeXLGraphGallery(
                            oThisWorkbook.InnerObject, oNodeXLControl) )
                        {
                            return;
                        }
                    }

                    if (bExportToEmail)
                    {
                        if ( !TryExportToEmail(
                            oThisWorkbook.InnerObject, oNodeXLControl) )
                        {
                            return;
                        }
                    }
                };

                oThisWorkbook.GraphLaidOut += oGraphLaidOutEventHandler;
            }

            // Read the workbook and lay out the graph.

            CommandDispatcher.SendNoParamCommand(oThisWorkbook,
                NoParamCommand.ShowGraphAndReadWorkbook);

            EnableLayoutTypeIsNullNotifications(
                bLayoutTypeIsNullNotificationsWereEnabled);
        }
        else
        {
            if (bSaveWorkbookIfNeverSaved)
            {
                if ( !TrySaveWorkbookIfNeverSaved(oWorkbook,
                    sFolderToSaveWorkbookTo) )
                {
                    return;
                }
            }
        }
    }
Esempio n. 17
0
 ShouldRunTask
 (
     AutomationTasks eTasksToRun,
     AutomationTasks eTaskToTest
 )
 {
     return ( (eTasksToRun & eTaskToTest) != 0 );
 }
Esempio n. 18
0
        RunReadWorkbookTasks
        (
            ThisWorkbook oThisWorkbook,
            NodeXLControl oNodeXLControl,
            AutomationTasks eTasksToRun,
            String sFolderToSaveWorkbookTo
        )
        {
            Debug.Assert(oThisWorkbook != null);
            Debug.Assert(oNodeXLControl != null);

            Boolean bReadWorkbook = ShouldRunTask(
                eTasksToRun, AutomationTasks.ReadWorkbook);

            Boolean bSaveWorkbookIfNeverSaved = ShouldRunTask(
                eTasksToRun, AutomationTasks.SaveWorkbookIfNeverSaved);

            Boolean bSaveGraphImageFile = ShouldRunTask(
                eTasksToRun, AutomationTasks.SaveGraphImageFile);

            Boolean bExportToNodeXLGraphGallery = ShouldRunTask(
                eTasksToRun, AutomationTasks.ExportToNodeXLGraphGallery);

            Boolean bExportToEmail = ShouldRunTask(
                eTasksToRun, AutomationTasks.ExportToEmail);

            Microsoft.Office.Interop.Excel.Workbook oWorkbook =
                oThisWorkbook.InnerObject;

            if (bReadWorkbook)
            {
                // If the vertex X and Y columns were autofilled, the layout type
                // was set to LayoutType.Null.  This will cause
                // TaskPane.ReadWorkbook() to display a warning.  Temporarily turn
                // the warning off.

                Boolean bLayoutTypeIsNullNotificationsWereEnabled =
                    EnableLayoutTypeIsNullNotifications(false);

                if (
                    bSaveWorkbookIfNeverSaved
                    ||
                    bSaveGraphImageFile
                    ||
                    bExportToNodeXLGraphGallery
                    ||
                    bExportToEmail
                    )
                {
                    // These tasks need to wait until the workbook is read and the
                    // graph is laid out.

                    EventHandler <GraphLaidOutEventArgs> oGraphLaidOutEventHandler =
                        null;

                    oGraphLaidOutEventHandler =
                        delegate(Object sender, GraphLaidOutEventArgs e)
                    {
                        // This delegate remains forever, even when the dialog
                        // class is destroyed.  Prevent it from being called again.

                        oThisWorkbook.GraphLaidOut -= oGraphLaidOutEventHandler;

                        if (bSaveWorkbookIfNeverSaved)
                        {
                            if (!TrySaveWorkbookIfNeverSaved(oWorkbook,
                                                             sFolderToSaveWorkbookTo))
                            {
                                return;
                            }
                        }

                        if (bSaveGraphImageFile)
                        {
                            Debug.Assert(!String.IsNullOrEmpty(
                                             oThisWorkbook.Path));

                            SaveGraphImageFile(e.NodeXLControl, e.LegendControls,
                                               oThisWorkbook.FullName);
                        }

                        if (bExportToNodeXLGraphGallery)
                        {
                            if (!TryExportToNodeXLGraphGallery(
                                    oThisWorkbook.InnerObject, oNodeXLControl))
                            {
                                return;
                            }
                        }

                        if (bExportToEmail)
                        {
                            if (!TryExportToEmail(
                                    oThisWorkbook.InnerObject, oNodeXLControl))
                            {
                                return;
                            }
                        }
                    };

                    oThisWorkbook.GraphLaidOut += oGraphLaidOutEventHandler;
                }

                // Read the workbook and lay out the graph.

                CommandDispatcher.SendNoParamCommand(oThisWorkbook,
                                                     NoParamCommand.ShowGraphAndReadWorkbook);

                EnableLayoutTypeIsNullNotifications(
                    bLayoutTypeIsNullNotificationsWereEnabled);
            }
            else
            {
                if (bSaveWorkbookIfNeverSaved)
                {
                    if (!TrySaveWorkbookIfNeverSaved(oWorkbook,
                                                     sFolderToSaveWorkbookTo))
                    {
                        return;
                    }
                }
            }
        }
Esempio n. 19
0
        //*************************************************************************
        //  Method: AutomateThisWorkbook()
        //
        /// <summary>
        /// Runs a specified set of tasks on one NodeXL workbook.
        /// </summary>
        ///
        /// <param name="thisWorkbook">
        /// The NodeXL workbook to run the tasks on.
        /// </param>
        ///
        /// <param name="tasksToRun">
        /// The tasks to run, as an ORed combination of <see
        /// cref="AutomationTasks" /> flags.
        /// </param>
        ///
        /// <param name="ribbon">
        /// The workbook's Ribbon.
        /// </param>
        //*************************************************************************
        public static void AutomateThisWorkbook(
            ThisWorkbook thisWorkbook,
            AutomationTasks tasksToRun,
            Ribbon ribbon
            )
        {
            Debug.Assert(thisWorkbook != null);
            Debug.Assert(ribbon != null);

            Microsoft.Office.Interop.Excel.Workbook oWorkbook =
            thisWorkbook.InnerObject;

            if ( (tasksToRun & AutomationTasks.MergeDuplicateEdges) != 0 )
            {
            // In general, automation is best performed by simulating a click
            // of a Ribbon button, thus avoiding any duplicate code.

            if ( !ribbon.OnMergeDuplicateEdgesClick(false) )
            {
                return;
            }
            }

            if ( (tasksToRun & AutomationTasks.CalculateGraphMetrics) != 0 )
            {
            // In this case, clicking the corresponding Ribbon button opens a
            // GraphMetricsDialog, which allows the user to edit the graph
            // metric settings before calculating the graph metrics.  The
            // actual calculations are done by CalculateGraphMetricsDialog, so
            // just use that dialog directly.

            CalculateGraphMetricsDialog oCalculateGraphMetricsDialog =
                new CalculateGraphMetricsDialog( oWorkbook,
                    new GraphMetricUserSettings() );

            if (oCalculateGraphMetricsDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            }

            if ( (tasksToRun & AutomationTasks.AutoFillWorkbook) != 0 )
            {
            // In this case, clicking the corresponding Ribbon button opens an
            // AutoFillWorkbookDialog, which allows the user to edit the
            // autofill settings before autofilling the workbook.  The actual
            // autofilling is done by WorkbookAutoFiller, so just use that
            // class directly.

            try
            {
                WorkbookAutoFiller.AutoFillWorkbook(
                    oWorkbook, new AutoFillUserSettings(oWorkbook) );

                ribbon.OnWorkbookAutoFilled(false);
            }
            catch (Exception oException)
            {
                ErrorUtil.OnException(oException);
                return;
            }
            }

            if ( (tasksToRun & AutomationTasks.CreateSubgraphImages) != 0 )
            {
            ribbon.OnCreateSubgraphImagesClick(
                CreateSubgraphImagesDialog.DialogMode.Automate);
            }

            if ( (tasksToRun & AutomationTasks.CalculateClusters) != 0 )
            {
            if ( !ribbon.OnCalculateClustersClick() )
            {
                return;
            }
            }

            if ( (tasksToRun & AutomationTasks.ReadWorkbook) != 0 )
            {
            // If the vertex X and Y columns were autofilled, the layout type
            // was set to LayoutType.Null.  This will cause
            // TaskPane.ReadWorkbook() to display a warning.  Temporarily turn
            // the warning off.

            NotificationUserSettings oNotificationUserSettings =
                new NotificationUserSettings();

            Boolean bOldLayoutTypeIsNull =
                oNotificationUserSettings.LayoutTypeIsNull;

            oNotificationUserSettings.LayoutTypeIsNull = false;
            oNotificationUserSettings.Save();

            if ( (tasksToRun & AutomationTasks.SaveGraphImageFile) != 0 )
            {
                if ( String.IsNullOrEmpty(thisWorkbook.Path) )
                {
                    throw new InvalidOperationException(
                        WorkbookNotSavedMessage);
                }

                // After the workbook is read and the graph is laid out, save
                // an image of the graph to a file.

                GraphLaidOutEventHandler oGraphLaidOutEventHandler = null;

                oGraphLaidOutEventHandler =
                    delegate(Object sender, GraphLaidOutEventArgs e)
                {
                    // This delegate remains forever, even when the dialog
                    // class is destroyed.  Prevent it from being called again.

                    thisWorkbook.GraphLaidOut -= oGraphLaidOutEventHandler;

                    SaveGraphImageFile(e.NodeXLControl, thisWorkbook.FullName);
                };

                thisWorkbook.GraphLaidOut += oGraphLaidOutEventHandler;
            }

            ribbon.OnReadWorkbookClick();

            oNotificationUserSettings.LayoutTypeIsNull = bOldLayoutTypeIsNull;
            oNotificationUserSettings.Save();
            }
        }
Esempio n. 20
0
        private bool GetElementByName(AutomationTasks task, string elemname, string data)
        {
            if( (this.m_WBWebBrowser2 == null) ||
                string.IsNullOrEmpty(elemname) )
                return false;
            bool result = false;

            IHTMLDocument2 doc2 = this.m_WBWebBrowser2.Document as IHTMLDocument2;
            if (doc2 == null)
                return false;
            IHTMLElementCollection col = null;

            if (this.IsWBFrameset(doc2))
            {
                List<IWebBrowser2> frames = this.GetFrames(this.m_WBWebBrowser2);
                if (frames == null)
                    return false;
                foreach (IWebBrowser2 wb in frames)
                {
                    if (task == AutomationTasks.ClickLink)
                    {
                        IHTMLDocument2 framedoc = wb.Document as IHTMLDocument2;
                        if (framedoc == null)
                            continue;
                        col = framedoc.anchors as IHTMLElementCollection;
                    }
                    else if (task == AutomationTasks.SelectListItem)
                    {
                        IHTMLDocument3 doc3 = wb.Document as IHTMLDocument3;
                        if (doc3 == null)
                            continue;
                        col = doc3.getElementsByTagName("select") as IHTMLElementCollection;
                    }
                    else if (task == AutomationTasks.EnterDataTextArea)
                    {
                        IHTMLDocument3 doc3 = wb.Document as IHTMLDocument3;
                        if (doc3 == null)
                            continue;
                        col = doc3.getElementsByTagName("textarea") as IHTMLElementCollection;
                    }
                    else if (task == AutomationTasks.SubmitForm)
                    {
                        IHTMLDocument2 framedoc = wb.Document as IHTMLDocument2;
                        if (framedoc == null)
                            continue;
                        col = framedoc.forms as IHTMLElementCollection;
                    }
                    else
                    {
                        IHTMLDocument3 doc3 = wb.Document as IHTMLDocument3;
                        if (doc3 == null)
                            continue;
                        col = doc3.getElementsByTagName("input") as IHTMLElementCollection;
                    }

                    if (col == null)
                        continue;
                    result = this.PerformAutomationTask(col, task, elemname, data);
                    if (result)
                        return result;
                }
            }
            else
            {
                if (task == AutomationTasks.ClickLink)
                {
                    col = doc2.anchors as IHTMLElementCollection;
                }
                else if (task == AutomationTasks.SelectListItem)
                {
                    IHTMLDocument3 doc3 = this.m_WBWebBrowser2.Document as IHTMLDocument3;
                    if (doc3 == null)
                        return result;
                    col = doc3.getElementsByTagName("select") as IHTMLElementCollection;
                }
                else if (task == AutomationTasks.EnterDataTextArea)
                {
                    IHTMLDocument3 doc3 = this.m_WBWebBrowser2.Document as IHTMLDocument3;
                    if (doc3 == null)
                        return result;
                    col = doc3.getElementsByTagName("textarea") as IHTMLElementCollection;
                }
                else if (task == AutomationTasks.SubmitForm)
                {
                    IHTMLDocument2 framedoc = this.m_WBWebBrowser2.Document as IHTMLDocument2;
                    if (framedoc == null)
                        return result;
                    col = framedoc.forms as IHTMLElementCollection;
                }
                else
                {
                    IHTMLDocument3 doc3 = this.m_WBWebBrowser2.Document as IHTMLDocument3;
                    if (doc3 == null)
                        return result;
                    col = doc3.getElementsByTagName("input") as IHTMLElementCollection;
                }
                if (col == null)
                    return result;
                result = this.PerformAutomationTask(col, task, elemname, data);
            }
            return result;
        }
Esempio n. 21
0
        AutomateFolder
        (
            String folderToAutomate,
            AutomationTasks tasksToRun,
            Microsoft.Office.Interop.Excel.Application application
        )
        {
            Debug.Assert(!String.IsNullOrEmpty(folderToAutomate));
            Debug.Assert(application != null);

            foreach (String sFileName in Directory.GetFiles(folderToAutomate,
                                                            "*.xlsx"))
            {
                String sFilePath = Path.Combine(folderToAutomate, sFileName);

                try
                {
                    if (!NodeXLWorkbookUtil.FileIsNodeXLWorkbook(sFilePath))
                    {
                        continue;
                    }
                }
                catch (IOException)
                {
                    // Skip any workbooks that are already open, or that have any
                    // other problems that prevent them from being opened.

                    continue;
                }

                // Ideally, the Excel API would be used here to open the workbook
                // and run the AutomateThisWorkbook() method on it.  Two things
                // make that impossible:
                //
                //   1. When you open a workbook using
                //      Application.Workbooks.Open(), you get only a native Excel
                //      workbook, not an "extended" ThisWorkbook object or its
                //      associated Ribbon object.  AutomateThisWorkbook() requires
                //      a Ribbon object.
                //
                //      Although a GetVstoObject() extension method is available to
                //      convert a native Excel workbook to an extended workbook,
                //      that method doesn't work on a native workbook opened via
                //      the Excel API -- it always returns null.
                //
                //      It might be possible to refactor AutomateThisWorkbook() to
                //      require only a native workbook.  However, problem 2 would
                //      still make things impossible...
                //
                //   2. If this method is being run from a modal dialog, which it
                //      is (see AutomateTasksDialog), then code in the workbook
                //      that needs to be automated doesn't run until the modal
                //      dialog closes.
                //
                // The following code works around these problems.

                try
                {
                    // Store an "automate tasks on open" flag in the workbook,
                    // indicating that task automation should be run on it the next
                    // time it's opened.  This can be done via the Excel API.

                    Microsoft.Office.Interop.Excel.Workbook oWorkbookToAutomate =
                        ExcelUtil.OpenWorkbook(sFilePath, application);

                    PerWorkbookSettings oPerWorkbookSettings =
                        new PerWorkbookSettings(oWorkbookToAutomate);

                    oPerWorkbookSettings.AutomateTasksOnOpen = true;
                    oWorkbookToAutomate.Save();
                    oWorkbookToAutomate.Close(false, Missing.Value, Missing.Value);

                    // Now open the workbook in another instance of Excel, which
                    // bypasses problem 2.  Code in the workbook's Ribbon will
                    // detect the flag's presence, run task automation on it, close
                    // the workbook, and close the other instance of Excel.

                    OpenWorkbookToAutomate(sFilePath);
                }
                catch (Exception oException)
                {
                    ErrorUtil.OnException(oException);
                    return;
                }
            }
        }
Esempio n. 22
0
        private bool PerformAutomationTask(IHTMLElementCollection col, AutomationTasks task, string elemname, string data)
        {
            bool bret = false;

            if (col == null) return bret;

            foreach (IHTMLElement elem in col)
            {
                if (elem != null)
                {
                    switch (task)
                    {
                        case AutomationTasks.ClickButton:
                            {
                                IHTMLInputElement btn = elem as IHTMLInputElement;
                                if ((btn != null) &&
                                    (btn.name == elemname))
                                {
                                    elem.click();
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.ClickLink:
                            {
                                IHTMLAnchorElement anchor = elem as IHTMLAnchorElement;
                                if( (anchor != null) &&
                                    (anchor.name == elemname))
                                {
                                    elem.click();
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.EnterData:
                            {
                                IHTMLInputElement inputelem = elem as IHTMLInputElement;
                                if( (inputelem != null) &&
                                    (inputelem.name == elemname) )
                                {
                                    inputelem.value = data;
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.EnterDataTextArea:
                            {
                                IHTMLTextAreaElement txtarea = elem as IHTMLTextAreaElement;
                                if ((txtarea != null) &&
                                    (txtarea.name == elemname))
                                {
                                    txtarea.value = data;
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.SelectListItem:
                            {
                                IHTMLSelectElement selelem = elem as IHTMLSelectElement;
                                if( (selelem != null) &&
                                    (selelem.name == elemname) )
                                {
                                    selelem.value = data;
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.SelectRadioButton:
                            {
                                IHTMLInputElement inputelem = elem as IHTMLInputElement;
                                if( (inputelem != null) &&
                                    (inputelem.name == elemname) )
                                {
                                    inputelem.checkeda = true;
                                    return true;
                                }
                            }
                            break;
                        case AutomationTasks.SubmitForm:
                            {
                                IHTMLFormElement form = elem as IHTMLFormElement;
                                if ((form != null) &&
                                    (form.name == elemname))
                                {
                                    form.submit();
                                    return true;
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } //End foreach

            return bret;
        }
Esempio n. 23
0
        DoDataExchange
        (
            Boolean bFromControls
        )
        {
            AssertValid();

            if (bFromControls)
            {
                AutomationTasks eTasksToRun = AutomationTasks.None;

                // An AutomationTasks flag is stored in the Tag of each CheckBox.

                foreach (CheckBox oCheckBox in GetAutomationTaskCheckBoxes())
                {
                    if (oCheckBox.Checked)
                    {
                        eTasksToRun |= (AutomationTasks)oCheckBox.Tag;
                    }
                }

                if (eTasksToRun == AutomationTasks.None)
                {
                    this.ShowWarning("No tasks have been selected.");
                    return(false);
                }

                Boolean bAutomateThisWorkbookOnly =
                    radAutomateThisWorkbookOnly.Checked;

                if ((eTasksToRun & AutomationTasks.SaveGraphImageFile) != 0)
                {
                    if ((eTasksToRun & AutomationTasks.ReadWorkbook) == 0)
                    {
                        this.ShowWarning(
                            "You can't save an image to a file without first"
                            + " showing the graph.  Either check \"Show workbook\""
                            + " or uncheck \"Save image to file.\""
                            );

                        return(false);
                    }

                    if (bAutomateThisWorkbookOnly &&
                        String.IsNullOrEmpty(m_oThisWorkbook.Path))
                    {
                        this.ShowWarning(TaskAutomator.WorkbookNotSavedMessage);
                        return(false);
                    }
                }

                if (!bAutomateThisWorkbookOnly)
                {
                    if (!usrFolderToAutomate.Validate())
                    {
                        return(false);
                    }
                }

                m_oAutomateTasksUserSettings.TasksToRun = eTasksToRun;

                m_oAutomateTasksUserSettings.AutomateThisWorkbookOnly =
                    bAutomateThisWorkbookOnly;

                m_oAutomateTasksUserSettings.FolderToAutomate =
                    usrFolderToAutomate.FolderPath;
            }
            else
            {
                AutomationTasks eTasksToRun =
                    m_oAutomateTasksUserSettings.TasksToRun;

                foreach (CheckBox oCheckBox in GetAutomationTaskCheckBoxes())
                {
                    oCheckBox.Checked =
                        (eTasksToRun & (AutomationTasks)oCheckBox.Tag) != 0;
                }

                if (m_oAutomateTasksUserSettings.AutomateThisWorkbookOnly)
                {
                    radAutomateThisWorkbookOnly.Checked = true;
                }
                else
                {
                    radAutomateFolder.Checked = true;
                }

                usrFolderToAutomate.FolderPath =
                    m_oAutomateTasksUserSettings.FolderToAutomate;

                EnableControls();
            }

            return(true);
        }
Esempio n. 24
0
        //*************************************************************************
        //  Method: AutomateFolder()
        //
        /// <summary>
        /// Runs a specified set of tasks on every unopened NodeXL workbook in a
        /// folder.
        /// </summary>
        ///
        /// <param name="folderToAutomate">
        /// Path to the folder to automate.
        /// </param>
        ///
        /// <param name="tasksToRun">
        /// The tasks to run on each unopened NodeXL workbook in the folder, as an
        /// ORed combination of <see cref="AutomationTasks" /> flags.
        /// </param>
        ///
        /// <param name="application">
        /// The Excel application for the workbook calling this method.
        /// </param>
        //*************************************************************************
        public static void AutomateFolder(
            String folderToAutomate,
            AutomationTasks tasksToRun,
            Microsoft.Office.Interop.Excel.Application application
            )
        {
            Debug.Assert( !String.IsNullOrEmpty(folderToAutomate) );
            Debug.Assert(application != null);

            foreach ( String sFileName in Directory.GetFiles(folderToAutomate,
            "*.xlsx") )
            {
            String sFilePath = Path.Combine(folderToAutomate, sFileName);

            try
            {
                if (!NodeXLWorkbookUtil.FileIsNodeXLWorkbook(sFilePath))
                {
                    continue;
                }
            }
            catch (IOException)
            {
                // Skip any workbooks that are already open, or that have any
                // other problems that prevent them from being opened.

                continue;
            }

            // Ideally, the Excel API would be used here to open the workbook
            // and run the AutomateThisWorkbook() method on it.  Two things
            // make that impossible:
            //
            //   1. When you open a workbook using
            //      Application.Workbooks.Open(), you get only a native Excel
            //      workbook, not an "extended" ThisWorkbook object or its
            //      associated Ribbon object.  AutomateThisWorkbook() requires
            //      a Ribbon object.
            //
            //      Although a GetVstoObject() extension method is available to
            //      convert a native Excel workbook to an extended workbook,
            //      that method doesn't work on a native workbook opened via
            //      the Excel API -- it always returns null.
            //
            //      It might be possible to refactor AutomateThisWorkbook() to
            //      require only a native workbook.  However, problem 2 would
            //      still make things impossible...
            //
            //   2. If this method is being run from a modal dialog, which it
            //      is (see AutomateTasksDialog), then code in the workbook
            //      that needs to be automated doesn't run until the modal
            //      dialog closes.
            //
            // The following code works around these problems.

            try
            {
                // Store an "automate tasks on open" flag in the workbook,
                // indicating that task automation should be run on it the next
                // time it's opened.  This can be done via the Excel API.

                Microsoft.Office.Interop.Excel.Workbook oWorkbookToAutomate =
                    ExcelUtil.OpenWorkbook(sFilePath, application);

                PerWorkbookSettings oPerWorkbookSettings =
                    new PerWorkbookSettings(oWorkbookToAutomate);

                oPerWorkbookSettings.AutomateTasksOnOpen = true;
                oWorkbookToAutomate.Save();
                oWorkbookToAutomate.Close(false, Missing.Value, Missing.Value);

                // Now open the workbook in another instance of Excel, which
                // bypasses problem 2.  Code in the workbook's Ribbon will
                // detect the flag's presence, run task automation on it, close
                // the workbook, and close the other instance of Excel.

                OpenWorkbookToAutomate(sFilePath);
            }
            catch (Exception oException)
            {
                ErrorUtil.OnException(oException);
                return;
            }
            }
        }
Esempio n. 25
0
    CheckTasksToRunArgument
    (
        ref AutomationTasks eTasksToRun
    )
    {
        // Here are the various AutomationTasks flag dependencies:
        //
        // SaveGraphImageFile requires ReadWorkbook, because you can't save an
        // image of a graph that hasn't been shown yet.
        //
        // SaveGraphImageFile requires SaveWorkbookIfNeverSaved, because the
        // image is saved to a folder and the folder isn't determined until the
        // workbook is saved.
        //
        // ExportToNodeXLGraphGallery and ExportToEmail require ReadWorkbook,
        // because you can't export an image of a graph that hasn't been shown
        // yet.
        //
        // ExportToNodeXLGraphGallery and ExportToEmail require
        // SaveWorkbookIfNeverSaved, because the title or subject of the
        // exported graph is the workbook's file name.

        if ( ShouldRunTask(eTasksToRun,

            AutomationTasks.SaveGraphImageFile
            |
            AutomationTasks.ExportToNodeXLGraphGallery
            |
            AutomationTasks.ExportToEmail
            ) )
        {
            // The SaveWorkbookIfNeverSaved flag was introduced after the
            // SaveGraphImageFile flag, so it's possible to have an older
            // workbook that has SaveGraphImageFile set without the necessary
            // SaveWorkbookIfNeverSaved flag.  Fix this.
            //
            // The ExportToNodeXLGraphGallery and ExportToEmail flags were
            // introduced after all the others, so the dialogs that use this
            // class should ensure that ReadWorkbook and
            // SaveWorkbookIfNeverSaved are specified if
            // ExportToNodeXLGraphGallery is set.  Set it anyway, in case there
            // are any unforseen circumstances where this isn't done.

            eTasksToRun |=
                (
                AutomationTasks.ReadWorkbook
                |
                AutomationTasks.SaveWorkbookIfNeverSaved
                );
        }
    }