Пример #1
0
        public VisioDrawer()
        {
            //These variable allow Visio to run quickly, and quietly
            //Defer Recalc needs to be set to 0 after processing is done
            VisApp                         = new Visio.InvisibleApp();
            VisApp.UndoEnabled             = false;
            VisApp.LiveDynamics            = false;
            VisApp.AutoLayout              = false;
            VisApp.DeferRecalc             = -1;
            VisApp.DeferRelationshipRecalc = true;

            //Open the page holding the master collection so we can use it
            string executingSource = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string executingFolder = System.IO.Path.GetDirectoryName(executingSource);

            //Add a new document - this becomes the active document
            //if we do not do this, we get throw an exception
            VisApp.Documents.Add(executingFolder + "\\Config\\VisioTemplate.vsd");


            MastersDocuments = VisApp.Documents;
            MasterDoc        = MastersDocuments.OpenEx(executingFolder + "\\Config\\Stencil.vss", (short)Visio.VisOpenSaveArgs.visOpenHidden);

            //Now get a masters collection to use
            Masters = MasterDoc.Masters;

            //now get the active document
            ActiveDoc = VisApp.ActiveDocument;

            connectionMaster = GetMaster(@"Arrow");
            missingJobMaster = GetMaster(@"External Job");
            fullShapeMaster  = GetMaster(@"FullShapeTemplate");
            containerMaster  = GetMaster(@"Container");
        }
Пример #2
0
        /// <summary>
        /// Процедура отображения графа в документе Visio
        /// </summary>
        /// <param name="visioDocs">Документы Visio</param>
        /// <param name="visioPage">Текущая страница в Visio</param>
        public void PresentGraphInVisio(Visio.Documents visioDocs, Visio.Page visioPage)
        {
            PresentNodes(visioDocs, visioPage);
            PresentEdges(visioDocs, visioPage);

            visioPage.Layout();
        }
Пример #3
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);
        }
Пример #4
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>
        }
Пример #5
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.";
        }
Пример #6
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();
            }
        }
Пример #7
0
 public IVisio.Document TryOpen(IVisio.Documents docs, string filename)
 {
     using (var scope = new VA.Application.AlertResponseScope(docs.Application, VA.Application.AlertResponseCode.No))
     {
         var doc = docs.Open(filename);
         return(doc);
     }
 }
Пример #8
0
        public static IEnumerable <IVisio.Document> ToEnumerable(IVisio.Documents docs)
        {
            short count = docs.Count;

            for (int i = 0; i < count; i++)
            {
                yield return(docs[i + 1]);
            }
        }
Пример #9
0
        public static IVisio.Document OpenStencil(IVisio.Documents docs, string filename)
        {
            var stencil = DocumentHelper.TryOpenStencil(docs, filename);

            if (stencil == null)
            {
                string msg = String.Format("Could not open stencil \"{0}\"", filename);
                throw new AutomationException(msg);
            }
            return(stencil);
        }
Пример #10
0
        internal static IVisio.Document OpenStencil(this IVisio.Documents documents, string filename)
        {
            var stencil = VisioAutomation.Documents.DocumentHelper.TryOpenStencil(documents, filename);

            if (stencil == null)
            {
                string msg = string.Format("Could not open stencil \"{0}\"", filename);
                throw new VisioAutomation.Exceptions.VisioOperationException(msg);
            }
            return(stencil);
        }
        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
        }
Пример #12
0
        /// <summary>
        /// Event handler called before a different page is activated. Unloads
        /// all docked stencil windows.
        /// </summary>
        /// <param name="Window"></param>
        private void app_BeforeWindowPageTurn(Visio.Window Window)
        {
            Visio.Documents docs = app.Documents;

            foreach (Visio.Document d in docs)
            {
                if (d.Type == Visio.VisDocumentTypes.visTypeStencil)
                {
                    d.Close();
                }
            }
        }
Пример #13
0
        /// <summary>
        /// Returns all pages in a Document of type type.
        /// </summary>
        /// <param name="app">Application that contains the list of Documents.</param>
        /// <param name="type">The type of document in which to get the pages.</param>
        /// <returns>Pages collection, else null.</returns>
        public static Visio.Pages getPages(Visio.Application app, Visio.VisDocumentTypes type)
        {
            Visio.Documents docs = app.Documents;
            foreach (Visio.Document d in docs)
            {
                if (d.Type == type)
                {
                    return(d.Pages);
                }
            }

            return(null);
        }
Пример #14
0
        private static IVisio.Document TryOpenStencil(IVisio.Documents docs, string filename)
        {
            const short flags = (short)IVisio.VisOpenSaveArgs.visOpenRO | (short)IVisio.VisOpenSaveArgs.visOpenDocked;

            try
            {
                var doc = docs.OpenEx(filename, flags);
                return(doc);
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                return(null);
            }
        }
Пример #15
0
        /// <summary>
        /// Closes all the documents even if there are unsaved changes
        /// </summary>
        /// <param name="docs"> the Documents object</param>
        public static void ForceCloseAll(IVisio.Documents docs)
        {
            if (docs == null)
            {
                throw new System.ArgumentNullException(nameof(docs));
            }

            var application = docs.Application;

            while (docs.Count > 0)
            {
                var active_document = application.ActiveDocument;
                active_document.Close(true);
            }
        }
Пример #16
0
        /// <summary>
        /// Метод отображения графа в Visio
        /// </summary>
        /// <param name="input"></param>
        public void ShowGraph(string input)
        {
            Application.ActiveDocument.Pages.BeforePageDelete += Globals.ThisAddIn.DeleteGraph;

            Visio.Documents visioDocs = Application.Documents;
            Visio.Page      visioPage = Application.ActiveDocument.Pages.Add();

            graphs.Add(visioPage, new VisioGraph(input));
            graphs[visioPage].PresentGraphInVisio(visioDocs, visioPage);

            Application.ActivePage.BeforeShapeDelete  += DeleteShape;
            Application.ActivePage.ConnectionsDeleted += DeleteEdge;
            Application.ActivePage.ConnectionsAdded   += AddEdge;
            Application.ActivePage.TextChanged        += ChangeText;
            Application.ActivePage.ShapeAdded         += AddShape;
        }
Пример #17
0
        /// <summary>
        /// Retrieves a stencil document if it's open, else open it according to
        /// the openArgument.
        /// </summary>
        /// <param name="documents">Documents collection to look for Stencil.</param>
        /// <param name="stencilName">Name of the stencil.</param>
        /// <param name="openArg">How to open the stencil.</param>
        /// <returns></returns>
        public static Visio.Document getStencil(Visio.Documents documents, string stencilName,
                                                Visio.VisOpenSaveArgs openArg)
        {
            // if stencil is already open, return reference to it
            Visio.Document stencil = null;
            try
            {
                stencil = documents[stencilName];
            }
            catch
            {
                // Stencil isn't open, so open it
                string stencilPath = CaseTypes.stencilPath() + CaseTypes.OOSD_GENERAL_STENCIL;
                stencil = documents.OpenEx(stencilPath, (short)openArg);
            }

            return(stencil);
        }
        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");
        }
Пример #19
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";
            }
        }
Пример #20
0
        /// <summary>
        /// Процедура, сопоставляющая ключу-строке из допустимых фигур DOT мастер-фигуру Visio
        /// </summary>
        /// <param name="visioDocs"></param>
        /// <returns>Словарь string-Visio.Master</returns>
        private Dictionary <string, Visio.Master> GetMasterShapes(Visio.Documents visioDocs)
        {
            Visio.Document visioStencil1 = visioDocs.OpenEx("Basic Shapes.vss", (short)Visio.VisOpenSaveArgs.visOpenDocked);
            Visio.Document visioStencil2 = visioDocs.OpenEx("Audit Diagram Shapes.vss", (short)Visio.VisOpenSaveArgs.visOpenDocked);

            Dictionary <string, Visio.Master> result = new Dictionary <string, Visio.Master>();

            result.Add("TRIANGLE", visioStencil1.Masters.get_ItemU(@"Triangle"));
            result.Add("SQUARE", visioStencil1.Masters.get_ItemU(@"Square"));
            result.Add("PENTAGON", visioStencil1.Masters.get_ItemU(@"Pentagon"));
            result.Add("HEXAGON", visioStencil1.Masters.get_ItemU(@"Hexagon"));
            result.Add("OCTAGON", visioStencil1.Masters.get_ItemU(@"Octagon"));
            result.Add("RECTANGLE", visioStencil1.Masters.get_ItemU(@"Rectangle"));
            result.Add("RECT", visioStencil1.Masters.get_ItemU(@"Rectangle"));
            result.Add("BOX", visioStencil1.Masters.get_ItemU(@"Rectangle"));
            result.Add("CIRCLE", visioStencil1.Masters.get_ItemU(@"Circle"));
            result.Add("ELLIPSE", visioStencil1.Masters.get_ItemU(@"Ellipse"));
            result.Add("OVAL", visioStencil1.Masters.get_ItemU(@"Ellipse"));
            result.Add("DIAMOND", visioStencil1.Masters.get_ItemU(@"Diamond"));
            result.Add("PARALLELOGRAM", visioStencil2.Masters.get_ItemU(@"I/O"));
            return(result);
        }
 public static List <IVisio.Document> ToList(this IVisio.Documents documents)
 {
     return(VisioAutomation.Internal.Extensions.ExtensionHelpers.ToList(() => documents.Count, i => documents[i + 1]));;
 }
 public static IEnumerable <IVisio.Document> ToEnumerable(this IVisio.Documents documents)
 {
     return(VisioAutomation.Internal.Extensions.ExtensionHelpers.ToEnumerable(() => documents.Count, i => documents[i + 1]));;
 }
Пример #23
0
 public static IVisio.Document OpenStencil(this IVisio.Documents docs, string filename)
 {
     return(Documents.DocumentHelper.OpenStencil(docs, filename));
 }
Пример #24
0
 public static List <IVisio.Document> ToList(this IVisio.Documents documents)
 {
     return(ExtensionHelpers.ToList(() => documents.Count, i => documents[i + 1]));;
 }
Пример #25
0
 public static IEnumerable <IVisio.Document> ToEnumerable(this IVisio.Documents documents)
 {
     return(ExtensionHelpers.ToEnumerable(() => documents.Count, i => documents[i + 1]));;
 }
Пример #26
0
        public static void AutomateVisio()
        {
            Visio.Application oVisio     = null;
            Visio.Documents   oDocs      = null;
            Visio.Document    oDoc       = null;
            Visio.Pages       oPages     = null;
            Visio.Page        oPage      = null;
            Visio.Shape       oRectShape = null;
            Visio.Shape       oOvalShape = null;

            try
            {
                // Create an instance of Microsoft Visio and make it invisible.

                oVisio         = new Visio.Application();
                oVisio.Visible = false;
                Console.WriteLine("Visio.Application is started");

                // Create a new Document based on no template.

                oDocs = oVisio.Documents;
                oDoc  = oDocs.Add("");
                Console.WriteLine("A new document is created");

                // Draw a rectangle and a oval on the first page.

                Console.WriteLine("Draw a rectangle and a oval");

                oPages     = oDoc.Pages;
                oPage      = oPages[1];
                oRectShape = oPage.DrawRectangle(0.5, 10.25, 6.25, 7.375);
                oOvalShape = oPage.DrawOval(1.125, 6, 6.875, 2.125);

                // Save the document as a vsd file and close it.

                Console.WriteLine("Save and close the document");
                string fileName = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location) + "\\Sample1.vsd";
                oDoc.SaveAs(fileName);
                oDoc.Close();

                // Quit the Visio application.

                Console.WriteLine("Quit the Visio application");
                oVisio.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Solution1.AutomateVisio throws the error: {0}",
                                  ex.Message);
            }
            finally
            {
                // Clean up the unmanaged Visio COM resources by explicitly
                // calling Marshal.FinalReleaseComObject on all accessor objects.
                // See http://support.microsoft.com/kb/317109.

                if (oOvalShape != null)
                {
                    Marshal.FinalReleaseComObject(oOvalShape);
                    oOvalShape = null;
                }
                if (oRectShape != null)
                {
                    Marshal.FinalReleaseComObject(oRectShape);
                    oRectShape = null;
                }
                if (oPage != null)
                {
                    Marshal.FinalReleaseComObject(oPage);
                    oPage = null;
                }
                if (oPages != null)
                {
                    Marshal.FinalReleaseComObject(oPages);
                    oPages = null;
                }
                if (oDoc != null)
                {
                    Marshal.FinalReleaseComObject(oDoc);
                    oDoc = null;
                }
                if (oDocs != null)
                {
                    Marshal.FinalReleaseComObject(oDocs);
                    oDocs = null;
                }
                if (oVisio != null)
                {
                    Marshal.FinalReleaseComObject(oVisio);
                    oVisio = null;
                }
            }
        }
Пример #27
0
        public void Resolve(IVisio.Documents docs)
        {
            // first get the unique stencils (ignoring case)
            var comparer        = System.StringComparer.CurrentCultureIgnoreCase;
            var unique_stencils = new HashSet <string>(comparer);

            foreach (var master_ref in this._master_ref_dic.Values)
            {
                unique_stencils.Add(master_ref.StencilName);
            }

            // for each unique stencil, load the stencil doc
            var name_to_stencildoc = new Dictionary <string, IVisio.Document>(comparer);

            foreach (var stencil in unique_stencils.Where(s => s != null))
            {
                // If a stencil was stencified open the stencil if needed
                var stencil_doc = docs.OpenStencil(stencil);
                if (stencil_doc == null)
                {
                    string msg = string.Format("Failed to open stencil \"{0}\"", stencil);
                    throw new VisioOperationException(msg);
                }

                name_to_stencildoc[stencil] = stencil_doc;
            }

            // identify real master objects for all deferred shapes
            foreach (var master_ref in this._master_ref_dic.Values)
            {
                if (master_ref.VisioMaster == null)
                {
                    if (master_ref.StencilName != null)
                    {
                        // The stencil doc was specified so try to find the master in that stencil doc
                        var stencildoc     = name_to_stencildoc[master_ref.StencilName];
                        var stencilmasters = stencildoc.Masters;

                        var master_object = this.TryGetMaster(stencilmasters, master_ref.MasterName);
                        if (master_object == null)
                        {
                            string msg =
                                string.Format("No such master \"{0}\" in stencil \"{1}\"", master_ref.MasterName,
                                              master_ref.StencilName);
                            throw new System.ArgumentException(msg);
                        }
                        master_ref.VisioMaster = master_object;
                    }
                    else
                    {
                        // the stencil doc was not specified so try to find the master int the current doc
                        var app            = docs.Application;
                        var stencildoc     = app.ActiveDocument;
                        var stencilmasters = stencildoc.Masters;

                        var master_object = this.TryGetMaster(stencilmasters, master_ref.MasterName);
                        if (master_object == null)
                        {
                            string msg =
                                string.Format("No such master \"{0}\" in Active Document \"{1}\"", master_ref.MasterName,
                                              stencildoc.Name);
                            throw new System.ArgumentException(msg);
                        }
                        master_ref.VisioMaster = master_object;
                    }
                }
            }
        }
Пример #28
0
 public static IEnumerable <IVisio.Document> ToEnumerable(this IVisio.Documents docs)
 {
     return(Documents.DocumentHelper.ToEnumerable(docs));
 }
Пример #29
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();
        }