public IVisio.Application GetVisioApplication()
        {
            if (this.app == null)
            {
                // obviously if the current app reference is empty
                // then we must create a new once
                this.app = new IVisio.Application();
            }
            else
            {
                // OK, we have an instance, but it may not be valid
                // any longer because someome closed the app
                try
                {
                    // Try doing *something* with the instance
                    string s = app.Name;
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    // This COMException is a hint something
                    // is wrong with the instance. So, create a new
                    // visio application
                    this.app = new IVisio.Application();
                }
            }

            return this.app;
        }
示例#2
0
 public PageComparer(Visio.Application app, Visio.Page page1, Visio.Page page2, Visio.Page resultPage)
 {
     _page1 = page1;
     _page2 = page2;
     _resultPage = resultPage;
     _app = app;
 }
        public static void Run() 
        {
            // ExStart:SaveDiagramTo_VDX_PDF_JPEG_withVSTO
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_KnowledgeBase();

            // Create Visio Application Object
            Visio.Application vsdApp = new Visio.Application();

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

            // Create a document object and load a diagram
            Visio.Document vsdDoc = vsdApp.Documents.Open(dataDir + "Drawing1.vsd");

            // Save the VDX diagram
            vsdDoc.SaveAs(dataDir + "SaveDiagramToVDXwithVSTO_out.vdx");

            // Save as PDF file
            vsdDoc.ExportAsFixedFormat(Visio.VisFixedFormatTypes.visFixedFormatPDF,
                dataDir + "SaveDiagramToPDFwithVSTO_out.pdf", Visio.VisDocExIntent.visDocExIntentScreen,
                Visio.VisPrintOutRange.visPrintAll, 1, vsdDoc.Pages.Count, false, true,
                true, true, true, System.Reflection.Missing.Value);

            Visio.Page vsdPage = vsdDoc.Pages[1];

            // Save as JPEG Image
            vsdPage.Export(dataDir + "SaveDiagramToJPGwithVSTO_out.jpg");

            // Quit Visio Object
            vsdApp.Quit();
            // ExEnd:SaveDiagramTo_VDX_PDF_JPEG_withVSTO
        }
 public IVisio.Application New()
 {
     this.Client.WriteVerbose("Creating a new Instance of Visio");
     var app = new IVisio.Application();
     this.Client.WriteVerbose("Attaching that instance to current scripting client");
     this.VisioApplication = app;
     return app;
 }
示例#5
0
        /// <summary>This method destroys the command bar object added
        /// in the CreateCommandBar method.</summary>
        /// <param name="visioApplication">Current vision application.</param>
        /// <param name="commandBarName">Bar name to be removed.</param>
        public static void DestroyCommandBar( Application visioApplication, string commandBarName )
        {
            CommandBar commandBar = GetCommandBar( visioApplication, commandBarName );

            if ( commandBar != null )
            {
                // Delete the command bar object.
                commandBar.Delete();
                Marshal.ReleaseComObject( commandBar );
            }
        }
示例#6
0
        public PerfScope(IVisio.Application vis, PerfSettings new_settings)
        {
            this.app = vis;

            // save the old settings
            this.old_settings = new PerfSettings();
            this.old_settings.Load(this.app);

            // Set the new settings
            new_settings.Apply(this.app);
        }
        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
        }
        public void OrgChart_FiveNodes()
        {
            // Verify that basic org chart connectivity is maintained

            var orgchart_doc = new OCMODEL.OrgChartDocument();

            var n_a = new OCMODEL.Node("A");
            var n_b = new OCMODEL.Node("B");
            var n_c = new OCMODEL.Node("C");
            var n_d = new OCMODEL.Node("D");
            var n_e = new OCMODEL.Node("E");

            n_a.Children.Add(n_b);
            n_a.Children.Add(n_c);
            n_c.Children.Add(n_d);
            n_c.Children.Add(n_e);

            n_a.Size = new VA.Drawing.Size(4, 2);

            orgchart_doc.OrgCharts.Add(n_a);

            var app = new IVisio.Application();

            orgchart_doc.Render(app);

            var active_page = app.ActivePage;
            var page = active_page;
            page.ResizeToFitContents();

            var shapes = active_page.Shapes.AsEnumerable().ToList();
            var shapes_2d = shapes.Where(s => s.OneD == 0).ToList();
            var shapes_1d = shapes.Where(s => s.OneD != 0).ToList();
            var shapes_connector = shapes.Where(s => s.Master.NameU == "Dynamic connector").ToList();

            Assert.AreEqual(5 + 4, shapes.Count());
            Assert.AreEqual(5, shapes_2d.Count());
            Assert.AreEqual(4, shapes_1d.Count());
            Assert.AreEqual(4, shapes_connector.Count());

            Assert.AreEqual("A", n_a.VisioShape.Text.Trim());
                // trimming because extra ending space is added (don't know why)
            Assert.AreEqual("B", n_b.VisioShape.Text.Trim());
            Assert.AreEqual("C", n_c.VisioShape.Text.Trim());
            Assert.AreEqual("D", n_d.VisioShape.Text.Trim());
            Assert.AreEqual("E", n_e.VisioShape.Text.Trim());

            Assert.AreEqual(new VA.Drawing.Size(4, 2), VisioAutomationTest.GetSize(n_a.VisioShape));
            Assert.AreEqual(orgchart_doc.LayoutOptions.DefaultNodeSize,  VisioAutomationTest.GetSize(n_b.VisioShape));

            app.Quit(true);
        }
示例#9
0
 public VisioRenderer()
 {
     Application application;
     try
     {
         application = new Microsoft.Office.Interop.Visio.Application();
     }
     catch (System.Runtime.InteropServices.COMException ex)
     {
         throw new Exception("MS Visio not found", ex);
     }
     application.Documents.Add("");
     _page = application.Documents[1].Pages[1];
 }
        public static void FontCompare()
        {
            var visapp = new IVisio.Application();
            var doc = visapp.Documents.Add("");

            var fontnames = new[] {"Arial", "Calibri"};

            var sampletext = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" +
                             "<>[](),./|\\:;\'\"1234567890!@#$%^&*()`~";
            var samplechars = sampletext.Select(c => new string(new[] {c})).ToList();

            BoxLayoutSamples.FontGlyphComparision(doc, fontnames, samplechars);
            BoxLayoutSamples.FontGlyphComparision2(doc, fontnames, samplechars);
            BoxLayoutSamples.FontGlyphComparision3(doc, fontnames, samplechars);
        }
示例#11
0
        public static void Run()
        {
            // ExStart:UpdateShapePropsWithVSTO
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_KnowledgeBase();

            Visio.Application vsdApp = null;
            Visio.Document    vsdDoc = null;
            try
            {
                // Create Visio Application Object
                vsdApp = new Visio.Application();

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

                // Create a document object and load a diagram
                vsdDoc = vsdApp.Documents.Open(dataDir + "Drawing1.vsd");

                // Create page object to get required page
                Visio.Page page = vsdApp.ActivePage;

                // Create shape object to get required shape
                Visio.Shape shape = page.Shapes["Process1"];

                // Set shape text and text style
                shape.Text      = "Hello World";
                shape.TextStyle = "CustomStyle1";

                // Set shape's position
                shape.get_Cells("PinX").ResultIU = 5;
                shape.get_Cells("PinY").ResultIU = 5;

                // Set shape's height and width
                shape.get_Cells("Height").ResultIU = 2;
                shape.get_Cells("Width").ResultIU  = 3;

                // Save file as VDX
                vsdDoc.SaveAs(dataDir + "Drawing1.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:UpdateShapePropsWithVSTO
        }
示例#12
0
        public UndoScope(IVisio.Application app, string name)
        {
            if (app == null)
            {
                throw new System.ArgumentNullException("app");
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new System.ArgumentException("name");
            }

            this.Application = app;
            this.Name = name;
            this.ScopeID = this.Application.BeginUndoScope(name);
            this.Commit = true;
        }
示例#13
0
        public UndoScope(IVisio.Application app, string name)
        {
            if (app == null)
            {
                throw new System.ArgumentNullException("app");
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new System.ArgumentException("name");
            }

            this.Application = app;
            this.Name        = name;
            this.ScopeID     = this.Application.BeginUndoScope(name);
            this.Commit      = true;
        }
        public static void Run() 
        {
            // ExStart:UpdateShapePropsWithVSTO
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_KnowledgeBase();

            Visio.Application vsdApp = null;
            Visio.Document vsdDoc = null;
            try
            {
                // Create Visio Application Object
                vsdApp = new Visio.Application();

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

                // Create a document object and load a diagram
                vsdDoc = vsdApp.Documents.Open(dataDir + "Drawing1.vsd");

                // Create page object to get required page
                Visio.Page page = vsdApp.ActivePage;

                // Create shape object to get required shape
                Visio.Shape shape = page.Shapes["Process1"];

                // Set shape text and text style
                shape.Text = "Hello World";
                shape.TextStyle = "CustomStyle1";

                // Set shape's position
                shape.get_Cells("PinX").ResultIU = 5;
                shape.get_Cells("PinY").ResultIU = 5;

                // Set shape's height and width
                shape.get_Cells("Height").ResultIU = 2;
                shape.get_Cells("Width").ResultIU = 3;

                // Save file as VDX
                vsdDoc.SaveAs(dataDir + "Drawing1.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:UpdateShapePropsWithVSTO
        }
示例#15
0
        internal static void GetSourceFileInfo(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[@"Roslyn SuperFile"];

                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()));
            }
        }
示例#16
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;
                }
            }
        }
        public void OrgChart_SingleNode()
        {
            // Draw the minimum org chart - a chart with one nod
            var orgchart = new VAORGCHART.OrgChartDocument();

            var n_a = new VAORGCHART.Node("A");
            n_a.Size = new VA.Drawing.Size(4, 2);
            orgchart.OrgCharts.Add(n_a);

            var app = new IVisio.Application();
            orgchart.Render(app);

            var active_page = app.ActivePage;
            var page = active_page;
            page.ResizeToFitContents();

            app.Quit(true);
        }
示例#18
0
        void OnLoadCurrentSettingsExecute()
        {
            Log.EVENT_HANDLER("Enter", Common.LOG_CATEGORY);

            Visio.Application app = Globals.ThisAddIn.Application;

            Visio.Selection selection = app.ActiveWindow.Selection;

            // Verify only one shape, for now just grab first.

            foreach (Visio.Shape shape in selection)
            {
                GeometryRow = new GeometryRowWrapper(Visio_Shape.Get_GeometryRow(shape));
                OnPropertyChanged("GeometryRow");
            }

            Log.EVENT_HANDLER("Exit", Common.LOG_CATEGORY);
        }
示例#19
0
        public UndoScope(IVisio.Application app, string name)
        {
            if (app == null)
            {
                throw new System.ArgumentNullException(nameof(app));
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                string msg = string.Format("{0} cannot be null or empty", nameof(UndoScope));
                throw new System.ArgumentException(msg, nameof(name));
            }

            this.Application = app;
            this.Name        = name;
            this.ScopeID     = this.Application.BeginUndoScope(name);
            this.Commit      = true;
        }
示例#20
0
        public UndoScope(IVisio.Application app, string name)
        {
            if (app == null)
            {
                throw new System.ArgumentNullException(nameof(app));
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                string msg = $"{"name"} cannot be null or empty";
                throw new System.ArgumentException(msg,nameof(name));
            }

            this.Application = app;
            this.Name = name;
            this.ScopeID = this.Application.BeginUndoScope(name);
            this.Commit = true;
        }
示例#21
0
        public static void AutoSizePagesOn()
        {
            VisioHelper.DisplayInWatchWindow(string.Format("{0}()",
                                                           System.Reflection.MethodBase.GetCurrentMethod().Name));

            int undoScope = Globals.ThisAddIn.Application.BeginUndoScope("AutoSizePagesOn");

            Visio.Application app = Globals.ThisAddIn.Application;

            Visio.Document doc = app.ActiveDocument;

            foreach (Visio.Page page in doc.Pages)
            {
                Visio_Page.AutoSizePageOn(page);
            }

            Globals.ThisAddIn.Application.EndUndoScope(undoScope, true);
        }
示例#22
0
        /// <summary>
        /// 设置文本的上下标
        /// </summary>
        /// <param name="visioApp"></param>
        /// <param name="superOrSubscript">null 表示“正常”,true表示“上标”,false表示“下标”</param>
        public static void SetSuperOrSubScript(Application visioApp, bool?superOrSubscript)
        {
            int undoScopeID1 = visioApp.BeginUndoScope("设置文字上下标");

            try
            {
                SuperSubScript(visioApp, superOrSubscript);
            }
            catch (Exception ex)
            {
                string errorMessage = ex.Message + "\r\n\r\n" + ex.StackTrace;
                MessageBox.Show(errorMessage);
            }
            finally
            {
                visioApp.EndUndoScope(undoScopeID1, true);
            }
        }
示例#23
0
        private void ProcessCommand_Document_Add(XElement documentElement)
        {
            VisioHlp.DisplayInWatchWindow(string.Format("{0}()",
                                                        System.Reflection.MethodInfo.GetCurrentMethod().Name));

            try
            {
                Visio.Application app = Globals.ThisAddIn.Application;

                string documentName = documentElement.Attribute("Name").Value;

                app.Documents.Add(documentName);
            }
            catch (Exception ex)
            {
                VisioHlp.DisplayInWatchWindow(ex.ToString());
            }
        }
        /// <summary>
        /// Main entry point for the application.
        /// </summary>
        /// <param name="dbp">The Diagram Buildin g Properties.</param>
        /// <param name="worker">The worker.</param>
        /// <param name="e">The <see cref="DoWorkEventArgs"/> instance containing the event data.</param>
        /// <returns></returns>
        //public string GenerateDiagram(string connectionName, List<string> entities, RetrieveAllEntitiesResponse response, int selectedDiagramEntityLabelIndex, BackgroundWorker worker, DoWorkEventArgs e)
        public string GenerateDiagram(DiagramBuildingProperties dbp, BackgroundWorker worker, DoWorkEventArgs e)
        {
            String filename = String.Empty;

            VisioApi.Application application;
            VisioApi.Document    document;
            DiagramBuilder       builder = new DiagramBuilder();

            try
            {
                // Load Visio and create a new document.
                application         = new VisioApi.Application();
                application.Visible = false; // Not showing the UI increases rendering speed
                builder.VersionName = application.Version;
                document            = application.Documents.Add(String.Empty);

                builder._application = application;
                builder._document    = document;

                builder._metadataResponse     = dbp.environmentStructure;
                builder.selectedEntitiesNames = dbp.entities;
                builder.dbp = dbp;

                // Diagram all entities if given no command-line parameters, otherwise diagram
                // those entered as command-line parameters.
                builder.BuildDiagram(dbp.entities, worker, e);
                filename = "EntitesStructure\\Diagrams.vsd";

                // Save the diagram in the current directory using the name of the first
                // entity argument or "AllEntities" if none were given. Close the Visio application.
                document.SaveAs(Directory.GetCurrentDirectory() + "\\" + filename);
                application.Quit();
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                throw;
            }
            catch (System.Exception)
            {
                throw;
            }

            return(filename);
        }
示例#25
0
        // We need this to handle pasting - when objects are pasted the transitions have the old GUIDs but
        // visio may have assigned new ones to the pasted objects.  We stash the old GUIDs in OnWindowSelectionChange
        // and we make use of them here to get everyone in sync
        private void OnExitScope(Microsoft.Office.Interop.Visio.Application application, string moreInformation)
        {
            // moreInformation is a standard ;-delimited string from the scope events that contains what we need

            // 1344 is the Microsoft Scope Id for GotoPage
            if (moreInformation.StartsWith("1344"))
            {
                string pageName = visioControl.Document.Application.ActivePage.Name;
                int    index    = visioControl.Document.Pages[pageName].Index;
                gotoPageComboBox.SelectedIndex = index - 1;
            }
            // 1022 is the Microsoft Scope Id for Paste
            // 1024 is the Microsoft Scope Id for Duplicate
            else if (moreInformation.StartsWith(((int)VisUICmds.visCmdUFEditPaste).ToString()) ||
                     moreInformation.StartsWith(((int)VisUICmds.visCmdUFEditDuplicate).ToString()))
            {
                // first make a map of old GUIDs to new
                Dictionary <string, string> oldGUIDToNewGUIDMap = new Dictionary <string, string>();
                foreach (Shape shape in visioControl.Document.Application.ActiveWindow.Selection)
                {
                    string oldUID = Common.GetCellString(shape, Strings.CutCopyPasteTempCellName);
                    string newUID = shape.get_UniqueID((short)VisUniqueIDArgs.visGetOrMakeGUID);
                    oldGUIDToNewGUIDMap.Add(oldUID, newUID);
                }

                // now call each shadow to fix itself
                foreach (Shape shape in visioControl.Document.Application.ActiveWindow.Selection)
                {
                    Shadow s = PathMaker.LookupShadowByShape(shape);
                    if (s == null)
                    {
                        continue;
                    }
                    s.FixUIDReferencesAfterPaste(oldGUIDToNewGUIDMap);
                }

                // because we halt this when pasting, we now need to go fix all the ones that were pasted
                foreach (Shape s in visioControl.Document.Application.ActiveWindow.Selection)
                {
                    string uid = s.get_UniqueID((short)VisUniqueIDArgs.visGetOrMakeGUID);
                    Common.SetCellString(s, Strings.CutCopyPasteTempCellName, uid);
                }
            }
        }
        private void NoEventsPendingEventHandler(Application app) //Executed after all other events. Ensures we are never insides an undo scope
        {
            if ((app?.ActiveDocument?.Template.Contains(Information.TemplateName) ?? false) && !app.IsUndoingOrRedoing && rebuildTree)
            {
                try
                {
                    Log.Debug("No events pending event handler entered. Rebuilding tree...");
                    RebuildTree(app.ActiveDocument);
                    rebuildTree = false;
                }
                catch (Exception ex)
                {
                    Log.Error(ex, ex);
#if DEBUG
                    throw;
#endif
                }
            }
        }
示例#27
0
        /// <summary>
        /// Loads this addin in Visio.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            app = this.Application;

            objectSystem = new ObjectSystem();

            // Register event handlers

            /////////// TODO: Fix bug ///////////
            /// app.ShapeAdded += app_ShapeAdded;
            /// Danny: this event handler raises an exception when I try to call
            /// page.Draw... because the Draw method only returns a reference to
            /// the created Shape after it's done, but the ShapeAdded handler is called
            /// before a reference to new Shape could be passed to it.


            app.BeforeShapeTextEdit += app_BeforeShapeTextEdit;
            app.DocumentCreated     += app_DocumentCreated;
        }
示例#28
0
        public static string GetXmlErrorLogFilename(IVisio.Application app)
        {
            // the location of the xml error log file is specific to the user
            // we need to retrieve it from the registry
            var hkcu = Microsoft.Win32.Registry.CurrentUser;

            // The reg path is specific to the version of visio being used

            string ver            = app.Version;
            string ver_normalized = ver.Replace(",", ".");

            string path = string.Format(@"Software\Microsoft\Office\{0}\Visio\Application", ver_normalized);

            string logfilename = null;

            using (var key_visio_application = hkcu.OpenSubKey(path))
            {
                if (key_visio_application == null)
                {
                    // key doesn't exist - can't continue
                    throw new VisioAutomation.Exceptions.InternalAssertionException("Could not find the key visio application key in hkcu");
                }

                var subkeynames = key_visio_application.GetValueNames();
                if (!subkeynames.Contains("XMLErrorLogName"))
                {
                    return(null);
                }

                logfilename = (string)key_visio_application.GetValue("XMLErrorLogName");
            }

            // the folder that contains the file is located in the users internet cache
            // C:\Users\<your alias>\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.MSO\VisioLogFiles
            string internetcache = System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache);
            string folder        = System.IO.Path.Combine(internetcache, @"Content.MSO\VisioLogFiles");

            var s = System.IO.Path.Combine(folder, logfilename);

            System.Diagnostics.Debug.WriteLine("XmlErrorLogFilename: " + s);

            return(s);
        }
        private void Application_MarkerEvent(Application application, int sequence, string context)
        {
            if (application.ActiveDocument.Template.Contains(Information.TemplateName))
            {
                try
                {
                    Selection selection = Application.ActiveWindow.Selection; //event must originate from selected element

                    foreach (Shape s in selection)
                    {
                        if (s.CellExistsU[VisioFormulas.Cell_RationallyType, (short)VisExistsFlags.visExistsAnywhere] == Constants.CellExists)
                        {
                            string identifier = context;
                            if (context.Contains("."))
                            {
                                identifier = context.Split('.')[1];
                                context    = context.Split('.')[0];
                            }
                            Log.Debug("Marker event being handled for: " + s.Name);
                            MarkerEventHandlerRegistry.HandleEvent(s.CellsU[VisioFormulas.Cell_RationallyType].ResultStr[VisioFormulas.Value] + "." + context, s, identifier);
                            ContextMenuEventHandler.Instance.OnContextMenuEvent(application, sequence, context);
                        }
                    }
                }
                catch (COMException e)
                {
                    Log.Error("COMExeption occured:" + e.Message);
                    Log.Error("source: " + e.Source);
                    Log.Error("error code:" + e.ErrorCode);
                    Log.Error("inner exception:\n" + e.InnerException?.StackTrace);
#if DEBUG
                    throw;
#endif
                }
                catch (Exception ex)
                {
                    Log.Error(ex, ex);
#if DEBUG
                    throw;
#endif
                }
            }
        }
示例#30
0
        private void ProcessCommand_ActiveDocument(XElement activeDocumentElement)
        {
            VisioHlp.DisplayInWatchWindow(string.Format("{0}()",
                                                        System.Reflection.MethodInfo.GetCurrentMethod().Name));

            Visio.Application app = Globals.ThisAddIn.Application;

            Visio.Document doc = app.ActiveDocument;

            if (activeDocumentElement.Elements("Layers").Any())
            {
                ProcessCommand_Layers(activeDocumentElement.Element("Layers").Elements());
            }

            if (activeDocumentElement.Elements("ShapeSheet").Any())
            {
                ProcessCommand_ShapeSheet(doc, activeDocumentElement.Element("ShapeSheet"));
            }
        }
        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");
        }
示例#32
0
        // 开始具体的调试操作
        private static void SuperSubScript(Application vsoApp, bool?superOrSubscript)
        {
            Document doc = vsoApp.ActiveDocument;

            if (doc != null)
            {
                int diagramServices = doc.DiagramServicesEnabled;
                doc.DiagramServicesEnabled = (int)VisDiagramServices.visServiceVersion140 + (int)VisDiagramServices.visServiceVersion150;

                //
                Window    win = vsoApp.ActiveWindow;
                Selection sel = vsoApp.ActiveWindow.Selection;

                // 根据不同的编辑或选择情况而进行不同的处理
                int[]            selectedShapeIds;
                VisSelectionMode sm = SelectionUtils.GetSelectionMode(sel, out selectedShapeIds);
                switch (sm)
                {
                case VisSelectionMode.EditingCharactors:
                    var chs = win.SelectedText;
                    if (chs.CharCount > 0)
                    {
                        SuperOrSubScriptCharactors(chs, superOrSubscript);
                    }
                    break;

                case VisSelectionMode.SingleShape:
                    SuperOrSubScriptShape(sel[1], superOrSubscript);
                    break;

                case VisSelectionMode.MultiShapes:
                    foreach (Shape shp in sel)
                    {
                        SuperOrSubScriptShape(shp, superOrSubscript);
                    }
                    break;
                }

                // 将 DiagramServicesEnabled 属性复原
                doc.DiagramServicesEnabled = diagramServices;
            }
        }
示例#33
0
        public void VerifyDocCanBeLoaded(string filename)
        {
            var    app         = new IVisio.Application();
            var    version     = VA.Application.ApplicationHelper.GetVersion(app);
            string logfilename = VA.Application.ApplicationHelper.GetXmlErrorLogFilename(app);

            VA.Application.Logging.XmlErrorLog log_before = null;
            var old_fileinfo = new FileInfo(logfilename);

            if (File.Exists(logfilename))
            {
                log_before = new VA.Application.Logging.XmlErrorLog(logfilename);
            }

            var time = DateTime.Now;

            this.TryOpen(app.Documents, filename); // this causes the doc to load no matter what the error

            VA.Application.Logging.XmlErrorLog log_after = null;
            if (File.Exists(logfilename))
            {
                log_after = new VA.Application.Logging.XmlErrorLog(logfilename);
            }

            if (log_before != null && log_after == null)
            {
                Assert.Fail("Invalid case for all visio versions - if it existed before it must exist after");
                return;
            }

            if (log_before == null && log_after == null)
            {
                // Didn't exist before, didn't exist after - that's fine - the file loaded with no issues
                return;
            }

            // log_after exists
            VDX_Tests.VerifyNoErrorsInLog(log_after, filename, logfilename, version, time);

            // Force close all docs
            app.Quit(true);
        }
示例#34
0
        internal static async void AddLinkedWorkItems1(Visio.Application app, string doc, string page, string shape, string shapeu, string[] vs)
        {
            VisioHelper.DisplayInWatchWindow(string.Format("{0}()",
                                                           MethodBase.GetCurrentMethod().Name));

            // NOTE(crhodes)
            // Can launch a UI here.  Or earlier.

            //DxThemedWindowHost.DisplayUserControlInHost(ref addLinkedWorkItemsHost,
            //    "Edit Shape Control Points Text",
            //    Common.DEFAULT_WINDOW_WIDTH, Common.DEFAULT_WINDOW_HEIGHT,
            //    DxThemedWindowHost.ShowWindowMode.Modeless,
            //    new Presentation.Views.EditControlPoints());

            Visio.Page  activePage  = app.ActivePage;
            Visio.Shape activeShape = app.ActivePage.Shapes[shape];
            var         version     = WorkItemShapeInfo.WorkItemShapeVersion.V1;

            AddLinkedWorkItems(app, activePage, activeShape, "WI 1", version);
        }
示例#35
0
        /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        *
        * Shape commands
        *
        * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

        /// <summary>
        /// Handles marker events, as emitted by the shapes.
        /// </summary>
        /// <param name="app">Visio application.</param>
        /// <param name="sequenceNum">Sequence number.</param>
        /// <param name="contextString">Context string, as defined in shape.</param>
        private void Application_MarkerEvent(Visio.Application app, int sequenceNum, string contextString)
        {
            #region Validations

            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            #endregion

            try
            {
                Application_MarkerEventDo(app, sequenceNum, contextString);
            }
            catch (Exception ex)
            {
                ExceptionMessageBox.Show("Unhandled exception: Application_MarkerEvent", ex);
            }
        }
示例#36
0
        public static bool GetActiveSelection(Visio.Application visApp, out Visio.Selection visSelection)
        {
            Visio.Window visWindowDoc = null;

            visSelection = null;
            try
            {
                //Récupère la fenêtre courante
                if (GetVisActiveWindow(visApp, ref visWindowDoc))
                {
                    //Récupère la sélection courante
                    visSelection = visWindowDoc.Selection;
                }
            }
            catch
            {
                return(false);
            }
            return(true);
        }
示例#37
0
        public override void OnUpdateSettingsExecute()
        {
            Log.EVENT_HANDLER("Enter", Common.LOG_CATEGORY);

            // Wrap a big, OMG, what have I done ???, undo around the whole thing !!!
            int undoScope = Globals.ThisAddIn.Application.BeginUndoScope("UpdateStyleProperties");

            Visio.Application app = Globals.ThisAddIn.Application;

            Visio.Selection selection = app.ActiveWindow.Selection;

            foreach (Visio.Shape shape in selection)
            {
                //Visio_Shape.Set_StylePropertiesViewModel_Section(shape, StylePropertiesViewModel.Model);
            }

            Globals.ThisAddIn.Application.EndUndoScope(undoScope, true);

            Log.EVENT_HANDLER("Exit", Common.LOG_CATEGORY);
        }
示例#38
0
        public DocumentComparer(Visio.Application app, Visio.Document documentA, Visio.Document documentB)
        {
            _documentA = documentA;
            _documentB = documentB;
            _resultingDocument = app.Documents.Add("");

            //visio creates an initial (I call it "nil") page
            //just in case there are any more, give the same a guid name
            //these pages are removed at the end.
            if (_resultingDocument.Pages.Count > 0)
            {
                foreach (Visio.Page page in _resultingDocument.Pages)
                {
                    page.Name = Guid.NewGuid().ToString();
                    _guidsOfNilPages.Add(page.Name);
                }
            }

            _app = app;
        }
示例#39
0
 public string GetDSCContent()
 {
     System.Text.StringBuilder sb  = new System.Text.StringBuilder();
     Visio.Application         app = this.Application;
     Visio.Document            doc = app.ActiveDocument;
     sb.AppendLine("Configuration SharePointFarm");
     sb.AppendLine("{");
     sb.AppendLine("    Import-DscResource -ModuleName PSDesiredStateConfiguration");
     sb.AppendLine("    Import-DscResource -ModuleName SharePointDSC");
     //sb.AppendLine("    Import-DscResource -ModuleName xActiveDirectory");
     sb.AppendLine("    Import-DscResource -ModuleName xWebAdministration");
     sb.AppendLine("    Import-DscResource -ModuleName xCredSSP");
     sb.AppendLine("    $secPassword = ConvertTo-SecureString \"pass@word1\" -AsPlainText -Force");
     sb.AppendLine("    $farmAccountCreds = New-Object System.Management.Automation.PSCredential(\"contoso\\sp_farm\", $secPassword)");
     sb.AppendLine("    node " + Environment.MachineName);
     sb.AppendLine("    {");
     sb.AppendLine("        xCredSSP CredSSPServer { Ensure = \"Present\"; Role = \"Server\"; }");
     sb.AppendLine("        xCredSSP CredSSPClient { Ensure = \"Present\"; Role = \"Client\"; DelegateComputers = \"*.contoso.com\"; }");
     foreach (Visio.Page page in doc.Pages)
     {
         foreach (Visio.Shape shape in page.Shapes)
         {
             sb.AppendLine(GetDSCBlockContent(shape));
         }
     }
     sb.AppendLine("        LocalConfigurationManager");
     sb.AppendLine("        {");
     sb.AppendLine("            RebootNodeIfNeeded = $true");
     sb.AppendLine("        }");
     sb.AppendLine("    }");
     sb.AppendLine("}");
     sb.AppendLine("$ConfigData = @{");
     sb.AppendLine("AllNodes = @(");
     sb.AppendLine("    @{");
     sb.AppendLine("        NodeName = \"" + Environment.MachineName + "\";");
     sb.AppendLine("        PSDscAllowPlainTextPassword = $true;");
     sb.AppendLine("    }");
     sb.AppendLine(")}");
     sb.AppendLine("SharePointFarm -ConfigurationData $ConfigData");
     return(sb.ToString());
 }
示例#40
0
        public void VerifyDocCanBeLoaded(string filename)
        {
            var app = new IVisio.Application();
            var version = VA.Application.ApplicationHelper.GetVersion(app);
            string logfilename = VA.Application.ApplicationHelper.GetXMLErrorLogFilename(app);

            VA.Application.Logging.XmlErrorLog log_before = null;
            var old_fileinfo = new FileInfo(logfilename);

            if (File.Exists(logfilename))
            {
                log_before = new VA.Application.Logging.XmlErrorLog(logfilename);
            }

            var time = DateTime.Now;
            this.TryOpen(app.Documents, filename); // this causes the doc to load no matter what the error 

            VA.Application.Logging.XmlErrorLog log_after = null;
            if (File.Exists(logfilename))
            {
                log_after = new VA.Application.Logging.XmlErrorLog(logfilename);
            }

            if (log_before != null && log_after == null)
            {
                Assert.Fail("Invalid case for all visio versions - if it existed before it must exist after");
                return;
            }
 
            if (log_before == null && log_after == null)
            {
                // Didn't exist before, didn't exist after - that's fine - the file loaded with no issues
                return;
            }

            // log_after exists
            VDX_Tests.VerifyNoErrorsInLog(log_after, filename, logfilename, version, time);

            VA.Documents.DocumentHelper.ForceCloseAll(app.Documents);
            app.Quit();
        }
示例#41
0
        public void OrgChart_SingleNode()
        {
            // Draw the minimum org chart - a chart with one nod
            var orgchart = new OCMODEL.OrgChartDocument();

            var n_a = new OCMODEL.Node("A");

            n_a.Size = new VA.Drawing.Size(4, 2);
            orgchart.OrgCharts.Add(n_a);

            var app = new IVisio.Application();

            orgchart.Render(app);

            var active_page = app.ActivePage;
            var page        = active_page;

            page.ResizeToFitContents();

            app.Quit(true);
        }
示例#42
0
        public void Apply(IVisio.Application app)
        {
            var app_settings = app.Settings;

            if (this.ScreenUpdating.HasValue)
            {
                app.ScreenUpdating = this.ScreenUpdating.Value;
            }
            if (this.DeferRecalc.HasValue)
            {
                app.DeferRecalc = this.DeferRecalc.Value;
            }
            if (this.EnableAutoConnect.HasValue)
            {
                app_settings.EnableAutoConnect = this.EnableAutoConnect.Value;
            }
            if (this.LiveDynamics.HasValue)
            {
                app.LiveDynamics = this.LiveDynamics.Value;
            }
        }
示例#43
0
        public void VDX_DetectLoadWarnings()
        {
            string input_filename = this.GetTestResultsOutPath(@"datafiles\vdx_with_warnings_1.vdx");

            // Load the VDX
            var    app         = new IVisio.Application();
            var    version     = VA.Application.ApplicationHelper.GetVersion(app);
            string logfilename = VA.Application.ApplicationHelper.GetXmlErrorLogFilename(app);

            var doc = this.TryOpen(app.Documents, input_filename);

            // See what happened
            var log_after           = new VA.Application.Logging.XmlErrorLog(logfilename);
            var most_recent_session = log_after.FileSessions[0];
            var warnings            = most_recent_session.Records.Where(r => r.Type == "Warning").ToList();
            var errors = most_recent_session.Records.Where(r => r.Type == "Error").ToList();

            // Verify
            int expected_errors   = 0; // this VDX should not report any errors
            int expected_warnings = 4; // this VDX should contain four warnings for Visio2010 and two warnings for Visio 2013

            if (version.Major >= 15)
            {
                expected_warnings = 2;
            }

            Assert.AreEqual(expected_errors, errors.Count);     // this VDX should not report any errors
            Assert.AreEqual(expected_warnings, warnings.Count); // this VDX should contain exactly two warnings
            Assert.AreEqual(1, app.Documents.Count);

            // Cleanup
            // Force close all docs
            var docs = app.Documents.ToEnumerable().ToList();

            foreach (var d in docs)
            {
                d.Close(true);
            }
            app.Quit(true);
        }
示例#44
0
文件: Solution2.cs 项目: thexur/1code
        private static void AutomateVisioImpl()
        {
            try
            {
                // Create an instance of Microsoft Visio and make it invisible.

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

                // Create a new Document based on no template.

                Visio.Document oDoc = oVisio.Documents.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");
                oDoc.Pages[1].DrawRectangle(0.5, 10.25, 6.25, 7.375);
                oDoc.Pages[1].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) + "\\Sample2.vsd";
                oDoc.SaveAs(fileName);
                oDoc.Close();

                // Quit the Visio application.

                Console.WriteLine("Quit the Visio application");
                oVisio.Quit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Solution2.AutomateVisio throws the error: {0}",
                                  ex.Message);
            }
        }
示例#45
0
        public IVisio.Document Render(IVisio.Application app)
        {
            var appdocs = app.Documents;

            IVisio.Document doc = null;
            if (this._vst_template_file == null)
            {
                doc = appdocs.Add("");
            }
            else
            {
                const int flags  = 0; // (int)IVisio.VisOpenSaveArgs.visAddDocked;
                const int langid = 0;
                doc = appdocs.AddEx(this._vst_template_file, this._measurement_system, flags, langid);
            }
            this.VisioDocument = doc;
            var docpages  = doc.Pages;
            var startpage = docpages[1];

            this.Pages.Render(startpage);
            return(doc);
        }
示例#46
0
 public void OpenDocument()
 {
     VisioApp     = new Microsoft.Office.Interop.Visio.Application();
     VisioStencil = VisioApp.Documents.OpenEx(
         AppConfiguration.ShapesMastersFilePath,
         (short)VisOpenSaveArgs.visOpenDocked
         );
     Begin                = VisioStencil.Masters.get_ItemU(@"Begin");
     Process              = VisioStencil.Masters.get_ItemU(@"Process");
     InOutPut             = VisioStencil.Masters.get_ItemU(@"inoutput");
     IfState              = VisioStencil.Masters.get_ItemU(@"if");
     ForState             = VisioStencil.Masters.get_ItemU(@"for");
     Program              = VisioStencil.Masters.get_ItemU(@"program");
     Connector            = VisioStencil.Masters.get_ItemU(@"Connector");
     PageConnector        = VisioStencil.Masters.get_ItemU(@"pageConnector");
     Line                 = VisioStencil.Masters.get_ItemU(@"line");
     TextField            = VisioStencil.Masters.get_ItemU(@"textField");
     SmallTextField       = VisioStencil.Masters.get_ItemU(@"yesNo");
     Arrow                = VisioStencil.Masters.get_ItemU(@"arrowRight");
     LittleInvisibleBlock = VisioStencil.Masters.get_ItemU(@"LittleInvisibleBlock");
     VisioApp.Documents.Add("");
 }
示例#47
0
        public static new Boolean Convert(String inputFile, String outputFile) {
            Microsoft.Office.Interop.Visio.Application app;
            String tmpFile = null;
            try {
                app = new Microsoft.Office.Interop.Visio.Application();
                app.Documents.Open(inputFile);

                // Try and avoid dialogs about versions
                tmpFile = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".vsd";
                app.ActiveDocument.SaveAs(tmpFile);
                app.ActiveDocument.ExportAsFixedFormat(VisFixedFormatTypes.visFixedFormatPDF, outputFile, VisDocExIntent.visDocExIntentScreen, VisPrintOutRange.visPrintAll);
                app.ActiveDocument.Close();
                app.Quit();
                return true;
            } catch (Exception e) {
                Console.WriteLine(e.Message);
                return false;
            } finally {
                if (tmpFile != null) {
                    System.IO.File.Delete(tmpFile);
                }
                app = null;
            }
        }
 private static void create_new_app_instance()
 {
     SampleEnvironment.app = new IVisio.Application();
     var documents = SampleEnvironment.app.Documents;
     documents.Add("");
 }
示例#49
0
        static void Main(string[] args)
        {
            string visio_document = null;
            try
            {
                visio_document = args[0];
            }
            catch(IndexOutOfRangeException e)
            {
                OpenFileDialog dial = new OpenFileDialog();
                dial.Filter = "Visio files (*.vsdx)|*.vsdx";
                dial.RestoreDirectory = true;
                dial.Multiselect = false;
                if (dial.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                visio_document = dial.FileName;
            }

            Visio.Application app = null;
            try
            {
                app = new Visio.Application();
                app.Visible = false;
                Visio.Document doc = app.Documents.Open(visio_document);
                string folder = Path.GetDirectoryName(visio_document);
                string base_name = Path.GetFileNameWithoutExtension(visio_document);
                int ii = 0;
                foreach (Visio.Page p in doc.Pages)
                {
                    string filename = folder + "\\" + base_name + "-" + ii + ".png";
                    string filename_tmp = folder + "\\" + base_name + "-" + ii + "-tmp" + ".png";
                    Console.WriteLine(filename);
                    p.Export(filename_tmp);

                    // convert white to transparent
                    Bitmap bitmap = new Bitmap(filename_tmp);
                    //bitmap.MakeTransparent(Color.White);
                    int threshold = 255;
                    for (int x = 0; x < bitmap.Width; ++x)
                    {
                        for (int y = 0; y < bitmap.Height; ++y)
                        {
                            Color px = bitmap.GetPixel(x, y);
                            if (px.R >= threshold && px.G >= threshold && px.B >= threshold)
                            {
                                bitmap.SetPixel(x, y, Color.White);
                            }
                        }
                    }
                    bitmap.MakeTransparent(Color.White);
                    Image image = (Image)bitmap;
                    image.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
                    ++ii;
                }
                doc.Close();
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                MessageBox.Show(e.Message, "System error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if(app != null)
                    app.Quit();
            }
        }
示例#50
0
        /// <summary>
        /// Main entry point for the application.
        /// </summary>
        /// <param name="CmdArgs">Entities to place on the diagram</param>
        public static int Main(string[] args)
        {
            String filename = String.Empty;
            VisioApi.Application application;
            VisioApi.Document document;
            DiagramBuilder builder = new DiagramBuilder();

            try
            {
                // Obtain the target organization's Web address and client logon 
                // credentials from the user.
                ServerConnection serverConnect = new ServerConnection();
                ServerConnection.Configuration config = serverConnect.GetServerConfiguration();

                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(config))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Load Visio and create a new document.
                    application = new VisioApi.Application();
                    application.Visible = false; // Not showing the UI increases rendering speed  
                    builder.VersionName = application.Version;
                    document = application.Documents.Add(String.Empty);
                    builder._application = application;
                    builder._document = document;

                    // Load the metadata.
                    Console.WriteLine("Loading Metadata...");
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Entity | EntityFilters.Attributes | EntityFilters.Relationships,
                        RetrieveAsIfPublished = true,

                    };
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);
                    builder._metadataResponse = response;

                    // Diagram all entities if given no command-line parameters, otherwise diagram
                    // those entered as command-line parameters.
                    if (args.Length < 1)
                    {
                        ArrayList entities = new ArrayList();

                        foreach (EntityMetadata entity in response.EntityMetadata)
                        {
                            // Only draw an entity if it does not exist in the excluded entity table.
                            if (!_excludedEntityTable.ContainsKey(entity.LogicalName.GetHashCode()))
                            {
                                entities.Add(entity.LogicalName);
                            }
                            else
                            {
                                Console.WriteLine("Excluding entity: {0}", entity.LogicalName);
                            }
                        }

                        builder.BuildDiagram((string[])entities.ToArray(typeof(string)), "All Entities");
                        filename = "AllEntities.vsd";
                    }
                    else
                    {
                        builder.BuildDiagram(args, String.Join(", ", args));
                        filename = String.Concat(args[0], ".vsd");
                    }

                    // Save the diagram in the current directory using the name of the first
                    // entity argument or "AllEntities" if none were given. Close the Visio application. 
                    document.SaveAs(Directory.GetCurrentDirectory() + "\\" + filename);
                    application.Quit();
                }
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
                Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
                Console.WriteLine("Message: {0}", ex.Detail.Message);
                Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText);
                Console.WriteLine("Inner Fault: {0}",
                    null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
            }
            catch (System.TimeoutException ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Message: {0}", ex.Message);
                Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                Console.WriteLine("Inner Fault: {0}",
                    null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);

                    FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> fe
                        = ex.InnerException
                        as FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                    if (fe != null)
                    {
                        Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
                        Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
                        Console.WriteLine("Message: {0}", fe.Detail.Message);
                        Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText);
                        Console.WriteLine("Inner Fault: {0}",
                            null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                    }
                }
            }
            // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
            // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.

            finally
            {
                //Console.WriteLine("Rendering complete.");
                Console.WriteLine("Rendering complete.  Press any key to continue.");
                Console.ReadLine();
            }
            return 0;
        }
示例#51
0
        public void VDX_DetectLoadWarnings()
        {
            string input_filename = this.GetTestResultsOutPath(@"datafiles\vdx_with_warnings_1.vdx");
 
            // Load the VDX
            var app = new IVisio.Application();
            var version = VA.Application.ApplicationHelper.GetVersion(app);
            string logfilename = VA.Application.ApplicationHelper.GetXMLErrorLogFilename(app);

            var doc = this.TryOpen(app.Documents, input_filename);
            
            // See what happened
            var log_after = new VA.Application.Logging.XmlErrorLog(logfilename);
            var most_recent_session = log_after.FileSessions[0];
            var warnings = most_recent_session.Records.Where(r => r.Type == "Warning").ToList();
            var errors = most_recent_session.Records.Where(r => r.Type == "Error").ToList();

            // Verify
            int expected_errors = 0;  // this VDX should not report any errors
            int expected_warnings = 4; // this VDX should contain four warnings for Visio2010 and two warnings for Visio 2013         
            if (version.Major >= 15)
            {
                expected_warnings = 2;
            }

            Assert.AreEqual(expected_errors, errors.Count); // this VDX should not report any errors
            Assert.AreEqual(expected_warnings, warnings.Count); // this VDX should contain exactly two warnings                                
            Assert.AreEqual(1, app.Documents.Count);

            // Cleanup
            VA.Documents.DocumentHelper.ForceCloseAll(app.Documents);
            app.Quit(true);
        }
 private static void create_new_app_instance()
 {
     app = new IVisio.Application();
     var documents = app.Documents;
     documents.Add("");
 }
        public void OrgChart_MultipleOrgCharts()
        {
            // Verify that we can create multiple org charts in one
            // document

            var orgchart = new OCMODEL.OrgChartDocument();

            var n_a = new OCMODEL.Node("A");
            var n_b = new OCMODEL.Node("B");
            var n_c = new OCMODEL.Node("C");
            var n_d = new OCMODEL.Node("D");
            var n_e = new OCMODEL.Node("E");

            n_a.Children.Add(n_b);
            n_a.Children.Add(n_c);
            n_c.Children.Add(n_d);
            n_c.Children.Add(n_e);

            n_a.Size = new VA.Drawing.Size(4, 2);

            orgchart.OrgCharts.Add(n_a);
            orgchart.OrgCharts.Add(n_a);

            var app = new IVisio.Application();

            orgchart.Render(app);

            app.Quit(true);
        }
示例#54
0
        /// <summary>
        /// Main entry point for the application.
        /// </summary>
        /// <param name="connectionName">Name of the connection.</param>
        /// <param name="entities">The entities.</param>
        /// <param name="response">The response.</param>
        /// <param name="worker">The worker.</param>
        /// <param name="e">The <see cref="DoWorkEventArgs"/> instance containing the event data.</param>
        /// <returns></returns>
        public string GenerateDiagram(string connectionName, List<string> entities, RetrieveAllEntitiesResponse response, BackgroundWorker worker, DoWorkEventArgs e)
        {
            String filename = String.Empty;
            VisioApi.Application application;
            VisioApi.Document document;
            DiagramBuilder builder = new DiagramBuilder();

            try
            {
                // Load Visio and create a new document.
                application = new VisioApi.Application();
                application.Visible = false; // Not showing the UI increases rendering speed
                document = application.Documents.Add(String.Empty);

                builder._application = application;
                builder._document = document;

                builder._metadataResponse = response;
                builder.selectedEntitiesNames = entities;

                // Diagram all entities if given no command-line parameters, otherwise diagram
                // those entered as command-line parameters.
                builder.BuildDiagram(entities, String.Join(", ", entities), worker, e);
                filename = "EntitesStructure\\Diagrams.vsd";

                // Save the diagram in the current directory using the name of the first
                // entity argument or "AllEntities" if none were given. Close the Visio application.
                document.SaveAs(Directory.GetCurrentDirectory() + "\\" + filename);
                application.Quit();
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                throw;
            }
            catch (System.Exception)
            {
                throw;
            }

            return filename;
        }
示例#55
0
        public void VDX_CustomProperties()
        {
            string filename = TestGlobals.TestHelper.GetTestMethodOutputFilename(".vdx");

            var template = new VisioAutomation.VDX.Template();
            var doc_node = new VisioAutomation.VDX.Elements.Drawing(template);

            int rect_id = doc_node.GetMasterMetaData("REctAngle").ID;

            var node_page = new VisioAutomation.VDX.Elements.Page(8, 5);
            doc_node.Pages.Add(node_page);

            var node_shape = new VisioAutomation.VDX.Elements.Shape(rect_id, 4, 2, 3, 2);
            node_shape.CustomProps = new VisioAutomation.VDX.Elements.CustomProps();

            var node_custprop0 = new VisioAutomation.VDX.Elements.CustomProp("PROP1");
            node_custprop0.Value = "VALUE1";
            node_shape.CustomProps.Add(node_custprop0);

            var node_custprop1 = new VisioAutomation.VDX.Elements.CustomProp("PROP2");
            node_custprop1.Value = "123";
            node_custprop1.Type.Result = VisioAutomation.VDX.Enums.CustomPropType.String;
            node_shape.CustomProps.Add(node_custprop1);

            var node_custprop2 = new VisioAutomation.VDX.Elements.CustomProp("PROP3");
            node_custprop2.Value = "456";
            node_custprop2.Type.Result = VisioAutomation.VDX.Enums.CustomPropType.Number;
            node_shape.CustomProps.Add(node_custprop2);

            node_page.Shapes.Add(node_shape);

            doc_node.Save(filename);

            var app = new IVisio.Application();
            var docs = app.Documents;
            var doc = docs.Add(filename);

            var page = app.ActivePage;
            var shapes = page.Shapes;
            Assert.AreEqual(1,page.Shapes.Count);

            var shape = page.Shapes[1];
            var customprops = VACUSTPROP.CustomPropertyHelper.Get(shape);

            Assert.IsTrue(customprops.ContainsKey("PROP1"));
            Assert.AreEqual("\"VALUE1\"",customprops["PROP1"].Value.Formula);


            Assert.IsTrue(customprops.ContainsKey("PROP2"));
            Assert.AreEqual("\"123\"", customprops["PROP2"].Value.Formula);
            Assert.AreEqual("0", customprops["PROP2"].Type.Formula);

            Assert.IsTrue(customprops.ContainsKey("PROP3"));
            Assert.AreEqual("\"456\"", customprops["PROP3"].Value.Formula);
            Assert.AreEqual("2", customprops["PROP3"].Type.Formula);

            app.Quit(true);
        }
示例#56
0
 public static bool IsProcess(Application app)
 {
     bool isProcess = false;
     if (app.ActivePage !=null)
     {
         foreach (Layer l in app.ActivePage.Layers)
         {
             if (l.Name == "Process")
             {
                 isProcess = true;
                 break;
             }
         }
     }
         return isProcess;
 }
 public AlertResponseScope(IVisio.Application app, AlertResponseCode value)
 {
     this.app = app;
     this.old_alertresponse = (AlertResponseCode)this.app.AlertResponse;
     this.app.AlertResponse = (short)value;
 }
示例#58
0
 public Session()
 {
     this.app = new IVisio.Application();
     this.NewDocument();
 }
示例#59
0
 /// <summary>
 /// Initialize a new instance of the EventSink class.
 /// </summary>
 /// <param name="application">Reference to current Visio instance.</param>
 public EventSink(VisioApplication application)
 {
     _application = application;
     _events = new ArrayList();
     _displaySettings = new DisplaySettings();
 }
        static void Main(string[] args)
        {
            Visio.Application application = new Visio.Application();
            application.Visible = false; // Hiding the application speeds up rendering.
            application.AutoLayout = false; // Delay autolayout until after putting all shapes on page.

            Visio.Document document = application.Documents.Add(string.Empty);

            try
            {
                Bootstrapper.Bootstrap();

                List<Category> categories;
                List<Formula> formulae;
                List<Rule> rules;
                List<List> lists;
                List<Lookup> lookups;

                var series = repository.RetrieveSeries();

                int i = 0;
                for (; i < series.Count; i++)
                {
                    Console.WriteLine("[{0}] {1}", i + 1, series[i].Description);
                }
                Console.Write("Choose the series [1 - {0}]: ", i);

                int seriesIndex = 0;
                string seriesInput = Console.ReadLine();
                Console.WriteLine();
                Console.WriteLine();

                if (int.TryParse(seriesInput, out seriesIndex) && seriesIndex >= 0 && seriesIndex <= i)
                {
                    Series chosenSerie = series[seriesIndex - 1];

                    var models = repository.RetrieveModelsBySeriesID(chosenSerie.SeriesID);
                    int j = 0;
                    for (; j < models.Count; j++)
                    {
                        Console.WriteLine("[{0}] {1}", j + 1, models[j].Description);
                    }
                    Console.Write("Choose the model [1 - {0}]: ", j);

                    int modelIndex = 0;
                    string modelInput = Console.ReadLine();
                    Console.WriteLine();
                    Console.WriteLine();

                    if (int.TryParse(modelInput, out modelIndex) && modelIndex >= 0 && modelIndex <= j)
                    {
                        Model chosenModel = models[modelIndex - 1];
                        categories = repository.RetrieveCategoriesBySeriesID(chosenSerie.SeriesID);

                        formulae = repository.RetrieveFormulas();

                        rules = repository.RetrieveRulesByModelID(chosenModel.ModelID);

                        lists = repository.RetrieveLists();
                        lookups = repository.RetrieveLookupTables();

                        // Get the default page of our new document
                        Visio.Page page = document.Pages[1];
                        page.Name = "Experlogix";

                        // Set Placement Spacing to "25mm"
                        page.PageSheet.get_CellsU("AvenueSizeY").FormulaU = "25 mm";
                        page.PageSheet.get_CellsU("AvenueSizeX").FormulaU = "25 mm";

                        // Set Connector Appearance to "Curved"
                        page.PageSheet.get_CellsU("LineRouteExt").ResultIU = 2;

                        BuildDiagram(page, categories, formulae, rules, lists, lookups);
                    }
                    else
                    {
                        Console.WriteLine("Unknown model.");
                    }
                }
                else
                {
                    Console.WriteLine("Unknown series.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("An Exception occurred: {0}", e);
            }
            // The following is in a finally block to make sure the application is shown,
            // even when an exception is thrown.
            finally
            {
                // Set autolayout to true to update the layout.
                application.AutoLayout = true;

                // Show the application.
                application.Visible = true;
            }

            Console.WriteLine();
            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }