示例#1
0
        void open_component_folder()
        {
            this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name);

            CyPhy.Component comp    = GetCurrentComp();
            var             absPath = comp.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);

            if (false == Directory.Exists(absPath))
            {
                Logger.WriteError("Component path does not exist: {0}", absPath);
                clean_up(false);
                return;
            }

            // META-2517 Explorer doesn't like paths with mixed seperators, make them all the same
            string uniformabspath = absPath.Replace("\\", "/");

            try
            {
                Process.Start(@uniformabspath);
            }
            catch (Exception ex)
            {
                Logger.WriteError("Error opening Windows Explorer: {0}", ex.Message);
                clean_up(false);
                return;
            }

            clean_up(true);
        }
示例#2
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            this.Logger.WriteInfo("Running Component Authoring interpreter.");

            // verify we are running in a component and that it is not an instance or library
            string return_msg;

            if (!CheckPreConditions(currentobj, out return_msg))
            {
                this.Logger.WriteFailed(return_msg);
                return;
            }

            // assuming a component is open
            // stash off the project, currentobj and CurrentComponent parameters for use in the event handlers
            StashProject          = project;
            StashCurrentObj       = currentobj;
            StashCurrentComponent = CyPhyClasses.Component.Cast(currentobj);

            // use reflection to populate the dialog box objects
            PopulateDialogBox();

            // To use the domain-specific API:
            //  Create another project with the same name as the paradigm name
            //  Copy the paradigm .mga file to the directory containing the new project
            //  In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator)
            //  Add a Reference in this project to the other project
            //  Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file
            // if (currentobj.Meta.Name == "KindName")
            // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj);
        }
示例#3
0
        /// <summary>
        /// Finds the largest current GUI-positioning Y value currently used within a component.
        /// </summary>
        /// <remarks>
        /// We use this as part of the calculation of where to put our newly-created elements on screen.
        /// We want the new ones to be added below the existing design elements, so they won't
        /// appear to be overlapping other stuff.
        /// Y is zero at the top of the window, and increases in the downward direction.
        /// </remarks>
        /// <param name="component">The CyPhy.Component that will be analyzed.</param>
        /// <returns>The largest current Y value used by the component.</returns>
        /// <see>Based on code in SchematicModelImport.cs</see>
        public int getGreatestCurrentY(CyPhy.Component component)
        {
            int rVal = 0;

            // The children of the component may be things like schematic models, ports, etc.
            foreach (var child in component.AllChildren)
            {
                foreach (MgaPart item in (child.Impl as MgaFCO).Parts)
                {
                    // Each Parts/item has info corresponding to placement on a GME aspect,
                    // where each aspect is like a separate, but overlapping canvas.
                    // Although components may be moved to different places in each aspect,
                    // we'd like to create them so they start off at the same place in
                    // each aspect.  Otherwise, it disorients the user when they switch aspects.
                    // That's why we check all aspects to get a single maximum Y, so
                    // the newly created stuff won't be overlapping in any of its aspects.

                    int    x, y;
                    string read_str;
                    item.GetGmeAttrs(out read_str, out x, out y);
                    rVal = (y > rVal) ? y : rVal;
                }
            }
            return(rVal);
        }
示例#4
0
        public void visit(CyPhy.Component component)
        {
            Logger.WriteDebug("visit(CyPhy.Component): {0}", component.Path);

            var part = new MfgBom.Bom.Part();

            // Check for a Property called "octopart_mpn"
            var octopart_mpn = component.Children.PropertyCollection.FirstOrDefault(p => p.Name == "octopart_mpn" &&
                                                                                    !String.IsNullOrWhiteSpace(p.Attributes.Value));

            if (octopart_mpn != null)
            {
                part.octopart_mpn = octopart_mpn.Attributes.Value;
            }

            var instance = new MfgBom.Bom.ComponentInstance()
            {
                gme_object_id = component.ID,
                path          = TrimPath(component.Path)
            };

            part.AddInstance(instance);

            bom.AddPart(part);
        }
示例#5
0
        public void BrandNewComponent()
        {
            // Create a branch new component and submit the transaction.
            // This should trigger the add-on.
            // Next, go and check that the Component has a Path, and that that Path exists on disk.

            var project = fixture.GetProject();

            project.EnableAutoAddOns(true);

            project.PerformInTransaction(delegate
            {
                CyPhy.RootFolder rf = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.RootFolder>(project.RootFolder as MgaObject);
                CyPhy.Components cf = rf.Children.ComponentsCollection.First();

                CyPhy.Component comp = CyPhyClasses.Component.Create(cf);
                comp.Name            = "BrandNewComponent";
            });

            project.PerformInTransaction(delegate
            {
                var matchingComponents = project.GetComponentsByName("BrandNewComponent");
                Assert.Equal(1, matchingComponents.Count());

                var comp_Retrieved = matchingComponents.First();
                Assert.True(!String.IsNullOrWhiteSpace(comp_Retrieved.Attributes.AVMID), "Retrieved component is missing AVMID.");
                Assert.True(!String.IsNullOrWhiteSpace(comp_Retrieved.Attributes.Path), "Retrieved component is missing Path.");
                Assert.True(Directory.Exists(comp_Retrieved.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE)), "Component path doesn't exist.");
            });
            project.Save();
        }
示例#6
0
        /// <summary>
        /// Get OctoPart MPN CyPhy property value
        /// </summary>
        public string QueryCyPhyOctoPartMpnProperty(CyPhy.Component comp)
        {
            IEnumerable <CyPhy.Property> propertyCollection = comp.Children.PropertyCollection;

            CyPhy.Property property = propertyCollection.FirstOrDefault(p => p.Name.ToLower() == "octopart_mpn");
            return(property == null ? "" : property.Attributes.Value);
        }
示例#7
0
        private avm.Component FindAndConvert(string compName, string compFolName)
        {
            avm.Component avmComp = null;

            proj.PerformInTransaction(delegate
            {
                CyPhy.RootFolder rf  = CyPhyClasses.RootFolder.GetRootFolder(proj);
                CyPhy.Components cf  = rf.Children.ComponentsCollection.First(f => f.Name == compFolName);
                CyPhy.Component comp = cf.Children.ComponentCollection.First(c => c.Name == compName);

                avmComp = CyPhy2ComponentModel.Convert.CyPhyML2AVMComponent(comp);
            });

            string outPath = Path.Combine(testPath, "output");

            if (!Directory.Exists(outPath))
            {
                Directory.CreateDirectory(outPath);
            }

            CyPhyComponentExporter.CyPhyComponentExporterInterpreter.SerializeAvmComponent(avmComp, Path.Combine(outPath,
                                                                                                                 String.Format("{0}-{1}.exported.acm",
                                                                                                                               compFolName,
                                                                                                                               compName)));

            return(avmComp);
        }
示例#8
0
 public static CyPhyML.Component FindAVMComponent(MgaProject project, string avmid, ISIS.GME.Dsml.CyPhyML.Interfaces.Components root)
 {
     if (root == null)
     {
         var rf = CyPhyMLClasses.RootFolder.GetRootFolder(project);
         foreach (var components in rf.Children.ComponentsCollection)
         {
             CyPhyML.Component comp = FindAVMComponent(project, avmid, components);
             if (comp != null)
             {
                 return(comp);
             }
         }
     }
     else
     {
         foreach (var components in root.Children.ComponentsCollection)
         {
             CyPhyML.Component comp = FindAVMComponent(project, avmid, components);
             if (comp != null)
             {
                 return(comp);
             }
         }
         foreach (var component in root.Children.ComponentCollection)
         {
             if (component.Attributes.AVMID == avmid)
             {
                 return(component);
             }
         }
     }
     return(null);
 }
示例#9
0
        /// <summary>
        /// Gets name of the device for an Eagle model in a CyPhy component. Ensures only 1 EDAModel exists.
        /// This name will be the OctoPart MPN that is queried later.
        /// </summary>
        public string GetDeviceNameFromComponentEDAModel(CyPhy.Component component)
        {
            string edaModelDevice = "";
            IEnumerable <CyPhy.EDAModel> edaModels = component.Children.EDAModelCollection;
            int edaModelCount = edaModels.Count();

            if (edaModelCount == 0)
            {
                edaModelDevice = QueryCyPhyOctoPartMpnProperty(component);
                if (String.IsNullOrWhiteSpace(edaModelDevice))
                {
                    LogMessage("No EDAModel present in component.", CyPhyGUIs.SmartLogger.MessageType_enum.Warning);
                    disposeLogger();
                }
            }
            else if (edaModelCount > 1)
            {
                LogMessage("More than one EDAModel is present in component.", CyPhyGUIs.SmartLogger.MessageType_enum.Error);
                disposeLogger();
            }
            else
            {
                edaModelDevice = edaModels.FirstOrDefault().Attributes.DeviceSet;
                if (string.IsNullOrWhiteSpace(edaModelDevice))
                {
                    LogMessage("DeviceSet in EDAModel is not set.", CyPhyGUIs.SmartLogger.MessageType_enum.Error);
                    disposeLogger();
                }
            }

            return(edaModelDevice);
        }
示例#10
0
        public static HashSet <CyPhyML.Component> getCyPhyMLComponentSet(CyPhyML.Component cyPhyMLComponent)
        {
            HashSet <CyPhyML.Component> cyPhyMLComponentSet = new HashSet <CyPhyML.Component>();

            cyPhyMLComponentSet.Add(cyPhyMLComponent);
            return(cyPhyMLComponentSet);
        }
示例#11
0
        /// <summary>
        /// Returns the initial (x,y) coordinates for a new model that will be added to a component.
        /// </summary>
        /// <param name="component">The component the new model willbe added to</param>
        /// <param name="x">The X coordinate the new model should use.</param>
        /// <param name="y">The Y coordinate the new model should use.</param>
        public void getNewModelInitialCoordinates(CyPhy.Component component, out int x, out int y)
        {
            const int MODEL_START_X = 350;  // Always start new models at x = 650.
            const int MODEL_START_Y = 200;  // Y offset visually below the lowest element already in the component.

            x = MODEL_START_X;
            y = getGreatestCurrentY(component) + MODEL_START_Y;
        }
示例#12
0
        public void TestAddCustomIconTool()
        {
            string TestName  = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string path_Test = Path.Combine(testcreatepath, TestName);
            string path_Mga  = Path.Combine(path_Test, TestName + ".mga");

            // delete any previous test results
            if (Directory.Exists(path_Test))
            {
                Directory.Delete(path_Test, true);
            }

            // create a new blank project
            MgaProject proj = new MgaProject();

            proj.Create("MGA=" + path_Mga, "CyPhyML");

            // these are the actual steps of the test
            proj.PerformInTransaction(delegate
            {
                // create the environment for the Component authoring class
                CyPhy.RootFolder rf         = CyPhyClasses.RootFolder.GetRootFolder(proj);
                CyPhy.Components components = CyPhyClasses.Components.Create(rf);
                CyPhy.Component testcomp    = CyPhyClasses.Component.Create(components);

                // new instance of the class to test
                CyPhyComponentAuthoring.Modules.CustomIconAdd CATModule = new CyPhyComponentAuthoring.Modules.CustomIconAdd();

                //// these class variables need to be set to avoid NULL references
                CATModule.SetCurrentDesignElement(testcomp);
                CATModule.CurrentObj = testcomp.Impl as MgaFCO;

                // call the primary function directly
                CATModule.AddCustomIcon(testiconpath);

                // verify results
                // 1. insure the icon file was copied to the back-end folder correctly
                string iconAbsolutePath = Path.Combine(testcomp.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE), "Icon.png");
                Assert.True(File.Exists(iconAbsolutePath),
                            String.Format("Could not find the source file for the created resource, got {0}", iconAbsolutePath));

                // 2. insure the resource path was created correctly
                var iconResource = testcomp.Children.ResourceCollection.Where(p => p.Name == "Icon.png").First();
                Assert.True(iconResource.Attributes.Path == "Icon.png",
                            String.Format("{0} Resource should have had value {1}; instead found {2}", iconResource.Name, "Icon.png", iconResource.Attributes.Path)
                            );

                // 3. Verify the registry entry exists
                string expected_registry_entry = Path.Combine(testcomp.GetDirectoryPath(ComponentLibraryManager.PathConvention.REL_TO_PROJ_ROOT), "Icon.png");
                string registry_entry          = (testcomp.Impl as GME.MGA.IMgaFCO).get_RegistryValue("icon");
                Assert.True(registry_entry.Equals(expected_registry_entry),
                            String.Format("Registry should have had value {0}; instead found {1}", expected_registry_entry, registry_entry)
                            );
            });
            proj.Save();
            proj.Close();
            Directory.Delete(testcreatepath, true);
        }
示例#13
0
        public CADComponent(CyPhy.Component cyphycomp, string ProjectDirectory, bool size2fit = false,
                            CyPhyCOMInterfaces.IMgaTraceability Traceability = null, CyPhyClasses.CADModel.AttributesClass.FileFormat_enum cadFormat = CyPhyClasses.CADModel.AttributesClass.FileFormat_enum.Creo)
        {
            Type = CADDataType.Component;
            StructuralInterfaceNodes = new Dictionary <string, StructuralInterfaceConstraint>();
            DisplayID            = cyphycomp.Attributes.InstanceGUID;
            Id                   = cyphycomp.ID;
            GraphvizID           = UtilityHelpers.CleanString2(cyphycomp.ID, 50, "-");
            AVMID                = cyphycomp.Attributes.AVMID;
            RevID                = "";
            VersionID            = cyphycomp.Attributes.Version;
            CADFormat            = cadFormat;
            Name                 = cyphycomp.Name;
            CadParameters        = new List <CADParameter>();
            ModelType            = "Part";
            Size2Fit             = size2fit;
            MaterialName         = "";
            CyPhyModelPath       = cyphycomp.GetDirectoryPath(ProjectDirectory: ProjectDirectory);
            Classification       = cyphycomp.Attributes.Classifications;
            HyperLink            = cyphycomp.ToHyperLink();
            CadElementsList      = new List <CAD.ElementType>();
            pointCoordinatesList = new List <TestBenchModel.TBComputation>();
            this.Traceability    = Traceability;

            CreateStructuralInterfaceEquivalent(cyphycomp);

            AddManufacturingParameters(cyphycomp);

            var specialinstr = cyphycomp.Children.ParameterCollection.Where(p => p.Name.ToUpper() == SpecialInstrParamStr);

            if (specialinstr.Any())
            {
                SpecialInstructions = specialinstr.First().Attributes.Value.Replace("\"", "");
            }

            // META-3555 hack
            if (cyphycomp.Children.CADModelCollection.Any())
            {
                foreach (var datum in cyphycomp.Children.CADModelCollection.First().Children.CADDatumCollection)
                {
                    if (datum.Name == "FRONT" || datum.Name == "TOP" || datum.Name == "RIGHT")
                    {
                        SpecialDatums.Add(new Datum(datum, "", false));
                    }
                }
            }

            foreach (var prop in cyphycomp.Children.PropertyCollection)
            {
                if (prop.Name.StartsWith("METADATA."))
                {
                    MetaData.Add(prop.Name.Substring(9), prop.Attributes.Value);
                }
            }

            TraverseComposites(cyphycomp);
            CreatePointCoordinatesList(cyphycomp);
        }
示例#14
0
        private void Visit(CyPhyInterfaces.Component component)
        {
            var rfModel = component.Children.RFModelCollection.FirstOrDefault();

            if (rfModel != null)
            {
                string resourcePath = "";

                // Get all resources
                foreach (var resource in rfModel.SrcConnections.UsesResourceCollection.Select(c => c.SrcEnds.Resource).Union(
                             rfModel.DstConnections.UsesResourceCollection.Select(c => c.DstEnds.Resource)))
                {
                    if (resource != null && resource.Attributes.Path != String.Empty)
                    {
                        rfModel.TryGetResourcePath(out resourcePath, ComponentLibraryManager.PathConvention.ABSOLUTE);
                    }

                    break;  // max. one CSXCAD file supported
                }

                if (resourcePath.Length == 0)
                {
                    Logger.WriteError("No resource file specified for component {0}.", component.Name);
                    return;
                }

                if (!System.IO.File.Exists(resourcePath))
                {
                    Logger.WriteError("Resource file {0} not found for component {1}.", resourcePath, component.Name);
                    return;
                }

                var araModule = m_endo.GetModule(m_slotIndex);
                if (araModule == null)
                {
                    if (m_endo.Slots[m_slotIndex].Size[0] == 2 && m_endo.Slots[m_slotIndex].Size[1] == 2)
                    {
                        araModule = new CSXCAD.Ara.Module_2x2(component.Name);
                    }
                    else
                    {
                        araModule = new CSXCAD.Ara.Module_1x2(component.Name);
                    }
                }

                m_antenna = new CSXCAD.XmlCompound(
                    null,
                    component.Name,
                    new Vector3D(rfModel.Attributes.X, rfModel.Attributes.Y, araModule.PCB.Thickness),
                    (double)rfModel.Attributes.Rotation * Math.PI / 2
                    );
                m_antenna.Parse(XElement.Load(resourcePath));

                araModule.PCB.Add(m_antenna);
                m_endo.AddModule(m_slotIndex, araModule);
            }
        }
示例#15
0
        private Edit CreateComponentEditMessage(string instanceId, CyPhyML.Component component, CyPhyML.CADModel cadModel)
        {
            string cadModelRelativePath = "";

            if (false == cadModel.TryGetResourcePath(out cadModelRelativePath) || cadModelRelativePath == "")
            {
                // TODO log
                //return null;
            }

            var message = new Edit()
            {
                editMode = MetaLinkProtobuf.Edit.EditMode.POST,
                guid     = Guid.NewGuid().ToString(),
                //sequence = 0,
            };

            message.origin.Add(GMEOrigin);
            message.topic.Add(instanceId);
            edu.vanderbilt.isis.meta.Action action = new edu.vanderbilt.isis.meta.Action();
            message.actions.Add(action);
            action.actionMode = MetaLinkProtobuf.Action.ActionMode.UPDATE_CAD_COMPONENT;
            action.subjectID  = component.Attributes.AVMID;
            action.environment.Add(new edu.vanderbilt.isis.meta.Environment()
            {
                name = SearchPathStr,
            });
            AddSearchPathToEnvironment(component, action.environment[0]);
            if (cadModelRelativePath.Length != 0)
            {
                action.payload = new Payload();
                CADComponentType cadComponent = new CADComponentType()
                {
                    AvmComponentID = component.Attributes.AVMID,
                    CADModelID     = CyphyMetaLinkUtils.GetResourceID(cadModel),             // Using CADModelID to transport this information (the resource id)
                    Name           = Path.GetFileNameWithoutExtension(cadModelRelativePath), // the partial creo file name (less .prt or .asm)
                    Type           = (Path.GetExtension(cadModelRelativePath).EndsWith(".prt") || Path.GetExtension(cadModelRelativePath).EndsWith(".PRT")) ? "PART" : "ASSEMBLY"
                };
                foreach (var connector in component.Children.ConnectorCollection)
                {
                    cadComponent.Connectors.Add(new ConnectorType()
                    {
                        ID = connector.Guid.ToString(), DisplayName = connector.Name
                    });
                }
                foreach (var datum in cadModel.Children.CADDatumCollection)
                {
                    cadComponent.Datums.Add(new ConnectorDatumType()
                    {
                        ID = datum.Attributes.DatumName, DisplayName = datum.Name
                    });
                }
                action.payload.components.Add(cadComponent);
            }
            return(message);
        }
示例#16
0
        public static CyPhyML.Component CopyComponent(CyPhyML.Component original, bool createNewMgaComponent)
        {
            // This will fixup any errors/sync issues
            string componentDirectory = original.GetDirectoryPath();

            if (String.IsNullOrWhiteSpace(componentDirectory))
            {
                throw new ApplicationException(String.Format("Could not find component definition"));
            }

            CyPhyML.Component newComponent;
            if (createNewMgaComponent)
            {
                if (original.ParentContainer.Impl.ObjType == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER)
                {
                    newComponent = CyPhyMLClasses.Component.Cast(((MgaFolder)original.ParentContainer.Impl).CopyFCODisp((MgaFCO)original.Impl));
                }
                else
                {
                    newComponent = CyPhyMLClasses.Component.Cast(((MgaModel)original.ParentContainer.Impl).CopyFCODisp((MgaFCO)original.Impl, ((MgaModel)original.Impl).MetaRole));
                }
                string basename = newComponent.Name;
                newComponent.Name = basename + "_new";
                HashSet <string> childNames = new HashSet <string>();
                foreach (var child in newComponent.ParentContainer.AllChildren)
                {
                    if (child.ID != newComponent.ID)
                    {
                        childNames.Add(child.Name);
                    }
                }
                int i = 2;
                while (childNames.Contains(newComponent.Name))
                {
                    newComponent.Name = basename + "_new_" + i;
                    i++;
                    if (i > 100)
                    {
                        break;
                    }
                }
                newComponent.Attributes.AVMID = "";
                newComponent.Attributes.Path  = "";
                // this will also assign AVMID and Path, add to project manifest, etc
                string newModelpathDirectory = newComponent.GetDirectoryPath();

                CopyDirectory(Path.Combine(GetProjectDir(original.Impl.Project), componentDirectory), Path.Combine(GetProjectDir(original.Impl.Project), newModelpathDirectory));
            }
            else
            {
                newComponent = original;
            }

            return(newComponent);
        }
示例#17
0
        public void TestAddMfgModelTool()
        {
            string TestName  = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string path_Test = Path.Combine(testcreatepath, TestName);
            string path_Mga  = Path.Combine(path_Test, TestName + ".mga");

            // delete any previous test results
            if (Directory.Exists(path_Test))
            {
                Directory.Delete(path_Test, true);
            }

            // create a new blank project
            MgaProject proj = new MgaProject();

            proj.Create("MGA=" + path_Mga, "CyPhyML");

            // these are the actual steps of the test
            proj.PerformInTransaction(delegate
            {
                // create the environment for the Component authoring class
                CyPhy.RootFolder rf         = CyPhyClasses.RootFolder.GetRootFolder(proj);
                CyPhy.Components components = CyPhyClasses.Components.Create(rf);
                CyPhy.Component testcomp    = CyPhyClasses.Component.Create(components);

                // new instance of the class to test
                CyPhyComponentAuthoring.Modules.MfgModelImport CATModule = new CyPhyComponentAuthoring.Modules.MfgModelImport();

                //// these class variables need to be set to avoid NULL references
                CATModule.SetCurrentDesignElement(testcomp);
                CATModule.CurrentObj = testcomp.Impl as MgaFCO;

                // call the primary function directly
                CATModule.import_manufacturing_model(testmfgmdlpath);

                // verify results
                // 1. insure the mfg file was copied to the backend folder correctly
                // insure the part file was copied to the backend folder correctly
                var getmfgmdl = testcomp.Children.ManufacturingModelCollection.First();
                string returnedpath;
                getmfgmdl.TryGetResourcePath(out returnedpath, ComponentLibraryManager.PathConvention.ABSOLUTE);
                string demanglepathpath = returnedpath.Replace("\\", "/");
                Assert.True(File.Exists(demanglepathpath),
                            String.Format("Could not find the source file for the created resource, got {0}", demanglepathpath));

                // 2. insure the resource path was created correctly
                var mfgResource = testcomp.Children.ResourceCollection.Where(p => p.Name == "generic_cots_mfg.xml").First();
                Assert.True(mfgResource.Attributes.Path == Path.Combine("Manufacturing", "generic_cots_mfg.xml"),
                            String.Format("{0} Resource should have had value {1}; instead found {2}", mfgResource.Name, "generic_cots_mfg.xml", mfgResource.Attributes.Path)
                            );
            });
            proj.Save();
            proj.Close();
        }
示例#18
0
 public static CyPhy.Component DerivedFrom(this CyPhy.Component component)
 {
     if ((component.Impl as GME.MGA.IMgaFCO).DerivedFrom != null)
     {
         return(CyPhyClasses.Component.Cast((component.Impl as GME.MGA.IMgaFCO).DerivedFrom));
     }
     else
     {
         return(null);
     }
 }
示例#19
0
        private CyPhy.Component ExportThenImport(CyPhyML.Component comp, out CyPhy.Components importedcomponents, String testName)
        {
            // export the component
            avm.Component exportee = CyPhyML2AVM.AVMComponentBuilder.CyPhyML2AVM(comp);
            CyPhyComponentExporter.CyPhyComponentExporterInterpreter.SerializeAvmComponent(exportee, Path.Combine(testPath, testName + ".acm"));

            // import the component back in
            CyPhy.RootFolder rf = CyPhyClasses.RootFolder.GetRootFolder(fixture.proj);
            importedcomponents = CyPhyClasses.Components.Create(rf);
            return(AVM2CyPhyML.CyPhyMLComponentBuilder.AVM2CyPhyML(importedcomponents, exportee));
        }
示例#20
0
 public static CyPhyML.CADModel FindCADModelObject(CyPhyML.Component component)
 {
     foreach (CyPhyML.CADModel item in component.Children.CADModelCollection)
     {
         if (item.Attributes.FileFormat.ToString() == "Creo")
         {
             return(item);
         }
     }
     return(null);
 }
示例#21
0
 public static CyPhyML.Connector FindConnector(CyPhyML.Component component, string guid)
 {
     foreach (var connector in component.Children.ConnectorCollection)
     {
         if (connector.Guid.ToString() == guid)
         {
             return(connector);
         }
     }
     return(null);
 }
示例#22
0
        /// <summary>
        /// OctoPart query returns link to image of component. Download this image to the Windows temporary
        /// directory and invoke the Icon CAT module to store as part of the CyPhy component.
        /// </summary>
        public void AddOctoPartIconToComponent(CyPhy.Component comp, MfgBom.Bom.Part part)
        {
            if (!comp.Children.ResourceCollection.Any(r => r.Name == "Icon.png"))
            {
                //Download icon to temp directory
                WebClient webClient = new WebClient();
                webClient.Headers.Add("user-agent", "meta-tools/" + VersionInfo.CyPhyML);
                String iconPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName().Replace(".", "") + ".png");
                webClient.DownloadFile(part.Icon, iconPath);

                if (File.Exists(iconPath))
                {
                    // Invoke icon module
                    CustomIconAdd iconModule = new CustomIconAdd();
                    iconModule.SetCurrentDesignElement(comp);
                    iconModule.CurrentObj = CurrentObj;
                    iconModule.AddCustomIcon(iconPath);

                    // Relocate resource in component
                    CyPhy.Resource resource = comp.Children.ResourceCollection.FirstOrDefault(r => r.Name == "Icon.png");
                    if (resource != null)
                    {
                        foreach (MgaPart item in (resource.Impl as MgaFCO).Parts)
                        {
                            item.SetGmeAttrs(null, RESOURCE_START_X, RESOURCE_START_Y + (resources_created * RESOURCE_ADJUST_Y));
                        }
                        resources_created++;

                        String iconPath_RelativeToProjRoot = Path.Combine(comp.GetDirectoryPath(ComponentLibraryManager.PathConvention.REL_TO_PROJ_ROOT),
                                                                          "icon.png");
                        comp.Preferences.Icon = iconPath_RelativeToProjRoot;
                    }
                    else
                    {
                        LogMessage(String.Format("Error creating icon resource for component {0}.", comp.Name),
                                   CyPhyGUIs.SmartLogger.MessageType_enum.Error);
                    }

                    // Delete icon from temp directory for cleanup
                    File.Delete(iconPath);
                }
                else
                {
                    LogMessage(String.Format("Error downloading icon from OctoPart for MPN {0}", part.octopart_mpn),
                               CyPhyGUIs.SmartLogger.MessageType_enum.Error);
                }
            }
            else
            {
                LogMessage(String.Format("An icon is already specified for component {0}. Will not overwrite with OctoPart data.", comp.Name),
                           CyPhyGUIs.SmartLogger.MessageType_enum.Warning);
            }
        }
示例#23
0
        public void OutsideCopy_SameProjDir_MissingAVMID()
        {
            // Simulate copying a component from another MGA in the same project folder.
            // It will have a Path unique to this project, and the path will already exist.
            // However, it will be missing an AVMID.
            // WHAT DO WE EXPECT THE ADDON TO DO?
            // We expect it to assign a new AVMID, but change nothing else.

            var compName = Utils.GetCurrentMethod();

            // First, let's create such a path.
            var path_ToCopy = Path.Combine(fixture.path_Test,
                                           "components",
                                           "z672jsd8");
            var path_NewCopy = Path.Combine(fixture.path_Test,
                                            "components",
                                            compName);

            Utils.DirectoryCopy(path_ToCopy, path_NewCopy);

            // Now let's simulate copying a component from another project.
            // It should have a Path, AVMID, and a Resource.
            String org_AVMID = "";
            String org_Path  = "";

            var project = fixture.GetProject();

            project.EnableAutoAddOns(true);
            project.PerformInTransaction(delegate
            {
                CyPhy.RootFolder rf = ISIS.GME.Dsml.CyPhyML.Classes.RootFolder.GetRootFolder(project);

                CyPhy.Components cf = rf.Children.ComponentsCollection.First();
                CyPhy.Component c   = CyPhyClasses.Component.Create(cf);

                c.Name             = compName;
                c.Attributes.AVMID = org_AVMID;
                org_Path           = c.Attributes.Path = Path.Combine("components", compName);

                CyPhy.Resource res  = CyPhyClasses.Resource.Create(c);
                res.Attributes.Path = "generic_cots_mfg.xml";
                res.Name            = res.Attributes.Path;
            });

            project.PerformInTransaction(delegate
            {
                var c = project.GetComponentsByName(compName).FirstOrDefault();
                Assert.True(org_AVMID != c.Attributes.AVMID, "A new AVMID should have been assigned.");
                Assert.True(org_Path == c.Attributes.Path, "The path should not have been changed.");
            });
            project.Save();
        }
示例#24
0
        private void AddCadModelToComponent(CyPhy.CAD2EDATransform xform,
                                            CyPhy.CADModel cadModel,
                                            CyPhy.Component component,
                                            AbstractClasses.Component rtn)
        {
            string cadPath;
            bool   retVal = cadModel.TryGetResourcePath(out cadPath, ComponentLibraryManager.PathConvention.REL_TO_PROJ_ROOT);

            if (retVal == false)
            {
                logger.WriteError("Unable to get CADModel's associated resource file path for component {0}", component.Name);
            }

            if (cadModel.Attributes.FileFormat == CyPhyClasses.CADModel.AttributesClass.FileFormat_enum.AP_203 ||
                cadModel.Attributes.FileFormat == CyPhyClasses.CADModel.AttributesClass.FileFormat_enum.AP_214)
            {
                rtn.cadModels.Add(new AbstractClasses.STEPModel()
                {
                    path           = cadPath,
                    rotationVector = new XYZTuple <Double, Double, Double>(xform.Attributes.RotationX,
                                                                           xform.Attributes.RotationY,
                                                                           xform.Attributes.RotationZ),
                    translationVector = new XYZTuple <Double, Double, Double>(xform.Attributes.TranslationX,
                                                                              xform.Attributes.TranslationY,
                                                                              xform.Attributes.TranslationZ),
                    scalingVector = new XYZTuple <Double, Double, Double>(xform.Attributes.ScaleX,
                                                                          xform.Attributes.ScaleY,
                                                                          xform.Attributes.ScaleZ),
                });
            }
            else if (cadModel.Attributes.FileFormat == CyPhyClasses.CADModel.AttributesClass.FileFormat_enum.STL)
            {
                rtn.cadModels.Add(new AbstractClasses.STLModel()
                {
                    path           = cadPath,
                    rotationVector = new XYZTuple <Double, Double, Double>(xform.Attributes.RotationX,
                                                                           xform.Attributes.RotationY,
                                                                           xform.Attributes.RotationZ),
                    translationVector = new XYZTuple <Double, Double, Double>(xform.Attributes.TranslationX,
                                                                              xform.Attributes.TranslationY,
                                                                              xform.Attributes.TranslationZ),
                    scalingVector = new XYZTuple <Double, Double, Double>(xform.Attributes.ScaleX,
                                                                          xform.Attributes.ScaleY,
                                                                          xform.Attributes.ScaleZ),
                });
            }
            else
            {
                logger.WriteError("Visualizer currently only supports STP & STL files. Component {0} has an " +
                                  "EDAModel connected to a non-STEP/STL formatted CADModel.", component.Name);
            }
        }
示例#25
0
        /// <summary>
        /// OctoPart query returns link to datasheet of component. Download this file to the Windows temporary
        /// directory and invoke the Documentation CAT module to store as part of the CyPhy component.
        /// </summary>
        public void AddOctoPartDatasheetToComponent(CyPhy.Component comp, MfgBom.Bom.Part part)
        {
            if (!comp.Children.ResourceCollection.Any(r => r.Name == "Datasheet.pdf"))
            {
                //Download icon to temp directory
                WebClient webClient = new WebClient();
                webClient.Headers.Add("user-agent", "meta-tools/" + VersionInfo.CyPhyML);
                String datasheetPath = Path.Combine(Path.GetTempPath(), "Datasheet.pdf");
                webClient.DownloadFile(part.Datasheet, datasheetPath);

                if (File.Exists(datasheetPath))
                {
                    // Invoke icon module
                    AddDocumentation docModule = new AddDocumentation();
                    docModule.SetCurrentDesignElement(comp);
                    docModule.CurrentObj = CurrentObj;
                    docModule.AddDocument(datasheetPath);

                    // Relocate resource in component
                    CyPhy.Resource resource = comp.Children.ResourceCollection.FirstOrDefault(r => r.Name.Contains("Datasheet"));

                    if (resource != null)
                    {
                        foreach (MgaPart item in (resource.Impl as MgaFCO).Parts)
                        {
                            item.SetGmeAttrs(null, RESOURCE_START_X, RESOURCE_START_Y + (resources_created * RESOURCE_ADJUST_Y));
                        }
                        resources_created++;
                    }
                    else
                    {
                        LogMessage(String.Format("Error creating datasheet resource for component {0}.", comp.Name),
                                   CyPhyGUIs.SmartLogger.MessageType_enum.Error);
                    }

                    // Delete icon from temp directory for cleanup
                    File.Delete(datasheetPath);
                }
                else
                {
                    LogMessage(String.Format("Error downloading icon from OctoPart for MPN {0}", part.octopart_mpn),
                               CyPhyGUIs.SmartLogger.MessageType_enum.Error);
                }
            }
            else
            {
                LogMessage(String.Format("A datasheet is already specified for component {0}. ", comp.Name) +
                           String.Format("Datasheet returned by OctoPart query is at: {0}. ", part.Datasheet) +
                           "Will not overwrite with OctoPart data.",
                           CyPhyGUIs.SmartLogger.MessageType_enum.Warning);
            }
        }
示例#26
0
        private void CopyResourceFromComp(Tonka.Component comp, string resName, string destFileName = null)
        {
            var res = (comp != null) ? comp.Children.ResourceCollection.Where(r =>
                                                                              r.Name.ToUpper().Contains(resName.ToUpper())).FirstOrDefault() : null;

            if (res != null)
            {
                var rPath = Path.Combine(comp.GetDirectoryPath(ComponentLibraryManager.PathConvention.REL_TO_PROJ_ROOT),
                                         res.Attributes.Path);

                if (String.IsNullOrWhiteSpace(destFileName))
                {
                    destFileName = Path.GetFileName(rPath);
                }

                try
                {
                    CopyFile(rPath, destFileName);
                }
                catch (FileNotFoundException)
                {
                    Logger.WriteError("PCB Template <a href=\"mga:{0}\">{1}</a> specifies a {2} file, {3}, that cannot be found.",
                                      comp.ID,
                                      comp.Name,
                                      resName,
                                      rPath);
                    throw;
                }
                catch (DirectoryNotFoundException)
                {
                    // If the directory of the source file doesn't exist, throw this error.
                    if (!Directory.Exists(Path.Combine(this.mainParameters.ProjectDirectory,
                                                       Path.GetDirectoryName(rPath))))
                    {
                        Logger.WriteError("PCB Template <a href=\"mga:{0}\">{1}</a> specifies a {2} file, {3}, that cannot be found.",
                                          comp.ID,
                                          comp.Name,
                                          resName,
                                          rPath);
                        throw;
                    }
                    else
                    {
                        // The destination directory must not exist.
                        Logger.WriteError("The output directory, {0}, does not exist.",
                                          this.mainParameters.OutputDirectory);
                        throw;
                    }
                }
            }
        }
示例#27
0
        public void OutsideCopy_SameProjDir()
        {
            // Create a new component.
            // Its AVMID and Path will be unique to this project, and that path will exist already on disk.
            // We expect that the Add-on isn't going to change anything.

            var compName = Utils.GetCurrentMethod();

            // First, let's create such a path.
            var path_ToCopy = Path.Combine(fixture.path_Test,
                                           "components",
                                           "z672jsd8");
            var path_NewCopy = Path.Combine(fixture.path_Test,
                                            "components",
                                            compName);

            Utils.DirectoryCopy(path_ToCopy, path_NewCopy);

            // Now let's simulate copying a component from another project.
            // It should have a Path, AVMID, and a Resource.
            String org_AVMID = "";
            String org_Path  = "";

            var project = fixture.GetProject();

            project.EnableAutoAddOns(true);
            Assert.Contains("MGA.Addon.ComponentLibraryManagerAddOn", project.AddOnComponents.Cast <IMgaComponentEx>().Select(x => x.ComponentProgID));
            project.PerformInTransaction(delegate
            {
                CyPhy.RootFolder rf = ISIS.GME.Dsml.CyPhyML.Classes.RootFolder.GetRootFolder(project);

                CyPhy.Components cf = rf.Children.ComponentsCollection.First();
                CyPhy.Component c   = CyPhyClasses.Component.Create(cf);

                c.Name    = compName;
                org_AVMID = c.Attributes.AVMID = Guid.NewGuid().ToString("D");
                org_Path  = c.Attributes.Path = Path.Combine("components", compName);

                CyPhy.Resource res  = CyPhyClasses.Resource.Create(c);
                res.Attributes.Path = "generic_cots_mfg.xml";
                res.Name            = res.Attributes.Path;
            });

            project.PerformInTransaction(delegate
            {
                var c = project.GetComponentsByName(compName).FirstOrDefault();
                Assert.True(org_AVMID == c.Attributes.AVMID, "AVMID was changed.");
                Assert.True(org_Path == c.Attributes.Path, "Path was changed.");
            });
            project.Save();
        }
示例#28
0
        /// <summary>
        /// Creates a CyPhy property for each technical detail kept on file for an OctoPart component
        /// </summary>
        public void AddOctoPartTechSpecsToComponent(CyPhy.Component comp, MfgBom.Bom.Part part)
        {
            dynamic dynJson = Newtonsoft.Json.JsonConvert.DeserializeObject(part.TechnicalSpecifications);

            if (dynJson != null)
            {
                foreach (var spec in dynJson)
                {
                    CyPhyClasses.Property.AttributesClass.DataType_enum type =
                        DeterminePropertyDataType((string)spec.Value.metadata.datatype, (string)spec.Value.metadata.key);

                    if (spec.Value.value.Count > 0)
                    {
                        BuildCyPhyProperty(comp, (string)spec.Value.metadata.key, (string)spec.Value.value[0], type, false);
                    }
                    // TODO: Add symbols if applicable ?
                    // spec.metadata.unit  // <-- returns null or {name, symbol}
                }

                #region layout

                // find the largest current X value so our new elements are added to the right of existing design elements
                // choose the greater value of PARAMETER_START_X and greatest_current_x, to handle case where models
                // have not yet been added (give user more space before the property list).
                greatest_current_x = 0;
                foreach (var child in GetCurrentDesignElement().AllChildren)
                {
                    foreach (MgaPart item in (child.Impl as MgaFCO).Parts)
                    {
                        int    read_x, read_y;
                        string read_str;
                        item.GetGmeAttrs(out read_str, out read_x, out read_y);
                        greatest_current_x = (read_x > greatest_current_x) ? read_x : greatest_current_x;
                    }
                }

                int PARAMETER_START = (PARAMETER_START_X > greatest_current_x) ? PARAMETER_START_X : greatest_current_x;

                int num_parsed_properties = 0;
                foreach (var property in comp.Children.PropertyCollection)
                {
                    foreach (MgaPart item in (property.Impl as MgaFCO).Parts)
                    {
                        item.SetGmeAttrs(null, PARAMETER_START, PARAMETER_START_Y + (num_parsed_properties * PARAMETER_ADJUST_Y));
                    }
                    num_parsed_properties++;
                }

                #endregion
            }
        }
示例#29
0
        public void TestCADImportResourceNaming()
        {
            string TestName  = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string path_Test = Path.Combine(testcreatepath, TestName);
            string path_Mga  = Path.Combine(path_Test, TestName + ".mga");

            // delete any previous test results
            if (Directory.Exists(path_Test))
            {
                Directory.Delete(path_Test, true);
            }

            // create a new blank project
            MgaProject proj = new MgaProject();

            proj.Create("MGA=" + path_Mga, "CyPhyML");

            // these are the actual steps of the test
            proj.PerformInTransaction(delegate
            {
                // create the environment for the Component authoring class
                CyPhy.RootFolder rf         = CyPhyClasses.RootFolder.GetRootFolder(proj);
                CyPhy.Components components = CyPhyClasses.Components.Create(rf);
                CyPhy.Component testcomp    = CyPhyClasses.Component.Create(components);

                // new instance of the class to test
                CyPhyComponentAuthoring.Modules.CADModelImport testcam = new CyPhyComponentAuthoring.Modules.CADModelImport();
                // these class variables need to be set to avoid NULL references
                testcam.SetCurrentDesignElement(testcomp);
                testcam.CurrentObj = testcomp.Impl as MgaFCO;

                // call the module with a part file to skip the CREO steps
                testcam.ImportCADModel(testpartpath);

                // verify results
                // insure the resource path was created correctly
                var correct_name = testcomp.Children.ResourceCollection.Where(p => p.Name == "damper.prt").First();
                Assert.True(correct_name.Attributes.Path == "CAD\\damper.prt",
                            String.Format("{0} should have had value {1}; instead found {2}", correct_name.Name, "CAD\\damper.prt", correct_name.Attributes.Path)
                            );
                // insure the part file was copied to the back-end folder correctly
                var getcadmdl = testcomp.Children.CADModelCollection.First();
                string returnedpath;
                getcadmdl.TryGetResourcePath(out returnedpath, ComponentLibraryManager.PathConvention.ABSOLUTE);
                Assert.True(File.Exists(returnedpath + ".36"),
                            String.Format("Could not find the source file for the created resource, got {0}", returnedpath));
            });
            proj.Save();
            proj.Close();
        }
示例#30
0
        private bool CheckComponent(CyPhy.Component cyphycomp)
        {
            bool   status   = true;
            string comppath = cyphycomp.Path;

            CyPhy.CADModel cadmodel = cyphycomp.Children.CADModelCollection.FirstOrDefault(x => x.Attributes.FileFormat.ToString() == cadFormat);
            if (cadmodel == null || cadmodel.Attributes.FileFormat.ToString() != cadFormat)
            {
                Logger.Instance.AddLogMessage("Component is missing CADModel object, it will be excluded from assembly xml: [" + comppath + "]", Severity.Normal);
                return(false);
            }

            return(status);
        }
示例#31
0
 public ComponentTreeNode(CyPhy.Component component)
 {
     this.Component = component;
     this.Name = component.Name;
 }
示例#32
0
 public void SetCurrentComp(CyPhy.Component comp)
 {
     CurrentComp = comp;
 }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            this.Logger.WriteInfo("Running Component Authoring interpreter.");

            // verify we are running in a component and that it is not an instance or library
            string return_msg;
            if (!CheckPreConditions(currentobj, out return_msg))
            {
                this.Logger.WriteFailed(return_msg);
                return;
            }

            // assuming a component is open
            // stash off the project, currentobj and CurrentComponent parameters for use in the event handlers
            StashProject = project;
            StashCurrentObj = currentobj;
            StashCurrentComponent = CyPhyClasses.Component.Cast(currentobj);

            // use reflection to populate the dialog box objects
            PopulateDialogBox();

            // To use the domain-specific API:
            //  Create another project with the same name as the paradigm name
            //  Copy the paradigm .mga file to the directory containing the new project
            //  In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator)
            //  Add a Reference in this project to the other project
            //  Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file
            // if (currentobj.Meta.Name == "KindName")
            // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj);			
        }