static void Main(string[] args)
        {
            //Type t = Type.GetTypeFromProgID("UbtRfidScanner.ComComponent");
            //dynamic component = Activator.CreateInstance(t);
            var component = new ComComponent();

            bool result = component.ConnectComPort(5);

            component.OnRfidArrived2 += new EventHandler <string>(OnRfidArrived2);

            if (!component.ConnectComPort(5))
            {
                Console.WriteLine("Не удалось подключиться " + component.LastReturnCodeDescription());
            }
            else
            {
                Console.WriteLine("Подключились");
            }

            //component.OnRfidArrived += OnRfidArrived;
            component.StartScanning();

            Console.ReadKey();
            //component.DisconnectComPort();
        }
Пример #2
0
        public bool EnqueueJob(
            string runCommand,
            string title,
            string testbenchName,
            string workingDirectory,
            string projectDirectory,
            ComComponent interpreter)
        {
            // TODO: cut down the number of input variables. interpreter and title should be enough
            JobServer manager;
            Job       j = CreateJob(out manager, projectDirectory);

            j.RunCommand       = runCommand;
            j.Title            = title;
            j.TestBenchName    = testbenchName;
            j.WorkingDirectory = workingDirectory;

            j.Labels = String.IsNullOrWhiteSpace(interpreter.result.Labels) ?
                       Job.DefaultLabels :
                       interpreter.result.Labels;

            j.BuildQuery = String.IsNullOrWhiteSpace(interpreter.result.BuildQuery) ?
                           Job.DefaultBuildQuery :
                           interpreter.result.BuildQuery;

            if (String.IsNullOrWhiteSpace(interpreter.result.ZippyServerSideHook) == false)
            {
                j.ResultsZip = interpreter.result.ZippyServerSideHook as string;
            }

            jobsToAdd.Enqueue(new KeyValuePair <JobServer, Job>(manager, j));
            return(true);
        }
Пример #3
0
        private void CallCAD(
            MgaProject project,
            MgaFCO currentobj,
            MgaFCOs selectedobjs,
            int param)
        {
            Type tCAD = Type.GetTypeFromProgID("MGA.Interpreter.CyPhy2CAD_CSharp");

            if (tCAD == null)
            {
                GMEConsole.Info.WriteLine("CyPhy2CAD is not installed on your machine.");
                return;
            }
            ComComponent cyPhy2CAD = new ComComponent("MGA.Interpreter.CyPhy2CAD_CSharp");

            //cyPhy2CAD.WorkflowParameters["prepIFab"] = "true";
            cyPhy2CAD.Initialize(project);
            cyPhy2CAD.InterpreterConfig = cadSettings;
            // TODO cyPhy2CAD.MainParameters.config.prepIFab = true;
            //cyPhy2CAD.MainParameters.ConsoleMessages = ;
            cyPhy2CAD.MainParameters.Project          = project;
            cyPhy2CAD.MainParameters.CurrentFCO       = currentobj;
            cyPhy2CAD.MainParameters.SelectedFCOs     = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs"));
            cyPhy2CAD.MainParameters.StartModeParam   = param;
            cyPhy2CAD.MainParameters.OutputDirectory  = this.OutputDirectory;
            cyPhy2CAD.MainParameters.ProjectDirectory = this.ProjectRootDirectory;
            cyPhy2CAD.Main();


            this.componentParameters["results_zip_py"] = cyPhy2CAD.result.ZippyServerSideHook;
        }
Пример #4
0
        private void LoadInterpreters()
        {
            List <ComComponent> ComComponents = new List <ComComponent>();

            MgaRegistrar       registrar  = new MgaRegistrar();
            regaccessmode_enum r          = regaccessmode_enum.REGACCESS_BOTH;
            IEnumerable        components = (IEnumerable)(object)registrar.GetComponentsDisp(r);

            string paradigm = "CyPhyML";

            foreach (string comProgId in components)
            {
                try
                {
                    bool isAssociated;
                    bool canAssociate;

                    registrar.IsAssociated(comProgId, paradigm, out isAssociated, out canAssociate, r);
                    string DllPath = registrar.LocalDllPath[comProgId];

                    componenttype_enum Type;
                    string             desc;
                    registrar.QueryComponent(
                        comProgId,
                        out Type,
                        out desc,
                        regaccessmode_enum.REGACCESS_BOTH);

                    bool isInterpreter = false;
                    isInterpreter = (Type == componenttype_enum.COMPONENTTYPE_INTERPRETER);

                    if (canAssociate &&
                        File.Exists(DllPath) &&
                        isInterpreter)
                    {
                        ComComponent component = new ComComponent(comProgId);
                        if (component.isValid)
                        {
                            ComComponents.Add(component);
                        }
                    }
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    // don't add to list
                }
            }

            lbInterpreters.Items.Clear();
            ComComponents.Sort((Comparison <ComComponent>)((a, b) => a.ToString().CompareTo(b.ToString())));
            foreach (ComComponent c in ComComponents)
            {
                lbInterpreters.Items.Add(c);
            }
        }
Пример #5
0
        public void MouseLeftButtonDoubleClick(uint nFlags, int pointx, int pointy, ulong transformHDC)
        {
            if (Parameters == null || TaskProgId == null)
            {
                throw new COMException("Not handled", S_DECORATOR_EVENT_NOT_HANDLED);
            }

            ComComponent c = new ComComponent(TaskProgId);
            Dictionary <string, string> ParametersDict = new Dictionary <string, string>();

            if (string.IsNullOrWhiteSpace(Parameters) == false)
            {
                try
                {
                    ParametersDict = (Dictionary <string, string>)JsonConvert.DeserializeObject(Parameters, typeof(Dictionary <string, string>));
                }
                catch (Newtonsoft.Json.JsonReaderException) { }
            }

            foreach (var parameter in c.WorkflowParameterList.Where(p => !ParametersDict.ContainsKey(p)))
            {
                ParametersDict[parameter] = c.GetWorkflowParameterValue(parameter);
            }

            List <ParameterSettingsForm.Parameter> parameters;

            parameters = ParametersDict.Select(x => new ParameterSettingsForm.Parameter()
            {
                Name  = x.Key,
                Value = x.Value,
            }).ToList();

            myobj.Project.BeginTransactionInNewTerr();
            if (c.isValid == false || myobj.IsLibObject || myobj.HasReadOnlyAccess())
            {
                myobj.Project.AbortTransaction();
                return;
            }
            using (ParameterSettingsForm form = new ParameterSettingsForm(parameters, TaskProgId))
            {
                form.ShowDialog();
                Dictionary <String, String> d = form.parameters.ToDictionary(p => p.Name, p => p.Value);
                string serialized             = JsonConvert.SerializeObject(d, Formatting.Indented);
                try
                {
                    Parameters = myobj.StrAttrByName["Parameters"] = serialized;
                }
                catch
                {
                    myobj.Project.AbortTransaction();
                    return;
                }
                myobj.Project.CommitTransaction();
            }
        }
Пример #6
0
        public IInterpreterConfiguration DoGUIConfiguration(IInterpreterPreConfiguration preConfig, IInterpreterConfiguration previousConfig)
        {
            var          config    = (PrepareIFabConfig)preConfig;
            ComComponent cyPhy2CAD = new ComComponent("MGA.Interpreter.CyPhy2CAD_CSharp");

            cyPhy2CAD.DoGUIConfiguration(config.ProjectDirectory);
            // TODO: when CyPhy2CAD implements ICyPhyInterpreter, save its config in ours
            CyPhy2CAD_CSharp.CyPhy2CADSettings cadSettings = (CyPhy2CAD_CSharp.CyPhy2CADSettings)(cyPhy2CAD.InterpreterConfig);
            config.AuxiliaryDirectory = cadSettings.AuxiliaryDirectory;
            config.StepFormats        = cadSettings.StepFormats;

            return(config);
        }
Пример #7
0
        public IInterpreterConfiguration DoGUIConfiguration(IInterpreterPreConfiguration preConfig, IInterpreterConfiguration previousConfig)
        {
            var          config    = (CADAnalysisConfig)preConfig;
            ComComponent cyPhy2CAD = new ComComponent("MGA.Interpreter.CyPhy2CAD_CSharp");
            bool         cyPhy2CADConfigWasSuccessful = cyPhy2CAD.DoGUIConfiguration(config.ProjectDirectory);

            if (cyPhy2CADConfigWasSuccessful == false)
            {
                return(null);
            }
            // TODO: when CyPhy2CAD implements ICyPhyInterpreter, save its config in ours
            CyPhy2CAD_CSharp.CyPhy2CADSettings cadSettings = (CyPhy2CAD_CSharp.CyPhy2CADSettings)(cyPhy2CAD.InterpreterConfig);
            config.AuxiliaryDirectory = cadSettings.AuxiliaryDirectory;
            config.StepFormats        = cadSettings.StepFormats;

            return(config);
        }
Пример #8
0
        // JS: 7/15/13
        private void CallComponentExporter(
            MgaProject project,
            MgaFCO currentobj,
            MgaFCOs selectedobjs,
            int param)
        {
            Type tCAD = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyComponentExporter");

            if (tCAD == null)
            {
                GMEConsole.Info.WriteLine("CyPhyComponentExporter is not installed on your machine.");
                return;
            }
            ComComponent cyPhyCompExp = new ComComponent("MGA.Interpreter.CyPhyComponentExporter");

            cyPhyCompExp.Initialize(project);

            // call component exporter to traverse design and build component index
            CyPhyComponentExporter.CyPhyComponentExporterInterpreter compExport = new CyPhyComponentExporter.CyPhyComponentExporterInterpreter();
            compExport.Initialize(project);
            compExport.TraverseTestBenchForComponentExport(currentobj, this.OutputDirectory, this.ProjectRootDirectory);
        }
Пример #9
0
        public override Queue <ComComponent> GetWorkflow()
        {
            // TODO: implement this method appropriately
            Queue <ComComponent> workflow = new Queue <ComComponent>();

            this.ExecuteInTransaction(() =>
            {
                var workflowRef = this.testBenchType
                                  .Children
                                  .WorkflowRefCollection
                                  .ToList();

                if (workflowRef.Count == 0)
                {
                    if (this.testBenchType.Kind == typeof(CyPhy.CADTestBench).Name)
                    {
                        // use CyPhy2CAD by default
                        workflow.Enqueue(new ComComponent("MGA.Interpreter.CyPhy2CAD_CSharp", true));
                    }
                    else if (this.testBenchType.Kind == typeof(CyPhy.KinematicTestBench).Name)
                    {
                        // use CyPhy2CAD_CSharp by default
                        workflow.Enqueue(new ComComponent("MGA.Interpreter.CyPhy2CAD_CSharp", true));
                    }
                    else if (this.testBenchType.Kind == typeof(CyPhy.BlastTestBench).Name)
                    {
                        // use CyPhy2CAD_CSharp by default
                        workflow.Enqueue(new ComComponent("MGA.Interpreter.CyPhy2CAD_CSharp", true));
                    }
                    else if (this.testBenchType.Kind == typeof(CyPhy.BallisticTestBench).Name)
                    {
                        // use CyPhy2CAD_CSharp by default
                        workflow.Enqueue(new ComComponent("MGA.Interpreter.CyPhy2CAD_CSharp", true));
                    }
                    else if (this.testBenchType.Kind == typeof(CyPhy.CFDTestBench).Name)
                    {
                        // use CyPhy2CAD_CSharp by default
                        workflow.Enqueue(new ComComponent("MGA.Interpreter.CyPhy2CAD_CSharp", true));
                    }
                    else
                    {
                        // use NOTHING by default see JIRA
                    }
                }
                else if (workflowRef.Count == 1)
                {
                    workflow.Clear();

                    Queue <string> items = new Queue <string>();
                    var tasks            = new List <CyPhy.Task>();
                    var processed        = new List <CyPhy.TaskBase>();

                    if (workflowRef[0].Referred.Workflow != null)
                    {
                        //tasks.AddRange(workflowRef[0].Referred.Workflow.Children.TaskCollection);

                        //CyPhy.Task startTask = null;

                        //startTask = tasks
                        //    .Where(x => x.AllSrcConnections.Count() == 0)
                        //    .FirstOrDefault();

                        // TODO: signal a warning/error if there are multiple sources

                        CyPhy.Task nextTask = this.GetInitialTask(workflowRef[0].Referred.Workflow);

                        // avoid loops
                        while (nextTask != null &&
                               processed.Contains(nextTask) == false)
                        {
                            processed.Add(nextTask);
                            ComComponent component = new ComComponent(nextTask.Attributes.COMName);
                            if (component.isValid == false)
                            {
                                throw new ApplicationException("Could not create " + nextTask.Attributes.COMName);
                            }
                            string parameters = nextTask.Attributes.Parameters;

                            try
                            {
                                component.WorkflowParameters = (Dictionary <string, string>)JsonConvert.DeserializeObject(parameters, typeof(Dictionary <string, string>));
                                if (component.WorkflowParameters == null)
                                {
                                    component.WorkflowParameters = new Dictionary <string, string>();
                                }
                            }
                            catch (JsonException ex)
                            {
                                throw new ApplicationException(String.Format("Could not parse Parameters for '{0}'", nextTask.Name), ex);
                            }
                            workflow.Enqueue(component);

                            var flow = nextTask.DstConnections.FlowCollection.FirstOrDefault();
                            if (flow == null)
                            {
                                nextTask = null;
                            }
                            else // skip all execution tasks
                            {
                                var taskBase = flow.DstEnds.TaskBase;
                                while (taskBase != null &&
                                       processed.Contains(taskBase) == false)
                                {
                                    if (taskBase.Impl.MetaBase.Name == (typeof(CyPhy.Task).Name))
                                    {
                                        nextTask = CyPhyClasses.Task.Cast(taskBase.Impl);
                                        break;
                                    }

                                    processed.Add(taskBase);
                                    flow = taskBase.DstConnections.FlowCollection.FirstOrDefault();
                                    if (flow == null)
                                    {
                                        taskBase = null;
                                        nextTask = null;
                                        break;
                                    }
                                    else
                                    {
                                        taskBase = flow.DstEnds.TaskBase;
                                    }
                                }
                            }
                        }
                    }
                }
                else if (workflowRef.Count > 1)
                {
                    // not supported
                    throw new NotImplementedException("WorkflowRef is greater than 1.");
                }
            });
            return(workflow);
        }
Пример #10
0
        public void Initialize(
            MgaProject project,
            MgaMetaPart meta,
            MgaFCO obj)
        {
            // only store temporarily, they might be unavailable later
            myobj     = obj;
            mymetaobj = null;
            FCOKind   = myobj?.Meta?.Name;
            MetaKind  = meta.Name;

            // obtain the metaobject
            GetMetaFCO(meta, out mymetaobj);

            if (obj != null)
            {
                // concrete object
                name = myobj.Name;
                if (myobj.Meta.Name == "Task")
                {
                    // task
                    // get progid check whether it is already in the cache
                    TaskProgId = myobj.StrAttrByName["COMName"];
                    if (interpreters.Keys.Contains(TaskProgId) == false)
                    {
                        // create an instance
                        ComComponent task = new ComComponent(TaskProgId);
                        interpreters.Add(TaskProgId, task);
                    }
                    // save parameters
                    Parameters = myobj.StrAttrByName["Parameters"];
                    h          = IconHeight;
                    w          = IconWidth;
                }
                else if (myobj.Meta.Name == "WorkflowRef")
                {
                    // Workflow reference get the tasks
                    // TODO: get those in the right order
                    workflow.Clear();
                    MgaReference   wfRef     = myobj as MgaReference;
                    Queue <string> items     = new Queue <string>();
                    List <MgaAtom> tasks     = new List <MgaAtom>();
                    List <MgaFCO>  processed = new List <MgaFCO>();

                    if (wfRef.Referred != null)
                    {
                        HashSet <string> taskKinds = new HashSet <string>()
                        {
                            "ExecutionTask",
                            "Task"
                        };
                        tasks.AddRange(wfRef.Referred.ChildObjects.OfType <MgaAtom>().Where(atom => taskKinds.Contains(atom.Meta.Name)));

                        MgaAtom StartTask = null;

                        StartTask = tasks.
                                    Where(x => x.ExSrcFcos().Count() == 0).
                                    FirstOrDefault();

                        if (StartTask != null)
                        {
                            this.EnqueueTask(StartTask as MgaFCO);
                            processed.Add(StartTask as MgaFCO);

                            MgaFCO NextTask = StartTask.ExDstFcos().FirstOrDefault();

                            // avoid loops
                            while (NextTask != null &&
                                   processed.Contains(NextTask) == false)
                            {
                                processed.Add(NextTask as MgaFCO);
                                this.EnqueueTask(NextTask);
                                NextTask = NextTask.ExDstFcos().FirstOrDefault();
                            }
                        }
                    }
                    h = IconHeight;
                    if (workflow.Count > 0)
                    {
                        w = IconWidth * workflow.Count +
                            TaskPadding * (workflow.Count - 1);
                    }
                    else
                    {
                        w = IconWidth;
                    }
                }
                else if (myobj.Meta.Name == "MetricConstraint")
                {
                    h = 40;
                    w = 40;
                    MetricConstraint_TargetType = myobj.GetStrAttrByNameDisp("TargetType");
                }
            }
            else
            {
                // not a concreter object (maybe in part browser?)
                name = mymetaobj.DisplayedName;
                h    = IconHeight;
                w    = IconWidth;
                if (MetaKind == "MetricConstraint")
                {
                    h = 40;
                    w = 40;
                }
            }

            // to handle color and labelColor settings in GME
            if (!GetColorPreference(out color, "color"))
            {
                color = Color.Black;
            }
            if (!GetColorPreference(out labelColor, "nameColor"))
            {
                labelColor = Color.Black;
            }

            // null them for sure
            // myobj = null;
            mymetaobj = null;
        }
Пример #11
0
        private void DrawWorkflowRef(Graphics g)
        {
            int  i    = 0;
            Icon icon = null;

            foreach (TaskInfo taskInfo in workflow)
            {
                IntPtr hIcon  = IntPtr.Zero;
                Bitmap bitmap = null;
                if (taskInfo.IsComComponent)
                {
                    var comComponent = new ComComponent(taskInfo.COMName);
                    // FIXME cache this per-process for performance
                    if (comComponent.isValid)
                    {
                        MgaRegistrar registrar   = new MgaRegistrar();
                        string       DllFileName = registrar.LocalDllPath[comComponent.ProgId];
                        try
                        {
                            // if the value is ,IDI_COMPICON get the icon from the dll
                            string iconFileNameGuess = Path.ChangeExtension(DllFileName, ".ico");
                            string iconPath          = null;
                            try
                            {
                                iconPath = registrar.ComponentExtraInfo[regaccessmode_enum.REGACCESS_BOTH, taskInfo.COMName, "Icon"];
                            }
                            catch (COMException)
                            {
                            }

                            if (File.Exists(iconFileNameGuess))
                            {
                                icon = Icon.ExtractAssociatedIcon(iconFileNameGuess);
                            }
                            else if (iconPath != null && File.Exists(iconPath))
                            {
                                icon = Icon.ExtractAssociatedIcon(iconPath);
                            }
                            else
                            {
                                icon = Icon.ExtractAssociatedIcon(DllFileName);
                            }
                        }
                        catch (ArgumentException)
                        {
                        }
                    }
                    else
                    {
                        // draw error image
                        icon = new Icon(InvalidTask, InvalidTask.Size);
                    }
                }
                else
                {
                    string iconFileName = taskInfo.IconName;
                    if (!string.IsNullOrWhiteSpace(iconFileName) &&
                        File.Exists(iconFileName))
                    {
                        bitmap = (Bitmap)Image.FromFile(iconFileName);
                        hIcon  = bitmap.GetHicon();
                        icon   = Icon.FromHandle(hIcon);
                    }
                    else
                    {
                        icon = new Icon(InvalidTask, InvalidTask.Size);
                    }
                }

                try
                {
                    int IconStartX = x + (IconWidth + TaskPadding) * i;
                    var placedIcon = new Icon(icon, IconWidth, IconHeight);
                    using (placedIcon)
                    {
                        g.DrawIcon(placedIcon, new Rectangle(IconStartX, y, IconWidth, IconHeight));
                    }

                    if (taskInfo != workflow.Last())
                    {
                        Pen p = new Pen(Color.Black, LineWidth * g.DpiX / 96);
                        using (p)
                        {
                            p.StartCap = LineStartCap;
                            p.EndCap   = LineEndCap;
                            int LineStartX = IconStartX + IconWidth;
                            g.DrawLine(p,
                                       new Point(
                                           LineStartX + LineStartPadding,
                                           y + IconHeight / 2),
                                       new Point(
                                           LineStartX + TaskPadding - LineEndPadding,
                                           y + IconHeight / 2));
                        }
                    }
                    i++;
                }
                catch (ArgumentException)
                {
                }
                finally
                {
                    if (bitmap != null)
                    {
                        bitmap.Dispose();
                        bitmap = null;
                    }
                    if (icon != null)
                    {
                        icon.Dispose();
                        icon = null;
                    }
                    if (hIcon != IntPtr.Zero)
                    {
                        if (DestroyIcon(hIcon) == false)
                        {
                            throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                }
            }
            if (workflow.Count == 0)
            {
                icon = UndefinedWorkFlow;
                g.DrawIcon(
                    icon, // new Icon(icon, IconWidth, IconHeight),
                    new Rectangle(x, y, IconWidth, IconHeight));
            }
        }
Пример #12
0
        public void Draw(uint hdc)
        {
            // VERY important to cast to int
            System.IntPtr hdcptr;
            unchecked { hdcptr = (System.IntPtr)(int) hdc; }

            // Create graphics object
            Graphics g = Graphics.FromHdc(hdcptr);

            // Set up string format for the label
            StringFormat sf = new StringFormat(StringFormatFlags.NoClip);

            sf.Alignment     = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;

            // Drawing style
            // n.b. GME decorators are based on pixels and shouldn't be scaled by DPI changes
            Font  font  = new Font("Arial", 12f, GraphicsUnit.Pixel);
            Pen   pen   = new Pen(color);
            Brush brush = new SolidBrush(color);

#if DEBUG
            // Draw the place
            g.DrawRectangle(pen, x, y, w, h);
#endif
            Color  contentColor = Color.Black;
            string Content      = "";
            //if (myobj == null)
            //{
            //  g.Dispose();
            //  return;
            //}
            if (FCOKind == "Task")
            {
                Icon icon = null;
                if (interpreters[TaskProgId].isValid)
                {
                    contentColor = Color.Blue;
                    Content      = interpreters[TaskProgId].ToolTip;
                    if (string.IsNullOrWhiteSpace(Content))
                    {
                        Content = interpreters[TaskProgId].Name;
                    }
                    if (Content.StartsWith("MGA.Interpreter.", StringComparison.InvariantCultureIgnoreCase))
                    {
                        Content = Content.Substring("MGA.Interpreter.".Length);
                    }
                    MgaRegistrar registrar   = new MgaRegistrar();
                    string       DllFileName = registrar.LocalDllPath[TaskProgId];
                    try
                    {
                        // if the value is ,IDI_COMPICON get the icon from the dll
                        string iconFileNameGuess = Path.ChangeExtension(DllFileName, ".ico");
                        string iconPath          = null;
                        try
                        {
                            iconPath = registrar.ComponentExtraInfo[regaccessmode_enum.REGACCESS_BOTH, TaskProgId, "Icon"];
                        }
                        catch (COMException)
                        {
                        }

                        if (File.Exists(iconFileNameGuess))
                        {
                            icon = Icon.ExtractAssociatedIcon(iconFileNameGuess);
                        }
                        else if (iconPath != null && File.Exists(iconPath))
                        {
                            icon = Icon.ExtractAssociatedIcon(iconPath);
                        }
                        else
                        {
                            icon = Icon.ExtractAssociatedIcon(DllFileName);
                        }
                    }
                    catch (ArgumentException)
                    {
                    }
                }
                else
                {
                    contentColor = Color.Red;
                    Content      = "INVALID" + Environment.NewLine + TaskProgId;
                    icon         = InvalidTask;
                }
                using (Icon icon2 = new Icon(icon, IconWidth, IconHeight))
                    g.DrawIcon(icon2, new Rectangle(x, y, IconWidth, IconHeight));

                g.DrawString(
                    Content,
                    font,
                    new SolidBrush(contentColor),
                    x + w / 2.0f,
                    y + h + LabelSize.Height * 1.2f, sf);
            }
            else if (FCOKind == "WorkflowRef")
            {
                int  i    = 0;
                Icon icon = null;

                foreach (TaskInfo taskInfo in workflow)
                {
                    Bitmap bitmap = null;
                    if (taskInfo.IsComComponent)
                    {
                        var comComponent = new ComComponent(taskInfo.COMName);
                        // FIXME cache this per-process for performance
                        if (comComponent.isValid)
                        {
                            MgaRegistrar registrar   = new MgaRegistrar();
                            string       DllFileName = registrar.LocalDllPath[comComponent.ProgId];
                            try
                            {
                                // if the value is ,IDI_COMPICON get the icon from the dll
                                string iconFileNameGuess = Path.ChangeExtension(DllFileName, ".ico");
                                string iconPath          = null;
                                try
                                {
                                    iconPath = registrar.ComponentExtraInfo[regaccessmode_enum.REGACCESS_BOTH, taskInfo.COMName, "Icon"];
                                }
                                catch (COMException)
                                {
                                }

                                if (File.Exists(iconFileNameGuess))
                                {
                                    icon = Icon.ExtractAssociatedIcon(iconFileNameGuess);
                                }
                                else if (iconPath != null && File.Exists(iconPath))
                                {
                                    icon = Icon.ExtractAssociatedIcon(iconPath);
                                }
                                else
                                {
                                    icon = Icon.ExtractAssociatedIcon(DllFileName);
                                }
                            }
                            catch (ArgumentException)
                            {
                            }
                        }
                        else
                        {
                            // draw error image
                            icon = new Icon(InvalidTask, InvalidTask.Size);
                        }
                    }
                    else
                    {
                        string iconFileName = taskInfo.IconName;
                        if (!string.IsNullOrWhiteSpace(iconFileName) &&
                            File.Exists(iconFileName))
                        {
                            bitmap = (Bitmap)Image.FromFile(iconFileName);
                            icon   = Icon.FromHandle(bitmap.GetHicon());
                        }
                        else
                        {
                            icon = new Icon(InvalidTask, InvalidTask.Size);
                        }
                    }

                    try
                    {
                        int IconStartX = x + (IconWidth + TaskPadding) * i;
                        var placedIcon = new Icon(icon, IconWidth, IconHeight);
                        using (placedIcon)
                        {
                            g.DrawIcon(placedIcon, new Rectangle(IconStartX, y, IconWidth, IconHeight));
                        }

                        if (taskInfo != workflow.Last())
                        {
                            Pen p = new Pen(Color.Black, LineWidth * g.DpiX / 96);
                            using (p)
                            {
                                p.StartCap = LineStartCap;
                                p.EndCap   = LineEndCap;
                                int LineStartX = IconStartX + IconWidth;
                                g.DrawLine(p,
                                           new Point(
                                               LineStartX + LineStartPadding,
                                               y + IconHeight / 2),
                                           new Point(
                                               LineStartX + TaskPadding - LineEndPadding,
                                               y + IconHeight / 2));
                            }
                        }
                        i++;
                    }
                    catch (ArgumentException)
                    {
                    }
                    finally
                    {
                        if (bitmap != null)
                        {
                            bitmap.Dispose();
                            bitmap = null;
                        }
                        if (icon != null)
                        {
                            icon.Dispose();
                            icon = null;
                        }
                    }
                }
                if (workflow.Count == 0)
                {
                    icon = UndefinedWorkFlow;
                    g.DrawIcon(
                        icon, // new Icon(icon, IconWidth, IconHeight),
                        new Rectangle(x, y, IconWidth, IconHeight));
                }
            }
            if (this.MetaKind == "MetricConstraint")
            {
                string symbol = ">";
                if (MetricConstraint_TargetType == "Must Exceed")
                {
                    symbol = ">";
                }
                else if (MetricConstraint_TargetType == "Must Not Exceed")
                {
                    symbol = "\u2264";
                }
                else if (MetricConstraint_TargetType == "Must Equal")
                {
                    symbol = "=";
                }
                using (Font symbolFont = new Font(SystemFonts.DefaultFont.FontFamily, 40f, GraphicsUnit.Pixel))
                    using (StringFormat symbolFormat = new StringFormat(StringFormatFlags.NoClip))
                    {
                        g.TextRenderingHint        = System.Drawing.Text.TextRenderingHint.AntiAlias;
                        symbolFormat.Alignment     = StringAlignment.Center;
                        symbolFormat.LineAlignment = StringAlignment.Center;

                        g.DrawString(symbol, symbolFont, new SolidBrush(labelColor), new PointF(x + w / 2.0f, y + h / 2.0f), symbolFormat);
                    }
            }

            // Draw the label
            g.DrawString(name, font, new SolidBrush(labelColor),
                         new RectangleF(x + w / 2.0f - LabelSize.Width / 2.0f, y + h, LabelSize.Width, LabelSize.Height), sf);

            font.Dispose();
            sf.Dispose();
            g.Dispose();
        }
Пример #13
0
        public void Run()
        {
            AVM.DDP.MetaAvmProject avmProj;
            var terr = this.Project.BeginTransactionInNewTerr();

            try
            {
                this.CurrentObj = this.Project.GetFCOByID(this.m_CurrentObjId);

                // This can only be a testbench at this point
                ISIS.GME.Dsml.CyPhyML.Interfaces.TestBenchType tb = ISIS.GME.Dsml.CyPhyML.Classes.TestBenchType.Cast(this.CurrentObj as MgaObject);
                this.CallFormulaEvaluator(this.CurrentObj); // FIXME: KMS: For multijobrun, is this necessary?
                avmProj = AVM.DDP.MetaAvmProject.Create(Path.GetDirectoryName(OriginalProjectFileName), Project);
                avmProj.SaveSummaryReportJson(this.OutputDirectory, this.CurrentObj);
                avmProj.SaveTestBenchManifest(this.OutputDirectory, tb, Dependencies);
                avmProj.UpdateResultsJson(this.CurrentObj, this.OutputDirectory, DateTime.Now);
                // TODO: test bench export??
            }
            finally
            {
                this.Project.AbortTransaction();
            }
            var          currentProjectDir = Path.GetDirectoryName(this.Project.ProjectConnStr.Substring("MGA=".Length));
            ComComponent interpreter       = new ComComponent(ProgId);


            // Read the copied over configuration (the original one may be changed and/or opened).
            if (interpreter.InterpreterConfig != null)
            {
                interpreter.InterpreterConfig = META.ComComponent.DeserializeConfiguration(currentProjectDir, interpreter.InterpreterConfig.GetType(), interpreter.ProgId);
            }

            this.Interpreter = interpreter;

            interpreter.Initialize(Project);

            interpreter.WorkflowParameters = WorkflowParametersDict;
            interpreter.SetWorkflowParameterValues();
            interpreter.MainParameters.OutputDirectory  = this.OutputDirectory;
            interpreter.MainParameters.ProjectDirectory = Path.GetDirectoryName(this.OriginalProjectFileName);
            interpreter.MainParameters.ConsoleMessages  = false;
            interpreter.MainParameters.Project          = Project;
            interpreter.MainParameters.CurrentFCO       = CurrentObj;
            interpreter.MainParameters.SelectedFCOs     = SelectedObjs;
            interpreter.MainParameters.StartModeParam   = ParamInvoke;

            interpreter.Main();

            this.RunCommand = interpreter.result.RunCommand;
            this.Labels     = interpreter.result.Labels;
            this.BuildQuery = interpreter.result.BuildQuery;
            this.ResultsZip = interpreter.result.ZippyServerSideHook;

            this.Project.BeginTransaction(terr);
            try
            {
                var manifest = AVM.DDP.MetaTBManifest.OpenForUpdate(this.OutputDirectory);
                manifest.AddAllTasks(ISIS.GME.Dsml.CyPhyML.Classes.TestBenchType.Cast(this.CurrentObj), new ComComponent[] { interpreter }, "..\\..");
                manifest.Serialize(this.OutputDirectory);
                // if some magic happens in the test bench and some interpreters would update the model
                // and they are NOT updating the summary file accordingly we will do it here.
                // RISK: if any interpreter wants to update the summary file like CyPython this could mess up the values.
                this.CallFormulaEvaluator(this.CurrentObj);
                avmProj.SaveSummaryReportJson(this.OutputDirectory, this.CurrentObj);
            }
            finally
            {
                this.Project.AbortTransaction();
            }
        }
Пример #14
0
        /// <summary>
        /// Called when an FCO or folder changes
        /// </summary>
        /// <param name="subject">
        ///   the object the event(s) happened to
        /// </param>
        /// <param name="eventMask">
        ///   objectevent_enum values ORed together
        /// </param>
        /// <param name="param">
        ///   extra information provided for cetertain event types
        /// </param>
        public void ObjectEvent(
            MgaObject subject,
            uint eventMask,
            object param)
        {
            if (!componentEnabled)
            {
                return;
            }
            else if (isXMLImportInProgress)
            {
                return;
            }
            //else if (isProjectInTransation)
            //{
            //  return;
            //}

            if (subject.HasReadOnlyAccess() ||
                subject.IsLibObject)
            {
                return;
            }

            uint uOBJEVENT_CREATED = 0;
            uint uOBJEVENT_COPIED  = 0;

            unchecked { uOBJEVENT_CREATED = (uint)objectevent_enum.OBJEVENT_CREATED; }
            unchecked { uOBJEVENT_COPIED = (uint)objectevent_enum.OBJEVENT_COPIED; }



            if ((eventMask & uOBJEVENT_COPIED) != 0)
            {
                isCopied = true;
            }
            else if ((eventMask & uOBJEVENT_CREATED) != 0 && subject.Status == 0)
            // check Status, since object can be created and deleted in same tx
            {
                if (isCopied)
                {
                    // handle copy event
                    isCopied = false;
                }
                else
                {
                    //subject.Project.RootMeta.RootFolder.DefinedFCOByName["Task",
                    //MgaMetaBase task;
                    //if (task.MetaRef == subject.MetaBase.MetaRef)
                    {
                    }
                    // handle new object event
                    bool isBasicTask = (subject.MetaBase.Name == "Task");

                    if (subject.MetaBase.Name == "Task" || subject.MetaBase.Name == "ExecutionTask")
                    {
                        if (subject.MetaBase.Name == "Task" && string.IsNullOrEmpty((subject as MgaFCO).StrAttrByName["COMName"]) == false)
                        {
                            return;
                        }
                        if (subject.MetaBase.Name == "ExecutionTask" && string.IsNullOrEmpty((subject as MgaFCO).StrAttrByName["Invocation"]) == false)
                        {
                            return;
                        }
                        using (InterpreterSelectionForm form = new InterpreterSelectionForm())
                        {
                            form.addon = this;
                            form.Init();

                            HashSet <string> taskKinds = new HashSet <string>()
                            {
                                "ExecutionTask",
                                "Task"
                            };

                            IEnumerable <MgaAtom> taskChildren = subject.ExGetParent().
                                                                 ChildObjects.
                                                                 OfType <MgaAtom>().
                                                                 Where(x => x.ExDstFcos().Count() == 0).
                                                                 Where(x => x.ID != subject.ID).
                                                                 Where(x => taskKinds.Contains(x.Meta.Name));

                            form.lbTasks.Items.Clear();
                            foreach (var currTask in taskChildren)
                            {
                                var atomWrapper = new MgaAtomWrapper(currTask);
                                form.lbTasks.Items.Add(new MgaAtomWrapper(currTask));
                                form.lbTasks.SelectedItem = atomWrapper;
                            }

                            if (form.lbTasks.Items.Count > 0)
                            {
                                form.lbTasks.SetSelected(0, true);
                            }

                            if (!isBasicTask) // remove interpreter selection and reset positions
                            {
                                form.lbInterpreters.Items.Clear();
                                form.lbInterpreters.Visible       = false;
                                form.lblSelectInterpreter.Visible = false;
                                form.chbAutoConnect.Location      = form.label1.Location;
                                form.label1.Location  = form.lblSelectInterpreter.Location;
                                form.lbTasks.Location = form.lbInterpreters.Location;
                            }

                            DialogResult dgr = form.ShowDialog();
                            if (dgr == DialogResult.OK)
                            {
                                if (isBasicTask)
                                {
                                    ComComponent c = form.lbInterpreters.SelectedItem as ComComponent;
                                    try
                                    {
                                        if (c != null &&
                                            c.isValid)
                                        {
                                            (subject as MgaFCO).StrAttrByName["COMName"] = c.ProgId;
                                        }
                                    }
                                    catch
                                    {
                                        MessageBox.Show("Cannot save interpreter settings. 'COMName' is not a parameter of 'Task'.");
                                    }
                                }

                                //Flow
                                if (form.chbAutoConnect.Checked && (form.lbTasks.SelectedItem != null))
                                {
                                    MgaAtomWrapper selectedTask   = form.lbTasks.SelectedItem as MgaAtomWrapper;
                                    MgaAtom        lastInWorkflow = null;

                                    if (selectedTask != null)
                                    {
                                        lastInWorkflow = selectedTask.Atom;
                                    }

                                    if (lastInWorkflow != null)
                                    {
                                        MgaMetaRole role = ((subject.ExGetParent() as MgaModel).
                                                            Meta as MgaMetaModel).RoleByName["Flow"];

                                        (subject.ExGetParent() as MgaModel).CreateSimplerConnDisp(
                                            role,
                                            lastInWorkflow as MgaFCO,
                                            subject as MgaFCO);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // TODO: Handle object events (OR eventMask with the members of objectevent_enum)
            // Warning: Only those events are received that you have subscribed for by setting ComponentConfig.eventMask

            // MessageBox.Show(eventMask.ToString());
        }