public ProgressDialog(CyPhyMasterInterpreterAPI masterInterpreter)
        {
            InitializeComponent();

            this.MasterInterpreter = masterInterpreter;

            this.m_stopwatch = new System.Diagnostics.Stopwatch();

            // Set default position of the dialog box to not overlay the console.
            var workingArea = Screen.GetWorkingArea(this);
            this.Top = 200;
        }
        private void Process(MgaFCO currentobj)
        {
            if (currentobj == null)
            {
                this.Logger.WriteError("Context is invalid. This component can be executed only if a valid context is open in the main editor (e.g.: Test Bench, Component Assembly).");
                return;
            }

            MgaGateway.PerformInTransaction(() =>
            {
                this.Logger.WriteInfo("Processing {0} [{1}] model", currentobj.Name, currentobj.MetaBase.Name);
            });

            using (var masterInterpreter = new CyPhyMasterInterpreterAPI(currentobj.Project, this.Logger))
            {
                masterInterpreter.IsInteractive = this.InteractiveMode;
                this.Logger.WriteDebug("Interactive mode: {0}", masterInterpreter.IsInteractive);

                Rules.ContextCheckerResult[] contextCheckerResults = null;

                // check context
                var checkerSuccess = false;
                try
                {
                    checkerSuccess = masterInterpreter.TryCheckContext(currentobj as MgaModel, out contextCheckerResults);
                }
                catch (ArgumentOutOfRangeException ex)
                {
                    this.Logger.WriteDebug(ex.ToString());
                    this.Logger.WriteError(ex.Message);
                    return;
                }

                List<Rules.ContextCheckerResult> sortedResults = contextCheckerResults.ToList();

                // sort results Passed, Failed, then alphabetically based on message.
                sortedResults.Sort((x, y) =>
                {
                    return x.Success == y.Success ?
                        x.Message.CompareTo(y.Message) :
                        y.Success.CompareTo(x.Success);
                });

                // Print Checker results
                MgaGateway.PerformInTransaction(() =>
                {
                    foreach (var result in sortedResults)
                    {
                        if (result.Success)
                        {
                            this.Logger.WriteCheckPassed(" <i><a href=\"mga:{0}\">{1}</a></i> {2}", result.Subject.ID, result.Subject.Name, result.Message);
                        }
                        else
                        {
                            this.Logger.WriteCheckFailed(" <i><a href=\"mga:{0}\">{1}</a></i> {2}", result.Subject.ID, result.Subject.Name, result.Message);
                        }
                    }
                });

                if (sortedResults.Any(x => x.Success == false))
                {
                    this.Logger.WriteError("Context is invalid see messeges above. Please fix the problems.");

                    bool controlWasHeld = false;
                    int VK_CONTROL = 0x11;
                    // if user held the control ignore the checker results ... for debugging purposes ONLY!
                    if ((bool)((GetKeyState(VK_CONTROL) & 0x8000) == 0x8000))
                    {
                        controlWasHeld = true;
                    }

                    if (controlWasHeld == false)
                    {
                        return;
                    }
                    else
                    {
                        this.Logger.WriteWarning("Bypassing checker results. This mode is strictly for debugging purposes.");
                    }
                }

                if (checkerSuccess == false)
                {
                    return;
                }

                // context is valid
                // show GUI for the user
                ConfigurationSelection selection = null;

                try
                {
                    selection = masterInterpreter.ShowConfigurationSelectionForm(currentobj as MgaModel);
                    MgaGateway.PerformInTransaction(() =>
                    {
                        this.Logger.WriteDebug("MasterExe command: CyPhyMasterExe.exe \"{0}\" \"{1}\" \"{2}\"", currentobj.Project.ProjectConnStr, GMELightObject.ShortenAbsPath(currentobj.AbsPath),
                            String.Join("\" \"", selection.SelectedConfigurations.Cast<IMgaFCO>().Select(f => GMELightObject.ShortenAbsPath(f.AbsPath)).ToArray()));
                    });
                }
                catch (ExecutionCanceledByUserException ex)
                {
                    this.Logger.WriteWarning("Operation was canceled by user. {0}", ex.Message);
                    return;
                }



                MasterInterpreterResult[] miResults = null;

                // Get a progress dialog
                using (var progressDialog = new ProgressDialog(masterInterpreter))
                {
                    masterInterpreter.MultipleConfigurationProgress += progressDialog.MultipleConfigurationProgressHandler;
                    masterInterpreter.SingleConfigurationProgress += progressDialog.SingleConfigurationProgressHandler;

                    if (masterInterpreter.IsInteractive)
                    {
                        progressDialog.ShowWithDisabledMainWindow();
                    }

                    try
                    {
                        miResults = masterInterpreter.RunInTransactionWithConfig(selection);
                    }
                    catch (AnalysisModelInterpreterConfigurationFailedException ex)
                    {
                        this.Logger.WriteWarning("Operation was canceled by user. {0}", ex.Message);
                    }
                    catch (ExecutionCanceledByUserException ex)
                    {
                        this.Logger.WriteWarning("Operation was canceled by user. {0}", ex.Message);
                    }
                }

                if (selection.OpenDashboard)
                {
                    masterInterpreter.OpenDashboardWithChrome();
                }

                masterInterpreter.WriteSummary(miResults);
            }
        }
Beispiel #3
0
        public void PCBMfg_WorkflowTests()
        {
            var    pathTestbench = "/@TestBenches|kind=Testing|relpos=0/PCB_Manufacturing|kind=TestBench|relpos=0";
            String testName      = System.Reflection.MethodBase.GetCurrentMethod().Name;
            String pathOutput    = Path.Combine(project.GetRootDirectoryPath(),
                                                "output",
                                                testName);
            string configAbsPath = "/@ComponentAssemblies|kind=ComponentAssemblies|relpos=0/@AstableMultivibrator|kind=ComponentAssembly|relpos=0";


            // CyPhy2PCBMfg.CyPhy2PCBMfgInterpreter interpreter = null;

            MgaObject objTestbench = null;
            MgaFCO    configObj    = null;

            project.PerformInTransaction(delegate
            {
                objTestbench = project.get_ObjectByPath(pathTestbench);
                Assert.NotNull(objTestbench);

                configObj = project.get_ObjectByPath(configAbsPath) as MgaFCO;
                Assert.NotNull(configObj);
            });

            bool   postToJobManager = false;
            bool   keepTempModels   = false;
            bool   result           = false;
            string outputDirectory  = "";

            // Use the master Interpreter to create a JSON file in the results folder based on the Testbench's Workflow
            using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project))
            {
                masterInterpreter.Logger.GMEConsoleLoggingLevel = CyPhyGUIs.SmartLogger.MessageType_enum.Debug;

                var miResults = masterInterpreter.RunInTransactionOnOneConfig(objTestbench as MgaModel, configObj, postToJobManager, keepTempModels);
                outputDirectory = miResults[0].OutputDirectory;

                result = miResults.Any(x => x.Success == false) ? false : true;
            }
            Assert.True(result);
            string manifestFileName   = "testbench_manifest.json";
            var    pathToManifestFile = Path.Combine(outputDirectory, manifestFileName);

            Assert.True(File.Exists(pathToManifestFile));
            var fileContents = File.ReadAllText(pathToManifestFile);

            Assert.False(String.IsNullOrWhiteSpace(fileContents));

            // Use a process to start a Python script to execute the JSON file, similar to the Job Manager, but with synchronous execution.
            // See LocalPool.cs around lines 165-186, from the CyPhyMl solution, TestBenchExecutionFramework folder, JobManager project.
            using (var proc0 = new System.Diagnostics.Process())
            {
                proc0.StartInfo.FileName               = META.VersionInfo.PythonVEnvExe;
                proc0.StartInfo.Arguments              = "-m testbenchexecutor testbench_manifest.json";
                proc0.StartInfo.UseShellExecute        = false;
                proc0.StartInfo.CreateNoWindow         = true;
                proc0.StartInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Minimized;
                proc0.StartInfo.WorkingDirectory       = Path.Combine(outputDirectory);
                proc0.StartInfo.RedirectStandardError  = true;
                proc0.StartInfo.RedirectStandardOutput = true;

                proc0.Start();

                StringBuilder output = new StringBuilder();
                proc0.ErrorDataReceived += (o, dataArgs) =>
                {
                    if (dataArgs.Data != null)
                    {
                        try
                        {
                            output.Append(dataArgs.Data);
                        }
                        catch (ObjectDisposedException) { }
                    }
                };
                proc0.OutputDataReceived += (o, dataArgs) =>
                {
                    if (dataArgs.Data != null)
                    {
                        try
                        {
                            output.Append(dataArgs.Data);
                        }
                        catch (ObjectDisposedException) { }
                    }
                };
                proc0.BeginOutputReadLine();
                proc0.BeginErrorReadLine();

                bool isFinished = proc0.WaitForExit(60000);   // Wait up to a minute for the workflow tests to finish.
                Assert.True(isFinished, String.Format("python {0} in {1} timed out", proc0.StartInfo.Arguments, outputDirectory));

                proc0.Refresh();

                if (0 != proc0.ExitCode)
                {
                    Console.WriteLine("Process exit code: {0}",
                                      proc0.ExitCode);
                }
                Assert.True(0 == proc0.ExitCode, "Testbench run failed: " + output.ToString() + "  " + outputDirectory + "  " + File.ReadAllText(Path.Combine(outputDirectory, "testbench_manifest.json")));    // Check that the job finished OK.
            }

            // Check that files were created in the output path.
            string[] createdFileNames =
            {
                "schema.boardoutline.ger",
                "schema.boardoutline.gpi",
                "schema.bottomlayer.ger",
                "schema.bottomlayer.gpi",
                "schema.bottomsilkscreen.ger",
                "schema.bottomsilkscreen.gpi",
                "schema.bottomsoldermask.ger",
                "schema.bottomsoldermask.gpi",
                "schema.drills.dri",
                "schema.drills.xln",
                "schema.tcream.ger",
                "schema.tcream.gpi",
                "schema.toplayer.ger",
                "schema.toplayer.gpi",
                "schema.topsoldermask.ger",
                "schema.topsoldermask.gpi",
                "schema_centroids.csv",
                "schema.XYRS",  // MOT-743
                "assemblyBom.csv"
            };

            foreach (string filename in createdFileNames)
            {
                var pathOutputFile = Path.Combine(outputDirectory, filename);
                Assert.True(File.Exists(pathOutputFile));
                var fileText = File.ReadAllText(pathOutputFile);
                Assert.False(String.IsNullOrWhiteSpace(fileText));
            }
        }
Beispiel #4
0
        public static void Main(string[] args)
        {
            try
            {
                bool noJobCollectionDone = false;
                // parse command line arguments
                string jobCollectionId = new Guid().ToString("D");
                while (true)
                {
                    if (args[0] == "--job-collection-id")
                    {
                        jobCollectionId = args[1];
                        args            = args.Skip(2).ToArray();
                    }
                    else if (args[0] == "--no-job-collection-done")
                    {
                        noJobCollectionDone = true;
                        args = args.Skip(1).ToArray();
                    }
                    else
                    {
                        break;
                    }
                }
                if (args[0] == "--send-job-collection-done")
                {
                    var dispatch = new JobManagerDispatch(jobCollectionId);
                    dispatch.StartJobManager(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
                    dispatch.Done();
                    return;
                }
                string   projectConnStr    = args[0];
                string   originalSubjectID = args[1];
                string[] configIDs         = args.Skip(2).ToArray();

                if (projectConnStr.StartsWith("MGA=") == false)
                {
                    // use the full absolute path
                    projectConnStr = "MGA=" + Path.GetFullPath(projectConnStr);
                }

                MgaProject project = new MgaProject();
                bool       ro_mode;
                project.Open(projectConnStr, out ro_mode);

                try
                {
                    // get an instance of the master interpreter
                    using (var master = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project))
                    {
                        master.SetJobCollectionID(jobCollectionId);
                        if (noJobCollectionDone == true)
                        {
                            master.SetSendJobCollectionDone(false);
                        }
                        // create a configuration for the run
                        var configLight = new CyPhyMasterInterpreter.ConfigurationSelectionLight();
                        configLight.ContextId = originalSubjectID;
                        configLight.SelectedConfigurationIds = configIDs;
                        configLight.KeepTemporaryModels      = false;
                        configLight.PostToJobManager         = true;

                        // run master interpreter on configuration
                        var results = master.RunInTransactionWithConfigLight(configLight);

                        // summarize results
                        master.WriteSummary(results);
                        System.Environment.Exit(results.Where(r => r.Success == false).Count());
                    }
                }
                finally
                {
                    project.Close(true);
                }
            }
            catch (Exception e)
            {
                System.Console.Error.WriteLine(e.ToString());
                System.Environment.Exit(5);
            }
        }