예제 #1
0
        public void TestRelativePathUNC()
        {
            string fromPath = "\\\\ComponentsAndArchitectureTeam\\ComponentLibraryManager\\components\\a786d5f1\\/";
            string toPath   = "\\\\ComponentsAndArchitectureTeam\\ComponentLibraryManager\\components\\a786d5f1\\generic_cots_mfg.xml";

            Assert.Equal("generic_cots_mfg.xml", ComponentLibraryManager.MakeRelativePath(fromPath, toPath));
        }
예제 #2
0
        public void TestRelativePath()
        {
            string fromPath = "C:\\Users\\kevin\\Documents\\meta-tonka\\META\\models\\ComponentsAndArchitectureTeam\\ComponentLibraryManager\\components\\a786d5f1\\/";
            string toPath   = "C:\\Users\\kevin\\Documents\\meta-tonka\\META\\models\\ComponentsAndArchitectureTeam\\ComponentLibraryManager\\components\\a786d5f1\\generic_cots_mfg.xml";

            Assert.Equal("generic_cots_mfg.xml", ComponentLibraryManager.MakeRelativePath(fromPath, toPath));
        }
예제 #3
0
        /// <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);

            var safe_component_name = InvalidFileNameRegex.Replace(component.Name, "_");

            // Create a ZIP filename
            String filename = String.Format("{0}.zip", safe_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", safe_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);
                IEnumerable <string> filePaths;
                if (Directory.Exists(compDirAbsPath))
                {
                    filePaths = Directory
                                .EnumerateFiles(compDirAbsPath, "*.*", SearchOption.AllDirectories)
                                .Where(f => Path.GetExtension(f).ToLower() != ".acm" &&
                                       Path.GetFileName(f).ToLower() != "componentdata.xml");
                }
                else
                {
                    filePaths = new string[] { };
                }
                foreach (var filePath in filePaths)
                {
                    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 (canonicalizeRelativePath(x.Path).Equals(canonicalizeRelativePath(match.Groups[1].Value + match.Groups[2].Value), StringComparison.InvariantCultureIgnoreCase))
                            {
                                return(true);
                            }
                            Match m = cadResourceRegex.Match(x.Path);
                            return(m.Success && m.Groups[1].Value.Equals(match.Groups[1].Value, StringComparison.InvariantCultureIgnoreCase) &&
                                   m.Groups[2].Value.Equals(match.Groups[2].Value, StringComparison.InvariantCultureIgnoreCase));
                        };
                        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", safe_component_name);

                zip.Save();
            }

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

            return(zipFileAbsPath);
        }
예제 #4
0
        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
            })
            {
                Queue <CyPhy.ComponentAssembly> cas = new Queue <CyPhy.ComponentAssembly>();
                cas.Enqueue(ca);
                while (cas.Count != 0)
                {
                    var componentAssembly = cas.Dequeue();
                    var pathCA            = componentAssembly.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);
                    if (false == (pathCA.EndsWith("//") ||
                                  pathCA.EndsWith("\\\\")))
                    {
                        pathCA += "//";
                    }

                    string dirName     = componentAssembly.Attributes.ID.ToString();
                    string managedGUID = componentAssembly.Attributes.ManagedGUID;
                    if (string.IsNullOrEmpty(managedGUID) == false)
                    {
                        dirName = managedGUID;
                    }
                    foreach (var file in Directory.EnumerateFiles(pathCA, "*.*", SearchOption.AllDirectories))
                    {
                        var relpath = Path.GetDirectoryName(ComponentLibraryManager.MakeRelativePath(pathCA, file));
                        zip.AddFile(file, dirName + "/" + relpath);
                    }

                    foreach (var subCA in componentAssembly.Children.ComponentAssemblyCollection)
                    {
                        cas.Enqueue(subCA);
                    }
                }

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

                zip.Save();
            }

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

            return(pathADP);
        }
예제 #5
0
        public void RenameCADFile(string CADpath = null, string NewName = null)
        {
            string StartingCadFilename = "";
            string CadFilenamePath     = "";
            string cad_extension       = "";
            string RenamedCadFilename  = "";

            this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name);

            // Get the file name desirous of changing
            #region get_name
            //  - Display a dialog box to let the user choose their Creo model file
            bool cad_file_chosen = false;
            bool test_mode_only  = false;
            if (string.IsNullOrWhiteSpace(CADpath))
            {
                cad_file_chosen = get_cad_file(out StartingCadFilename);
            }
            else
            {
                test_mode_only      = true;
                StartingCadFilename = CADpath.Replace("/", "\\");
                if (File.Exists(StartingCadFilename))
                {
                    cad_file_chosen = true;
                }
                else
                {
                    if (!test_mode_only)
                    {
                        this.Logger.WriteError("Invalid CAD file path passed in: " + CADpath);
                    }
                }
            }
            #endregion

            // check chosen file constraints
            #region check_constraints
            if (cad_file_chosen)
            {
                // -    file chosen is in the component folder structure
                string must_be_in_dir = ((CyPhy.Component)GetCurrentDesignElement()).GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE).Replace("/", "\\");
                if (!StartingCadFilename.Contains(must_be_in_dir))
                {
                    if (!test_mode_only)
                    {
                        this.Logger.WriteError("File to rename must reside in current component's folder:" + must_be_in_dir);
                    }
                    //cleanup
                    cleanup(false);
                    return;
                }
                // -    file chosen is a CREO .prt or .asm file
                if (!(StartingCadFilename.Contains(".prt") || StartingCadFilename.Contains(".asm")))
                {
                    if (!test_mode_only)
                    {
                        this.Logger.WriteError("File to rename must be a CAD .prt or .asm file only");
                    }
                    //cleanup
                    cleanup(false);
                    return;
                }
            }
            #endregion

            // Get new desired name
            #region get_new_name
            if (cad_file_chosen)
            {
                string new_file_name = "";

                if (test_mode_only)
                {
                    new_file_name = NewName;
                }
                else
                {
                    new_file_name = GetNewFilename();
                }

                if (!String.IsNullOrEmpty(new_file_name))
                {
                    // massage new name
                    CadFilenamePath = Path.GetDirectoryName(StartingCadFilename);
                    //  -   strip off the CREO version extension
                    string just_the_name = Path.GetFileNameWithoutExtension(new_file_name);
                    // -    retain the original extension type (.prt or .asm)
                    cad_extension = FileExtensionType(StartingCadFilename);

                    // construct the new file name
                    RenamedCadFilename = Path.Combine(CadFilenamePath, just_the_name) + cad_extension + ".1";
                    // -    verify chosen name does not alreay exist
                    if (File.Exists(RenamedCadFilename))
                    {
                        if (!test_mode_only)
                        {
                            this.Logger.WriteError("Chosen new filename already exists: ", RenamedCadFilename);
                        }
                        //cleanup
                        cleanup(false);
                        return;
                    }
                }
                else
                {
                    if (!test_mode_only)
                    {
                        this.Logger.WriteError("Chosen new filename is invalid or null: ", RenamedCadFilename);
                    }
                    //cleanup
                    cleanup(false);
                    return;
                }
            }
            #endregion

            // change model and resource names and path to match new name
            if (cad_file_chosen)
            {
                // Step 1 - Look for a Resource object that has a "Path" attribute that matches the "old path".
                //- Does the file path chosen match the "Path" attribute of a Resource?
                //  - If not, quit.
                CyPhy.Resource ResourceObj  = null;
                var            resourcePath = ComponentLibraryManager.MakeRelativePath(
                    ((CyPhy.Component)GetCurrentDesignElement()).GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE),
                    AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(StartingCadFilename));
                // n.b. current dir doesn't matter, we just want to canonicalize .. . / et al
                resourcePath = Path.GetFullPath(resourcePath);
                try
                {
                    ResourceObj = GetCurrentDesignElement().Children.ResourceCollection
                                  .Where(p => Path.GetFullPath(AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(p.Attributes.Path))
                                         == resourcePath).First();
                }
                catch (InvalidOperationException ex)
                {
                    if (!test_mode_only)
                    {
                        this.Logger.WriteError("No resource found with that CAD file path", ComponentLibraryManager.MakeRelativePath(
                                                   ((CyPhy.Component)GetCurrentDesignElement()).GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE), StartingCadFilename), ex.Message);
                    }
                    cleanup(false);
                    return;
                }

                // Step 2 - Check if the Resource is attached to a CADModel.
                //  - If not, quit.
                bool ResourceConnected2Model = true;
                // first check if Resource is Source, Model is Destination
                try
                {
                    ResourceConnected2Model = ResourceObj.DstConnections.UsesResourceCollection.Where(c => c.DstEnds.CADModel != null).Any();
                }
                catch (Exception ex)
                {
                    ResourceConnected2Model = false;
                    if (!test_mode_only)
                    {
                        this.Logger.WriteError("No connection from this Resource to a CAD model", ex.Message);
                    }
                }
                // check opposite direction if connection not found
                if (!ResourceConnected2Model)
                {
                    // next check if Resource is Destination, Model is Source
                    try
                    {
                        ResourceConnected2Model = ResourceObj.SrcConnections.UsesResourceCollection.Where(c => c.SrcEnds.CADModel != null).Any();
                        ResourceConnected2Model = true;
                    }
                    catch (Exception ex)
                    {
                        if (!test_mode_only)
                        {
                            this.Logger.WriteError("No connection from this Resource to a CAD model", ex.Message);
                        }
                        cleanup(true);
                        return;
                    }
                }

                // Step 3 - rename the file in the folder
                try
                {
                    //TODO commented out for debug
                    File.Move(StartingCadFilename, RenamedCadFilename);
                }
                catch (Exception ex)
                {
                    // the rename failed.  bail out
                    this.Logger.WriteError("Error renaming CAD file:", Path.GetFileName(StartingCadFilename), ex.Message);
                    cleanup(true);
                    return;
                }

                // Step 4 - Change that "Path" attribute to the new name.
                // change the resource name and path
                // Path name needs to be relative to component folder
                string new_path = ComponentLibraryManager.MakeRelativePath(((CyPhy.Component)GetCurrentDesignElement()).GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE),
                                                                           AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(RenamedCadFilename));
                ResourceObj.Attributes.Path = new_path;

                // Step 5 - If the Resource name happens to be the filename, change it too.
                if (AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(ResourceObj.Name)
                    == Path.GetFileName(AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(StartingCadFilename)))
                {
                    ResourceObj.Name = Path.GetFileName(AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(RenamedCadFilename));
                }

                // Step 6 - If the CAD Model name happens to be the filename, change it too.
                // change the model name
                CyPhy.CADModel ModelObj       = null;
                bool           ModelObjExists = true;
                var            modelObjName   = AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(Path.GetFileName(StartingCadFilename));
                try
                {
                    // FIXME: check that it is connected to ResourceObj
                    ModelObj = GetCurrentDesignElement().Children.CADModelCollection.Where(p => p.Name == modelObjName).First();
                }
                // check if ModelObj exists
                catch (InvalidOperationException)
                {
                    ModelObjExists = false;
                    if (!test_mode_only)
                    {
                        // this doesn't matter, don't confuse the user
                        // this.Logger.WriteWarning("Cannot rename CADModel, because there is no CADModel named '{0}'", modelObjName, ex.Message);
                    }
                }
                if (ModelObjExists)
                {
                    ModelObj.Name = AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(Path.GetFileName(RenamedCadFilename));
                }
            }
            //cleanup
            cleanup(cad_file_chosen && !test_mode_only);
            return;
        }