Exemplo n.º 1
0
        public CADComponent(CyPhy.Component cyphycomp, string ProjectDirectory, bool size2fit = false, string format = "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 = format;
            Name = cyphycomp.Name;
            CadParameters = new List<CADParameter>();
            ModelType = "Part";
            Size2Fit = size2fit;
            MaterialName = "";
            CyPhyModelPath = cyphycomp.GetDirectoryPath(ProjectDirectory: ProjectDirectory);
            Classification = cyphycomp.Attributes.Classifications;
            HyperLink = cyphycomp.ToHyperLink();

            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);
                }
            }
        }
 private string GetCadModelPath(CyPhyML.Component component)
 {
     string modelPath = component.GetDirectoryPath();
     if (modelPath == null)
     {
         return null;
     }
     else
     {
         foreach (var cadModel in component.Children.CADModelCollection)
         {
             string cadModelAbsolutePath;
             if (cadModel.TryGetResourcePath(out cadModelAbsolutePath, META.ComponentLibraryManager.PathConvention.ABSOLUTE))
             {
                 return cadModelAbsolutePath;
             }
         }
     }
     return null;
 }
Exemplo n.º 3
0
        /// <summary>
        /// Retrieves the path to the component's original ACM file, stored when it was imported.
        /// Note that ANY ACM file found will be flagged as a match, even if it has been updated for some reason.
        /// </summary>
        /// <param name="component"></param>
        /// <param name="path">The path to the ACM file, according to the PathConvention</param>
        /// <param name="pathConvention"></param>
        /// <param name="ProjectDirectory">Directory in which component files reside. Defaults to project directory of <paramref name="component"/></param>
        /// <returns>True only if an ACM was found</returns>
        public static bool TryGetOriginalACMFilePath(CyPhy.Component component, out string path, PathConvention pathConvention = PathConvention.REL_TO_COMP_DIR, string ProjectDirectory = null)
        {
            var componentPath = component.GetDirectoryPath(pathConvention, ProjectDirectory: ProjectDirectory);

            var acmFiles = Directory.EnumerateFiles(componentPath, "*.acm", SearchOption.TopDirectoryOnly);
            if (acmFiles.Any())
            {
                path = Path.Combine(componentPath, acmFiles.First());
                return true;
            }
            else if (File.Exists(Path.Combine(componentPath, "ComponentData.xml")))
            {
                path = Path.Combine(componentPath, "ComponentData.xml");
                return true;
            }

            path = "";
            return false;
        }
        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;
        }
        /// <summary>
        /// Given a CyPhy Component, builds a .ZIP-format Component Package, which includes
        /// an ACM version, as well as all artifacts from the component's
        /// backend folder. Note that it will grab ALL artifacts from that folder, not just
        /// those called out as Resources by the Component. It will also exclude any
        /// *.acm file found in that folder, opting to create a new ACM file from the
        /// current state of the component.
        /// </summary>
        /// <param name="component"></param>
        /// <param name="outputFolder">The folder where the component package should be created. If null, a temporary folder will be used.</param>
        /// <returns>The absolute path of the component package.</returns>
        public static String ExportComponentPackage(CyPhy.Component component, String outputFolder = null)
        {
            if (String.IsNullOrWhiteSpace(outputFolder))
            {
                // Assign a temp folder
                outputFolder = Path.Combine(System.IO.Path.GetTempPath(), Path.GetRandomFileName());
                Directory.CreateDirectory(outputFolder);
            }

            String acmFilePath = String.Format("{0}\\{1}.component.acm", outputFolder, System.IO.Path.GetRandomFileName());
            if (acmFilePath == null)
            {
                return null;
            }

            avm.Component avmComponent;

            var componentBuilder = new CyPhyML2AVM.AVMComponentBuilder();
            avmComponent = componentBuilder.CyPhyML2AVMNonStatic(component);

            // Create a ZIP filename
            String filename = String.Format("{0}.zip", component.Name);
            
            // If not unique, try a few different ones
            int counter = 1;
            while (File.Exists(Path.Combine(outputFolder, filename)))
            {
                filename = String.Format("{0}({1}).zip", component.Name, counter++);
            }

            String zipFileAbsPath = Path.Combine(outputFolder, filename);
            using (ZipFile zip = new ZipFile(zipFileAbsPath)
            {
                CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression
            })
            {
                String compDirAbsPath = component.GetDirectoryPath(META.ComponentLibraryManager.PathConvention.ABSOLUTE);
                foreach (var filePath in Directory
                                    .EnumerateFiles(compDirAbsPath,"*.*",SearchOption.AllDirectories)
                                    .Where(f => Path.GetExtension(f).ToLower() != ".acm"
                                             && Path.GetFileName(f).ToLower() != "componentdata.xml"))
                {
                    String fileRelDir;
                    if (compDirAbsPath.EndsWith("/"))
                    {
                        fileRelDir = Path.GetDirectoryName(
                                                ComponentLibraryManager.MakeRelativePath(compDirAbsPath, filePath));
                    }
                    else
                    {
                        fileRelDir = Path.GetDirectoryName(
                                                ComponentLibraryManager.MakeRelativePath(compDirAbsPath + "/", filePath));
                    }


                    zip.AddFile(filePath, fileRelDir);
                    Match match = cadResourceRegex.Match(Path.Combine(fileRelDir, Path.GetFileName(filePath)));
                    if (match.Success)
                    {
                        Func<Resource, bool> sameFile = delegate (Resource x) {
                            if (x.Path == match.Groups[1].Value + match.Groups[2].Value)
                                return true;
                            Match m = cadResourceRegex.Match(x.Path);
                            return m.Success && m.Groups[1].Value == match.Groups[1].Value && m.Groups[2].Value == match.Groups[2].Value;
                        };
                        foreach (var resource in avmComponent.ResourceDependency.Where(sameFile))
                        {
                            Match currentMatch = cadResourceRegex.Match(resource.Path);
                            if (currentMatch.Success == false || (Int32.Parse(match.Groups[3].Value) > Int32.Parse(currentMatch.Groups[3].Value)))
                            {
                                resource.Path = Path.Combine(fileRelDir, Path.GetFileName(filePath));
                            }
                        }
                    }
                }
                // Add the ACM file.
                SerializeAvmComponent(avmComponent, acmFilePath);
                zip.AddFile(acmFilePath, "").FileName = String.Format("{0}.acm", component.Name);

                zip.Save();
            }

            // Delete that ACM file
            File.Delete(acmFilePath);

            return zipFileAbsPath;
        }
 private void VerifyCADResources(CyPhyML.Component component, List<string> errorList)
 {
     string comppath = component.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);
     foreach (var res in component.Children.ResourceCollection)
     {
         if (CyphyMetaLinkUtils.IsCADResource(res))
         {
             string fullpath = Path.Combine(comppath, res.Attributes.Path);
             string[] files = Directory.GetFiles(Path.GetDirectoryName(fullpath), Path.GetFileName(fullpath) + "*");
             if (files.Length == 0)
             {
                 errorList.Add("Missing CAD resource file: " + fullpath);
             }
         }
     }
 }
        public string ExportToPackage(CyPhy.ComponentAssembly ca, String s_outFolder)
        {
            // Create a temp folder
            var pathTemp = Path.Combine(System.IO.Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(pathTemp);

            // Export an ADM file to that temp folder
            var pathADM = ExportToFile(ca, pathTemp);

            // Generate zip file
            String pathADP = Path.Combine(s_outFolder,
                                          Path.GetFileNameWithoutExtension(pathADM) + ".adp");
            File.Delete(pathADP);
            using (ZipFile zip = new ZipFile(pathADP)
                                 {
                                    CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression
                                 })
            {
                var pathCA = ca.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);
                if (false == (pathCA.EndsWith("//") || 
                              pathCA.EndsWith("\\\\")))
                {
                    pathCA += "//";
                }

                foreach (var file in Directory.EnumerateFiles(pathCA, "*.*", SearchOption.AllDirectories))
                {
                    var relpath = Path.GetDirectoryName(ComponentLibraryManager.MakeRelativePath(pathCA, file));
                    zip.AddFile(file, relpath);
                }

                // Add the ADM file
                zip.AddFile(pathADM, "");

                zip.Save();
            }

            // Delete temporary directory
            Directory.Delete(pathTemp, true);            

            return pathADP;
        }
        /// <summary>
        /// Copy a SPICE file into a component's subdirectory.
        /// </summary>
        /// <param name="component">The component that is getting the SPICE file.</param>
        /// <param name="path_SpiceFile">The full path to the input SPICE (".cir") file, including the file name.</param>
        /// <param name="subdirectory">The subdirectory where the SPICE file will be copied, typically "Spice".</param>
        /// <param name="destFileName">The name of the SPICE file after it has been uniquely copied.  (See MOT-221).</param>
        /// <param name="verbose">String used for exception debugging.</param>
        /// <remarks>May throw an exception from the file system.</remarks>
        private void CopySpiceFile(
            CyPhy.Component component, 
            String path_SpiceFile, 
            string subdirectory, 
            out string destFileName, 
            out string verbose)
        {
            // used in creating the resource object below
            string PathforComp = null;
            verbose = "Begin CopySpiceFile()\n"; // Used for debugging.

            // create the destination path
            verbose += "step 1\n";
            PathforComp = META.ComponentLibraryManager.EnsureComponentFolder(component);
            verbose += "step 2\n";

            PathforComp = component.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);
            verbose += "step 3\n";

            PathforComp = PathforComp.Replace('/', Path.DirectorySeparatorChar);

            string finalPathName = Path.Combine(PathforComp, subdirectory);
            verbose += "step 4\n";

            if (Directory.Exists(finalPathName) == false)
            {
                Directory.CreateDirectory(finalPathName);
            }

            verbose += string.Format("Created directory '{0}' OK.\n", finalPathName);


            destFileName = Path.GetFileName(path_SpiceFile);

            // Find a file name that doesn't already exist, MOT-221.
            string destinationSpiceFilePathAndName = Path.Combine(finalPathName, destFileName);
            int cnt = 1;

            // Make sure the named file doesn't already exist for MOT-221.
            while (File.Exists(destinationSpiceFilePathAndName))
            {
                Logger.WriteInfo("File {0} already exists.", destinationSpiceFilePathAndName);
                destFileName = Path.GetFileNameWithoutExtension(path_SpiceFile) + "_" + (cnt++) + Path.GetExtension(path_SpiceFile);
                destinationSpiceFilePathAndName = Path.Combine(finalPathName, destFileName);
            }
 
            verbose += string.Format("About to copy file '{0}' to '{1}'.\n",
               path_SpiceFile, destinationSpiceFilePathAndName);
            System.IO.File.Copy(path_SpiceFile, destinationSpiceFilePathAndName, true);
            Logger.WriteInfo("Copied file \"{0}\" to \"{1}\".", path_SpiceFile, destinationSpiceFilePathAndName);
        }