示例#1
0
        private static void DrawCube(DocCube docCube, bool withSysDims)
        {
            Visio.Shape cubeShape = adaptPage.Drop(visioCubeMaster, posX > 6 ? posX = 1.25 : posX += 1.5, posX == 1.25 ? posY += 1.5 : posY);

            // set font size for CubeShape
            cubeShape.Shapes[2].CellsSRC[(short)Visio.VisSectionIndices.visSectionCharacter,
                                         (short)Visio.VisRowIndices.visRowCharacter,
                                         (short)Visio.VisCellIndices.visCharacterSize].Formula = "=7 pt.";

            cubeShape.Text = docCube.name;
            cubeShape.Name = docCube.name;

            // get DimShape
            Visio.Shape   dimShape = cubeShape.Shapes[1];
            StringBuilder dims     = new StringBuilder();

            foreach (DocDimension docDim in docCube.dims)
            {
                if (withSysDims || !docDim.name.StartsWith("}", StringComparison.OrdinalIgnoreCase))
                {
                    dims.AppendLine(docDim.name);
                }
            }

            // set font size for DimShape
            dimShape.CellsSRC[(short)Visio.VisSectionIndices.visSectionCharacter,
                              (short)Visio.VisRowIndices.visRowCharacter,
                              (short)Visio.VisCellIndices.visCharacterSize].Formula = "=5 pt.";

            // write dims to DimShape
            dimShape.Text = dims.ToString();

            cubeList.Add(cubeShape);
        }
示例#2
0
        /// <summary>
        /// Draws an Architecture Chart on the given outputPage from the nodes given.
        /// </summary>
        /// <param name="outputPage">Page to draw the chart.</param>
        /// <param name="root">Root node of the chart.</param>
        /// <param name="inputs">Inputs for the Input Node.</param>
        /// <param name="process">Processes for the Process Node.</param>
        /// <param name="outputs">Outputs for the Output Node.</param>
        private void outputChart(Visio.Page outputPage, Visio.Shape root, List <Visio.Shape> inputs,
                                 List <Visio.Shape> process, List <Visio.Shape> outputs)
        {
            // Space to leave open between shapes
            double yPad = .5, xPad = .1;

            // sets the first open position to start dropping shapes onto the page
            // into the field variables drawXPos, drawYPos.
            setShapeDropPosition(outputPage);

            // Get a Rectangle Master from the OOSD General Stencil to serve
            // as the container for each Node in the chart.
            Visio.Master nodeMaster = Utilities.getMasterFromStencil(app, CaseTypes.OOSD_GENERAL_STENCIL,
                                                                     CaseTypes.OOSD_RECTANGLE);

            // Root of the Architecture Chart
            Visio.Shape transformRoot = outputPage.Drop(nodeMaster, drawXPos, drawYPos);
            transformRoot.Text = root.Text;

            // Use the root node width and height as the basis for performing layout
            double nodeHeight = transformRoot.Cells["Height"].Result["inches"];
            double nodeWidth  = transformRoot.Cells["Width"].Result["inches"];

            // Root of the Process subtree, set it directly under transform center root.
            drawYPos -= nodeHeight / 2 + yPad;
            Visio.Shape processRoot = outputPage.Drop(nodeMaster, drawXPos, drawYPos);
            processRoot.Text = @"Process";

            // Root of the Input subtree, set to left of Process Root
            Visio.Shape inputRoot = outputPage.Drop(nodeMaster, drawXPos - (nodeWidth * 3), drawYPos);
            inputRoot.Text = @"Input";

            // Root of the Output subtree, set to right of Process Root
            Visio.Shape outputRoot = outputPage.Drop(nodeMaster, drawXPos + (nodeWidth * 3), drawYPos);
            outputRoot.Text = @"Output";

            // Calculate starting position of the first Input child node based on
            // the number of all children (input, process, output) and the nodeWidth
            // Set the start y position as the next level down
            drawYPos -= nodeHeight / 2 + yPad;
            int    childrenCount = inputs.Count + process.Count + outputs.Count;
            double totalWidth    = childrenCount * (nodeWidth + xPad);

            drawXPos = drawXPos - (totalWidth / 2) + (nodeWidth / 2) + xPad;

            double             pad             = nodeWidth + xPad; // distance from one center of a shape to another center
            List <Visio.Shape> inputChildren   = dropShapes(outputPage, nodeMaster, inputs, pad);
            List <Visio.Shape> processChildren = dropShapes(outputPage, nodeMaster, process, pad);
            List <Visio.Shape> outputChildren  = dropShapes(outputPage, nodeMaster, outputs, pad);

            // Connects all shapes together to form tree
            glueRootToChildren(outputPage, transformRoot,
                               new List <Visio.Shape>()
            {
                inputRoot, processRoot, outputRoot
            });
            glueRootToChildren(outputPage, inputRoot, inputChildren);
            glueRootToChildren(outputPage, processRoot, processChildren);
            glueRootToChildren(outputPage, outputRoot, outputChildren);
        }
示例#3
0
        private void addShapes2()
        {
            //this.Application.Documents.Add(@"Basic Diagram.vst");
            //<Snippet13>
            this.Application.Documents.Add("");

            Visio.Documents visioDocs    = this.Application.Documents;
            Visio.Document  visioStencil = visioDocs.OpenEx("Basic Shapes.vss",
                                                            (short)Microsoft.Office.Interop.Visio.VisOpenSaveArgs.visOpenDocked);

            Visio.Page visioPage = this.Application.ActivePage;

            Visio.Master visioRectMaster = visioStencil.Masters.get_ItemU(@"Rectangle");
            Visio.Shape  visioRectShape  = visioPage.Drop(visioRectMaster, 4.25, 5.5);
            visioRectShape.Text = @"Rectangle text.";

            Visio.Master visioStarMaster = visioStencil.Masters.get_ItemU(@"Star 7");
            Visio.Shape  visioStarShape  = visioPage.Drop(visioStarMaster, 2.0, 5.5);
            visioStarShape.Text = @"Star text.";

            Visio.Master visioHexagonMaster = visioStencil.Masters.get_ItemU(@"Hexagon");
            Visio.Shape  visioHexagonShape  = visioPage.Drop(visioHexagonMaster, 7.0, 5.5);
            visioHexagonShape.Text = @"Hexagon text.";
            //</Snippet13>
        }
示例#4
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Visio.Application vsdApp = null;
            Visio.Document    vsdDoc = null;

            //Create Visio Application Object
            vsdApp = Application;

            //Make Visio Application Invisible
            vsdApp.Visible = false;

            //Create a document object and load a diagram
            vsdDoc = vsdApp.Documents.Open("Add Shapes.vdx");

            Visio.Documents visioDocs    = this.Application.Documents;
            Visio.Document  visioStencil = visioDocs.OpenEx("Basic Shapes.vss",
                                                            (short)Microsoft.Office.Interop.Visio.VisOpenSaveArgs.visOpenDocked);

            Visio.Page visioPage = this.Application.ActivePage;

            Visio.Master visioRectMaster = visioStencil.Masters.get_ItemU(@"Rectangle");
            Visio.Shape  visioRectShape  = visioPage.Drop(visioRectMaster, 4.25, 5.5);
            visioRectShape.Text = @"Rectangle text.";

            Visio.Master visioStarMaster = visioStencil.Masters.get_ItemU(@"Star 7");
            Visio.Shape  visioStarShape  = visioPage.Drop(visioStarMaster, 2.0, 5.5);
            visioStarShape.Text = @"Star text.";

            Visio.Master visioHexagonMaster = visioStencil.Masters.get_ItemU(@"Hexagon");
            Visio.Shape  visioHexagonShape  = visioPage.Drop(visioHexagonMaster, 7.0, 5.5);
            visioHexagonShape.Text = @"Hexagon text.";
        }
        public static void Run()
        {
            // ExStart:CreatingDiagramWithVSTO
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_KnowledgeBase();

            Visio.Application vdxApp = null;
            Visio.Document    vdxDoc = null;
            try
            {
                // Create Visio Application Object
                vdxApp = new Visio.Application();

                // Make Visio Application Invisible
                vdxApp.Visible = false;

                // Create a new diagram
                vdxDoc = vdxApp.Documents.Add("");

                // Load Visio Stencil
                Visio.Documents visioDocs    = vdxApp.Documents;
                Visio.Document  visioStencil = visioDocs.OpenEx("Basic Shapes.vss",
                                                                (short)Microsoft.Office.Interop.Visio.VisOpenSaveArgs.visOpenHidden);

                // Set active page
                Visio.Page visioPage = vdxApp.ActivePage;

                // Add a new rectangle shape
                Visio.Master visioRectMaster = visioStencil.Masters.get_ItemU(@"Rectangle");
                Visio.Shape  visioRectShape  = visioPage.Drop(visioRectMaster, 4.25, 5.5);
                visioRectShape.Text = @"Rectangle text.";

                // Add a new star shape
                Visio.Master visioStarMaster = visioStencil.Masters.get_ItemU(@"Star 7");
                Visio.Shape  visioStarShape  = visioPage.Drop(visioStarMaster, 2.0, 5.5);
                visioStarShape.Text = @"Star text.";

                // Add a new hexagon shape
                Visio.Master visioHexagonMaster = visioStencil.Masters.get_ItemU(@"Hexagon");
                Visio.Shape  visioHexagonShape  = visioPage.Drop(visioHexagonMaster, 7.0, 5.5);
                visioHexagonShape.Text = @"Hexagon text.";


                // Save diagram as VDX
                vdxDoc.SaveAs(dataDir + "CreatingDiagramWithVSTO_Out.vdx");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx.");
            }

            // ExEnd:CreatingDiagramWithVSTO
        }
示例#6
0
        /// <summary>
        /// Connects a fromShape to a toShape using a Dynamic Connector.
        /// </summary>
        /// <param name="page">Page to drop the Shapes in.</param>
        /// <param name="fromShape">The Shape to start the connection at.</param>
        /// <param name="toShape">The Shape to end the connection at.</param>
        /// <param name="fromXPercent">
        /// X coordinate (in percent of the fromShape's width) to Glue</param>
        /// <param name="fromYPercent">
        /// Y coordinate (in percent of the fromShape's height) to Glue.</param>
        /// <param name="toXPercent">
        /// X coordinate (in percent of the toShape's width) to Glue.</param>
        /// <param name="toYPercent">
        /// X coordinate (in percent of the toShape's width) to Glue.</param>
        public static void glueShapesWithDynamicConnector(Visio.Page page, Visio.Shape fromShape, Visio.Shape toShape,
                                                          double fromXPercent, double fromYPercent, double toXPercent, double toYPercent)
        {
            Visio.Documents appDocuments = page.Application.Documents;

            // We only want to get the Dynamic Connector Master from the Stencil,
            // so keep the stencil hidden since user won't need to use it.
            Visio.Document stencil = getStencil(appDocuments, CaseTypes.OOSD_GENERAL_STENCIL,
                                                Visio.VisOpenSaveArgs.visOpenHidden);

            Visio.Master connectorMaster = stencil.Masters[CaseTypes.OOSD_CONNECTOR];
            Visio.Shape  connector       = page.Drop(connectorMaster, 0, 0);

            // The Dynamic Connector has an end point and a begin point, which are
            // the glue points used to connect to shapes. These points are stored
            // in the 1-D Endpoints Shapesheet section.
            Visio.Cell beginCell = connector.get_CellsSRC(
                (short)Visio.VisSectionIndices.visSectionObject,
                (short)Visio.VisRowIndices.visRowXForm1D,
                (short)Visio.VisCellIndices.vis1DBeginX);
            Visio.Cell endCell = connector.get_CellsSRC(
                (short)Visio.VisSectionIndices.visSectionObject,
                (short)Visio.VisRowIndices.visRowXForm1D,
                (short)Visio.VisCellIndices.vis1DEndX);

            // Connect the connector end points to the from and to shapes
            beginCell.GlueToPos(fromShape, fromXPercent, fromYPercent);
            endCell.GlueToPos(toShape, toXPercent, toYPercent);
        }
示例#7
0
        /// <summary>
        /// Процедура отображения ребер графа в документе Visio
        /// </summary>
        /// <param name="visioDocs">Документы Visio</param>
        /// <param name="visioPage">Текущая страница в Visio</param>
        private void PresentEdges(Visio.Documents visioDocs, Visio.Page visioPage)
        {
            Visio.Document visioConnectors = visioDocs.OpenEx("Basic Flowchart Shapes (US units).vss", (short)Visio.VisOpenSaveArgs.visOpenDocked);

            // Соединение вершин графа ребрами
            for (int i = 0; i < graph.VerticesEdges.Count(); ++i)
            {
                // Ребро
                var edge = graph.VerticesEdges.ElementAt(i);

                // Фигура соединидельной линии (коннектора)
                Visio.Shape connector = visioPage.Drop(visioConnectors.Masters.get_ItemU("Dynamic connector"), 0, 0);
                connector.get_Cells("ConLineRouteExt").FormulaU = "2";
                connector.get_Cells("EndArrow").Formula         = "=5";

                // Стили ребра
                string label     = edge.Attributes.ContainsKey("label") ? edge.Attributes["label"] : "";
                string color     = edge.Attributes.ContainsKey("color") ? edge.Attributes["color"] : "black";
                string linestyle = edge.Attributes.ContainsKey("style") ? LineStyle(edge.Attributes["style"].ToLower()) : "1";

                // Установка стилей для фигуры на странице Visio
                connector.Text = label;
                connector.get_CellsU("LineColor").FormulaU   = VisioColor.ColorToRgb(color.ToLower());
                connector.get_CellsU("LinePattern").FormulaU = linestyle;

                // Соединение вершин при помощи данного коннектора
                vertices[edge.Source].AutoConnect(vertices[edge.Destination], Visio.VisAutoConnectDir.visAutoConnectDirDown, connector);

                edges.Add(edge, vertices[edge.Source].FromConnects[vertices[edge.Source].FromConnects.Count].FromSheet);

                // Удаление коннектора-болванки
                connector.Delete();
            }
        }
示例#8
0
        //Arrows: 0=Standard, 1 = keine, 2= beide
        private static void ConnectWithDynamicGlueAndConnector(Visio.Shape shapeFrom, Visio.Shape shapeTo, int arrows)
        {
            // if (!cubeList.Contains(shapeFrom) || !cubeList.Contains(shapeTo))
            //     return;

            Visio.Cell  beginXCell;
            Visio.Cell  endXCell;
            Visio.Cell  beginArrow;
            Visio.Cell  endArrow;
            Visio.Shape connector;

            // Add a Dynamic connector to the page.
            connector = page.Drop(visioConnectorMaster, 0, 0);

            beginArrow = connector.get_CellsSRC(
                (short)Visio.VisSectionIndices.visSectionObject,
                (short)Visio.VisRowIndices.visRowLine,
                (short)Visio.VisCellIndices.visLineBeginArrow);

            endArrow = connector.get_CellsSRC(
                (short)Visio.VisSectionIndices.visSectionObject,
                (short)Visio.VisRowIndices.visRowLine,
                (short)Visio.VisCellIndices.visLineEndArrow);


            if (arrows == 1)
            {
                endArrow.FormulaU = "0";
            }
            if (arrows == 2)
            {
                beginArrow.FormulaU = "4";
            }

            // Connect the begin point.
            beginXCell = connector.get_CellsSRC(
                (short)Visio.VisSectionIndices.visSectionObject,
                (short)Visio.VisRowIndices.visRowXForm1D,
                (short)Visio.VisCellIndices.vis1DBeginX);

            beginXCell.GlueTo(shapeFrom.get_CellsSRC(
                                  (short)Visio.VisSectionIndices.visSectionConnectionPts,
                                  (short)1,
                                  (short)Visio.VisCellIndices.visCnnctX));

            // Connect the end point.
            endXCell = connector.get_CellsSRC(
                (short)Visio.VisSectionIndices.visSectionObject,
                (short)Visio.VisRowIndices.visRowXForm1D,
                (short)Visio.VisCellIndices.vis1DEndX);

            endXCell.GlueTo(shapeTo.get_CellsSRC(
                                (short)Visio.VisSectionIndices.visSectionConnectionPts,
                                (short)1,
                                (short)Visio.VisCellIndices.visCnnctX));
        }
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Visio.Application vdxApp = null;
            Visio.Document    vdxDoc = null;

            //Create Visio Application Object
            vdxApp = Application;

            //Make Visio Application Invisible
            vdxApp.Visible = false;

            //Create a new diagram
            vdxDoc = vdxApp.Documents.Add("Drawing.vsd");

            //Load Visio Stencil
            Visio.Documents visioDocs = vdxApp.Documents;

            Visio.Document visioStencil = visioDocs.OpenEx("sample.vss",
                                                           (short)Microsoft.Office.Interop.Visio.VisOpenSaveArgs.visOpenHidden);

            //Set active page
            Visio.Page visioPage = vdxApp.ActivePage;

            //Add a new rectangle shape
            Visio.Master visioRectMaster = visioStencil.Masters.get_ItemU(@"Rectangle");
            Visio.Shape  visioRectShape  = visioPage.Drop(visioRectMaster, 4.25, 5.5);
            visioRectShape.Text = @"Rectangle text.";

            //Add a new star shape
            Visio.Master visioStarMaster = visioStencil.Masters.get_ItemU(@"Star 7");
            Visio.Shape  visioStarShape  = visioPage.Drop(visioStarMaster, 2.0, 5.5);
            visioStarShape.Text = @"Star text.";

            //Add a new hexagon shape
            Visio.Master visioHexagonMaster = visioStencil.Masters.get_ItemU(@"Hexagon");
            Visio.Shape  visioHexagonShape  = visioPage.Drop(visioHexagonMaster, 7.0, 5.5);
            visioHexagonShape.Text = @"Hexagon text.";


            //Save diagram as VDX
            vdxDoc.SaveAs("Drawing1.vdx");
        }
示例#10
0
        private void addShapes()
        {
            this.Application.Documents.Add("");

            Visio.Page visioPage = this.Application.ActivePage;

            Visio.Document visioStencil = this.Application.Documents.Open(@"Basic Shapes.vss");

            Visio.Master visioRectMaster = visioStencil.Masters.get_ItemU(@"Rectangle");
            Visio.Shape  visioRectShape  = visioPage.Drop(visioRectMaster, 4.25, 5.5);
            visioRectShape.Text = @"Rectangle text.";

            Visio.Master visioStarMaster = visioStencil.Masters.get_ItemU(@"Star 7");
            Visio.Shape  visioStarShape  = visioPage.Drop(visioStarMaster, 2.0, 5.5);
            visioStarShape.Text = @"Star text.";

            Visio.Master visioHexagonMaster = visioStencil.Masters.get_ItemU(@"Hexagon");
            Visio.Shape  visioHexagonShape  = visioPage.Drop(visioHexagonMaster, 7.0, 5.5);
            visioHexagonShape.Text = @"Hexagon text.";
        }
示例#11
0
        /// <summary>
        /// Places a decorated shape over an already placed shape
        /// </summary>
        /// <param name="page"></param>
        /// <param name="elementShape">the already placed element - to be decorated</param>
        /// <param name="decorationStencil">the stencial to be used for decoration</param>
        /// <param name="decorationElement">the element with the decoration parameters</param>
        /// <param name="columnMap">the mapping between column names and numbers</param>
        /// <param name="showNotes"></param>
        public static void PlaceDecorationElement(Page page, Shape elementShape, Master decorationStencil, GenericElement decorationElement,
                                                  Dictionary <int, String> columnMap,
                                                  bool showNotes)
        {
            Shape decorShape = page.Drop(decorationStencil, 0.0, 0.0);

            DecorateShape(decorationElement, columnMap, showNotes, decorShape);

            decorShape.Cells["PinX"].ResultIU = elementShape.CellsU["PinX"].ResultIU;
            decorShape.Cells["PinY"].ResultIU = elementShape.CellsU["PinY"].ResultIU;
        }
示例#12
0
        /// <summary>
        /// Creates an instance of Master for every shape given in the shapes list
        /// and drops it onto the page. Uses & modifies the field variables drawXPos, drawYPos.
        /// </summary>
        /// <param name="page">The page to drop shapes on.</param>
        /// <param name="master">The master to derive instances of shapes.</param>
        /// <param name="shapes">The list of shapes to get properties from.</param>
        /// <param name="pad">Distance from one center of a shape to another center.</param>
        /// <returns>List of shapes dropped.</returns>
        private List <Visio.Shape> dropShapes(Visio.Page page, Visio.Master master, List <Visio.Shape> shapes, double pad)
        {
            List <Visio.Shape> shapesDropped = new List <Visio.Shape>();

            foreach (Visio.Shape s in shapes)
            {
                Visio.Shape dropped = page.Drop(master, drawXPos, drawYPos);
                dropped.Text = s.Text;

                drawXPos += pad;

                shapesDropped.Add(dropped);
            }

            return(shapesDropped);
        }
示例#13
0
        public static Shape PlaceGenericElement(Page page,
                                                Master elementStencil,
                                                GenericElement element,
                                                double ex, double ey,
                                                Dictionary <int, String> columnMap,
                                                bool showNotes)
        {
            Shape elementShape = page.Drop(elementStencil, 0.0, 0.0);

            DecorateShape(element, columnMap, showNotes, elementShape);


            elementShape.Cells["PinX"].ResultIU = ex;
            elementShape.Cells["PinY"].ResultIU = ey;

            return(elementShape);
        }
示例#14
0
        internal static void CreateMethodShapes(Visio.Application app, string doc, string page, string shape, string shapeu, string[] v)
        {
            VisioHelper.DisplayInWatchWindow(string.Format("{0}()",
                                                           MethodBase.GetCurrentMethod().Name));

            Visio.Page  activePage  = app.ActivePage;
            Visio.Shape activeShape = app.ActivePage.Shapes[shape];

            try
            {
                FileInfoShape fileInfoShape = new FileInfoShape(activeShape);


                VisioHelper.DisplayInWatchWindow(string.Format("{0}",
                                                               fileInfoShape.ToString()));

                VisioHelper.DisplayInWatchWindow(string.Format("{0}",
                                                               fileInfoShape.DisplayInfo()));

                string fileNameAndPath = fileInfoShape.SourceFileFileName;

                var sourceCode = "";

                using (var sr = new StreamReader(fileNameAndPath))
                {
                    sourceCode = sr.ReadToEnd();
                }

                List <String> methodNames = VNC.CodeAnalysis.Helpers.VB.GetMethodNames(sourceCode);

                // OK.  Now we have a list of Method Names.  Let's add shapes for each of them.

                Visio.Master methodMaster = app.Documents[@"API.vssx"].Masters[@"Method"];

                foreach (string methodName in methodNames)
                {
                    Visio.Shape newMethod = activePage.Drop(methodMaster, 5.0, 5.0);
                    newMethod.CellsU["Prop.MethodName"].FormulaU = methodName.WrapInDblQuotes();
                }
            }
            catch (Exception ex)
            {
                VisioHelper.DisplayInWatchWindow(string.Format("{0}",
                                                               ex.ToString()));
            }
        }
示例#15
0
        public void Generate(CfgSystem system)
        {
            Visio.Application visio = new Visio.Application();
            Visio.Document    doc   = visio.Documents.Add("");
            Visio.Page        page  = doc.Pages[1];
            page.Name = "Architecture";

            // Open with flags Visio.VisOpenSaveArgs.visOpenRO | Visio.VisOpenSaveArgs.visOpenDocked.
            Visio.Document stencil      = visio.Documents.OpenEx(Settings.StencilName, 0x2 | 0x4);
            Visio.Master   serverMaster = stencil.Masters["Server"];

            double paperHeight = doc.get_PaperHeight(Visio.VisUnitCodes.visInches);
            double paperWidth  = doc.get_PaperWidth(Visio.VisUnitCodes.visInches);

            int    numColumns       = 2;
            int    numRows          = (system.Hosts.Count + (numColumns - 1)) / numColumns;
            double verticalGap      = paperHeight / numRows;
            double horizontalGap    = paperWidth / numColumns;
            double verticalMargin   = verticalGap / 2;
            double horizontalMargin = horizontalGap / 2;

            double verticalPosition   = verticalMargin;
            double horizontalPosition = horizontalMargin;
            int    verticalIndex      = 1;
            int    horizontalIndex    = 1;

            foreach (CfgHost host in system.Hosts)
            {
                Visio.Shape shape = page.Drop(serverMaster, horizontalPosition, verticalPosition);
                modifyShapeText(shape, host);

                if (verticalIndex == numRows)
                {
                    verticalIndex       = 1;
                    verticalPosition    = verticalMargin;
                    horizontalIndex    += 1;
                    horizontalPosition += horizontalGap;
                }
                else
                {
                    verticalIndex    += 1;
                    verticalPosition += verticalGap;
                }
            }
        }
示例#16
0
        public static Shape PlaceGenericElement(Page page,
                                                Master elementStencil,
                                                GenericElement element,
                                                int row, int column, double space,
                                                Dictionary <int, String> columnMap,
                                                bool showNotes)
        {
            Shape elementShape = page.Drop(elementStencil, 0.0, 0.0);

            DecorateShape(element, columnMap, showNotes, elementShape);

            double elementWidth  = elementShape.CellsU["Width"].ResultIU;
            double elementHeight = elementShape.CellsU["Height"].ResultIU;

            elementShape.Cells["PinX"].ResultIU = CalculateX(column, elementWidth, space);
            elementShape.Cells["PinY"].ResultIU = CalculateY(row, elementHeight, space);

            return(elementShape);
        }
示例#17
0
        /// <summary>
        /// Процедура отображения вершин графа в документе Visio
        /// </summary>
        /// <param name="visioDocs">Документы Visio</param>
        /// <param name="visioPage">Текущая страница в Visio</param>
        private void PresentNodes(Visio.Documents visioDocs, Visio.Page visioPage)
        {
            // Мастер-объект базовых фигур Visio
            Dictionary <string, Visio.Master> visioMasters = GetMasterShapes(visioDocs);

            // Расстановка вершин графа
            for (int i = 0; i < graph.AllVertices.Count(); ++i)
            {
                // Вершина
                var node = graph.AllVertices.ElementAt(i);

                // Стили вершины
                string shape     = node.Attributes.ContainsKey("shape") ? node.Attributes["shape"] : "ELLIPSE";
                string label     = node.Attributes.ContainsKey("label") ? node.Attributes["label"] : node.Id;
                string color     = node.Attributes.ContainsKey("color") ? node.Attributes["color"] : "black";
                string fontcolor = node.Attributes.ContainsKey("fontcolor") ? node.Attributes["fontcolor"] : "black";
                string style     = node.Attributes.ContainsKey("style") ? node.Attributes["style"] == "filled" ? "filled" : LineStyle(node.Attributes["style"].ToLower()) : "1";

                // Добавление вершины на страницу Visio
                vertices.Add(node, visioPage.Drop(visioMasters[shape.ToUpper()], 1 + i / 2.0, 11 - i / 2.0));

                // Установка стилей для фигуры на странице Visio
                vertices[node].Text = label;
                vertices[node].get_CellsSRC((short)Visio.VisSectionIndices.visSectionCharacter, (short)Visio.VisRowIndices.visRowCharacter, (short)Visio.VisCellIndices.visCharacterColor).FormulaU = VisioColor.ColorToRgb(fontcolor.ToLower());
                if (style == "filled")
                {
                    vertices[node].get_CellsSRC((short)Visio.VisSectionIndices.visSectionObject, (short)Visio.VisRowIndices.visRowFill, (short)Visio.VisCellIndices.visFillForegnd).FormulaU = VisioColor.ColorToRgb(color.ToLower());
                }
                else
                {
                    vertices[node].get_CellsU("LinePattern").FormulaU = style;
                }
                vertices[node].get_CellsU("LineColor").FormulaU = VisioColor.ColorToRgb(color.ToLower());

                // Ресайзинг
                vertices[node].Resize(Visio.VisResizeDirection.visResizeDirNW, -0.8, Visio.VisUnitCodes.visInches);

                // Чтобы не допустить пересечений
                vertices[node].get_CellsSRC((short)Visio.VisSectionIndices.visSectionObject, (short)Visio.VisRowIndices.visRowMisc, (short)Visio.VisCellIndices.visLOFlags).FormulaU            = "1";
                vertices[node].get_CellsSRC((short)Visio.VisSectionIndices.visSectionObject, (short)Visio.VisRowIndices.visRowShapeLayout, (short)Visio.VisCellIndices.visSLOPlowCode).FormulaU = "2";
            }
        }
示例#18
0
        private static async void AddNewWorkItemRevisionShapeToPage(Visio.Page page, Visio.Master linkMaster,
                                                                    WorkItem workItem, Point insertionPoint,
                                                                    WorkItemShapeInfo relatedShape,
                                                                    WorkItemShapeInfo.WorkItemShapeVersion version)
        {
            try
            {
                Visio.Shape       newWorkItemShape = page.Drop(linkMaster, insertionPoint.X, insertionPoint.Y);
                WorkItemShapeInfo shapeInfo        = new WorkItemShapeInfo(newWorkItemShape);
                shapeInfo.InitializeFromWorkItemRevision(workItem, int.Parse(relatedShape.ID));

                //int bugs = await VNC.AZDO.Helper.QueryRelatedBugsById(shapeInfo.Organization, int.Parse(shapeInfo.ID));

                //shapeInfo.RelatedBugs = bugs.ToString();

                shapeInfo.PopulateShapeDataFromInfo(newWorkItemShape, version);
            }
            catch (Exception ex)
            {
                VisioHelper.DisplayInWatchWindow($"{workItem.Id} - {ex}");
            }
        }
示例#19
0
        public void GenerateVSS()
        {
            visapp         = new IVisio.InvisibleApp();
            visapp.Visible = false;
            foreach (fileListElement fileEl in fileList)
            {
                try
                {
                    string templateFileName = Directory.GetCurrentDirectory() + "\\template.vss";
                    string newFullfileName  = fileEl.filePath + "\\result\\" + fileEl.fileName.Replace(".kml", ".vsd");

                    if (!File.Exists(templateFileName))
                    {
                        throw new Exception("Не найден шаблон выходного файла: " + templateFileName);
                    }

                    Directory.CreateDirectory(fileEl.filePath + "\\result\\");

                    string fileName = fileEl.fileName;
                    string caption  = "Поопорная схема ВЛ 0,4 кВ от ";
                    string firstTmp = "";
                    int    tpPos    = fileName.IndexOf("ТП");
                    if (tpPos >= 0)
                    {
                        firstTmp = fileName.Substring(tpPos, fileName.Length - tpPos).Replace('_', '/').Replace(".kml", "");
                        string secondTmp = fileName.Substring(0, tpPos - 1);
                        fileName = firstTmp + " кВА " + secondTmp;
                    }
                    else
                    {
                        throw new Exception("Не корректное название файла: " + fileName);
                    }
                    caption = caption + fileName + " " + fileEl.city;

                    IVisio.Document doc  = visapp.Documents.Open(templateFileName);// (short)IVisio.VisOpenSaveArgs.visAddHidden + (short)IVisio.VisOpenSaveArgs.visOpenNoWorkspace);
                    IVisio.Page     page = doc.Pages[1];

                    IVisio.Shape visioRectMaster = page.Shapes.get_ItemU("Sheet.1");
                    visioRectMaster.Text = caption;

                    visioRectMaster      = page.Shapes.get_ItemU("Sheet.509");
                    visioRectMaster.Text = caption;

                    visioRectMaster      = page.Shapes.get_ItemU("Sheet.496");
                    visioRectMaster.Text = fileEl.make;

                    visioRectMaster      = page.Shapes.get_ItemU("Sheet.508");
                    visioRectMaster.Text = fileEl.makeDate;

                    visioRectMaster      = page.Shapes.get_ItemU("Sheet.495");
                    visioRectMaster.Text = fileEl.check;

                    visioRectMaster      = page.Shapes.get_ItemU("Sheet.507");
                    visioRectMaster.Text = fileEl.checkDate;

                    int    pos2 = firstTmp.LastIndexOf('-');
                    int    pos3 = firstTmp.LastIndexOf('/');
                    string tmp2 = "?";
                    if (pos2 != -1 & pos3 != -1 & pos3 > pos2)
                    {
                        tmp2 = firstTmp.Substring(pos2 + 1, pos3 - pos2 - 1);
                    }

                    visioRectMaster      = page.Shapes.get_ItemU("Sheet.314");
                    visioRectMaster.Text = "РЛНД - " + tmp2;

                    IVisio.Master aMaster;
                    switch (fileEl.tpType)
                    {
                    case "Столбовая":
                        aMaster         = doc.Masters.get_ItemU(@"СТП");
                        visioRectMaster = page.Drop(aMaster, 6.3400314961, 5.4108622047);
                        //visioRectMaster.tra
                        visioRectMaster.Shapes[2].Text = "С" + firstTmp;
                        break;

                    case "Мачтовая":
                        aMaster         = doc.Masters.get_ItemU(@"МТП");
                        visioRectMaster = page.Drop(aMaster, 6.3976378, 5.4108622047);
                        visioRectMaster.Shapes[2].Text = "М" + firstTmp;
                        break;

                    case "Закрытая":
                        aMaster         = doc.Masters.get_ItemU(@"ЗТП");
                        visioRectMaster = page.Drop(aMaster, 6.313976378, 5.23622);
                        visioRectMaster.Shapes[2].Text = "З" + firstTmp;
                        break;

                    case "Комплектная":
                        aMaster         = doc.Masters.get_ItemU(@"КТП");
                        visioRectMaster = page.Drop(aMaster, 6.4422795276, 5.4108622047);
                        visioRectMaster.Shapes[2].Text = "К" + firstTmp;
                        break;
                    }

                    doc.SaveAs(newFullfileName);
                    doc.Close();
                    //visapp.Quit();
                }
                catch (Exception ex)
                {
                    LogTextEvent(Color.Red, ex.Message);
                }
            }
            foreach (IVisio.Document aDoc in visapp.Documents)
            {
                aDoc.Close();
            }
            visapp.Quit();
        }
示例#20
0
        /// <summary>
        /// Given a color map (Name:color), this function plots the information as
        /// as a key on the page.
        /// </summary>
        /// <param name="colorMap">Colro information to display.</param>
        /// <param name="contentDocument">Document to display the info.</param>
        private static void DisplayNamespaceKey(
            Dictionary <string, string> colorMap,
            Visio.Document contentDocument)
        {
            const double KeyPitchX = 2.0;
            const double KeyX      = 1.75;

            const double KeyPitchY = 1.0;
            const double KeyY      = 0.75;

            const double KeyInitialX = 1.5;

            Visio.Document stencilDocument = contentDocument.Application.Documents.OpenEx(
                "Basic_U.vss",
                (short)Visio.VisOpenSaveArgs.visOpenDocked);
            Visio.Master shape = stencilDocument.Masters["Rectangle"];

            Visio.Page targetPage = contentDocument.Pages[1];

            int    i     = 0;
            double dropX = KeyInitialX;
            double dropY = 1.0;

            // group all of the items in the key
            Program.selectionTree = contentDocument.DocumentSheet.Application.ActiveWindow.Selection;
            Program.selectionTree.DeselectAll();

            foreach (string colorName in colorMap.Keys)
            {
                Visio.Shape boxShape = targetPage.Drop(shape, dropX, dropY);
                Program.selectionTree.Select(boxShape, (short)Visio.VisSelectArgs.visSelect);

                // set the templateShape height, width, text, and color
                boxShape.get_CellsSRC(
                    (short)Visio.VisSectionIndices.visSectionObject,
                    (short)Visio.VisRowIndices.visRowXFormIn,
                    (short)Visio.VisCellIndices.visXFormHeight).ResultIU = KeyY;

                boxShape.get_CellsSRC(
                    (short)Visio.VisSectionIndices.visSectionObject,
                    (short)Visio.VisRowIndices.visRowXFormIn,
                    (short)Visio.VisCellIndices.visXFormWidth).ResultIU = KeyX;

                boxShape.get_CellsSRC(
                    (short)Visio.VisSectionIndices.visSectionObject,
                    (short)Visio.VisRowIndices.visRowFill,
                    (short)Visio.VisCellIndices.visFillForegnd).FormulaU =
                    colorMap[colorName];

                string[] namespaceTokens = colorName.Split(new char[] { '.' });
                string   shortNamespace  = namespaceTokens[namespaceTokens.Length - 1];
                boxShape.Text = string.Format("{0}\n({1})", shortNamespace, colorName);

                i++;
                dropX += KeyPitchX;

                // bit of a kluge, but it works.
                if (i % 4 == 0)
                {
                    dropX  = KeyInitialX;
                    dropY += KeyPitchY;
                }
            }

            Program.selectionTree.Group();
            Program.selectionTree.DeselectAll();
        }
示例#21
0
        private void decorate_Click(object sender, EventArgs e)
        {
            // open log if not yet open
            var tr2 = new TextWriterTraceListener(File.CreateText(selectedLogFileName.Text));

            Trace.Listeners.Add(tr2);

            // do it with Excel ....
            // all the excel stuff
            var connectionList = new List <ShapeConnection>();


            // Excel related aspects

            var xlApp = new Microsoft.Office.Interop.Excel.Application {
                Visible = true
            };

            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            // open the excel file
            String   excelFileName = connectionsFileName.Text;
            Workbook xlWorkBook    = xlApp.Workbooks.Open(excelFileName,
                                                          _missing, _missing, _missing, _missing, _missing, _missing,
                                                          _missing, _missing,
                                                          _missing, _missing, _missing, _missing, _missing, _missing);



            if (excelFileName != "" && File.Exists(excelFileName))
            {
                xlWorkBook = xlApp.Workbooks.Open(excelFileName,
                                                  _missing, _missing, _missing, _missing, _missing, _missing, _missing,
                                                  _missing,
                                                  _missing, _missing, _missing, _missing, _missing, _missing);

                var xlWorkSheet = (Worksheet)xlWorkBook.Sheets[connectionsSheetName.Text];


                int sourceElementNameCol = MmExcelUtil.ColumnNumber(xlWorkSheet, sourceElementColumnName.Text);
                int targetElementNameCol = MmExcelUtil.ColumnNumber(xlWorkSheet, targetElementColumnName.Text);

                Trace.WriteLine("  source element name column " + sourceElementNameCol);
                Trace.WriteLine("  target element name column " + targetElementNameCol);


                int  row      = 2;
                bool finished = false;

                while (!finished)
                {
                    String sourceElement = MmExcelUtil.GetCell(xlWorkSheet, row, sourceElementNameCol);
                    String targetElement = MmExcelUtil.GetCell(xlWorkSheet, row, targetElementNameCol);


                    finished = sourceElement == "" && targetElement == "";

                    if (!finished)
                    {
                        connectionList.Add(
                            new ShapeConnection(sourceElement, targetElement));
                    }
                    row++;
                }

                Trace.WriteLine("  connections read from Excel " + connectionList.Count);
            }

            // Visio related aspects

            var visapp = new Microsoft.Office.Interop.Visio.Application();



            Document landscape = visapp.Documents.Open(visioFileName.Text);
            Page     page      = visapp.ActivePage;



            Trace.WriteLine("Landscape Masters " + landscape.Masters.Count);
            foreach (Master m in landscape.Masters)
            {
                Trace.WriteLine("VisioStencil Master " + m.Name);
            }



            Master connectorMaster = landscape.Masters[connectorStencilName.Text];



            var placedMapShapes = new Dictionary <String, ShapeRef>();

            MmVisioUtil.GetShapeList(shapeName.Text, page, elementTagName.Text, placedMapShapes);


            Trace.WriteLine("  shapes in Visio " + placedMapShapes.Count);


            // filter internal flows
            for (int con = connectionList.Count - 1; con >= 1; con--)
            {
                if (connectionList[con].SourceElement == connectionList[con].TargetElement)
                {
                    connectionList.RemoveAt(con);
                }
            }
            Trace.WriteLine("  number of cross system connections  " + connectionList.Count);


            if (summarizeCheckBox.Checked)
            {
                connectionList.Sort((c1, c2) => String.CompareOrdinal(c1.ConnectionName(), c2.ConnectionName()));

                for (int con = connectionList.Count - 1; con >= 1; con--)
                {
                    if (connectionList[con - 1].ConnectionName() == connectionList[con].ConnectionName())
                    {
                        connectionList[con - 1].Weight = (connectionList[con].Weight + 1);
                        connectionList.RemoveAt(con);
                    }
                    else
                    {
                        Trace.WriteLine(connectionList[con].ConnectionName() + " " + connectionList[con].Weight);
                    }
                }

                Trace.WriteLine("  summarized to  " + connectionList.Count);
            }



            int progressValue = 0;

            decorationProgressBar.Minimum = 0;
            decorationProgressBar.Maximum = connectionList.Count - 1;

            // tweak performance
            bool  pInhibitSelectChange = visapp.InhibitSelectChange;
            short pDeferRecalc         = visapp.DeferRecalc;
            bool  pShowChanges         = visapp.ShowChanges;
            short pScreenUpdating      = visapp.ScreenUpdating;
            int   pOnDataChangeDelay   = visapp.OnDataChangeDelay;

            visapp.InhibitSelectChange = true;
            visapp.DeferRecalc         = 1;
            visapp.ShowChanges         = false;
            visapp.ScreenUpdating      = 0;
            visapp.OnDataChangeDelay   = -2;


            foreach (ShapeConnection con in connectionList)
            {
                decorationProgressBar.Value = progressValue++;
                if (progressValue % 50 == 0)
                {
                    Trace.Flush();
                }

                ShapeRef source = null;
                ShapeRef target = null;

                if (placedMapShapes.ContainsKey(con.SourceElement))
                {
                    source = placedMapShapes[con.SourceElement];
                }

                if (placedMapShapes.ContainsKey(con.TargetElement))
                {
                    target = placedMapShapes[con.TargetElement];
                }

                if (source != null && target != null)
                {
                    Shape connector = page.Drop(connectorMaster, 4.50, 4.50);
                    MmVisioUtil.ConnectShapes(source.Shape, target.Shape, connector);
                    // connector.Cells["EndArrow"].Formula = "=5";
                }
                else
                {
                    Trace.WriteLine(" cannot add connector between " + con.SourceElement + " to " + con.TargetElement);
                }
            }



            Trace.WriteLine("  decorations read from Excel " + connectionList.Count);

            // Reset Visio properties
            visapp.InhibitSelectChange = pInhibitSelectChange;
            visapp.DeferRecalc         = pDeferRecalc;
            visapp.ShowChanges         = pShowChanges;
            visapp.ScreenUpdating      = pScreenUpdating;
            visapp.OnDataChangeDelay   = pOnDataChangeDelay;



            Trace.Flush();
            Trace.Close();
        }
示例#22
0
        public static void DrawModel(DBModel model, bool withViews, bool showVisio, string path, bool physNames, bool allFields)
        {
            if (!System.IO.File.Exists(path + @"Files\SLModel.VSDX"))
            {
                MessageBox.Show("Das Template SLModel.vsdx wurde nicht unter " + path + @"Files\ gefunden. Bitte die README-Datei lesen.");
                return;
            }

            var fokus      = (bool)((MainWindow)Application.Current.MainWindow).Fokus_Aktiv.IsChecked;
            var fokusTable = ((MainWindow)Application.Current.MainWindow).Fokus_Tabelle.Text;

            if (fokus)
            {
                if (fokusTable.Length < 1)
                {
                    MessageBox.Show(@"Bitte Fokus-Tabelle eingeben oder Fokus deaktivieren.");
                    return;
                }
                if (!model.TablesList.Exists(tab => tab.Name.ToLower().Equals(fokusTable.ToLower())))
                {
                    MessageBox.Show(@"Fokus-Tabelle " + fokusTable + " nicht gefunden.");
                    return;
                }
                if (((MainWindow)Application.Current.MainWindow).Fokus_Tiefe.Text.Length < 1)
                {
                    MessageBox.Show(@"Tiefe des Fokus zu kurz.");
                    return;
                }
            }

            try
            {
                var x = -5;
                var y = 11;
                // ToDo: erst berechnen nach Fokus
                var breite  = (int)Math.Sqrt(model.TablesList.Count);
                var hoehe   = 0;
                var counter = 0;

                application         = new Visio.Application();
                application.Visible = showVisio;

                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }

                doc = application.Documents.Open(path + @"Files\SLModel.VSDX");
                //doc = application.Documents.Open(Environment.CurrentDirectory + @"\Files\SLModel.VSDX");
                doc.SaveAs(path + (fokus ? "Auschnittsfokus_" + fokusTable + "_" : "") + model.serverName + ".vsdx");
                doc.Creator = @"Hicham Ait Ayad";
                doc.Title   = model.serverName;

                page                 = doc.Pages[1];
                page.Name            = @"Scopeland DB Model Builder";
                page.AutoSize        = true;
                visioEntityMaster    = doc.Masters.get_ItemU(@"Entity");
                visioAttributeMaster = doc.Masters.get_ItemU(@"Attribute");
                visioConnectorMaster = doc.Masters.get_ItemU(@"Relationship");

                /***************************************************************************
                * ****************************** FOKUS ************************************
                ***************************************************************************/
                if (fokus)
                {
                    //var fokusTable = ((MainWindow)Application.Current.MainWindow).Fokus_Tabelle.Text.ToLower();
                    var fokusDepth = Int32.Parse(((MainWindow)Application.Current.MainWindow).Fokus_Tiefe.Text);
                    //var mandanten = "t_mandanten";

                    List <Table> TablesToLeaveList = new List <Table>();

                    model.RelationsList.FindAll(rel =>
                                                //!rel.FromField.Table.Name.ToLower().Equals(mandanten) &&
                                                //!rel.ToField.Table.Name.ToLower().Equals(mandanten) &&
                                                (rel.FromField.Table.Name.ToLower().Equals(fokusTable.ToLower()) ||
                                                 rel.ToField.Table.Name.ToLower().Equals(fokusTable.ToLower())))
                    .ForEach(rel =>
                    {
                        TablesToLeaveList.Add(rel.FromField.Table);
                        TablesToLeaveList.Add(rel.ToField.Table);
                    }

                             );

                    for (var i = 0; i < fokusDepth - 1; i++)
                    {
                        List <Table> tablesListTemp = new List <Table>();

                        TablesToLeaveList.ForEach(table => model.RelationsList.FindAll(rel => rel.FromField.Table.Equals(table)).ForEach(rel2 =>
                        {
                            tablesListTemp.Add(rel2.FromField.Table);
                            tablesListTemp.Add(rel2.ToField.Table);
                        }));

                        TablesToLeaveList.AddRange(tablesListTemp);
                    }


                    model.TablesList.RemoveAll(table => !TablesToLeaveList.Contains(table));
                }
                /***************************************************************************/

                /***************************************************************************
                * ****************************** Black/Whitelists ************************************
                ***************************************************************************/
                List <string> tableBlacklist = new List <string>(((MainWindow)Application.Current.MainWindow).Table_Blacklist_Text.Text.Trim().Split(','));
                List <string> tableWhitelist = new List <string>(((MainWindow)Application.Current.MainWindow).Table_Whitelist_Text.Text.Trim().Split(','));

                if (tableBlacklist.Count > 0 && !tableBlacklist[0].Equals(""))
                {
                    model.TablesList.RemoveAll(table => tableBlacklist.Contains(table.Name));
                }

                if (tableWhitelist.Count > 0 && !tableWhitelist[0].Equals(""))
                {
                    model.TablesList.RemoveAll(table => !tableWhitelist.Contains(table.Name));
                }
                /***************************************************************************/

                foreach (Table table in model.TablesList)
                {
                    if (withViews || !table.KindOfObject.Trim().Equals("View"))
                    {
                        if (counter++ % breite == 0)
                        {
                            y    -= hoehe / 2;
                            hoehe = 0;
                            x     = -5;
                        }
                        Visio.Shape entity = page.Drop(visioEntityMaster, x += 5, y);

                        if (allFields && table.Fields.Count > hoehe)
                        {
                            hoehe = table.Fields.Count;
                        }
                        else
                        if (!allFields)
                        {
                            foreach (Field field in table.Fields)
                            {
                                hoehe += model.FieldList.Contains(field) ? 1 : 0;
                            }
                        }


                        Array members = entity.ContainerProperties.GetListMembers();
                        foreach (int member in members)
                        {
                            entity.Shapes.ItemFromID[member].Delete();
                        }
                        //tablesID.Add(table.Name, entity.ID);
                        //printProperties(entity.Shapes);
                        entity.Text = physNames ? table.Name : table.NameD;
                        int i = 1;


                        foreach (Field field in table.Fields)
                        {
                            if (allFields || model.FieldList.Contains(field))
                            {
                                Visio.Shape attribute = page.Drop(visioAttributeMaster, 0, 0);
                                field.ShapeID = attribute.UniqueID[(short)Visio.VisUniqueIDArgs.visGetOrMakeGUID];
                                //fieldsID.Add(field.Table.Name + "_" + field.Name, attribute.ID);
                                attribute.Text = physNames ? field.Name : field.NameD;
                                entity.ContainerProperties.InsertListMember(attribute, i++);
                                //entity.ContainerProperties.AddMember(visioAttributeMaster, Visio.VisMemberAddOptions.visMemberAddUseResizeSetting);
                            }
                        }
                    }
                }
                page.CreateSelection(Visio.VisSelectionTypes.visSelTypeAll).Layout();

                foreach (Relation relation in model.RelationsList)
                {
                    if (relation.FromField.ShapeID != null && relation.ToField.ShapeID != null && relation.TypeFrom != null && relation.TypeTo != null)
                    {
                        int index;
                        if ((relation.TypeFrom.Substring(3).Equals(">>") && relation.TypeTo.Substring(3).Equals("->")) || (relation.TypeFrom.Substring(3).Equals("->") && relation.TypeTo.Substring(3).Equals(">>")))
                        {
                            fromField = relation.TypeFrom.Substring(3).Equals(">>") ? page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID] : page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID];
                            toField   = relation.TypeFrom.Substring(3).Equals(">>") ? page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID] : page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID];
                            index     = 0;
                        }
                        else
                        {
                            if (relation.TypeFrom.Substring(3).Equals(">>") && relation.TypeTo.Substring(3).Equals(">>"))
                            {
                                fromField = page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID];
                                toField   = page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID];
                                index     = 2;
                            }
                            else
                            {
                                fromField = page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID];
                                toField   = page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID];
                                index     = 1;
                            }
                        }
                        ConnectWithDynamicGlueAndConnector(fromField, toField, index);
                    }
                }
                page.AutoSizeDrawing();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                doc.Save();
                if (showVisio)
                {
                    application.Quit();
                }
            }
            MessageBox.Show("All done!");
        }
示例#23
0
        /// <summary>
        /// This function uses the node information to place a copy of the templateShape
        /// on the targetPage, in the right color, at the specified location.
        /// The new shape is linked to the parent.  The Children of the node are then
        /// (recursively) placed on the page, linked to this new node.
        /// </summary>
        /// <param name="colorMap">Namespace color map to used for rendering.</param>
        /// <param name="targetPage">Visio page to place the objects.</param>
        /// <param name="node">Node object to place.</param>
        /// <param name="templateShape">Which shape to use to display.</param>
        /// <param name="parentShape">Parent visio node to attach child to.</param>
        /// <param name="baseLocationX">XLocation to start displaying subtree.</param>
        /// <param name="baseLocationY">YLocation to start displaying subtree.</param>
        /// <returns>Returns the next available Y coordinate to display an object.</returns>
        private static double PlaceOneShape(
            Dictionary <string, string> colorMap,
            Visio.Page targetPage,
            TypeTreeNode node,
            Visio.Master templateShape,
            Visio.Shape parentShape,
            double baseLocationX,
            double baseLocationY)
        {
            double movingYBase = baseLocationY;

            Visio.Shape newlyPlacedShape = targetPage.Drop(templateShape, baseLocationX, baseLocationY);

            // add the new object to the selection group for later "group" operation
            Program.selectionTree.Select(newlyPlacedShape, (short)Visio.VisSelectArgs.visSelect);

            if (parentShape != null)
            {
                Visio.Document stencilDocument = targetPage.Application.Documents.OpenEx(
                    "Blocks.vss",
                    (short)Visio.VisOpenSaveArgs.visOpenDocked);
                Visio.Master connectorMaster = stencilDocument.Masters["Dynamic connector"];
                Visio.Shape  connectorShape  = targetPage.Drop(connectorMaster, 1.0, 1.0);
                Program.selectionTree.Select(connectorShape, (short)Visio.VisSelectArgs.visSelect);
                ConnectShapes(parentShape, newlyPlacedShape, connectorShape);
            }

            // set the templateShape height, width, text, and color
            newlyPlacedShape.get_CellsSRC(
                (short)Visio.VisSectionIndices.visSectionObject,
                (short)Visio.VisRowIndices.visRowXFormIn,
                (short)Visio.VisCellIndices.visXFormHeight).ResultIU = Program.BoxY;

            newlyPlacedShape.get_CellsSRC(
                (short)Visio.VisSectionIndices.visSectionObject,
                (short)Visio.VisRowIndices.visRowXFormIn,
                (short)Visio.VisCellIndices.visXFormWidth).ResultIU = Program.BoxX;

            string shortNamespace = String.Empty;

            if (!String.IsNullOrEmpty(node.RawType.Namespace))
            {
                string[] namespaceTokens = node.RawType.Namespace.Split(new char[] { '.' });
                shortNamespace = namespaceTokens[namespaceTokens.Length - 1];
            }

            newlyPlacedShape.Text = string.Format("{0} ({1})", node.Name, shortNamespace);

            // if there is an entry in the color map, use it.
            if (!String.IsNullOrEmpty(node.RawType.Namespace) && colorMap.ContainsKey(node.RawType.Namespace))
            {
                newlyPlacedShape.get_CellsSRC(
                    (short)Visio.VisSectionIndices.visSectionObject,
                    (short)Visio.VisRowIndices.visRowFill,
                    (short)Visio.VisCellIndices.visFillForegnd).FormulaU =
                    colorMap[node.RawType.Namespace];
            }

            movingYBase += Program.BoxPitchY;

            foreach (TypeTreeNode t in node.Children.Values.OrderBy(t => t.RawType.Namespace).ThenBy(t => t.RawType.Name))
            {
                movingYBase = PlaceOneShape(
                    colorMap,
                    targetPage,
                    t,
                    templateShape,
                    newlyPlacedShape,
                    baseLocationX + Program.BoxPitchX,              // x adds Depth
                    movingYBase);
            }

            return(movingYBase);
        }
示例#24
0
        public static void DrawModel(Model.DBModel model, bool withViews, bool showVisio, string path, bool physNames, bool allFields)
        {
            if (!System.IO.File.Exists(path + @"Files\SLModel.VSDX"))
            {
                System.Windows.MessageBox.Show("Das Template SLModel.vsdx wurde nicht unter " + path + @"Files\ gefunden. Bitte die README-Datei lesen.");
                return;
            }

            try
            {
                var x       = -5;
                var y       = 11;
                var breite  = (int)Math.Sqrt(model.TablesList.Count);
                var hoehe   = 0;
                var counter = 0;

                application         = new Visio.Application();
                application.Visible = showVisio;

                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }

                doc = application.Documents.Open(path + @"Files\SLModel.VSDX");
                //doc = application.Documents.Open(Environment.CurrentDirectory + @"\Files\SLModel.VSDX");
                doc.SaveAs(path + model.serverName + ".vsdx");
                doc.Creator = @"Hicham Ait Ayad";
                doc.Title   = model.serverName;

                page                 = doc.Pages[1];
                page.Name            = @"Scopeland DB Model Builder";
                page.AutoSize        = true;
                visioEntityMaster    = doc.Masters.get_ItemU(@"Entity");
                visioAttributeMaster = doc.Masters.get_ItemU(@"Attribute");
                visioConnectorMaster = doc.Masters.get_ItemU(@"Relationship");

                foreach (Model.Table table in model.TablesList)
                {
                    if (withViews || !table.KindOfObject.Trim().Equals("View"))
                    {
                        if (counter++ % breite == 0)
                        {
                            y    -= hoehe / 2;
                            hoehe = 0;
                            x     = -5;
                        }
                        Visio.Shape entity = page.Drop(visioEntityMaster, x += 5, y);

                        if (allFields && table.Fields.Count > hoehe)
                        {
                            hoehe = table.Fields.Count;
                        }
                        else
                        if (!allFields)
                        {
                            foreach (Model.Field field in table.Fields)
                            {
                                hoehe += model.FieldList.Contains(field) ? 1 : 0;
                            }
                        }


                        Array members = entity.ContainerProperties.GetListMembers();
                        foreach (int member in members)
                        {
                            entity.Shapes.ItemFromID[member].Delete();
                        }
                        //tablesID.Add(table.Name, entity.ID);
                        //printProperties(entity.Shapes);
                        entity.Text = physNames ? table.Name : table.NameD;
                        int i = 1;


                        foreach (Model.Field field in table.Fields)
                        {
                            if (allFields || model.FieldList.Contains(field))
                            {
                                Visio.Shape attribute = page.Drop(visioAttributeMaster, 0, 0);
                                field.ShapeID = attribute.UniqueID[(short)Visio.VisUniqueIDArgs.visGetOrMakeGUID];
                                //fieldsID.Add(field.Table.Name + "_" + field.Name, attribute.ID);
                                attribute.Text = physNames ? field.Name : field.NameD;
                                entity.ContainerProperties.InsertListMember(attribute, i++);
                                //entity.ContainerProperties.AddMember(visioAttributeMaster, Visio.VisMemberAddOptions.visMemberAddUseResizeSetting);
                            }
                        }
                    }
                }
                page.CreateSelection(Visio.VisSelectionTypes.visSelTypeAll).Layout();

                foreach (Model.Relation relation in model.RelationsList)
                {
                    if (relation.FromField.ShapeID != null && relation.ToField.ShapeID != null && relation.TypeFrom != null && relation.TypeTo != null)
                    {
                        int index;
                        if ((relation.TypeFrom.Substring(3).Equals(">>") && relation.TypeTo.Substring(3).Equals("->")) || (relation.TypeFrom.Substring(3).Equals("->") && relation.TypeTo.Substring(3).Equals(">>")))
                        {
                            fromField = relation.TypeFrom.Substring(3).Equals(">>") ? page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID] : page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID];
                            toField   = relation.TypeFrom.Substring(3).Equals(">>") ? page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID] : page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID];
                            index     = 0;
                        }
                        else
                        {
                            if (relation.TypeFrom.Substring(3).Equals(">>") && relation.TypeTo.Substring(3).Equals(">>"))
                            {
                                fromField = page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID];
                                toField   = page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID];
                                index     = 2;
                            }
                            else
                            {
                                fromField = page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID];
                                toField   = page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID];
                                index     = 1;
                            }
                        }
                        ConnectWithDynamicGlueAndConnector(fromField, toField, index);
                    }
                }
                page.AutoSizeDrawing();
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.Message);
            }
            finally
            {
                doc.Save();
                if (showVisio)
                {
                    application.Quit();
                }
            }
            System.Windows.MessageBox.Show("All done!");
        }
示例#25
0
        private void MapItButtonClick(object sender, EventArgs e)
        {
            // open log if not yet open
            var tr2 = new TextWriterTraceListener(File.CreateText(selectedLogFileName.Text));

            Trace.Listeners.Add(tr2);

            // Excel related aspects

            var xlApp = new Microsoft.Office.Interop.Excel.Application {
                Visible = true
            };

            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            // open the excel file
            String   excelFileName = mapFileName.Text;
            Workbook xlWorkBook    = xlApp.Workbooks.Open(excelFileName,
                                                          _missing, _missing, _missing, _missing, _missing, _missing, _missing, _missing,
                                                          _missing, _missing, _missing, _missing, _missing, _missing);


            // read the columns of the sheets containing the map and the elements


            // reference column number --> tag for the elements
            var elementColumnMap = new Dictionary <int, string>();
            int elementMaxColumnNr;
            int elementNameColumnNr;

            MmExcelUtil.BuildColumnMap(xlWorkBook, elementSheetName.Text, elementNameColumnName.Text, elementColumnMap, out elementMaxColumnNr, out elementNameColumnNr);


            // reference column number --> tag for the map
            var taxXColumnMap = new Dictionary <int, string>();
            int taxXMaxColumnNr;
            int taxXNameColumnNr;

            MmExcelUtil.BuildColumnMap(xlWorkBook, xTaxonomySheetName.Text, xTaxonomyNameColumnName.Text, taxXColumnMap, out taxXMaxColumnNr, out taxXNameColumnNr);

            // reference column number --> tag for the map
            var taxYColumnMap = new Dictionary <int, string>();
            int taxYMaxColumnNr;
            int taxYNameColumnNr;

            MmExcelUtil.BuildColumnMap(xlWorkBook, yTaxonomySheetName.Text, yTaxonomyNameColumnName.Text, taxYColumnMap, out taxYMaxColumnNr, out taxYNameColumnNr);

            // list of all the elements to be maped
            var elementList = new List <GenericElement>();

            MmExcelUtil.BuildList(xlWorkBook, elementSheetName.Text, elementNameColumnNr, elementMaxColumnNr, elementColumnMap, elementList, elementNameColumnName.Text);

            // list of all the constituents of the map
            var xTaxonomyList = new List <GenericElement>();

            MmExcelUtil.BuildList(xlWorkBook, xTaxonomySheetName.Text, taxXNameColumnNr, taxXMaxColumnNr, taxXColumnMap, xTaxonomyList, xTaxonomyNameColumnName.Text);

            // list of all the constituents of the map
            var yTaxonomyList = new List <GenericElement>();

            MmExcelUtil.BuildList(xlWorkBook, yTaxonomySheetName.Text, taxYNameColumnNr, taxYMaxColumnNr, taxYColumnMap, yTaxonomyList, yTaxonomyNameColumnName.Text);


            // xTaxonomyMapping
            var xTaxonomyMappingList = new List <Mapping>();

            MmExcelUtil.BuildMapping(xlWorkBook, xTaxonomyMappingList, xMapSheetName.Text, xMapElementNameColumnName.Text,
                                     xMapXTaxNameColumnName.Text);

            var yTaxonomyMappingList = new List <Mapping>();

            MmExcelUtil.BuildMapping(xlWorkBook, yTaxonomyMappingList, yMapSheetName.Text, yMapElementNameColumnName.Text,
                                     yMapYTaxNameColumnName.Text);

            // create the map

            int x      = 0;
            int y      = 0;
            var matrix = new List <String> [xTaxonomyList.Count, yTaxonomyList.Count];

            for (int xi = 0; xi < xTaxonomyList.Count(); xi++)
            {
                for (int yi = 0; yi < yTaxonomyList.Count(); yi++)
                {
                    matrix[xi, yi] = new List <String>();
                }
            }


            foreach (GenericElement yElement in yTaxonomyList)
            {
                x = 0;
                foreach (GenericElement xElement in xTaxonomyList)
                {
                    Trace.WriteLine("  checking for x " + xElement.Name + " and y " + yElement.Name);


                    foreach (GenericElement element in elementList)
                    {
                        // if there is a mapping element to x and y taxonomy then add the element to the matrix

                        Mapping yMap = yTaxonomyMappingList.Find(
                            delegate(Mapping me)
                        {
                            return
                            (me.ElementName == element.Name &&
                             me.MapName == yElement.Name);
                        }
                            );
                        Mapping xMap = xTaxonomyMappingList.Find(
                            delegate(Mapping me)
                        {
                            return
                            (me.ElementName == element.Name &&
                             me.MapName == xElement.Name);
                        }
                            );

                        if (xMap != null && yMap != null)
                        {
                            matrix[x, y].Add(element.Name);
                        }
                    }
                    x += 1;
                }
                y += 1;
            }

            // determine per row the number of different applications and the max number in a cell

            int[] maxNumApplications      = new int [yTaxonomyList.Count];
            int   totalMaxNumApplications = 0;

            int[] diffNumApplications      = new int[yTaxonomyList.Count];
            int   totalDiffNumApplications = 0;
            int   emptyRows = 0;

            for (int yi = 0; yi < yTaxonomyList.Count(); yi++)
            {
                maxNumApplications[yi] = 0;
                List <String> appNames = new List <string>();
                for (int xi = 0; xi < xTaxonomyList.Count(); xi++)
                {
                    maxNumApplications[yi] = Math.Max(maxNumApplications[yi], matrix[xi, yi].Count);
                    foreach (String s in matrix[xi, yi])
                    {
                        if (!appNames.Contains(s))
                        {
                            appNames.Add(s);
                        }
                    }
                }
                diffNumApplications[yi]   = appNames.Count;
                totalDiffNumApplications += diffNumApplications[yi];
                totalMaxNumApplications  += maxNumApplications[yi];
                if (maxNumApplications[yi] == 0)
                {
                    emptyRows++;
                }

                Trace.WriteLine(" Row " + yi + " max num application " + maxNumApplications[yi] + " diff num applications " + diffNumApplications[yi]);
            }

            Trace.WriteLine("Max total number applications " + totalMaxNumApplications);
            Trace.WriteLine("Total number of different applications " + totalDiffNumApplications);
            Trace.WriteLine("Number of empty rows " + emptyRows);

            // Visio related aspects

            var visapp = new Microsoft.Office.Interop.Visio.Application();

            // Prepare Visio
            Document landscape = visapp.Documents.Open(visioFileName.Text);
            Document stencil   = visapp.Documents.OpenEx(stencilFileName.Text, (short)VisOpenSaveArgs.visOpenDocked);
            Page     page      = visapp.ActivePage;


            Master elementStencil   = stencil.Masters[elementStencilName.Text];
            Master taxonomyXStencil = stencil.Masters[xTaxonomyStencilName.Text];
            Master taxomomyYStencil = stencil.Masters[yTaxonomyStencilName.Text];

            if (elementStencil == null)
            {
                throw new ArgumentNullException("elementStencil");
            }
            if (taxonomyXStencil == null)
            {
                throw new ArgumentNullException("taxonomyXStencil");
            }
            if (taxomomyYStencil == null)
            {
                throw new ArgumentNullException("taxomomyYStencil");
            }

            Shape elementShape   = page.Drop(elementStencil, 0.0, 0.0);
            Shape taxonomyXShape = page.Drop(taxonomyXStencil, 0.0, 0.0);
            Shape taxonomyYShape = page.Drop(taxomomyYStencil, 0.0, 0.0);

            double pageWidth = page.PageSheet.CellsU["PageWidth"].ResultIU;
            double pageHight = page.PageSheet.CellsU["PageHeight"].ResultIU;

            double elementWidth  = elementShape.CellsU["Width"].ResultIU;
            double elementHeight = elementShape.CellsU["Height"].ResultIU;

            double taxonomyXHeight = taxonomyXShape.CellsU["Height"].ResultIU;
            double taxonomyXWidth  = taxonomyXShape.CellsU["Width"].ResultIU;
            double taxonomyYHeight = taxonomyYShape.CellsU["Height"].ResultIU;
            double taxonomyYWidth  = taxonomyYShape.CellsU["Width"].ResultIU;


            double space = double.Parse(spaceText.Text);

            elementShape.Delete();
            taxonomyXShape.Delete();
            taxonomyYShape.Delete();

            Trace.WriteLine("Size of an page    " + pageWidth + " " + pageHight);
            Trace.WriteLine("Size of an element " + elementWidth + " " + elementHeight);

            double yTaxonomyYRoot = pageHight - 2 * space - taxonomyXHeight;
            double xTaxonomyXRoot = 2 * space + taxonomyYWidth;

            double taxYHeight = 0.0;

            if (emptyRowSuppressionCheckBox.Checked)
            {
                taxYHeight = (yTaxonomyYRoot - 2 * space) / totalDiffNumApplications;
            }
            else
            {
                taxYHeight = (yTaxonomyYRoot - 2 * space) / (totalDiffNumApplications + emptyRows);
            }
            double taxXWidth = (pageWidth - xTaxonomyXRoot - 2 * space) / xTaxonomyList.Count;


            double yPos = yTaxonomyYRoot;


            for (int xi = 0; xi < xTaxonomyList.Count; xi++)
            {
                MmVisioUtil.PlaceGenericElement(page, taxonomyXStencil, xTaxonomyList[xi],
                                                xTaxonomyXRoot + (xi + 0.5) * taxXWidth,
                                                yTaxonomyYRoot + taxonomyXHeight * 0.5,
                                                taxXWidth,
                                                taxonomyXHeight,
                                                taxXColumnMap,
                                                false);
            }



            for (int yi = 0; yi < yTaxonomyList.Count(); yi++)
            {
                double xPos = space * 2.0 + taxonomyXWidth / 2.0;

                if (emptyRowSuppressionCheckBox.Checked && diffNumApplications[yi] == 0)
                {
                    // do noting
                }
                else
                {
                    double height = Math.Max(1, diffNumApplications[yi]) * taxYHeight;

                    MmVisioUtil.PlaceGenericElement(page, taxomomyYStencil, yTaxonomyList[yi],
                                                    xPos, yPos - height / 2,
                                                    taxonomyYWidth, height,
                                                    taxYColumnMap,
                                                    false);

                    // draw applications

                    List <String> appNames = new List <string>();

                    for (int xi = 0; xi < xTaxonomyList.Count; xi++)
                    {
                        foreach (String s in matrix[xi, yi])
                        {
                            if (!appNames.Contains(s))
                            {
                                appNames.Add(s);
                            }
                        }
                    }

                    int nApp = 0;
                    foreach (String Name in appNames)
                    {
                        GenericElement app = elementList.Find(
                            delegate(GenericElement ele)
                        {
                            return(ele.Name == Name);
                        }
                            );

                        if (app != null)
                        {
                            elementShape = null;

                            for (int xi = 0; xi < xTaxonomyList.Count; xi++)
                            {
                                if (matrix[xi, yi].Contains(Name))
                                {
                                    if (mergeApplicationsCheckBox.Checked && elementShape != null)
                                    {
                                        elementShape.CellsU["Width"].ResultIU += taxXWidth;
                                        elementShape.CellsU["PinX"].ResultIU  += taxXWidth / 2;
                                    }
                                    else
                                    {
                                        if (applySpaceCheckBox.Checked)
                                        {
                                            elementShape = MmVisioUtil.PlaceGenericElement(page, elementStencil, app,
                                                                                           xTaxonomyXRoot +
                                                                                           (xi + 0.5) * (taxXWidth),
                                                                                           yPos -
                                                                                           (nApp + 0.5) * taxYHeight,
                                                                                           taxXWidth - space, taxYHeight,
                                                                                           elementColumnMap,
                                                                                           false);
                                        }
                                        else
                                        {
                                            elementShape = MmVisioUtil.PlaceGenericElement(page, elementStencil, app,
                                                                                           xTaxonomyXRoot +
                                                                                           (xi + 0.5) * taxXWidth,
                                                                                           yPos -
                                                                                           (nApp + 0.5) * taxYHeight,
                                                                                           taxXWidth, taxYHeight,
                                                                                           elementColumnMap,
                                                                                           false);
                                        }
                                    }
                                }
                                else
                                {
                                    elementShape = null;
                                }
                            }
                            nApp++;
                        }
                        else
                        {
                            String error = "### unknown element " + elementShape.Name;
                            Trace.WriteLine(error);
                            errorListBox.Items.Add(error);
                        }
                    }


                    yPos -= height;
                }
            }


            Trace.Flush();
            Trace.Close();
        }
示例#26
0
        /// <summary>
        /// The main routine which generates the map based on the parameters specified in the
        /// dialog on the user interface. The resolut is the final map with placed elements
        /// and right sized and adjusted map in the background.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GenerateLandscapeButtonClick(object sender, EventArgs e)
        {
            // open log if not yet open
            var tr2 = new TextWriterTraceListener(File.CreateText(selectedLogFileName.Text));

            Trace.Listeners.Add(tr2);

            var errorList = new List <String>();

            // Excel related aspects
            var xlApp = new Microsoft.Office.Interop.Excel.Application {
                Visible = true
            };

            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            // open the excel file
            String   excelFileName = mapFileName.Text;
            Workbook xlWorkBook    = xlApp.Workbooks.Open(excelFileName,
                                                          _missing, _missing, _missing, _missing, _missing, _missing,
                                                          _missing, _missing,
                                                          _missing, _missing, _missing, _missing, _missing, _missing);


            // read the columns of the sheets containing the map and the elements

            // reference column number --> tag for the map
            var mapColumnMap = new Dictionary <int, string>();
            int mapMaxColumn;
            int mapNameColumn;

            MmExcelUtil.BuildColumnMap(xlWorkBook, mapSheetName.Text, mapNameColumnName.Text, mapColumnMap,
                                       out mapMaxColumn, out mapNameColumn);

            // reference column number --> tag for the elements
            var elementColumnMap = new Dictionary <int, string>();
            int elementMaxColumn;
            int elementNameColumn;

            MmExcelUtil.BuildColumnMap(xlWorkBook, elementSheetName.Text, elementNameColumnName.Text, elementColumnMap,
                                       out elementMaxColumn, out elementNameColumn);

            // list of all the constituents of the map
            var mapList = new List <GenericElement>();

            MmExcelUtil.BuildList(xlWorkBook, mapSheetName.Text, mapNameColumn, mapMaxColumn, mapColumnMap, mapList,
                                  mapNameColumnName.Text);

            // list of all the elements to be maped
            var elementList = new List <GenericElement>();

            MmExcelUtil.BuildList(xlWorkBook, elementSheetName.Text, elementNameColumn, elementMaxColumn,
                                  elementColumnMap, elementList, elementNameColumnName.Text);



            // Visio related aspects

            var visapp = new Microsoft.Office.Interop.Visio.Application();

            // Prepare Visio
            Document landscape = visapp.Documents.Open(visioFileName.Text);
            Document stencil   = visapp.Documents.OpenEx(stencilFileName.Text, (short)VisOpenSaveArgs.visOpenDocked);
            Page     page      = visapp.ActivePage;


            var placedMapShapes     = new Dictionary <String, ShapeRef>();
            var placedElementShapes = new Dictionary <String, ShapeRef>();

            MmVisioUtil.GetShapeList(mapStencilName.Text, page, mapNameColumnName.Text, placedMapShapes);
            MmVisioUtil.GetShapeList(elementStencilName.Text, page, elementNameColumnName.Text, placedElementShapes);


            var missingMapShapes = new List <String>();

            DetermineMissingMapShapes(mapList, placedMapShapes, missingMapShapes);


            // Read all the mappings

            var mappingList = new List <Mapping>();

            MmExcelUtil.BuildMapping(xlWorkBook, mappingList, mappingSheetName.Text, mappingElementNameColumnName.Text,
                                     mappingMapNameColumnName.Text);


            // Create the mapping layout data structure

            var mapLayout = new Dictionary <String, MapLayoutElement>();

            PopulateMapLayout(mapList, elementList, mappingList, mapLayout);


            Master elementStencil = stencil.Masters[elementStencilName.Text];

//            Master marker = stencil.Masters["Marker"];

            Shape elementShape = page.Drop(elementStencil, 0.0, 0.0);

            double pageWidth = page.PageSheet.CellsU["PageWidth"].ResultIU;
            double pageHight = page.PageSheet.CellsU["PageHeight"].ResultIU;

            double elementWidth  = elementShape.CellsU["Width"].ResultIU;
            double elementHeight = elementShape.CellsU["Height"].ResultIU;
            double space         = double.Parse(spaceText.Text);

            double numColumns = (pageWidth - space) / (elementWidth + space);
            double numRows    = (pageHight - space) / (elementHeight + space);


            Trace.WriteLine("Size of an page     w " + pageWidth + " " + pageHight);
            Trace.WriteLine("Size of an element  w " + elementWidth + " " + elementHeight);
            Trace.WriteLine("Space                 " + space);
            Trace.WriteLine("Number                " + numRows + " rows " + numColumns + " columns");

            elementShape.Delete();

            // determines size of map stencil on drawing in terms of elements which can be placed on it
            // the results are kept in the MapLayoutElement
            CaclulateMapLayout(mapLayout, placedMapShapes, elementHeight, elementWidth, space);

            // Move elements on map to lower left

            foreach (ShapeRef sr in placedElementShapes.Values)
            {
                sr.Shape.Cells["PinX"].ResultIU = 0;
                sr.Shape.Cells["PinY"].ResultIU = 0;
            }

            // Populate Map with Elements

            if (optimitzeElementLayoutCheckBox.Checked)
            {
                foreach (MapLayoutElement mle in mapLayout.Values)
                {
                    String mapElementName = mle.Name;
                    if (placedMapShapes.ContainsKey(mapElementName))
                    {
                        Shape mapShape = placedMapShapes[mapElementName].Shape;


                        double mapWidth  = mapShape.CellsU["Width"].ResultIU;
                        double mapHeight = mapShape.CellsU["Height"].ResultIU;
                        double mapX      = mapShape.CellsU["PinX"].ResultIU;
                        double mapY      = mapShape.CellsU["PinY"].ResultIU;

                        if (titleSpaceCheckBox.Checked)
                        {
                            mapHeight -= space * 1.5;
                            mapY      -= space * 0.75;
                        }

                        double offsetX = elementWidth / 2 + (mapWidth - (mle.MaxColumn - mle.MinColumn + 1) * elementWidth - (mle.MaxColumn - mle.MinColumn) * space) / 2;
                        double offsetY = mapHeight - (mle.MaxRow - mle.MinRow + 1) * elementHeight - (mle.MaxRow - mle.MinRow) * space;

                        int row = mle.MaxRow;
                        int col = mle.MinColumn;

                        if (titleRowCheckBox.Checked)
                        {
                            row--;
                        }

                        int topRow = row; // keep to use below in layout

                        mle.mapElements().Sort();

                        foreach (String meName in mle.mapElements())
                        {
                            GenericElement ge = elementList.Find(delegate(GenericElement x)
                            {
                                return(x.Name == meName);
                            });

                            double ex = mapX - mapWidth / 2 + (col - mle.MinColumn) * (elementWidth + space) + offsetX;
                            double ey = mapY - mapHeight / 2 + (row - mle.MinRow) * (elementHeight + space) + offsetY;
                            MmVisioUtil.PlaceGenericElement(page, elementStencil, ge, ex, ey, elementColumnMap, showDescriptionsCheckBox.Checked);


                            DetermineNextCell(mle, topRow, ref row, ref col);
                        }
                    }
                }
            }
            else
            {
                foreach (MapLayoutElement mle in mapLayout.Values)
                {
                    int row = mle.MaxRow;
                    int col = mle.MinColumn;

                    if (titleRowCheckBox.Checked)
                    {
                        row--;
                    }
                    int topRow = row; // keep to use below in layout

                    mle.mapElements().Sort();

                    foreach (String meName in mle.mapElements())
                    {
                        GenericElement ge = elementList.Find(delegate(GenericElement x)
                        {
                            return(x.Name == meName);
                        });


                        MmVisioUtil.PlaceGenericElement(page, elementStencil, ge, row, col, space, elementColumnMap, true);


                        DetermineNextCell(mle, topRow, ref row, ref col);
                    }
                }
            }

            // Beautify Map

            if (!freezeMapCheckBox.Checked)
            {
                foreach (MapLayoutElement mle in mapLayout.Values)
                {
                    String mapElementName = mle.Name;
                    if (placedMapShapes.ContainsKey(mapElementName))
                    {
                        Shape mapShape = placedMapShapes[mapElementName].Shape;



                        double x = MmVisioUtil.CalculateX(mle.MinColumn, elementWidth, space) +
                                   (MmVisioUtil.CalculateX(mle.MaxColumn, elementWidth, space) -
                                    MmVisioUtil.CalculateX(mle.MinColumn, elementWidth, space)) / 2;
                        double y = MmVisioUtil.CalculateY(mle.MinRow, elementHeight, space) + 0.2 * space +
                                   (MmVisioUtil.CalculateY(mle.MaxRow, elementHeight, space) -
                                    MmVisioUtil.CalculateY(mle.MinRow, elementHeight, space)) / 2;
                        double w = (mle.MaxColumn - mle.MinColumn + 1) * (elementWidth + space) - 0.2 * space;
                        double h = (mle.MaxRow - mle.MinRow + 1) * (elementHeight + space) - 0.2 * space;

                        Trace.WriteLine(mle.Name + " raw    " +
                                        " X= " + String.Format("{0:0.00}", x) + " Y= " + String.Format("{0:0.00}", y) +
                                        " W= " + String.Format("{0:0.00}", w) + " H= " + String.Format("{0:0.00}", h));

                        if (titleSpaceCheckBox.Checked)
                        {
                            h += space * 1.5;
                            y += space * 0.75;
                        }

                        Trace.WriteLine(mle.Name + " spaced " +
                                        " X= " + String.Format("{0:0.00}", x) + " Y= " + String.Format("{0:0.00}", y) +
                                        " W= " + String.Format("{0:0.00}", w) + " H= " + String.Format("{0:0.00}", h));


                        mapShape.Cells["PinX"].ResultIU   = x;
                        mapShape.Cells["PinY"].ResultIU   = y;
                        mapShape.Cells["Width"].ResultIU  = w;
                        mapShape.Cells["Height"].ResultIU = h;
                    }
                }
            }

            Trace.Flush();
            Trace.Close();
        }
示例#27
0
        /// <summary>
        /// Utility function to help to prepare a map. It puts elements in a grid onto the visio
        /// and allows to tune the rough layout of the map background elements. Once the elements have been
        /// put onto the map, all map background elements are right sized and aligned.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PrepareClick(object sender, EventArgs e)
        {
            // open log if not yet open
            var tr2 = new TextWriterTraceListener(File.CreateText(selectedLogFileName.Text));

            Trace.Listeners.Add(tr2);

            // Excel related aspects

            var xlApp = new Microsoft.Office.Interop.Excel.Application {
                Visible = true
            };

            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            // open the excel file
            String   excelFileName = mapFileName.Text;
            Workbook xlWorkBook    = xlApp.Workbooks.Open(excelFileName,
                                                          _missing, _missing, _missing, _missing, _missing, _missing, _missing, _missing,
                                                          _missing, _missing, _missing, _missing, _missing, _missing);


            // read the columns of the sheets containing the map and the elements

            // reference column number --> column name for the map
            var mapColumnMap = new Dictionary <int, string>();
            int mapMaxColumn;
            int mapNameColumn;

            MmExcelUtil.BuildColumnMap(xlWorkBook, mapSheetName.Text, mapNameColumnName.Text, mapColumnMap, out mapMaxColumn, out mapNameColumn);


            // reference column number --> tag for the elements
            var elementColumnMap = new Dictionary <int, string>();
            int elementMaxColumn;
            int elementNameColumn;

            MmExcelUtil.BuildColumnMap(xlWorkBook, elementSheetName.Text, elementNameColumnName.Text, elementColumnMap, out elementMaxColumn, out elementNameColumn);

            // list of all the constituents of the map
            var mapList = new List <GenericElement>();

            MmExcelUtil.BuildList(xlWorkBook, mapSheetName.Text, mapNameColumn, mapMaxColumn, mapColumnMap, mapList, mapNameColumnName.Text);

            // list of all the elements to be maped
            var elementList = new List <GenericElement>();

            MmExcelUtil.BuildList(xlWorkBook, elementSheetName.Text, elementNameColumn, elementMaxColumn, elementColumnMap, elementList, elementNameColumnName.Text);


            // Visio related aspects

            var visapp = new Microsoft.Office.Interop.Visio.Application();

            // Prepare Visio
            Document landscape = visapp.Documents.Open(visioFileName.Text);
            Document stencil   = visapp.Documents.OpenEx(stencilFileName.Text, (short)VisOpenSaveArgs.visOpenDocked);
            Page     page      = visapp.ActivePage;



            Master elementStencil = stencil.Masters[elementStencilName.Text];

            if (elementStencil == null)
            {
                throw new ArgumentNullException("elementStencil");
            }

            Shape elementShape = page.Drop(elementStencil, 0.0, 0.0);

            double pageWidth = page.PageSheet.CellsU["PageWidth"].ResultIU;
            double pageHight = page.PageSheet.CellsU["PageHeight"].ResultIU;

            double elementWidth  = elementShape.CellsU["Width"].ResultIU;
            double elementHeight = elementShape.CellsU["Height"].ResultIU;
            double space         = double.Parse(spaceText.Text);

            double numColumns = (pageWidth - space) / (elementWidth + space);
            double numRows    = (pageHight - space) / (elementHeight + space);


            Trace.WriteLine("Size of an page    " + pageWidth + " " + pageHight);
            Trace.WriteLine("Size of an element " + elementWidth + " " + elementHeight);
            Trace.WriteLine("Number " + numRows + " rows " + numColumns + " columns");

            for (int r = 1; r < numRows; r++)
            {
                for (int c = 1; c < numColumns; c++)
                {
                    if (r == 1 && c == 1)
                    {
                        elementShape.Cells["PinX"].ResultIU = MmVisioUtil.CalculateX(c, elementWidth, space);
                        elementShape.Cells["PinY"].ResultIU = MmVisioUtil.CalculateY(r, elementHeight, space);
                    }
                    else
                    {
                        elementShape = page.Drop(elementStencil, MmVisioUtil.CalculateX(c, elementWidth, space), MmVisioUtil.CalculateY(r, elementHeight, space));
                    }

                    double elementX    = elementShape.CellsU["PinX"].ResultIU;
                    double elementY    = elementShape.CellsU["PinY"].ResultIU;
                    String coordinates = "Element at " + String.Format("{0:0.00}", elementX) + "/" + String.Format("{0:0.00}", elementY);
                    elementShape.Text = coordinates;
                }
            }


            var placedMapShapes = new Dictionary <String, ShapeRef>();

            MmVisioUtil.GetShapeList(mapStencilName.Text, page, mapNameColumnName.Text, placedMapShapes);

            // Place missing map Elements on Landscape
            var missingMapShapes = new List <String>();

            DetermineMissingMapShapes(mapList, placedMapShapes, missingMapShapes);


            Master mapStencil = stencil.Masters[mapStencilName.Text];


            foreach (GenericElement ge in mapList)
            {
                if (missingMapShapes.Contains(ge.Name))
                {
                    MmVisioUtil.PlaceGenericElement(page, mapStencil, ge, 0, 0, space, mapColumnMap, false);
                }
            }


            Trace.Flush();
            Trace.Close();
        }
示例#28
0
        public void AddShapes()
        {
            Visio.Application visio     = this.Application;
            Visio.Documents   documents = this.Application.Documents;

            Visio.Page     page     = visio.ActivePage;
            Visio.Document document = visio.ActiveDocument;
            if (document == null)
            {
                document = visio.Documents.Add("");
            }

            if (page == null)
            {
                page = document.Pages.Add();
            }

            List <Service> services = null;

            try
            {
                ServicesApi api = new ServicesApi();
                services = api.getServices(true, "");
            }
            catch (ApiException e)
            {
                System.Windows.Forms.MessageBox.Show("Error calling the LeanIX API: " + e.Message);
                return;
            }
            catch (System.Net.WebException)
            {
                System.Windows.Forms.MessageBox.Show("Please check your internet connection");
                return;
            }

            if (services == null || services.Count == 0)
            {
                System.Windows.Forms.MessageBox.Show("No data received from API");
                return;
            }

            Dictionary <String, Visio.Shape> placedShapes = new Dictionary <String, Visio.Shape>();

            //add shapes
            foreach (Service s in services)
            {
                if (s.serviceHasInterfaces == null || s.serviceHasInterfaces.Count == 0)
                {
                    continue;
                }

                Visio.Document stencil = documents.OpenEx("Basic Shapes.vss",
                                                          (short)Microsoft.Office.Interop.Visio.VisOpenSaveArgs.visOpenDocked);
                Visio.Master visioRectMaster = stencil.Masters.get_ItemU(@"Rounded Rectangle");

                Visio.Shape visioRectShape = page.Drop(visioRectMaster, 0, 0);
                visioRectShape.Text = s.name;
                placedShapes.Add(s.ID, visioRectShape);
            }

            //connect shapes
            foreach (Service s in services)
            {
                foreach (ServiceHasInterface si in s.serviceHasInterfaces)
                {
                    Visio.Shape sourceShape = placedShapes[s.ID];
                    Visio.Shape targetShape = placedShapes[si.serviceRefID];
                    if (targetShape != null)
                    {
                        sourceShape.AutoConnect(targetShape, Visio.VisAutoConnectDir.visAutoConnectDirLeft);
                    }
                }
            }

            //set the layout and resize the page
            page.PageSheet.get_CellsSRC(
                (short)Visio.VisSectionIndices.visSectionObject,
                (short)Visio.VisRowIndices.visRowPageLayout,
                (short)Visio.VisCellIndices.visPLOPlaceStyle).ResultIU = 6;

            page.PageSheet.get_CellsSRC(
                (short)Visio.VisSectionIndices.visSectionObject,
                (short)Visio.VisRowIndices.visRowPageLayout,
                (short)Visio.VisCellIndices.visPLORouteStyle).ResultIU = 1;

            page.PageSheet.get_CellsSRC(
                (short)Visio.VisSectionIndices.visSectionObject,
                (short)Visio.VisRowIndices.visRowPageLayout,
                (short)Visio.VisCellIndices.visPLOSplit).ResultIU = 1;

            page.Layout();
            page.ResizeToFitContents();
        }