Example #1
0
        SelectEdgeOrVertexTableRows
        (
            Boolean bSelectEdgeTableRows
        )
        {
            AssertValid();

            Sheets1And2Helper oSheets1And2Helper = bSelectEdgeTableRows ?
                                                   m_oEdgeWorksheet.Sheets1And2Helper :
                                                   m_oVertexWorksheet.Sheets1And2Helper;

            if (!oSheets1And2Helper.TableExists)
            {
                return;
            }

            m_bIgnoreSelectionEvents = true;

            try
            {
                oSheets1And2Helper.SelectTableRowsByRowIDs(bSelectEdgeTableRows ?
                                                           m_oTaskPane.GetSelectedEdgeRowIDs() :
                                                           m_oTaskPane.GetSelectedVertexRowIDs()
                                                           );
            }
            catch (Exception oException)
            {
                ErrorUtil.OnException(oException);
            }
            finally
            {
                m_bIgnoreSelectionEvents = false;
            }
        }
Example #2
0
        SelectGroupTableRows()
        {
            AssertValid();

            SheetHelper oSheetHelper = m_oGroupWorksheet.SheetHelper;

            if (!oSheetHelper.TableExists)
            {
                return;
            }

            m_bIgnoreSelectionEvents = true;

            try
            {
                oSheetHelper.SelectTableRowsByColumnValues <String>(
                    GroupTableColumnNames.Name,
                    m_oTaskPane.GetSelectedCollapsedGroupNames(),
                    ExcelUtil.TryGetNonEmptyStringFromCell
                    );
            }
            catch (Exception oException)
            {
                ErrorUtil.OnException(oException);
            }
            finally
            {
                m_bIgnoreSelectionEvents = false;
            }
        }
        ConvertNodeXLWorkbook
        (
            String sOtherWorkbookFile,
            String sConvertedWorkbookFile
        )
        {
            AssertValid();
            Debug.Assert(!String.IsNullOrEmpty(sOtherWorkbookFile));
            Debug.Assert(!String.IsNullOrEmpty(sConvertedWorkbookFile));

            try
            {
                NodeXLWorkbookConverter.ConvertNodeXLWorkbook(sOtherWorkbookFile,
                                                              sConvertedWorkbookFile);
            }
            catch (NodeXLWorkbookConversionException
                   oNodeXLWorkbookConversionException)
            {
                this.ShowWarning(oNodeXLWorkbookConversionException.Message);

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

                return(false);
            }

            return(true);
        }
Example #4
0
        GetRequiredTables
        (
            Microsoft.Office.Interop.Excel.Workbook oWorkbook,
            out ListObject oEdgeTable,
            out ListObject oVertexTable
        )
        {
            Debug.Assert(oWorkbook != null);
            AssertValid();

            // Get the required table that contains edge data.  GetEdgeTable()
            // checks for the required vertex name columns.

            EdgeWorksheetReader oEdgeWorksheetReader = new EdgeWorksheetReader();

            oEdgeTable = oEdgeWorksheetReader.GetEdgeTable(oWorkbook);

            // Normally, the vertex table isn't required, but to avoid having to
            // create the table in code if it's missing, require it here.

            if (ExcelUtil.TryGetTable(oWorkbook, WorksheetNames.Vertices,
                                      TableNames.Vertices, out oVertexTable))
            {
                // Make sure the vertex name column exists.

                ListColumn oColumn;

                if (!ExcelUtil.TryGetTableColumn(oVertexTable,
                                                 VertexTableColumnNames.VertexName, out oColumn))
                {
                    oVertexTable = null;
                }
            }
            else
            {
                oVertexTable = null;
            }

            if (oVertexTable == null)
            {
                throw new WorkbookFormatException(String.Format(

                                                      "To use this feature, there must be a worksheet named \"{0}\""
                                                      + " that contains a table named \"{1}\", and that table must"
                                                      + " contain a column named \"{2}\"."
                                                      + "\r\n\r\n"
                                                      + "{3}"
                                                      ,
                                                      WorksheetNames.Vertices,
                                                      TableNames.Vertices,
                                                      VertexTableColumnNames.VertexName,
                                                      ErrorUtil.GetTemplateMessage()
                                                      ));
            }
        }
Example #5
0
        GetEdgeTable
        (
            Microsoft.Office.Interop.Excel.Workbook workbook
        )
        {
            Debug.Assert(workbook != null);
            AssertValid();

            // Get the worksheet that contains edge data.

            Worksheet oEdgeWorksheet;

            if (!ExcelUtil.TryGetWorksheet(workbook, WorksheetNames.Edges,
                                           out oEdgeWorksheet))
            {
                OnWorkbookFormatError(String.Format(

                                          "The workbook must contain a worksheet named \"{0}\" that"
                                          + " contains edge data.\r\n\r\n{1}"
                                          ,
                                          WorksheetNames.Edges,
                                          ErrorUtil.GetTemplateMessage()
                                          ));
            }

            // Get the table (ListObject) that contains edge data.

            ListObject oEdgeTable;

            if (!ExcelUtil.TryGetTable(oEdgeWorksheet, TableNames.Edges,
                                       out oEdgeTable))
            {
                OnWorkbookFormatError(String.Format(

                                          "The worksheet named \"{0}\" must have a table named \"{1}\""
                                          + " that contains edge data.\r\n\r\n{2}"
                                          ,
                                          WorksheetNames.Edges,
                                          TableNames.Edges,
                                          ErrorUtil.GetTemplateMessage()
                                          ));
            }

            // Make sure the vertex name columns exist.

            GetTableColumnIndex(oEdgeTable, EdgeTableColumnNames.Vertex1Name,
                                true);

            GetTableColumnIndex(oEdgeTable, EdgeTableColumnNames.Vertex2Name,
                                true);

            return(oEdgeTable);
        }
        StartImageCreation()
        {
            AssertValid();

            // Read the workbook into a new IGraph.

            IGraph oGraph;

            try
            {
                oGraph = ReadWorkbook(m_oWorkbook);
            }
            catch (Exception oException)
            {
                ErrorUtil.OnException(oException);
                this.State = DialogState.Idle;

                return;
            }

            lblStatus.Text = "Creating subgraph images.";

            ICollection <IVertex> oSelectedVertices = new IVertex[0];

            if (m_oCreateSubgraphImagesDialogUserSettings.SelectedVerticesOnly)
            {
                // Get the vertices corresponding to the selected rows in the
                // vertex worksheet.

                oSelectedVertices = GetSelectedVertices(
                    oGraph, m_oSelectedVertexNames);
            }

            m_oSubgraphImageCreator.CreateSubgraphImagesAsync(
                oGraph,
                oSelectedVertices,
                m_oCreateSubgraphImagesDialogUserSettings.Levels,
                m_oCreateSubgraphImagesDialogUserSettings.SaveToFolder,
                m_oCreateSubgraphImagesDialogUserSettings.Folder,
                m_oCreateSubgraphImagesDialogUserSettings.ImageSizePx,
                m_oCreateSubgraphImagesDialogUserSettings.ImageFormat,
                m_oCreateSubgraphImagesDialogUserSettings.InsertThumbnails,
                m_oCreateSubgraphImagesDialogUserSettings.ThumbnailSizePx,
                m_oCreateSubgraphImagesDialogUserSettings.SelectedVerticesOnly,
                m_oCreateSubgraphImagesDialogUserSettings.SelectVertex,
                m_oCreateSubgraphImagesDialogUserSettings.SelectIncidentEdges,
                new GeneralUserSettings(),
                new LayoutUserSettings()
                );
        }
Example #7
0
        btnOK_Click
        (
            object sender,
            System.EventArgs e
        )
        {
            if (!DoDataExchange(true))
            {
                return;
            }

            m_oAutomateTasksUserSettings.Save();

            try
            {
                if (m_oAutomateTasksUserSettings.AutomateThisWorkbookOnly)
                {
                    TaskAutomator.AutomateThisWorkbook(m_oThisWorkbook,
                                                       m_oAutomateTasksUserSettings.TasksToRun, m_oRibbon);
                }
                else
                {
                    TaskAutomator.AutomateFolder(
                        m_oAutomateTasksUserSettings.FolderToAutomate,
                        m_oAutomateTasksUserSettings.TasksToRun,
                        m_oThisWorkbook.Application);
                }
            }
            catch (UnauthorizedAccessException oUnauthorizedAccessException)
            {
                // This occurs when a workbook is read-only.

                this.ShowWarning(
                    "A problem occurred while running tasks.  Details:"
                    + "\r\n\r\n"
                    + oUnauthorizedAccessException.Message
                    );

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

            this.DialogResult = DialogResult.OK;
            this.Close();
        }
        OnLoad
        (
            EventArgs e
        )
        {
            AssertValid();

            base.OnLoad(e);

            // Start the calculations.

            try
            {
                if (m_oGraphMetricCalculators != null)
                {
                    // Use the specified graph metric calculators.

                    m_oGraphMetricCalculationManager.CalculateGraphMetricsAsync(
                        m_oWorkbook, m_oGraphMetricCalculators,
                        m_oGraphMetricUserSettings);
                }
                else
                {
                    // Use a default list of graph metric calculators.

                    m_oGraphMetricCalculationManager.CalculateGraphMetricsAsync(
                        m_oWorkbook, m_oGraphMetricUserSettings);
                }
            }
            catch (Exception oException)
            {
                // An exception was thrown from the synchronous code within
                // CalculateGraphMetricsAsync().  (Exceptions thrown from the
                // asynchronous code are handled by the
                // GraphMetricCalculationCompleted event handler.)

                ErrorUtil.OnException(oException);

                this.Close();
            }
        }
        GraphMetricCalculationManager_GraphMetricCalculationCompleted
        (
            object sender,
            RunWorkerCompletedEventArgs e
        )
        {
            AssertValid();

            Exception oException = e.Error;

            if (oException != null)
            {
                if (oException is GraphMetricException)
                {
                    // This is a known exception.

                    this.ShowWarning(oException.Message);
                }
                else
                {
                    // The exception is unexpected.

                    ErrorUtil.OnException(oException);
                }
            }
            else if (!e.Cancelled)
            {
                Debug.Assert(e.Result is GraphMetricColumn[]);

                WriteGraphMetricColumnsToWorkbook(
                    ( GraphMetricColumn[] )e.Result);

                // Everything succeeded.

                this.DialogResult = DialogResult.OK;
            }

            this.Close();
        }
        WriteGraphMetricColumnsToWorkbook
        (
            GraphMetricColumn [] aoGraphMetricColumns
        )
        {
            Debug.Assert(aoGraphMetricColumns != null);
            AssertValid();

            Microsoft.Office.Interop.Excel.Application oApplication =
                m_oWorkbook.Application;

            GraphMetricWriter oGraphMetricWriter = new GraphMetricWriter();

            oApplication.ScreenUpdating = false;

            try
            {
                oGraphMetricWriter.WriteGraphMetricColumnsToWorkbook(
                    aoGraphMetricColumns, m_oWorkbook);

                // Let the user know that graph metrics have been calculated.

                oGraphMetricWriter.ActivateRelevantWorksheet(
                    aoGraphMetricColumns, m_oWorkbook);
            }
            catch (Exception oException)
            {
                oApplication.ScreenUpdating = true;

                ErrorUtil.OnException(oException);

                this.Close();
                return;
            }

            oApplication.ScreenUpdating = true;
        }
Example #11
0
        btnOK_Click
        (
            object sender,
            System.EventArgs e
        )
        {
            AssertValid();

            if (!DoDataExchange(true))
            {
                return;
            }

            this.Cursor = Cursors.WaitCursor;
            Exception oExpectedException = null;

            try
            {
                OpenUcinetFile();
            }
            catch (IOException oIOException)
            {
                oExpectedException = oIOException;
            }
            catch (UnauthorizedAccessException oUnauthorizedAccessException)
            {
                oExpectedException = oUnauthorizedAccessException;
            }
            catch (FormatException oFormatException)
            {
                oExpectedException = oFormatException;
            }
            catch (Exception oUnexpectedException)
            {
                ErrorUtil.OnException(oUnexpectedException);
                return;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

            if (oExpectedException != null)
            {
                String sMessage =
                    "The file could not be opened.  Details:\n\n"
                    + oExpectedException.Message;

                if (oExpectedException is FormatException)
                {
                    sMessage +=
                        "\n\nThis does not appear to be a UCINET full matrix DL"
                        + " file.  "
                        + FormatMessage
                    ;
                }

                this.ShowWarning(sMessage);
                return;
            }

            DialogResult = DialogResult.OK;
            this.Close();
        }
Example #12
0
        AddColumnPair
        (
            Microsoft.Office.Interop.Excel.Workbook workbook,
            String worksheetName,
            String tableName,
            String column1NameBase,
            Single column1WidthChars,
            String column2NameBase,
            Single column2WidthChars
        )
        {
            Debug.Assert(workbook != null);
            Debug.Assert(!String.IsNullOrEmpty(worksheetName));
            Debug.Assert(!String.IsNullOrEmpty(tableName));
            Debug.Assert(!String.IsNullOrEmpty(column1NameBase));
            Debug.Assert(column1WidthChars > 0);
            Debug.Assert(!String.IsNullOrEmpty(column2NameBase));
            Debug.Assert(column2WidthChars > 0);
            AssertValid();

            ListObject oTable;

            if (!ExcelUtil.TryGetTable(workbook, worksheetName, tableName,
                                       out oTable))
            {
                throw new WorkbookFormatException(String.Format(

                                                      "To use this feature, there must be a worksheet named \"{0}\""
                                                      + " that contains a table named \"{1}\"."
                                                      + "\r\n\r\n"
                                                      + "{2}"
                                                      ,
                                                      worksheetName,
                                                      tableName,
                                                      ErrorUtil.GetTemplateMessage()
                                                      ));
            }

            Int32 iMaximumAppendedNumber = Math.Max(
                GetMaximumAppendedNumber(oTable, column1NameBase),
                GetMaximumAppendedNumber(oTable, column2NameBase)
                );

            if (iMaximumAppendedNumber != 0)
            {
                String sStringToAppend =
                    " " + (iMaximumAppendedNumber + 1).ToString();

                column1NameBase += sStringToAppend;
                column2NameBase += sStringToAppend;
            }

            ListColumn oListColumn1, oListColumn2;

            if (
                !ExcelUtil.TryAddTableColumn(oTable, column1NameBase,
                                             column1WidthChars, null, out oListColumn1)
                ||
                !ExcelUtil.TryAddTableColumn(oTable, column2NameBase,
                                             column2WidthChars, null, out oListColumn2)
                )
            {
                FormUtil.ShowWarning("The columns weren't added.");
            }

            ExcelUtil.ActivateWorksheet(oTable);
        }
Example #13
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();
            }
        }
        OnImageCreationCompleted
        (
            RunWorkerCompletedEventArgs e
        )
        {
            AssertValid();

            if (e.Cancelled)
            {
                this.State = DialogState.Idle;

                lblStatus.Text = "Image creation stopped.";
            }
            else if (e.Error != null)
            {
                this.State = DialogState.Idle;

                Exception oException = e.Error;

                if (oException is System.IO.IOException)
                {
                    lblStatus.Text = "Image creation error.";

                    this.ShowWarning(oException.Message);
                }
                else
                {
                    ErrorUtil.OnException(oException);
                }
            }
            else
            {
                // Success.  Were temporary images created that need to be inserted
                // into the vertex worksheet?

                Debug.Assert(e.Result is TemporaryImages);

                TemporaryImages oTemporaryImages = (TemporaryImages)e.Result;

                if (oTemporaryImages.Folder != null)
                {
                    // Yes.  Insert them, then delete the temporary images.

                    this.State = DialogState.PopulatingImageColumn;

                    String sLastStatusFromSubgraphImageCreator = lblStatus.Text;

                    lblStatus.Text =
                        "Inserting subgraph thumbnails into the worksheet.  Please"
                        + " wait...";

                    TableImagePopulator.PopulateColumnWithImages(m_oWorkbook,
                                                                 WorksheetNames.Vertices, TableNames.Vertices,
                                                                 VertexTableColumnNames.SubgraphImage,
                                                                 VertexTableColumnNames.VertexName, oTemporaryImages
                                                                 );

                    lblStatus.Text = sLastStatusFromSubgraphImageCreator;
                }

                this.State = DialogState.Idle;

                if (m_eMode == DialogMode.Automate)
                {
                    this.Close();
                }
            }
        }
Example #15
0
        OnEdgeOrVertexTableSelectionChange
        (
            Boolean bChangeInEdgeTable
        )
        {
            AssertValid();

            Sheets1And2Helper oSheets1And2Helper = bChangeInEdgeTable ?
                                                   m_oEdgeWorksheet.Sheets1And2Helper :
                                                   m_oVertexWorksheet.Sheets1And2Helper;

            if (IgnoreTableSelectionChange(oSheets1And2Helper))
            {
                return;
            }

            m_bIgnoreSelectionEvents = true;

            try
            {
                // (The following comments are for the bChangeInEdgeTable=true
                // case.

                // Get an array of unique row IDs for all edge rows that have at
                // least one cell selected.

                ICollection <Int32> oSelectedRowIDs =
                    oSheets1And2Helper.GetSelectedRowIDs();

                // Select those edges (and possibly their adjacent vertices) in the
                // TaskPane.  This will cause the TaskPane.SelectionChangedInGraph
                // event to fire, but this class will ignore it because
                // m_bIgnoreSelectionEvents is currently set to true.

                if (bChangeInEdgeTable)
                {
                    m_oTaskPane.SetSelectedEdgesByRowID(oSelectedRowIDs);
                }
                else
                {
                    m_oTaskPane.SetSelectedVerticesByRowID(oSelectedRowIDs);
                }

                // The selection in the vertex table may now be out of sync with
                // the TaskPane.  Ideally, the vertex table would be updated right
                // now.  However, you can't select rows in a worksheet that isn't
                // active.  As a workaround, set a flag that will cause the
                // selection in the vertex table to be updated the next time the
                // vertex worksheet is activated.
                //
                // It would be possible to avoid deferring the selection by turning
                // off screen updating and temporarily selecting the vertex
                // worksheet.  Selecting a worksheet is slow, however, even with
                // screen updating turned off.  It takes about 250ms on a fast
                // machine.  That's too slow to keep up with the user if he is
                // scrolling through a table with the down-arrow key, for example.

                if (bChangeInEdgeTable)
                {
                    m_bUpdateVertexSelectionOnActivation = true;
                }
                else
                {
                    m_bUpdateEdgeSelectionOnActivation = true;
                }

                // Selecting an edge or vertex invalidates any selected groups.

                m_bUpdateGroupSelectionOnActivation = true;

                // Enable the "set visual attribute" buttons in the Ribbon.

                m_oThisWorkbook.EnableSetVisualAttributes();
            }
            catch (COMException)
            {
                // A user reported a bug in which Application.Intersect() throws a
                // COMException with an HRESULT of 0x800AC472.
                // (Application.Intersect() gets called indirectly by
                // OnSelectionChangedInTable().)  The bug occurred while switching
                // windows.  I couldn't reproduce the bug, but the following post
                // suggests that the HRESULT, which is VBA_E_IGNORE, occurs when an
                // object model call is made while the object model is "suspended."
                //
                // http://social.msdn.microsoft.com/forums/en-US/vsto/thread/
                // 9168f9f2-e5bc-4535-8d7d-4e374ab8ff09/
                //
                // Other posts also mention that it can occur during window
                // switches.
                //
                // I can't reproduce the bug and I'm not sure of the root cause,
                // but catching and ignoring the error should lead to nothing worse
                // than a mouse click being ignored.
            }
            catch (Exception oException)
            {
                ErrorUtil.OnException(oException);
            }
            finally
            {
                m_bIgnoreSelectionEvents = false;
            }
        }
Example #16
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;
                }
            }
        }
Example #17
0
        Open()
        {
            Debug.Assert(m_oDynamicFilterSettingsTable == null);
            AssertValid();

            // Get the table that contains the dynamic filter settings.

            if (!ExcelUtil.TryGetTable(m_oWorkbook, WorksheetNames.Miscellaneous,
                                       TableNames.DynamicFilterSettings,
                                       out m_oDynamicFilterSettingsTable))
            {
                OnWorkbookFormatError(String.Format(

                                          "A table that is required to use this feature is missing."
                                          + "\r\n\r\n{0}"
                                          ,
                                          ErrorUtil.GetTemplateMessage()
                                          ));
            }

            // Read the table.

            Range oDataBodyRange;

            if (!ExcelUtil.TryGetVisibleTableRange(
                    m_oDynamicFilterSettingsTable, out oDataBodyRange))
            {
                // The table is empty.  This is not an error.

                return;
            }

            // The table is hidden, so no one should ever be able to filter its
            // rows.

            Debug.Assert(oDataBodyRange.Areas.Count == 1);

            // Get the indexes of the columns within the table.

            DynamicFilterSettingsTableColumnIndexes
                oDynamicFilterSettingsTableColumnIndexes =
                GetDynamicFilterSettingsTableColumnIndexes(
                    m_oDynamicFilterSettingsTable);

            // The table contains one row per dynamic filter.  Loop through the
            // rows.

            Int32 iRows = oDataBodyRange.Rows.Count;

            Object [,] aoValues = ExcelUtil.GetRangeValues(oDataBodyRange);

            Range oSelectedMinimumCell =
                ((Range)oDataBodyRange.Cells[1, 1]).get_Offset(0,
                                                               oDynamicFilterSettingsTableColumnIndexes.SelectedMinimum - 1);

            Range oSelectedMaximumCell =
                ((Range)oDataBodyRange.Cells[1, 1]).get_Offset(0,
                                                               oDynamicFilterSettingsTableColumnIndexes.SelectedMaximum - 1);

            for (Int32 iRowOneBased = 1; iRowOneBased <= iRows; iRowOneBased++)
            {
                String sTableName, sColumnName;
                Double dSelectedMinimum, dSelectedMaximum;

                if (
                    ExcelUtil.TryGetNonEmptyStringFromCell(aoValues, iRowOneBased,
                                                           oDynamicFilterSettingsTableColumnIndexes.TableName,
                                                           out sTableName)
                    &&
                    ExcelUtil.TryGetNonEmptyStringFromCell(aoValues, iRowOneBased,
                                                           oDynamicFilterSettingsTableColumnIndexes.ColumnName, false,
                                                           out sColumnName)
                    &&
                    ExcelUtil.TryGetDoubleFromCell(aoValues, iRowOneBased,
                                                   oDynamicFilterSettingsTableColumnIndexes.SelectedMinimum,
                                                   out dSelectedMinimum)
                    &&
                    ExcelUtil.TryGetDoubleFromCell(aoValues, iRowOneBased,
                                                   oDynamicFilterSettingsTableColumnIndexes.SelectedMaximum,
                                                   out dSelectedMaximum)
                    )
                {
                    // Create a SettingsForOneFilter object for each filter and
                    // store it in a dictionary.

                    SettingsForOneFilter oSettingsForOneFilter =
                        new SettingsForOneFilter();

                    oSettingsForOneFilter.SelectedMinimum =
                        (Decimal)dSelectedMinimum;

                    oSettingsForOneFilter.SelectedMaximum =
                        (Decimal)dSelectedMaximum;

                    oSettingsForOneFilter.SelectedMinimumAddress =
                        ExcelUtil.GetRangeAddressAbsolute(oSelectedMinimumCell);

                    oSettingsForOneFilter.SelectedMaximumAddress =
                        ExcelUtil.GetRangeAddressAbsolute(oSelectedMaximumCell);

                    m_oDynamicFilterSettingsDictionary.Add(
                        GetDictionaryKey(sTableName, sColumnName),
                        oSettingsForOneFilter);
                }

                oSelectedMinimumCell = oSelectedMinimumCell.get_Offset(1, 0);
                oSelectedMaximumCell = oSelectedMaximumCell.get_Offset(1, 0);
            }
        }
Example #18
0
        AutoFillByVertexCategory
        (
            Microsoft.Office.Interop.Excel.Workbook oWorkbook,
            Microsoft.Office.Interop.Excel.ListObject oEdgeTable,
            Microsoft.Office.Interop.Excel.ListObject oVertexTable,
            String sVertexCategoryColumnName,
            Boolean bShowVertexLabels,
            String sVertexLabelColumnName
        )
        {
            Debug.Assert(oWorkbook != null);
            Debug.Assert(oEdgeTable != null);
            Debug.Assert(oVertexTable != null);
            Debug.Assert(!String.IsNullOrEmpty(sVertexCategoryColumnName));

            Debug.Assert(!bShowVertexLabels ||
                         !String.IsNullOrEmpty(sVertexLabelColumnName));

            Range oVisibleCategoryRange = null;
            Range oVisibleShapeRange    = null;
            Range oVisibleColorRange    = null;
            Range oVisibleRadiusRange   = null;;

            if (
                !ExcelUtil.TryGetVisibleTableColumnData(oVertexTable,
                                                        sVertexCategoryColumnName, out oVisibleCategoryRange)
                ||
                !ExcelUtil.TryGetVisibleTableColumnData(oVertexTable,
                                                        VertexTableColumnNames.Shape, out oVisibleShapeRange)
                ||
                !ExcelUtil.TryGetVisibleTableColumnData(oVertexTable,
                                                        VertexTableColumnNames.Color, out oVisibleColorRange)
                ||
                !ExcelUtil.TryGetVisibleTableColumnData(oVertexTable,
                                                        VertexTableColumnNames.Radius, out oVisibleRadiusRange)
                )
            {
                ErrorUtil.OnMissingColumn();
            }

            // Loop through the visible areas to create a dictionary of categories.
            // The key is a unique category name and the value is a scheme index.
            // If the category column contains three unique categories, for
            // example, the dictionary entries will look like this:
            //
            // Category A, 0
            // Category B, 1
            // Category C, 2

            Dictionary <String, Int32> oCategoryDictionary =
                new Dictionary <String, Int32>();

            Areas oCategoryAreas = oVisibleCategoryRange.Areas;
            Int32 iAreas         = oCategoryAreas.Count;
            Int32 iSchemeIndex   = 0;

            for (Int32 iArea = 1; iArea <= iAreas; iArea++)
            {
                Object [,] aoCategoryValues = ExcelUtil.GetRangeValues(
                    oCategoryAreas[iArea]);

                Int32  iRows = aoCategoryValues.GetUpperBound(0);
                String sCategory;

                for (Int32 iRow = 1; iRow <= iRows; iRow++)
                {
                    if (ExcelUtil.TryGetNonEmptyStringFromCell(aoCategoryValues,
                                                               iRow, 1, out sCategory))
                    {
                        if (!oCategoryDictionary.ContainsKey(sCategory))
                        {
                            oCategoryDictionary[sCategory] = iSchemeIndex;
                            iSchemeIndex++;
                        }
                    }
                }
            }

            // Scheme index that will be used for vertices that have an empty
            // category cell.

            Int32 SchemeIndexForNoCategory = iSchemeIndex;

            Areas oShapeAreas  = oVisibleShapeRange.Areas;
            Areas oColorAreas  = oVisibleColorRange.Areas;
            Areas oRadiusAreas = oVisibleRadiusRange.Areas;

            Debug.Assert(oShapeAreas.Count == iAreas);
            Debug.Assert(oColorAreas.Count == iAreas);
            Debug.Assert(oRadiusAreas.Count == iAreas);

            ColorConverter2 oColorConverter2 = new ColorConverter2();

            VertexShapeConverter oVertexShapeConverter =
                new VertexShapeConverter();

            // Loop through the visible areas again, this time to fill in the
            // vertex shape, color, and radius columns.

            for (Int32 iArea = 1; iArea <= iAreas; iArea++)
            {
                Object [,] aoCategoryValues = ExcelUtil.GetRangeValues(
                    oCategoryAreas[iArea]);

                Range oShapeArea  = oShapeAreas[iArea];
                Range oColorArea  = oColorAreas[iArea];
                Range oRadiusArea = oRadiusAreas[iArea];

                Object [,] aoShapeValues  = ExcelUtil.GetRangeValues(oShapeArea);
                Object [,] aoColorValues  = ExcelUtil.GetRangeValues(oColorArea);
                Object [,] aoRadiusValues = ExcelUtil.GetRangeValues(oRadiusArea);

                Int32 iRows = aoCategoryValues.GetUpperBound(0);

                Debug.Assert(aoShapeValues.GetUpperBound(0) == iRows);
                Debug.Assert(aoColorValues.GetUpperBound(0) == iRows);
                Debug.Assert(aoRadiusValues.GetUpperBound(0) == iRows);

                String sCategory;

                for (Int32 iRow = 1; iRow <= iRows; iRow++)
                {
                    if (ExcelUtil.TryGetNonEmptyStringFromCell(aoCategoryValues,
                                                               iRow, 1, out sCategory))
                    {
                        iSchemeIndex = oCategoryDictionary[sCategory];
                    }
                    else
                    {
                        iSchemeIndex = SchemeIndexForNoCategory;
                    }

                    VertexShape eShape;
                    Color       oColor;
                    Single      fRadius;

                    GetVertexCategoryScheme(iSchemeIndex, out eShape, out oColor,
                                            out fRadius);

                    aoShapeValues[iRow, 1] =
                        oVertexShapeConverter.GraphToWorkbook(eShape);

                    // Write the color in a format that is understood by
                    // ColorConverter.ConvertFromString(), which is what
                    // WorksheetReaderBase uses.

                    aoColorValues[iRow, 1] =
                        oColorConverter2.GraphToWorkbook(oColor);

                    aoRadiusValues[iRow, 1] = fRadius;
                }

                oShapeArea.set_Value(Missing.Value, aoShapeValues);
                oColorArea.set_Value(Missing.Value, aoColorValues);
                oRadiusArea.set_Value(Missing.Value, aoRadiusValues);
            }

            // Fill in other columns with constants.

            FillColumnsWithConstants(

                oVertexTable, CommonTableColumnNames.Alpha,
                AlphaConverter.MaximumAlphaWorkbook,

                oEdgeTable, EdgeTableColumnNames.Color,
                oColorConverter2.GraphToWorkbook(
                    Color.FromArgb(179, 179, 179)),

                oEdgeTable, EdgeTableColumnNames.Width, 1.0F,

                oEdgeTable, CommonTableColumnNames.Alpha,
                AlphaConverter.MaximumAlphaWorkbook
                );

            // Save the results.

            SaveVertexCategoryResults(oWorkbook, sVertexCategoryColumnName,
                                      oCategoryDictionary);
        }
Example #19
0
        btnCustomizeVertexMenu_Click
        (
            object sender,
            EventArgs e
        )
        {
            AssertValid();

            const String Message =
                "Use this to add custom menu items to the menu that appears when"
                + " you right-click a vertex in the NodeXL graph."
                + "\r\n\r\n"
                + "Clicking \"Yes\" below will add a pair of columns to the"
                + " Vertices worksheet -- one for menu item text and another for"
                + " the action to take when the menu item is selected."
                + "\r\n\r\n"
                + "For example, if you add the column pair and enter \"Send Mail"
                + " To\" for a vertex's menu item text and \"mailto:[email protected]\""
                + " for the action, then right-clicking the vertex in the NodeXL"
                + " graph and selecting \"Send Mail To\" from the right-click menu"
                + " will open a new email message addressed to [email protected]."
                + "\r\n\r\n"
                + "If you want to open a Web page when the menu item is selected,"
                + " enter an URL for the action."
                + "\r\n\r\n"
                + "If you want to add more than one custom menu item to a vertex's"
                + " right-click menu, run this again to add another pair of"
                + " columns."
                + "\r\n\r\n"
                + "Do you want to add a pair of columns to the Vertices worksheet?"
            ;

            if (MessageBox.Show(Message, this.ApplicationName,
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information) !=
                DialogResult.Yes)
            {
                return;
            }

            // Create and use the object that adds the columns to the vertex
            // table.

            TableColumnAdder oTableColumnAdder = new TableColumnAdder();

            this.UseWaitCursor = true;

            try
            {
                oTableColumnAdder.AddColumnPair(m_oWorkbook,
                                                WorksheetNames.Vertices, TableNames.Vertices,
                                                VertexTableColumnNames.CustomMenuItemTextBase,
                                                VertexTableColumnWidths.CustomMenuItemText,
                                                VertexTableColumnNames.CustomMenuItemActionBase,
                                                VertexTableColumnWidths.CustomMenuItemAction
                                                );

                this.UseWaitCursor = false;
            }
            catch (Exception oException)
            {
                this.UseWaitCursor = false;

                ErrorUtil.OnException(oException);
            }
        }
Example #20
0
        ImportGraph
        (
            IGraph sourceGraph,
            String [] edgeAttributes,
            String [] vertexAttributes,
            Boolean clearTablesFirst,
            Microsoft.Office.Interop.Excel.Workbook destinationNodeXLWorkbook
        )
        {
            Debug.Assert(sourceGraph != null);
            Debug.Assert(destinationNodeXLWorkbook != null);
            AssertValid();

            if (clearTablesFirst)
            {
                NodeXLWorkbookUtil.ClearAllNodeXLTables(destinationNodeXLWorkbook);
            }

            // Get the required table that contains edge data.  GetEdgeTable()
            // throws an exception if the table is missing.

            EdgeWorksheetReader oEdgeWorksheetReader = new EdgeWorksheetReader();

            ListObject oEdgeTable =
                oEdgeWorksheetReader.GetEdgeTable(destinationNodeXLWorkbook);

            // Get the required columns.

            Range oVertex1NameColumnData = null;
            Range oVertex2NameColumnData = null;

            if (
                !ExcelUtil.TryGetTableColumnData(oEdgeTable,
                                                 EdgeTableColumnNames.Vertex1Name, out oVertex1NameColumnData)
                ||
                !ExcelUtil.TryGetTableColumnData(oEdgeTable,
                                                 EdgeTableColumnNames.Vertex2Name, out oVertex2NameColumnData)
                )
            {
                ErrorUtil.OnMissingColumn();
            }

            // Import the edges and their attributes into the workbook.

            ImportEdges(sourceGraph, edgeAttributes, oEdgeTable,
                        oVertex1NameColumnData, oVertex2NameColumnData, !clearTablesFirst);

            // Populate the vertex worksheet with the name of each unique vertex in
            // the edge worksheet.

            (new VertexWorksheetPopulator()).PopulateVertexWorksheet(
                destinationNodeXLWorkbook, false);

            // Get the table that contains vertex data.

            ListObject oVertexTable;
            Range      oVertexNameColumnData = null;
            Range      oVisibilityColumnData = null;

            if (
                !ExcelUtil.TryGetTable(destinationNodeXLWorkbook,
                                       WorksheetNames.Vertices, TableNames.Vertices, out oVertexTable)
                ||
                !ExcelUtil.TryGetTableColumnData(oVertexTable,
                                                 VertexTableColumnNames.VertexName, out oVertexNameColumnData)
                ||
                !ExcelUtil.TryGetTableColumnData(oVertexTable,
                                                 CommonTableColumnNames.Visibility, out oVisibilityColumnData)
                )
            {
                ErrorUtil.OnMissingColumn();
            }

            // Import isolated vertices and the attributes for all the graph's
            // vertices.

            ImportVertices(sourceGraph, vertexAttributes, oVertexTable,
                           oVertexNameColumnData, oVisibilityColumnData);
        }
Example #21
0
        CheckForUpdate()
        {
            // Get the version of the installed version of the application.

            FileVersionInfo oCurrentFileVersionInfo =
                AssemblyUtil2.GetFileVersionInfo();

            // Get the version information for the latest version of the
            // application.

            Int32 iLatestVersionFileMajorPart   = 0;
            Int32 iLatestVersionFileMinorPart   = 0;
            Int32 iLatestVersionFileBuildPart   = 0;
            Int32 iLatestVersionFilePrivatePart = 0;

            try
            {
                GetLatestVersionInfo(out iLatestVersionFileMajorPart,
                                     out iLatestVersionFileMinorPart,
                                     out iLatestVersionFileBuildPart,
                                     out iLatestVersionFilePrivatePart
                                     );
            }
            catch (WebException)
            {
                FormUtil.ShowWarning(
                    "The Web site from which updates are obtained could not be"
                    + " reached.  Either an Internet connection isn't available,"
                    + " or the Web site isn't available."
                    );

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

                return;
            }

            if (
                iLatestVersionFileMajorPart > oCurrentFileVersionInfo.FileMajorPart
                ||
                iLatestVersionFileMinorPart > oCurrentFileVersionInfo.FileMinorPart
                ||
                iLatestVersionFileBuildPart > oCurrentFileVersionInfo.FileBuildPart
                ||
                iLatestVersionFilePrivatePart >
                oCurrentFileVersionInfo.FilePrivatePart
                )
            {
                String sMessage = String.Format(

                    "A new version of {0} is available.  Do you want to open the"
                    + " Web page from which the new version can be downloaded?"
                    ,
                    FormUtil.ApplicationName
                    );

                if (MessageBox.Show(sMessage, FormUtil.ApplicationName,
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Information) ==
                    DialogResult.Yes)
                {
                    Process.Start(ProjectInformation.DownloadPageUrl);
                }
            }
            else
            {
                FormUtil.ShowInformation(String.Format(

                                             "You have the latest version of {0}."
                                             ,
                                             FormUtil.ApplicationName
                                             ));
            }
        }