Ejemplo n.º 1
0
        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);
        }
        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 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
        }
Ejemplo n.º 4
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 void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            //Create Visio Application Object
            Visio.Application vsdApp = Application;

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

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

            //Save the VDX diagram
            vsdDoc.SaveAs("Drawing1.vdx");

            //Save as PDF file
            vsdDoc.ExportAsFixedFormat(Visio.VisFixedFormatTypes.visFixedFormatPDF,
                                       "Drawing1.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("Drawing1.jpg");

            //Quit Visio Object
            vsdApp.Quit();
        }
Ejemplo n.º 6
0
        public static void Quit(this IVisio.Application app, bool force_close)
        {
            if (force_close)
            {
                const short new_alert_response = 7;
                app.AlertResponse = new_alert_response;
            }

            app.Quit();
        }
Ejemplo n.º 7
0
        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);
        }
Ejemplo n.º 8
0
        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);
        }
        static void Main(string[] args)
        {
            var app  = new Visio.Application();
            var doc  = app.Documents.Open(args[0]);
            var page = doc.Pages[1];

            foreach (Visio.Shape shp in page.Shapes)
            {
                Console.WriteLine("shape #{0}: text: '{1}'", shp.ID, shp.Text);
            }
            foreach (Visio.Connect conn in page.Connects)
            {
                Console.WriteLine("connector: #{0} -> #{1}", conn.FromSheet.ID, conn.ToSheet.ID);
            }
            app.Quit();
        }
        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);
        }
Ejemplo n.º 11
0
        /// <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);
        }
Ejemplo n.º 12
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);
        }
Ejemplo n.º 13
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();
        }
Ejemplo n.º 14
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);
        }
Ejemplo n.º 15
0
        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);
            }
        }
Ejemplo n.º 16
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);
        }
Ejemplo n.º 17
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;
            }
        }
Ejemplo n.º 18
0
        public static void DrawModel(Model.DBModel model, bool withViews, bool showVisio, string path, bool physNames, bool allFields)
        {
            if (!System.IO.File.Exists(path + @"Files\SLModel.VSDX"))
            {
                System.Windows.MessageBox.Show("Das Template SLModel.vsdx wurde nicht unter " + path + @"Files\ gefunden. Bitte die README-Datei lesen.");
                return;
            }

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

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

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

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

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

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

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


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


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

                foreach (Model.Relation relation in model.RelationsList)
                {
                    if (relation.FromField.ShapeID != null && relation.ToField.ShapeID != null && relation.TypeFrom != null && relation.TypeTo != null)
                    {
                        int index;
                        if ((relation.TypeFrom.Substring(3).Equals(">>") && relation.TypeTo.Substring(3).Equals("->")) || (relation.TypeFrom.Substring(3).Equals("->") && relation.TypeTo.Substring(3).Equals(">>")))
                        {
                            fromField = relation.TypeFrom.Substring(3).Equals(">>") ? page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID] : page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID];
                            toField   = relation.TypeFrom.Substring(3).Equals(">>") ? page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID] : page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID];
                            index     = 0;
                        }
                        else
                        {
                            if (relation.TypeFrom.Substring(3).Equals(">>") && relation.TypeTo.Substring(3).Equals(">>"))
                            {
                                fromField = page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID];
                                toField   = page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID];
                                index     = 2;
                            }
                            else
                            {
                                fromField = page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID];
                                toField   = page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID];
                                index     = 1;
                            }
                        }
                        ConnectWithDynamicGlueAndConnector(fromField, toField, index);
                    }
                }
                page.AutoSizeDrawing();
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.Message);
            }
            finally
            {
                doc.Save();
                if (showVisio)
                {
                    application.Quit();
                }
            }
            System.Windows.MessageBox.Show("All done!");
        }
Ejemplo n.º 19
0
        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);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Loads a Visio file, reads values from the 'States' and 'Transitions' contained within.
        /// </summary>
        /// <returns>Returns true if no errors were encountered.</returns>
        private bool LoadVisioFileAlex()
        {
            bool   returnval = true;
            string filepath  = m_visioFileTextBox.Text;

            Microsoft.Office.Interop.Visio.Application visio = null;
            Document doc = null;

            //try
            //{
            if (!filepath.EndsWith(".vsd") || !System.IO.File.Exists(filepath))
            {
                return(false);
            }
            _statesList      = new List <State>();
            _transitionsList = new List <Transition>();
            _shapetextlist   = new List <string>();
            m_lcTrans        = new List <Pair>();
            State _State;
            var   _Trans  = new Transition(null, null, null, null);
            var   newACEs = new Dictionary <long, _ACE>();

            //Cell customPropertyCell = null;
            //string teststr = null;

            visio = new Microsoft.Office.Interop.Visio.Application();
            doc   = visio.Documents.Open(filepath);
            var page = doc.Pages[1];

            var connectorMap = new Dictionary <string, ConnectorInfo>();

            foreach (Shape shape in page.Shapes)
            {
                if (shape.Name.StartsWith("Admin") || shape.Name.StartsWith("QA") || shape.Name.StartsWith("Design"))
                {
                    _State           = new State();
                    _State.Statename = shape.Text;
                    //_State.Statename = ReadANamedCustomProperty(shape, DisplayName, true);
                    if (_State.Statename == null)
                    {
                        continue;
                    }
                    if (_shapetextlist.Contains(shape.Text))
                    {
                        throw new Exception("Each state name must be unique.  " +
                                            "State " + shape.Text + " shows up multiple times.");
                    }

                    //Users allowed to have this permission in each state.
                    var tmpACEUsers = ReadANamedCustomProperty(shape, AccessControlEntryUsers, true);
                    if (tmpACEUsers.Contains(","))
                    {
                        var tmpACEusers = tmpACEUsers.Split(',');
                        foreach (var user in tmpACEusers)
                        {
                            _State.AccessControlEntryUserGroups.Add(Convert.ToInt64(user));
                        }
                    }
                    else
                    {
                        _State.AccessControlEntryUserGroups.Add(Convert.ToInt64(tmpACEUsers));
                    }
                    // Permissions for each State.
                    var tmpACEPermissions = ReadANamedCustomProperty(shape, AccessControlEntryPermissions, true);
                    _State.AccessControlEntry = AssignACEPermissions(_State.Statename, tmpACEPermissions,
                                                                     _State.AccessControlEntryUserGroups);
                    var comments = ReadANamedCustomProperty(shape, Comments, true);
                    if (comments.Contains(";"))
                    {
                        var tmpcomments = comments.Split(';');
                        _State.Comments.Add(Convert.ToString(tmpcomments));
                    }
                    else
                    {
                        _State.Comments.Add(comments);
                    }
                    //_State.Comments = ReadANamedCustomProp(shape, _comments, true);
                    if (ReadANamedCustomProperty(shape, IsDefault, true).ToUpper() == Str.ToUpper())
                    {
                        _State.IsDefault = true;
                    }
                    else
                    {
                        _State.IsDefault = false;
                    }
                    if (ReadANamedCustomProperty(shape, IsReleasedState, true).ToUpper() == Str.ToUpper())
                    {
                        _State.IsReleasedState = true;
                    }
                    else
                    {
                        _State.IsReleasedState = false;
                    }
                    switch (ReadANamedCustomProperty(shape, MyRestrictPurgeOption, true))
                    {
                    case ".All":
                        _State.RestrictPurgeOption = RestrictPurgeOption.All;
                        break;

                    case ".FirstAndLast":
                        _State.RestrictPurgeOption = RestrictPurgeOption.FirstAndLast;
                        break;

                    case ".Last":
                        _State.RestrictPurgeOption = RestrictPurgeOption.Last;
                        break;

                    case ".None":
                        _State.RestrictPurgeOption = RestrictPurgeOption.None;
                        break;
                    }
                    _State.StateDescription = ReadANamedCustomProperty(shape, Description, true);
                    if (ReadANamedCustomProperty(shape, UseStateBasedSecurity, true).ToUpper() == Str.ToUpper())
                    {
                        _State.UseStateBasedSecurity = true;
                    }
                    else
                    {
                        _State.UseStateBasedSecurity = false;
                    }
                    if (shape.Text != null)
                    {
                        _shapetextlist.Add(shape.Text);
                        _statesList.Add(_State);
                    }
                }
                else if (shape.Name.StartsWith("Dynamic connector"))
                {
                    _Trans = new Transition(null, null, null, null);
                    foreach (Microsoft.Office.Interop.Visio.Connect connect in shape.Connects)
                    {
                        var fromtext = connect.FromCell.Shape.Text;
                        var fromname = connect.FromCell.Shape.Name;
                        var totext   = connect.ToCell.Shape.Text;
                        _Trans.FromStateName        = fromtext;
                        _Trans.ToStateName          = totext;
                        _Trans.ReverseFromStateName = totext;
                        _Trans.ReverseToStateName   = fromtext;
                        var tmpallowedusers = ReadANamedCustomProperty(shape, AllowedUserIds, true);
                        if (tmpallowedusers.Contains(","))
                        {
                            var tmpAllowedUsers = tmpallowedusers.Split(',');
                            foreach (var tmpstr in tmpAllowedUsers)
                            {
                                _Trans.AllowedUserIds.Add(Convert.ToInt64(tmpstr));
                            }
                        }
                        else
                        {
                            _Trans.AllowedUserIds.Add(Convert.ToInt64(tmpallowedusers));
                        }
                        var tmpdeniedusers = ReadANamedCustomProperty(shape, DeniedUserIds, true);
                        if (tmpdeniedusers.Contains(","))
                        {
                            var tmpDeniedUsers = tmpdeniedusers.Split(',');
                            foreach (var tmpstr in tmpDeniedUsers)
                            {
                                _Trans.DeniedUserIds.Add(Convert.ToInt64(tmpstr));
                            }
                        }
                        else
                        {
                            _Trans.DeniedUserIds.Add(Convert.ToInt64(tmpdeniedusers));
                        }
                        switch (ReadANamedCustomProperty(shape, SyncPropOption, true))
                        {
                        case "None":
                            _Trans.SyncPropOption = JobSyncPropEnum.None;
                            break;

                        case "SysncPropAndUpdateView":
                            _Trans.SyncPropOption = JobSyncPropEnum.SyncPropAndUpdateView;
                            break;

                        case "SyncPropOnly":
                            _Trans.SyncPropOption = JobSyncPropEnum.SyncPropOnly;
                            break;
                        }
                        if (ReadANamedCustomProperty(shape, EnforceChildStateSync, true).ToUpper() == Str.ToUpper())
                        {
                            _Trans.EnforceChildStateSync = true;
                        }
                        else
                        {
                            _Trans.EnforceChildStateSync = false;
                        }
                        if (ReadANamedCustomProperty(shape, UseTransitionBasedSecurity, true).ToUpper() == Str.ToUpper())
                        {
                            _Trans.UseTransitionBasedSecurity = true;
                        }
                        else
                        {
                            _Trans.UseTransitionBasedSecurity = false;
                        }
                        switch (ReadANamedCustomProperty(shape, BumpRevision, true))
                        {
                        case ".BumpPrimary":
                            _Trans.BumpRevision = BumpRevisionEnum.BumpPrimary;
                            break;

                        case ".BumpSecondary":
                            _Trans.BumpRevision = BumpRevisionEnum.BumpSecondary;
                            break;

                        case ".BumpTertiary":
                            _Trans.BumpRevision = BumpRevisionEnum.BumpTertiary;
                            break;

                        case ".None":
                            _Trans.BumpRevision = BumpRevisionEnum.None;
                            break;
                        }

                        var endarrow   = connect.FromSheet.Cells["endarrow"];
                        var beginarrow = connect.FromSheet.Cells["beginarrow"];

                        ConnectorInfo info = null;
                        if (connectorMap.ContainsKey(fromname))
                        {
                            info = connectorMap[fromname];
                        }
                        else
                        {
                            info = new ConnectorInfo(fromname);
                            connectorMap.Add(fromname, info);
                        }
                        var hasarrow = !beginarrow.Formula.StartsWith("theme");
                        info.AddConnection(totext, hasarrow);
                        if (info.ShapeNames.Count > 1)
                        {
                            if (info.ShapeNames[1] == _Trans.ToStateName)
                            {
                                _Trans.FromStateName      = info.ShapeNames[0];
                                _Trans.ReverseToStateName = _Trans.FromStateName;
                                _transitionsList.Add(_Trans);
                            }
                        }
                    }
                }
            }

            Dictionary <string, ConnectorInfo> .Enumerator enumerator = connectorMap.GetEnumerator();
            while (enumerator.MoveNext())
            {
                ConnectorInfo info = enumerator.Current.Value;

                if (info.ShapeNames.Count != 2)
                {
                    continue;
                }

                // the default connector
                if (!info.HasArrows[0] && !info.HasArrows[1])
                {
                    AddPair(new Pair(info.ShapeNames[0], info.ShapeNames[1]));
                }

                if (info.HasArrows[0])
                {
                    AddPair(new Pair(info.ShapeNames[0], info.ShapeNames[1]));
                }

                // the arrow goes the other way too
                if (info.HasArrows[1])
                {
                    AddPair(new Pair(info.ShapeNames[1], info.ShapeNames[0]));
                }
            }
            //}
            //catch (Exception e)
            //{
            //    m_lcStates = null;
            //    m_lcTrans = null;
            //    MessageBox.Show("Exception thrown: " + e.Message);
            //    returnval = false;
            //}
            //finally
            //{
            if (doc != null)
            {
                doc.Close();
            }

            if (visio != null)
            {
                visio.Quit();
            }
            //}
            return(returnval);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// This is the root of the recursive descent to display the tree on the Visio doc.
        /// The function uses PlaceOneShape() to start the recursive display.
        /// </summary>
        /// <param name="colorMap">Color map to use to render.</param>
        /// <param name="root">Root node to render.</param>
        private static void BuildAndDisplayWithVisio(
            Dictionary <string, string> colorMap,
            TypeTreeNode root)
        {
            Visio.Application app             = null;
            Visio.Document    contentDocument = null;

            try
            {
                app = new Visio.Application();
                app.Settings.EnableAutoConnect = false;
                ////app.Window.WindowState = (int)Visio.VisWindowStates.visWSRestored;
                app.Window.WindowState = (int)Visio.VisWindowStates.visWSMinimized;

                contentDocument = app.Documents.AddEx(
                    string.Empty,
                    Visio.VisMeasurementSystem.visMSUS,
                    (int)Visio.VisOpenSaveArgs.visAddDocked,
                    (int)0);

                contentDocument.PaperSize      = Visio.VisPaperSizes.visPaperSizeE;
                contentDocument.PrintLandscape = true;

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

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

                Visio.Page targetPage = contentDocument.Pages[1];
                targetPage.Name = "MFx Class Hirearchy";

                BuildHeadersAndFooters(colorMap, contentDocument);

                /*
                 * Program.selectionTree = app.ActiveWindow.Selection;
                 * Program.selectionTree.DeselectAll();
                 */

                double movingYBase = 4.0;
                foreach (TypeTreeNode t in
                         root.Children.Values.OrderBy(t => t.RawType.Namespace).ThenBy(t => t.RawType.Name))
                {
                    movingYBase = PlaceOneShape(
                        colorMap,
                        targetPage,
                        t,
                        shape,
                        null,
                        2.0,
                        movingYBase);
                }

                // now turn the selection into a group, and run the layout code
                // to make the tree look "right"
                ////Program.selectionTree.Group();

                // resize, set the placement, and connector routing styles
                Visio.Cell layoutCell;

                layoutCell = targetPage.PageSheet.get_CellsSRC(
                    (short)Visio.VisSectionIndices.visSectionObject,
                    (short)Visio.VisRowIndices.visRowPageLayout,
                    (short)Visio.VisCellIndices.visPLOResizePage);

                layoutCell.FormulaU = "FALSE";  // don't add more pages to contain the tree, let the user edit

                layoutCell = targetPage.PageSheet.get_CellsSRC(
                    (short)Visio.VisSectionIndices.visSectionObject,
                    (short)Visio.VisRowIndices.visRowPageLayout,
                    (short)Visio.VisCellIndices.visPLOPlaceStyle);

                layoutCell.set_Result(
                    Visio.VisUnitCodes.visPageUnits,
                    (double)Visio.VisCellVals.visPLOPlaceCompactDownRight);

                layoutCell = targetPage.PageSheet.get_CellsSRC(
                    (short)Visio.VisSectionIndices.visSectionObject,
                    (short)Visio.VisRowIndices.visRowPageLayout,
                    (short)Visio.VisCellIndices.visPLORouteStyle);

                layoutCell.set_Result(
                    Visio.VisUnitCodes.visPageUnits,
                    (double)Visio.VisCellVals.visLORouteOrgChartNS);

                targetPage.Layout();
                ////Program.selectionTree.Layout();

                Program.selectionTree.Group();

                Console.WriteLine("Print and save Visio doc if you want, then enter to quit (Visio will close).");
                Console.ReadLine();
            }
            finally
            {
                if (contentDocument != null)
                {
                    contentDocument.Saved = true;   // not really, but we can lie so the close/quit works.
                    contentDocument.Close();
                }

                if (app != null)
                {
                    app.Quit();
                }
            }
        }
Ejemplo n.º 22
0
        private void LoadVisioFile()
        {
            var filepath = m_visioFileTextBox.Text;

            Microsoft.Office.Interop.Visio.Application visio = null;
            Microsoft.Office.Interop.Visio.Document    doc   = null;
            try
            {
                if (!filepath.EndsWith(".vsd") || !System.IO.File.Exists(filepath))
                {
                    return;
                }

                m_lcStates = new List <string>();
                m_lcTrans  = new List <Pair>();

                visio = new Microsoft.Office.Interop.Visio.Application();
                doc   = visio.Documents.Open(filepath);
                var page = doc.Pages[1];

                var connectorMap = new Dictionary <string, ConnectorInfo>();

                foreach (Microsoft.Office.Interop.Visio.Shape shape in page.Shapes)
                {
                    if (shape.Name.StartsWith("Process"))
                    {
                        if (m_lcStates.Contains(shape.Text))
                        {
                            throw new Exception("Each state name must be unique.  " +
                                                "State " + shape.Text + " shows up multiple times.");
                        }

                        m_lcStates.Add(shape.Text);
                    }
                    else if (shape.Name.StartsWith("Dynamic connector"))
                    {
                        foreach (Connect connect in shape.Connects)
                        {
                            string fromName = connect.FromCell.Shape.Name;
                            string toText   = connect.ToCell.Shape.Text;

                            Cell endArrow   = connect.FromSheet.get_Cells("EndArrow");
                            Cell beginArrow = connect.FromSheet.get_Cells("BeginArrow");

                            ConnectorInfo info = null;
                            if (connectorMap.ContainsKey(fromName))
                            {
                                info = connectorMap[fromName];
                            }
                            else
                            {
                                info = new ConnectorInfo(fromName);
                                connectorMap.Add(fromName, info);
                            }
                            bool hasArrow = !beginArrow.Formula.StartsWith("THEME");
                            info.AddConnection(toText, hasArrow);
                        }
                    }
                }

                Dictionary <string, ConnectorInfo> .Enumerator enumerator = connectorMap.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    ConnectorInfo info = enumerator.Current.Value;

                    if (info.ShapeNames.Count != 2)
                    {
                        continue;
                    }

                    // the default connector
                    if (!info.HasArrows[0] && !info.HasArrows[1])
                    {
                        AddPair(new Pair(info.ShapeNames[0], info.ShapeNames[1]));
                    }

                    if (info.HasArrows[0])
                    {
                        AddPair(new Pair(info.ShapeNames[0], info.ShapeNames[1]));
                    }

                    // the arrow goes the other way too
                    if (info.HasArrows[1])
                    {
                        AddPair(new Pair(info.ShapeNames[1], info.ShapeNames[0]));
                    }
                }
            }
            catch (Exception e)
            {
                m_lcStates = null;
                m_lcTrans  = null;
                MessageBox.Show("Exception thrown: " + e.Message);
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();
                }

                if (visio != null)
                {
                    visio.Quit();
                }
            }
        }
Ejemplo n.º 23
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;
        }
Ejemplo n.º 24
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
            {
                // 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;

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

                var response = builder.RetrieveMetadata();
                Console.WriteLine("Metadata Loaded {0} ...", DateTime.Now.ToLongTimeString());
                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)
                    {
                        entities.Add(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);
        }
Ejemplo n.º 25
0
        public static void DrawModel(DBModel model, bool withViews, bool showVisio, string path, bool physNames, bool allFields)
        {
            if (!System.IO.File.Exists(path + @"Files\SLModel.VSDX"))
            {
                MessageBox.Show("Das Template SLModel.vsdx wurde nicht unter " + path + @"Files\ gefunden. Bitte die README-Datei lesen.");
                return;
            }

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

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

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

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

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

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

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

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

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

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

                             );

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

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

                        TablesToLeaveList.AddRange(tablesListTemp);
                    }


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

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

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

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

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

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


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


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

                foreach (Relation relation in model.RelationsList)
                {
                    if (relation.FromField.ShapeID != null && relation.ToField.ShapeID != null && relation.TypeFrom != null && relation.TypeTo != null)
                    {
                        int index;
                        if ((relation.TypeFrom.Substring(3).Equals(">>") && relation.TypeTo.Substring(3).Equals("->")) || (relation.TypeFrom.Substring(3).Equals("->") && relation.TypeTo.Substring(3).Equals(">>")))
                        {
                            fromField = relation.TypeFrom.Substring(3).Equals(">>") ? page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID] : page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID];
                            toField   = relation.TypeFrom.Substring(3).Equals(">>") ? page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID] : page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID];
                            index     = 0;
                        }
                        else
                        {
                            if (relation.TypeFrom.Substring(3).Equals(">>") && relation.TypeTo.Substring(3).Equals(">>"))
                            {
                                fromField = page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID];
                                toField   = page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID];
                                index     = 2;
                            }
                            else
                            {
                                fromField = page.Shapes.ItemFromUniqueID[relation.FromField.ShapeID];
                                toField   = page.Shapes.ItemFromUniqueID[relation.ToField.ShapeID];
                                index     = 1;
                            }
                        }
                        ConnectWithDynamicGlueAndConnector(fromField, toField, index);
                    }
                }
                page.AutoSizeDrawing();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                doc.Save();
                if (showVisio)
                {
                    application.Quit();
                }
            }
            MessageBox.Show("All done!");
        }
Ejemplo n.º 26
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);
        }
Ejemplo n.º 27
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;
        }
        public void Generate()
        {
            var builder = this;

            try
            {
                // Load Visio and create a new document.
                // Not showing the UI increases rendering speed
                builder.application = application = new VisioApi.Application
                {
                    Visible        = false,
                    ScreenUpdating = 1,
                    EventsEnabled  = 0,
                    ShowChanges    = false,
                    ShowStatusBar  = 0,
                    AlertResponse  = 0,
                    ShowMenus      = 0,
                    ShowProgress   = 0,
                    ShowToolbar    = 0,
                    UndoEnabled    = false,
                };
                builder.versionName = application.Version;
                builder.document    = document = application.Documents.Add(string.Empty);

                Settings.EntitiesSelected.ToList().ForEach(mainEntities.Enqueue);

                builder.processedRelationships = new List <Guid>();

                if (mainEntities.Count <= 0)
                {
                    OnMessage("No entities passed as argument; fetching all entities ...");
                    GetEntities().ToList().ForEach(entityName => mainEntities.Enqueue(entityName.LogicalName));
                }

                OnMessage(string.Format("Parsing {0} ...",
                                        mainEntities.Aggregate((entity1, entity2) => entity1 + ", " + entity2)));

                depth = Settings.Depth;

                // loop through entities to be drawn
                while (mainEntities.Count > 0 && depth >= 0)
                {
                    if (Cancel)
                    {
                        break;
                    }

                    var tempQueue = new Queue <string>();

                    mainEntities.ToList().ForEach(tempQueue.Enqueue);
                    mainEntities.Clear();
                    builder.Parse(tempQueue);

                    depth--;
                }

                // save the diagram in the current directory without overwriting
                var filename = "CRM_ERD.vsd";
                var index    = 1;
                while (File.Exists(filename))
                {
                    filename = "CRM_ERD_" + (index < 10 ? "0" + index++ : index++.ToString()) + ".vsd";
                }
                document.SaveAs(Directory.GetCurrentDirectory() + "\\" + filename);
                OnMessage(string.Format("\n\nSaved diagrams to {0}.", Directory.GetCurrentDirectory() + "\\" + filename));

                if (!Cancel)
                {
                    Done = true;
                }
                else
                {
                    Cancelled = true;
                }
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                OnMessage("\n\nThe application terminated with an error.");
                OnMessage(string.Format("Timestamp: {0}", ex.Detail.Timestamp));
                OnMessage(string.Format("Code: {0}", ex.Detail.ErrorCode));
                OnMessage(string.Format("Message: {0}", ex.Detail.Message));
                OnMessage(string.Format("Plugin Trace: {0}", ex.Detail.TraceText));
                OnMessage(string.Format(
                              "Inner Fault: {0}",
                              null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"));

                Error = ex;
            }
            catch (TimeoutException ex)
            {
                OnMessage("\n\nThe application terminated with an error.");
                OnMessage(string.Format("Message: {0}", ex.Message));
                OnMessage(string.Format("Stack Trace: {0}", ex.StackTrace));
                OnMessage(string.Format("Inner Fault: {0}",
                                        string.IsNullOrEmpty(ex.InnerException.Message) ? "No Inner Fault" : ex.InnerException.Message));

                Error = ex;
            }
            catch (Exception ex)
            {
                OnMessage("\n\nThe application terminated with an error.");
                OnMessage(string.Format(ex.Message));

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    OnMessage(string.Format(ex.InnerException.Message));

                    var fe
                        = ex.InnerException
                          as FaultException <OrganizationServiceFault>;
                    if (fe != null)
                    {
                        OnMessage(string.Format("Timestamp: {0}", fe.Detail.Timestamp));
                        OnMessage(string.Format("Code: {0}", fe.Detail.ErrorCode));
                        OnMessage(string.Format("Message: {0}", fe.Detail.Message));
                        OnMessage(string.Format("Plugin Trace: {0}", fe.Detail.TraceText));
                        OnMessage(string.Format(
                                      "Inner Fault: {0}",
                                      null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"));
                    }
                }

                Error = ex;
            }
            // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
            // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.
            finally
            {
                // close the Visio application.
                application.Quit();
            }
        }
        [STAThread] // Added to support UX
        public static void Main(string[] args)
        {
            CrmServiceClient service  = null;
            String           filename = String.Empty;

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

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    ////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate
                    // 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 = false,
                    };
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)service.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(service, (string[])entities.ToArray(typeof(string)), "All Entities");
                        filename = "AllEntities.vsd";
                    }
                    else
                    {
                        builder.BuildDiagram(service, 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();
                }
                #endregion Demonstrate
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Ejemplo n.º 30
0
 private static void kill()
 {
     doc.Save();
     application.Quit();
 }
Ejemplo n.º 31
0
 public void AbortOpenDocument()
 {
     VisioApp.ActiveDocument.Close();
     VisioApp.Quit();
 }
Ejemplo n.º 32
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;
                }
            }
        }
Ejemplo n.º 33
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();
            }
        }
Ejemplo n.º 34
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);
        }
        public static void Main(string[] args)
        {
            Console.WriteLine("Process models mining started...");

            string[] models = Directory.GetFiles(MODELS_PATH, "*.vsd", SearchOption.AllDirectories);

            foreach (string model in models)
            {
                Console.WriteLine(model);

                Visio.Application visioApp = new Visio.Application();
                Visio.Document    document = visioApp.Documents.Open(model);

                visioApp.Visible = true;

                VBA.VBComponent codeModule = document.VBProject.VBComponents.Add(VBA.vbext_ComponentType.vbext_ct_StdModule);

                string vbaCode = @"
                Sub ExtractProcessModel()
                    Set file = CreateObject(""Scripting.FileSystemObject"").CreateTextFile(""${models_path}"" & ActiveDocument.Name & "".java"", True, True)
    
                    file.Write (""/* "" & ActiveDocument.Name & "" */ {"" & vbNewLine)
                    file.Write (""Process process = repository.createProcess("""""" & ActiveDocument.Name & """""");"" & vbNewLine)
    
                    For i = 1 To ActivePage.Shapes.Count
                        'For native Visio-based EPC diagrams
                        If InStr(ActivePage.Shapes(i).NameU, ""Dynamic connector"") <> 0 Then
                            FromShape = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(1).ToSheet.Text
                            ToShape = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(2).ToSheet.Text
            
                            FromShapeID = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(1).ToSheet.ID
                            ToShapeID = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(2).ToSheet.ID
            
                            FromShapeName = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(1).ToSheet.NameU
                            ToShapeName = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(2).ToSheet.NameU
            
                            If InStr(FromShapeName, ""Organizational unit"") <> 0 Then
                                file.Write (""repository.createResourceFlow("")
                            ElseIf InStr(FromShapeName, ""Information/ Material"") <> 0 Then
                                file.Write (""repository.createInputFlow("")
                            ElseIf InStr(ToShapeName, ""Information/ Material"") <> 0 Then
                                file.Write (""repository.createOutputFlow("")
                            Else
                                file.Write (""repository.createControlFlow("")
                            End If
            
                            For j = 1 To ActivePage.Shapes(i).FromConnects.ToSheet.Connects.Count
                                CurrentShapeName = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.NameU
            
                                ResText = Null
                                ResID = Null
                
                                If j = 1 Then
                                    ResText = FromShape
                                    ResID = FromShapeID
                                Else
                                    ResText = ToShape
                                    ResID = ToShapeID
                                End If
            
                                If InStr(CurrentShapeName, ""Event"") <> 0 Then
                                    file.Write (""repository.createEvent("""""" & ResText & """""", process)"")
                                End If
                
                                If InStr(CurrentShapeName, ""Function"") <> 0 Then
                                    file.Write (""repository.createFunction("""""" & ResText & """""", process)"")
                                End If
                
                                If InStr(CurrentShapeName, ""XOR"") <> 0 Then
                                    file.Write (""repository.createXOrGateway("""""" & ResID & """""", process)"")
                                ElseIf InStr(CurrentShapeName, ""OR"") <> 0 Then
                                    file.Write (""repository.createOrGateway("""""" & ResID & """""", process)"")
                                End If
                
                                If InStr(CurrentShapeName, ""AND"") <> 0 Then
                                    file.Write (""repository.createAndGateway("""""" & ResID & """""", process)"")
                                End If
                
                                If InStr(CurrentShapeName, ""Process path"") <> 0 Then
                                    file.Write (""repository.createProcessInterface("""""" & ResText & """""", process)"")
                                End If
                
                                If InStr(CurrentShapeName, ""Organizational unit"") <> 0 Then
                                    file.Write (""repository.createOrganizationalUnit("""""" & ResText & """""")"")
                                End If
                
                                If InStr(CurrentShapeName, ""Information/ Material"") <> 0 Then
                                    file.Write (""repository.createBusinessObject("""""" & ResText & """""")"")
                                End If
                
                                If j = 1 Then
                                    file.Write ("", "")
                                Else
                                    file.Write ("");"" & vbNewLine)
                                End If
                            Next
                        End If

                        'For custom ARIS stencil-based diagrams
                        If InStr(ActivePage.Shapes(i).Name, ""IsPredecessorOfARIS"") <> 0 Then
                            Subj = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(1).ToSheet.Text
                            Obj = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(2).ToSheet.Text
            
                            file.Write (""repository.createControlFlow("")
            
                            For j = 1 To ActivePage.Shapes(i).FromConnects.ToSheet.Connects.Count
                                ResName = Null
                
                                If j = 1 Then
                                    ResName = Subj
                                Else
                                    ResName = Obj
                                End If
                
                                ValID = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.ID
                
                                If InStr(ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Name, ""EventARIS"") <> 0 Then
                                    file.Write (""repository.createEvent("""""" & ResName & """""", process)"")
                                End If
                
                                If InStr(ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Name, ""FunctionARIS"") <> 0 Then
                                    file.Write (""repository.createFunction("""""" & ResName & """""", process)"")
                                End If
                
                                If InStr(ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Name, ""ProcessInterfaceARIS"") <> 0 Then
                                    file.Write (""repository.createProcessInterface("""""" & ResName & """""", process)"")
                                End If
                
                                If InStr(ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Name, ""ANDruleARIS"") <> 0 Then
                                    file.Write (""repository.createAndGateway("""""" & ValID & """""", process)"")
                                End If
                
                                If InStr(ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Name, ""XORruleARIS"") <> 0 Then
                                    file.Write (""repository.createXOrGateway("""""" & ValID & """""", process)"")
                                ElseIf InStr(ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Name, ""ORruleARIS"") <> 0 Then
                                    file.Write (""repository.createOrGateway("""""" & ValID & """""", process)"")
                                End If
                
                                If j = 1 Then
                                    file.Write ("", "")
                                Else
                                    file.Write ("");"" & vbNewLine)
                                End If
                            Next
                        End If
    
                        If InStr(ActivePage.Shapes(i).Name, ""RoleInProcessARIS"") <> 0 Then
                            Subj = Null
                            Obj = Null
            
                            For j = 1 To ActivePage.Shapes(i).FromConnects.ToSheet.Connects.Count
                                If InStr(ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Name, ""FunctionARIS"") <> 0 Then
                                    Subj = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Text
                                Else
                                    Obj = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Text
                                End If
                            Next
            
                            file.Write (""repository.assignOrganizationalUnits(repository.createFunction("""""" & Subj & """""", process), repository.createOrganizationalUnit("""""" & Obj & """"""));"" & vbNewLine)
                        End If
        
                        If InStr(ActivePage.Shapes(i).Name, ""SoftwareRoleARIS"") <> 0 Then
                            Subj = Null
                            Obj = Null
            
                            For j = 1 To ActivePage.Shapes(i).FromConnects.ToSheet.Connects.Count
                                If InStr(ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Name, ""FunctionARIS"") <> 0 Then
                                    Subj = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Text
                                Else
                                    Obj = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Text
                                End If
                            Next
            
                            file.Write (""repository.assignApplicationSystems(repository.createFunction("""""" & Subj & """""", process), repository.createApplicationSystem("""""" & Obj & """"""));"" & vbNewLine)
                        End If
        
                        If InStr(ActivePage.Shapes(i).Name, ""InputObjectARIS"") <> 0 Then
                            Subj = Null
                            Obj = Null
            
                            For j = 1 To ActivePage.Shapes(i).FromConnects.ToSheet.Connects.Count
                                If InStr(ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Name, ""FunctionARIS"") <> 0 Then
                                    Subj = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Text
                                Else
                                    Obj = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Text
                                End If
                            Next
            
                            file.Write (""repository.assignInputs(repository.createFunction("""""" & Subj & """""", process), repository.createBusinessObject("""""" & Obj & """"""));"" & vbNewLine)
                        End If
        
                        If InStr(ActivePage.Shapes(i).Name, ""OutputObjectARIS"") <> 0 Then
                            Subj = Null
                            Obj = Null
            
                            For j = 1 To ActivePage.Shapes(i).FromConnects.ToSheet.Connects.Count
                                If InStr(ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Name, ""FunctionARIS"") <> 0 Then
                                    Subj = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Text
                                Else
                                    Obj = ActivePage.Shapes(i).FromConnects.ToSheet.Connects(j).ToSheet.Text
                                End If
                            Next
            
                            file.Write (""repository.assignOutputs(repository.createFunction("""""" & Subj & """""", process), repository.createBusinessObject("""""" & Obj & """"""));"" & vbNewLine)
                        End If
                    Next
    
                    file.Write (""repository.store();"" & vbNewLine)
                    file.Write (""}"")
    
                    file.Close
                End Sub";

                vbaCode = vbaCode.Replace("${models_path}", MODELS_PATH);

                codeModule.CodeModule.AddFromString(vbaCode);

                document.ExecuteLine("ExtractProcessModel");

                document.VBProject.VBComponents.Remove(codeModule);

                document.Save();
                document.Close();

                visioApp.Quit();
            }

            string[] files = Directory.GetFiles(MODELS_PATH, "*.java", SearchOption.AllDirectories);

            string modelsCollection = @"
            package main.resources.repository;

            import edu.kopp.phd.ProcessModelRepositoryApplication;
            import edu.kopp.phd.model.flow.Process;
            import edu.kopp.phd.repository.RDFRepository;

            import org.junit.Test;

            public class PortalProcessModelsCollection {
            public RDFRepository repository = RDFRepository.getInstance();
            ";

            foreach (string file in files)
            {
                modelsCollection += File.ReadAllText(file) + "\n";

                File.Delete(file);
            }

            modelsCollection += @"
                @Test
                public void deploy() {
                    ProcessModelRepositoryApplication.run();
                }
            }";

            File.WriteAllText(PORTAL_COLLECTION_PATH, modelsCollection);

            string[] pages = Directory.GetFiles(PAGES_PATH, "*.html", SearchOption.AllDirectories);

            foreach (string page in pages)
            {
                File.Delete(page);
            }

            Console.WriteLine("Done!");
        }
Ejemplo n.º 36
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);
        }
Ejemplo n.º 37
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);
        }