示例#1
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);
            }
        }
示例#2
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);
            }
        }
示例#3
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();
        }
示例#4
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();
        }
示例#5
0
        public void OutsideCopy_DifferentProjDir_AVMIDCollision()
        {
            // Create a new component.
            // Its AVMID will NOT be unique to this project, and thus a new (unique) AVMID must be assigned.
            // Its Path will be unique to this project, and that path will NOT exist already on disk,
            // because we expect in this case that the component was copied from another project somewhere else.
            // WHAT DO WE EXPECT THE ADD-ON TO DO?
            // 1. Assign a new AVMID.
            // 2. Because the folder does not exist on disk, a new path and backing folder will be created for this guy.

            var compName = Utils.GetCurrentMethod();

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

            // 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;
                org_AVMID = c.Attributes.AVMID = "101b"; // This AVMID should collide
                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, "Component should have been assigned a new path.");
                Assert.True(Directory.Exists(c.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE)), "New component folder doesn't exist on disk.");
            });
            project.Save();
        }
示例#6
0
        public void ImportCADModel(string CADpath = null)
        {
            string cadFilename = "";

            this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name);
            using (this.Logger)
            {
                //The CAT module will perform these steps, in this order:
                //  - Check that the user has Creo (so that the extraction will be successful)
                //      - Implementation Suggestion: The extraction utility may have special flag to have it indicates if all the dependencies are met

                //  - Display a dialog box to let the user choose their Creo model file
                bool cad_file_chosen         = false;
                bool test_copy_and_path_only = false;
                if (string.IsNullOrWhiteSpace(CADpath))
                {
                    cad_file_chosen = get_cad_file(out cadFilename);
                }
                else
                {
                    test_copy_and_path_only = true;
                    cadFilename             = CADpath;
                    if (File.Exists(cadFilename))
                    {
                        cad_file_chosen = true;
                    }
                    else
                    {
                        this.Logger.WriteError("Invalid CAD file path passed in: " + CADpath);
                    }
                }

                //  - Run the extractor on the Creo model file
                #region Run the Extractor

                bool   extractor_ran_success = test_copy_and_path_only;
                string tempXMLfile           = Path.GetTempFileName();
                this.Logger.WriteDebug("Temporary XML file created: " + tempXMLfile);

                if (cad_file_chosen && !test_copy_and_path_only)
                {
                    try
                    {
                        // assemble the arg string
                        // first the input CAD file
                        // include quotation marks to handle paths with white spaces
                        string argstring = "ExtractACM-XMLfromCreoModels -c \"";
                        argstring += cadFilename;
                        argstring += "\"";

                        // add the XML output file name
                        argstring += " -x \"";
                        argstring += tempXMLfile;
                        argstring += "\"";

                        // Debug only: pause before exit, graphics mode.
                        //argstring += " -p -g";

                        Process firstProc = new Process();

                        string path = Path.Combine(META.VersionInfo.MetaPath, "bin\\CAD\\Creo\\bin\\CADCreoParametricCreateAssembly.exe");
                        if (!File.Exists(path))
                        {
                            this.Logger.WriteError(String.Format("Cannot find '{0}'", path));
                            throw new Exception("CADCreoParametricCreateAssembly.exe not found.");
                        }

                        firstProc.StartInfo.FileName               = path;
                        firstProc.StartInfo.Arguments              = argstring;
                        firstProc.StartInfo.CreateNoWindow         = true;
                        firstProc.StartInfo.UseShellExecute        = false;
                        firstProc.StartInfo.RedirectStandardOutput = true;
                        firstProc.StartInfo.RedirectStandardError  = true;
                        firstProc.StartInfo.RedirectStandardInput  = true;

                        int           streamsClosed    = 0;
                        StringBuilder exeConsoleOutput = new StringBuilder();

                        DataReceivedEventHandler handler = (sender, e) =>
                        {
                            lock (Logger)
                            {
                                if (e.Data == null)
                                {
                                    streamsClosed += 1;
                                    if (streamsClosed == 2)
                                    {
                                    }
                                    return;
                                }
                                Logger.WriteDebug(e.Data);
                                exeConsoleOutput.AppendLine(e.Data);
                            }
                        };
                        firstProc.OutputDataReceived += handler;
                        firstProc.ErrorDataReceived  += handler;
                        firstProc.EnableRaisingEvents = true;
                        bool             showProgressBar        = sender != null && sender is IWin32Window;
                        bool             done                   = false;
                        Object           doneSyncObject         = new object();
                        GUIs.CADProgress progress               = null;
                        EventHandler     closeDialogWithSuccess = (e, o) =>
                        {
                            lock (doneSyncObject)
                            {
                                if (done == false)
                                {
                                    progress.BeginInvoke((Action)(() =>
                                    {
                                        done = true;
                                        progress.DialogResult = DialogResult.OK;
                                        progress.Close();
                                    }));
                                }
                            }
                        };
                        if (showProgressBar)
                        {
                            progress          = new GUIs.CADProgress();
                            firstProc.Exited += closeDialogWithSuccess;
                        }
                        IntPtr job = JobObjectPinvoke.CreateKillOnCloseJob();
                        firstProc.Exited += (s, o) =>
                        {
                            if (job != JobObjectPinvoke.INVALID_HANDLE_VALUE)
                            {
                                JobObjectPinvoke.CloseHandle(job);
                            }
                            if (progress != null && progress.DialogResult == DialogResult.Cancel)
                            {
                                File.Delete(tempXMLfile);
                            }
                        };

                        this.Logger.WriteDebug("Calling CADCreoParametricCreateAssembly.exe with argument string: " + argstring);

                        firstProc.Start();
                        JobObjectPinvoke.AssignProcessToJobObject(firstProc, job);
                        firstProc.StandardInput.Close();
                        firstProc.BeginOutputReadLine();
                        firstProc.BeginErrorReadLine();

                        if (showProgressBar)
                        {
                            progress.FormClosing += (e, o) =>
                            {
                                lock (doneSyncObject)
                                {
                                    firstProc.Exited -= closeDialogWithSuccess;
                                    done              = true;
                                }
                            };
                            var result = progress.ShowDialog((IWin32Window)sender);
                            if (result == DialogResult.Cancel)
                            {
                                cleanup(null, true);
                                return;
                            }
                        }
                        else
                        {
                            firstProc.WaitForExit();
                        }

                        this.Logger.WriteDebug("CADCreoParametricCreateAssembly.exe ExtractACM-XMLfromCreoModels has completed.");

                        if (firstProc.ExitCode == 0)
                        {
                            extractor_ran_success = true;
                        }
                        else
                        {
                            this.Logger.WriteDebug("CADCreoParametricCreateAssembly.exe ExtractACM-XMLfromCreoModels returned error code " + firstProc.ExitCode.ToString());
                            // Warn with last non-empty line, it should contain a useful error message
                            Regex lastLine = new Regex("[\\n^]([^\\n]+)(\\n|\\s)*$", RegexOptions.Singleline);
                            var   match    = lastLine.Match(exeConsoleOutput.ToString());
                            if (match != null && match.Success)
                            {
                                this.Logger.WriteWarning(match.Groups[1].Value);
                            }
                            throw new Exception("Extract executable returned error code " + firstProc.ExitCode.ToString() + ". Detailed log at " + this.Logger.LogFilenames.FirstOrDefault());
                        }
                    }
                    catch (Exception ex)
                    {
                        this.Logger.WriteError("An error occurred running Creo parametric: " + ex.Message + " - Extraction Failed. Insure you can access the Creo license server");
                        cleanup(tempXMLfile, true);
                        return;
                    }
                }
                #endregion

                //  - Use a function from CyPhy2ComponentModel to convert the extractor's XML format into a CyPhy model fragment
                #region Convert_to_XML
                // used in creating the resource object below
                CyPhy.CADModel ProcessedCADModel = null;

                if (extractor_ran_success && !test_copy_and_path_only)
                {
                    this.Logger.WriteDebug("About to call DeserializeAvmComponentXml...");
                    StreamReader  streamReader = new StreamReader(tempXMLfile);
                    avm.Component ac_import    = CyPhyComponentImporter.CyPhyComponentImporterInterpreter.DeserializeAvmComponentXml(streamReader);
                    streamReader.Close();
                    this.Logger.WriteDebug("... finished DeserializeAvmComponentXml call.");

                    foreach (var cadmodel in ac_import.DomainModel.Where(dm => dm is avm.cad.CADModel)
                             .Cast <avm.cad.CADModel>())
                    {
                        var rf = CyPhyClasses.RootFolder.GetRootFolder(CurrentProj);

                        AVM2CyPhyML.CyPhyMLComponentBuilder newComponent = new AVM2CyPhyML.CyPhyMLComponentBuilder(rf);
                        ProcessedCADModel      = newComponent.process(cadmodel, (CyPhy.Component)GetCurrentDesignElement());
                        ProcessedCADModel.Name = Path.GetFileName(AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(cadFilename));
                    }

                    // find the largest current Y value so our new elements are added below the existing design elements
                    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_y = (read_y > greatest_current_y) ? read_y : greatest_current_y;
                        }
                    }

                    // layout CAD model to the "south" of existing elements
                    foreach (MgaPart item in (ProcessedCADModel.Impl as MgaFCO).Parts)
                    {
                        item.SetGmeAttrs(null, CAD_MODEL_START_X, greatest_current_y + CAD_MODEL_START_Y);
                    }

                    // Extend it's properties out to the component level.
                    this.CADModuleImportExtension(ProcessedCADModel);
                }
                else if (test_copy_and_path_only)
                {
                    ProcessedCADModel      = CyPhyClasses.CADModel.Create((CyPhy.Component)GetCurrentDesignElement());
                    ProcessedCADModel.Name = Path.GetFileName(AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(CADpath));
                }

                #endregion

                //  - Copy the Creo Model files into the component's backend folder
                //      - Note: The solution includes a function that can find this folder using the project.manifest.json file.
                //      - For nice organization, create them in a subfolder called "CAD"
                // create avmproj
                #region Copy files to backend folder

                // used in creating the resource object below
                string PathforComp = null;

                var importedCADFiles = new List <String>();
                if (extractor_ran_success)
                {
                    try
                    {
                        // create the destination path
                        PathforComp = META.ComponentLibraryManager.EnsureComponentFolder((CyPhy.Component)GetCurrentDesignElement());
                        PathforComp = ((CyPhy.Component)GetCurrentDesignElement()).GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);

                        string finalPathName = Path.Combine(PathforComp, "CAD");

                        Directory.CreateDirectory(finalPathName);

                        // determine if one part file or all part and assembly files need to be copied
                        string cpsrcfile = System.IO.Path.GetFileName(cadFilename);

                        // copy the selected file
                        string cadFileCopyPath = System.IO.Path.Combine(finalPathName, cpsrcfile);
                        if (Path.GetFullPath(cadFilename) != Path.GetFullPath(cadFileCopyPath))
                        {
                            System.IO.File.Copy(cadFilename, cadFileCopyPath, true);
                        }

                        // Set "primary" file as the first in the list.
                        importedCADFiles.Add(Path.Combine("CAD", Path.GetFileName(cadFileCopyPath)));

                        if (fileISasm(cpsrcfile) && !test_copy_and_path_only)
                        {
                            // get a string of the XML contents
                            this.Logger.WriteDebug("About to read contents of XML file using class XmlDocument: " + tempXMLfile);

                            XmlDocument doc = new XmlDocument();
                            doc.Load(tempXMLfile);
                            string xmlcontents = doc.InnerXml;

                            // mine down to the Resource dependencies
                            using (XmlReader reader = XmlReader.Create(new StringReader(xmlcontents)))
                            {
                                // iterate through each file listed in the resourcedependency section
                                while (reader.ReadToFollowing("ResourceDependency") == true)
                                {
                                    string res_path = reader.GetAttribute("Path");
                                    this.Logger.WriteDebug("Copying this file: " + res_path);

                                    // CAD files end in .1 .2 etc. Pick the latest ones
                                    var allFiles = Directory.EnumerateFiles(Path.GetDirectoryName(res_path), "*prt." /*n.b. literal dot*/ + "*")
                                                   .Concat(Directory.EnumerateFiles(Path.GetDirectoryName(res_path), "*asm.*"))
                                                   .Select(Path.GetFileName)
                                                   .Select(filename => new { basename = filename.Substring(0, filename.LastIndexOf('.')), version = filename.Substring(filename.LastIndexOf('.') + 1) })
                                                   .Where(p => { int val; return(Int32.TryParse(p.version, out val)); })
                                                   .OrderByDescending(p => Int32.Parse(p.version))
                                                   .ToArray();
                                    foreach (var basename in allFiles.Select(p => p.basename).Distinct())
                                    {
                                        var latest = allFiles.Where(p => p.basename == basename).FirstOrDefault();
                                        if (latest != null)
                                        {
                                            string latestFilename = latest.basename + "." + latest.version;
                                            // Need to limit this down to just the filename in question
                                            // The XML file changes the name to all caps, so compare apples to apples
                                            if (latestFilename.ToUpperInvariant().StartsWith(Path.GetFileName(res_path).ToUpperInvariant()))
                                            {
                                                string destpathandname = Path.Combine(finalPathName, latestFilename);
                                                if (!importedCADFiles.Contains(Path.Combine("CAD", Path.GetFileName(destpathandname))))
                                                {
                                                    importedCADFiles.Add(Path.Combine("CAD", Path.GetFileName(destpathandname)));
                                                }
                                                var sourcepathandname = Path.Combine(Path.GetDirectoryName(res_path), latestFilename);
                                                if (Path.GetFullPath(sourcepathandname) != Path.GetFullPath(destpathandname))
                                                {
                                                    File.Copy(sourcepathandname, destpathandname, true);
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception err_create_proj)
                    {
                        this.Logger.WriteError("Error creating AVM project: " + err_create_proj.Message, " - Extraction Failed. Possible ComponentManagement issue.");
                        cleanup(tempXMLfile, true);
                        return;
                    }
                }
                #endregion

                //  - Create Resource objects in the CyPhy Component model that point to these Creo Model files
                //      - Note: The "paths" of these should be the relative path from that component's root folder
                if (extractor_ran_success)
                {
                    foreach (var cadFile in importedCADFiles)
                    {
                        CyPhy.Resource ResourceObj = CyPhyClasses.Resource.Create((CyPhy.Component)GetCurrentDesignElement());
                        ResourceObj.Attributes.ID    = Guid.NewGuid().ToString("B");
                        ResourceObj.Attributes.Path  = AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(cadFile);
                        ResourceObj.Attributes.Notes = "CAD Model Import tool added this resource object for the imported CAD file";
                        ResourceObj.Name             = Path.GetFileName(AVM2CyPhyML.CyPhyMLComponentBuilder.GetCreoFileWithoutVersion(cadFile));

                        // layout Resource just to the side of the CAD model
                        foreach (MgaPart item in (ResourceObj.Impl as MgaFCO).Parts)
                        {
                            item.SetGmeAttrs(null, RESOURCE_START_X, greatest_current_y + RESOURCE_START_Y);
                        }

                        // The "primary" CAD model is the first one -- associate it with the CyPhy CADModel object
                        if (importedCADFiles.IndexOf(cadFile) == 0)
                        {
                            //  - Create a UsesResource association between the CyPhy CADModel object and the Resource object that represents the top-level Creo Model file.
                            CyPhyClasses.UsesResource.Connect(ResourceObj, ProcessedCADModel, null, null, (CyPhy.Component)GetCurrentDesignElement());
                        }
                    }
                }

                // throw in an ACM file for the current state of the component.
                if (extractor_ran_success && !test_copy_and_path_only)
                {
                    var    exporter = new CyPhyComponentExporter.CyPhyComponentExporterInterpreter();
                    String acmPath  = Path.Combine(PathforComp, GetCurrentDesignElement().Name + ".component.acm");
                    CyPhyComponentExporterInterpreter.ExportToDirectory((CyPhy.Component)GetCurrentDesignElement(), Path.GetDirectoryName(acmPath));
                }

                // Clean up
                cleanup(tempXMLfile, (extractor_ran_success && !test_copy_and_path_only));
            }
        }
示例#7
0
        public void import_manufacturing_model(string mfgFilename = "")
        {
            this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name);

            this.Logger.WriteDebug("Starting Import Manufacturing Model module...");

            // Case 3211: determine if a manufacturing model already exists and give the user the option to abort if it does
            CyPhy.ManufacturingModel ExistingMfgModel = ((CyPhy.Component)GetCurrentDesignElement()).Children.ManufacturingModelCollection.FirstOrDefault();

            if (ExistingMfgModel != null)
            {
                // no exception means a manufacturing model exists
                this.Logger.WriteDebug("Detected pre-existing Manufacturing Model.");

                // skip the dialog box if we are in autotest mode
                if (String.IsNullOrEmpty(mfgFilename))
                {
                    // YesNoDialog to ask the user to overwrite the existing manufacturing model
                    var dialogResult = MessageBox.Show("Do you wish to overwrite the existing Manufacturing Model?", "Manufacturing Model Detected", MessageBoxButtons.YesNo);

                    // if user selected anything besides YES then the tool will abort
                    if (dialogResult != DialogResult.Yes)
                    {
                        this.Logger.WriteError("Import manufacturing model aborted. Model already exists");
                        cleanup(false);
                        return;
                    }
                }

                // delete any resources attached to the manufacturing model about to be deleted
                foreach (var ur in ExistingMfgModel.SrcConnections.UsesResourceCollection)
                {
                    ur.SrcEnd.Delete();
                }

                // delete existing manufacturing model
                ExistingMfgModel.Delete();
            }

            //  - Display a dialog box to let the user choose their manufacturing model XML file
            bool mfg_file_chosen = false;

            if (String.IsNullOrEmpty(mfgFilename))
            {
                mfg_file_chosen = get_mfg_file(out mfgFilename);
            }
            else
            {
                mfg_file_chosen = true;
            }

            // Step 1 - Copy the Manufacturing Model XML file into the component's folder
            #region Copy file to component folder

            // used in creating the resource object below
            string mfgFileCopyPath = null;

            if (mfg_file_chosen)
            {
                try
                {
                    // create the destination path
                    string PathforComp = META.ComponentLibraryManager.EnsureComponentFolder((CyPhy.Component)GetCurrentDesignElement());
                    PathforComp = ((CyPhy.Component)GetCurrentDesignElement()).GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);

                    string finalPathName = Path.Combine(PathforComp, "Manufacturing");

                    Directory.CreateDirectory(finalPathName);

                    // determine if one part file or all part and assembly files need to be copied
                    string cpsrcfile = System.IO.Path.GetFileName(mfgFilename);

                    // copy the selected file
                    mfgFileCopyPath = System.IO.Path.Combine(finalPathName, cpsrcfile);

                    // Check to see if the file exists
                    int counter = 1;
                    while (System.IO.File.Exists(mfgFileCopyPath))
                    {
                        string JustFileName = String.Format("{0}({1}){2}", System.IO.Path.GetFileNameWithoutExtension(mfgFilename), counter++, System.IO.Path.GetExtension(mfgFilename));
                        mfgFileCopyPath = System.IO.Path.Combine(finalPathName, JustFileName);
                    }

                    System.IO.File.Copy(mfgFilename, mfgFileCopyPath);
                }
                catch (Exception err_create_proj)
                {
                    this.Logger.WriteError("Error copying manufacturing file: " + err_create_proj.Message, " - Copy Failed. Possible disk drive issue.");
                    cleanup(false);
                    return;
                }
            }
            #endregion

            // Step 2 - In the CyPhy Component Model, create:
            #region Create_Manufacturing_Model_Object
            // Step 2a  - create a ManufacturingModel object
            // used in creating the resource object below, so kept outside of if loop for scope
            CyPhy.ManufacturingModel ProcessedMfgModel = null;

            if (mfg_file_chosen)
            {
                this.Logger.WriteDebug("Creating Manufacturing model object...");

                ProcessedMfgModel      = CyPhyClasses.ManufacturingModel.Create((CyPhy.Component)GetCurrentDesignElement());
                ProcessedMfgModel.Name = MFG_MODEL_NAME;

                // find the largest current Y value so our new elements are added below the existing design elements
                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_y = (read_y > greatest_current_y) ? read_y : greatest_current_y;
                    }
                }

                // layout new model to the "south" of existing elements
                foreach (MgaPart item in (ProcessedMfgModel.Impl as MgaFCO).Parts)
                {
                    item.SetGmeAttrs(null, MFG_MODEL_START_X, greatest_current_y + MFG_MODEL_START_Y);
                }
            }
            #endregion

            // Step 2b - create a Resource object pointing to the copied XML file
            #region Create_Resource_Object
            if (mfg_file_chosen)
            {
                this.Logger.WriteDebug("Creating Manufacturing model resource object...");
                CyPhy.Resource ResourceObj = CyPhyClasses.Resource.Create((CyPhy.Component)GetCurrentDesignElement());
                ResourceObj.Attributes.ID = Guid.NewGuid().ToString("B");
                // META-3136, fix PATH attribute to be relative to component directory
                // ResourceObj.Attributes.Path = mfgFileCopyPath;
                ResourceObj.Attributes.Path  = Path.Combine("Manufacturing", Path.GetFileName(mfgFileCopyPath));
                ResourceObj.Attributes.Notes = "Manufacturing Model Import tool added this resource object";
                ResourceObj.Name             = Path.GetFileName(mfgFileCopyPath);

                // layout Resource just to the side of the manufacturing model
                foreach (MgaPart item in (ResourceObj.Impl as MgaFCO).Parts)
                {
                    item.SetGmeAttrs(null, RESOURCE_START_X, greatest_current_y + RESOURCE_START_Y);
                }

                // Step 2c - Create a UsesResource association between the CyPhy ManufacturingModel object and the Resource object
                this.Logger.WriteDebug("Creating Manufacturing model UsesResource association...");
                CyPhyClasses.UsesResource.Connect(ResourceObj, ProcessedMfgModel, null, null, (CyPhy.Component)GetCurrentDesignElement());
            }
            #endregion

            // Clean up
            this.Logger.WriteDebug("Exiting Import Manufacturing Model module...");
            cleanup(mfg_file_chosen);
        }
示例#8
0
 public static bool IsCADResource(CyPhyML.Resource res)
 {
     return(Path.GetExtension(res.Attributes.Path).ToLower() == ".prt" || Path.GetExtension(res.Attributes.Path).ToLower() == ".asm");
 }
示例#9
0
        public void AddCustomIcon(string IconFileSourcePath = null)
        {
            this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name);
            string IconFileSourceName = "";

            //            To support this, Components can have custom icons. A Component's custom icon must:
            // - be in the Component's folder
            // - have a Resource reference to the file (with path relative to the component folder itself)
            // - have a path that includes "Icon.png" ("myIcon.png", "images/theIcon.png", "Icon.png", etc)
            // You can take a look at a Component's custom icon by opening a ComponentAssembly and creating a reference to the Component.

            // The goal of this ticket is to allow the user to add a custom icon for the component via the CAT. The user should be allowed to browse for a *.png file.
            #region choose_icon_file
            //  - Display a dialog box to let the user choose the Custom Icon file
            bool icon_file_chosen = false;
            bool test_mode        = false;
            if (string.IsNullOrWhiteSpace(IconFileSourcePath))
            {
                icon_file_chosen = get_icon_file(out IconFileSourceName);
            }
            else
            {
                test_mode          = true;
                IconFileSourceName = IconFileSourcePath;
                if (File.Exists(IconFileSourceName))
                {
                    icon_file_chosen = true;
                }
                else
                {
                    this.Logger.WriteError("Invalid Custom Icon file path passed in: " + IconFileSourcePath);
                }
            }
            #endregion

            // When that file is selected: - it should be copied into the component's folder, and have its name changed to "Icon.png".
            #region Copy files to backend folder

            // used in creating the resource object below
            string IconFileDestPath = null;
            string IconFileDestName = "";

            if (icon_file_chosen)
            {
                try
                {
                    // Find the path of the current component
                    IconFileDestPath = META.ComponentLibraryManager.EnsureComponentFolder((CyPhy.Component)GetCurrentDesignElement());
                    IconFileDestPath = ((CyPhy.Component)GetCurrentDesignElement()).GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);

                    // copy the selected file
                    var FileName = "Icon" + Path.GetExtension(IconFileSourceName).ToLowerInvariant();
                    IconFileDestName = System.IO.Path.Combine(IconFileDestPath, FileName);
                    System.IO.File.Copy(IconFileSourceName, IconFileDestName, true);
                }
                catch (Exception err_copy_icon_file)
                {
                    this.Logger.WriteError("Error copying Icon file" + err_copy_icon_file.Message);
                    clean_up(false);
                    return;
                }
            }
            #endregion

            //- A Resource object should be created in the CyPhy Component which points to the file.
            #region create_resource
            if (icon_file_chosen)
            {
                CyPhy.Resource ResourceObj = CyPhyClasses.Resource.Create((CyPhy.Component)GetCurrentDesignElement());
                ResourceObj.Attributes.ID    = Guid.NewGuid().ToString("B");
                ResourceObj.Attributes.Path  = Path.GetFileName(IconFileDestName);
                ResourceObj.Attributes.Notes = "Custom icon for this component";
                ResourceObj.Name             = Path.GetFileName(IconFileDestName);

                String iconPath_RelativeToProjRoot = Path.Combine(((CyPhy.Component)GetCurrentDesignElement()).GetDirectoryPath(ComponentLibraryManager.PathConvention.REL_TO_PROJ_ROOT),
                                                                  Path.GetFileName(IconFileDestName));

                if (Path.GetExtension(IconFileDestName) == ".png")
                {
                    //- Finally, it must be set as the CyPhy Component's icon
                    try
                    {
                        (GetCurrentDesignElement().Impl as GME.MGA.IMgaFCO).set_RegistryValue("icon", iconPath_RelativeToProjRoot);
                    }
                    catch (Exception err_set_registry)
                    {
                        this.Logger.WriteError("Error setting Icon Registry Value" + err_set_registry.Message);
                        clean_up(false);
                        return;
                    }
                }
            }
            #endregion

            clean_up(icon_file_chosen && !test_mode);
        }
示例#10
0
        public void ImportCyberModel(string Cyberpath = null)
        {
            string CyberFilename = "";

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

            //  - Display a dialog box to let the user choose their Cyber model file
            bool Cyber_file_chosen = false;

            //bool test_copy_and_path_only = false;
            if (string.IsNullOrWhiteSpace(Cyberpath))
            {
                Cyber_file_chosen = get_Cyber_file(out CyberFilename);
            }
            else
            {
                //test_copy_and_path_only = true;
                CyberFilename = Cyberpath;
                if (File.Exists(CyberFilename))
                {
                    Cyber_file_chosen = true;
                }
                else
                {
                    this.Logger.WriteError("Invalid Cyber file path passed in: " + Cyberpath);
                }
            }

            //  - Run the extractor on the Creo model file
            #region Run the Extractor

            List <string> componentList = new List <string>();
            IMgaProject   project       = (IMgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject"));
            string        compName;
            project.OpenEx("MGA=" + CyberFilename, "CyberComposition", null);
            try
            {
                project.BeginTransactionInNewTerr();
                IMgaFCO currentObj;
                try
                {
                    IMgaFolder  currentFolder = (IMgaFolder)project.RootFolder;
                    IMgaFolders cFolders      = currentFolder.ChildFolders;
                    foreach (IMgaFolder f in cFolders)
                    {
                        if (f.MetaFolder.Name == "Components")
                        {
                            IMgaFCOs objects = f.ChildFCOs;
                            foreach (IMgaFCO o in objects)
                            {
                                componentList.Add("/" + f.Name + "/" + o.Name);
                            }
                        }
                    }
                }
                finally
                {
                    project.CommitTransaction();
                }


                // Adapted from ModelicaImporter.cs
                string result = "";
                using (CyberComponentPicker cyberpicker = new CyberComponentPicker(componentList))
                {
                    var dialogResult = cyberpicker.ShowDialog();
                    if (dialogResult != System.Windows.Forms.DialogResult.OK)
                    {
                        this.Logger.WriteInfo("Modelica import was cancelled by the user.");
                        return;
                    }

                    result = cyberpicker.compResult;
                }

                var halves = result.Split('/');
                compName = halves[1];

                project.BeginTransactionInNewTerr();
                try
                {
                    currentObj = (IMgaFCO)project.RootFolder.ObjectByPath[result];
                }
                finally
                {
                    project.CommitTransaction();
                }

                IMgaComponentEx comp = (IMgaComponentEx)Activator.CreateInstance(Type.GetTypeFromProgID("MGA.Interpreter.CyberComponentExporter"));
                comp.Initialize((MgaProject)project);
                comp.InvokeEx((MgaProject)project, (MgaFCO)currentObj, null, 128);

                project.Save();
            }
            finally
            {
                project.Close(true);
            }

            #endregion

            //  - Use a function from CyPhy2ComponentModel to convert the extractor's XML format into a CyPhy model fragment
            #region Convert_to_XML
            // used in creating the resource object below
            CyPhy.CyberModel ProcessedCyberModel = null;

            if (true)
            {
                this.Logger.WriteDebug("About to call DeserializeAvmComponentXml...");
                StreamReader  streamReader = new StreamReader(compName + ".component.acm");
                avm.Component ac_import    = CyPhyComponentImporter.CyPhyComponentImporterInterpreter.DeserializeAvmComponentXml(streamReader);
                streamReader.Close();
                this.Logger.WriteDebug("... finished DeserializeAvmComponentXml call.");

                foreach (avm.cyber.CyberModel Cybermodel in ac_import.DomainModel.Where(dm => dm is avm.cyber.CyberModel)
                         .Cast <avm.cyber.CyberModel>())
                {
                    var rf = CyPhyClasses.RootFolder.GetRootFolder(CurrentProj);

                    Dictionary <string, CyPhy.Component> avmidComponentMap = new Dictionary <string, CyPhy.Component>();
                    AVM2CyPhyML.CyPhyMLComponentBuilder  newComponent      = new AVM2CyPhyML.CyPhyMLComponentBuilder(rf);
                    ProcessedCyberModel      = newComponent.process(Cybermodel, GetCurrentComp());
                    ProcessedCyberModel.Name = Path.GetFileNameWithoutExtension(CyberFilename);
                }

                // find the largest current Y value so our new elements are added below the existing design elements
                foreach (var child in GetCurrentComp().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_y = (read_y > greatest_current_y) ? read_y : greatest_current_y;
                    }
                }

                // layout Cyber model to the "south" of existing elements
                foreach (MgaPart item in (ProcessedCyberModel.Impl as MgaFCO).Parts)
                {
                    item.SetGmeAttrs(null, Cyber_MODEL_START_X, greatest_current_y + Cyber_MODEL_START_Y);
                }

                // Extend it's properties out to the component level.
                this.CyberModuleImportExtension(ProcessedCyberModel);
            }

            #endregion

            //  - Copy the Cyber Model files into the component's backend folder
            //      - Note: The solution includes a function that can find this folder using the project.manifest.json file.
            //      - For nice organization, create them in a subfolder called "Cyber"
            // create avmproj
            #region Copy files to backend folder

            // used in creating the resource object below
            string PathforComp = null;

            var importedCyberFiles = new List <String>();
            if (true)
            {
                try
                {
                    // create the destination path
                    PathforComp = GetCurrentComp().GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);

                    string finalPathName = Path.Combine(PathforComp, "Cyber");

                    Directory.CreateDirectory(finalPathName);

                    // determine if one part file or all part and assembly files need to be copied
                    string cpsrcfile = System.IO.Path.GetFileName(CyberFilename);

                    // copy the selected file
                    string CyberFileCopyPath = System.IO.Path.Combine(finalPathName, cpsrcfile);
                    System.IO.File.Copy(CyberFilename, CyberFileCopyPath, true);

                    // Set "primary" file as the first in the list.
                    importedCyberFiles.Add(Path.Combine("Cyber", Path.GetFileName(CyberFileCopyPath)));

                    if (true)
                    {
                        // get a string of the XML contents
                        this.Logger.WriteDebug("About to read contents of XML file using class XmlDocument: " + compName + ".component.acm");

                        XmlDocument doc = new XmlDocument();
                        doc.Load(compName + ".component.acm");
                        string xmlcontents = doc.InnerXml;

                        // mine down to the Resource dependencies
                        using (XmlReader reader = XmlReader.Create(new StringReader(xmlcontents)))
                        {
                            // iterate through each file listed in the resourcedependency section
                            while (reader.ReadToFollowing("ResourceDependency") == true)
                            {
                                string res_name = reader.GetAttribute("Name");
                                string res_path = reader.GetAttribute("Path");
                                this.Logger.WriteDebug("Copying this file: " + res_path + "\\" + res_name);

                                // Cyber files end in .1 .2 etc. Pick the latest ones
                                var allFiles = Directory.EnumerateFiles(Path.GetDirectoryName(res_path), "*mga." /*n.b. literal dot*/ + "*")
                                               .Select(Path.GetFileName)
                                               .Select(filename => new { basename = filename.Substring(0, filename.LastIndexOf('.')), version = filename.Substring(filename.LastIndexOf('.') + 1) })
                                               .Where(p => { int val; return(Int32.TryParse(p.version, out val)); })
                                               .OrderByDescending(p => Int32.Parse(p.version))
                                               .ToArray();
                                foreach (var basename in allFiles.Select(p => p.basename).Distinct())
                                {
                                    var latest = allFiles.Where(p => p.basename == basename).FirstOrDefault();
                                    if (latest != null)
                                    {
                                        string latestFilename = latest.basename + "." + latest.version;
                                        // Need to limit this down to just the filename in question
                                        // The XML file changes the name to all caps, so compare apples to apples
                                        if (latestFilename.ToUpper().StartsWith(res_name.ToUpper()))
                                        {
                                            string destpathandname = Path.Combine(finalPathName, latestFilename);
                                            if (!importedCyberFiles.Contains(Path.Combine("Cyber", Path.GetFileName(destpathandname))))
                                            {
                                                importedCyberFiles.Add(Path.Combine("Cyber", Path.GetFileName(destpathandname)));
                                            }
                                            File.Copy(Path.Combine(Path.GetDirectoryName(res_path), latestFilename), destpathandname, true);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception err_create_proj)
                {
                    this.Logger.WriteError("Error creating AVM project: " + err_create_proj.Message, " - Extraction Failed. Possible ComponentManagement issue.");
                    //cleanup(tempXMLfile, true);
                    return;
                }
            }
            #endregion

            //  - Create Resource objects in the CyPhy Component model that point to these Cyber Model files
            //      - Note: The "paths" of these should be the relative path from that component's root folder
            if (true)
            {
                foreach (var CyberFile in importedCyberFiles)
                {
                    CyPhy.Resource ResourceObj = CyPhyClasses.Resource.Create(GetCurrentComp());
                    ResourceObj.Attributes.ID    = Guid.NewGuid().ToString("B");
                    ResourceObj.Attributes.Path  = CyberFile;
                    ResourceObj.Attributes.Notes = "Cyber Model Import tool added this resource object for the imported Cyber file";
                    ResourceObj.Name             = Path.GetFileName(CyberFile);

                    // layout Resource just to the side of the Cyber model
                    foreach (MgaPart item in (ResourceObj.Impl as MgaFCO).Parts)
                    {
                        item.SetGmeAttrs(null, RESOURCE_START_X, greatest_current_y + RESOURCE_START_Y);
                    }

                    // The "primary" Cyber model is the first one -- associate it with the CyPhy CyberModel object
                    if (importedCyberFiles.IndexOf(CyberFile) == 0)
                    {
                        //  - Create a UsesResource association between the CyPhy CyberModel object and the Resource object that represents the top-level Creo Model file.
                        CyPhyClasses.UsesResource.Connect(ResourceObj, ProcessedCyberModel, null, null, GetCurrentComp());
                    }
                }
            }

            // throw in an ACM file for the current state of the component.
            if (true)
            {
                var    exporter = new CyPhyComponentExporter.CyPhyComponentExporterInterpreter();
                String acmPath  = Path.Combine(PathforComp, GetCurrentComp().Name + ".component.acm");
                CyPhyComponentExporterInterpreter.ExportToFile(GetCurrentComp(), Path.GetDirectoryName(acmPath));
            }

            // Clean up
            //cleanup(tempXMLfile, true);
        }
        public void TestCADFileReNaming()
        {
            // delete any previous test results
            if (Directory.Exists(testcreatepath))
            {
                Directory.Delete(testcreatepath, true);
            }
            // create a new blank project
            MgaProject proj = new MgaProject();

            proj.Create("MGA=" + testMGApath, "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);

                // Import a CAD file into the test project
                CyPhyComponentAuthoring.Modules.CADModelImport importcam = new CyPhyComponentAuthoring.Modules.CADModelImport();
                // these class variables need to be set to avoid NULL references
                importcam.SetCurrentComp(testcomp);
                importcam.CurrentProj = proj;
                importcam.CurrentObj  = testcomp.Impl as MgaFCO;

                // import the CAD file
                importcam.ImportCADModel(testpartpath);
                // Get a path to the imported Cad file
                var getcadmdl = testcomp.Children.CADModelCollection.First();
                string importedpath;
                getcadmdl.TryGetResourcePath(out importedpath, ComponentLibraryManager.PathConvention.ABSOLUTE);
                // add in Creo version number
                importedpath += Path.GetExtension(testpartpath);

                // Rename the CAD file
                CyPhyComponentAuthoring.Modules.CADFileRename renamecam = new CyPhyComponentAuthoring.Modules.CADFileRename();
                // these class variables need to be set to avoid NULL references
                renamecam.SetCurrentComp(testcomp);
                renamecam.CurrentProj = proj;
                renamecam.CurrentObj  = testcomp.Impl as MgaFCO;

                // call the module with a part file and the new file name
                renamecam.RenameCADFile(importedpath, RenamedFileNameWithoutExtension);

                // verify results
                // 1. Verify the file was renamed
                var renamecadmdl = testcomp.Children.CADModelCollection.First();
                string renamedpath;
                renamecadmdl.TryGetResourcePath(out renamedpath, ComponentLibraryManager.PathConvention.ABSOLUTE);
                // add in Creo version
                renamedpath += ".1";
                Assert.True(File.Exists(renamedpath),
                            String.Format("Could not find the renamed CAD file, found {0}", renamedpath));

                // 2. Verify the Model was renamed
                bool model_not_found = false;
                try
                {
                    var model_name = testcomp.Children.CADModelCollection.Where(p => p.Name == RenamedFileName).First();
                }
                catch (Exception ex)
                {
                    model_not_found = true;
                }
                Assert.False(model_not_found,
                             String.Format("No CAD model found with the renamed name {0}", RenamedFileName)
                             );

                // 3. Verify the resource name and path were changed
                CyPhy.Resource resource_name = null;
                bool resource_not_found      = false;
                try
                {
                    resource_name = testcomp.Children.ResourceCollection.Where(p => p.Name == RenamedFileName).First();
                }
                catch (Exception ex)
                {
                    resource_not_found = true;
                }
                Assert.False(resource_not_found,
                             String.Format("No resource found with the renamed name {0}", RenamedFileName)
                             );
                Assert.True(resource_name.Attributes.Path == RenamedFileNameRelativePath,
                            String.Format("{0} should have had value {1}; instead found {2}", resource_name.Name, RenamedFileNameRelativePath, resource_name.Attributes.Path)
                            );
            });
            proj.Save();
            proj.Close();
        }
示例#12
0
        public void AddDocument(string DocFileSourcePath = null)
        {
            this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name);

            #region Selection dialog
            //  - Display a dialog box to let the user choose the Custom Icon file
            bool doc_file_chosen = false;
            bool test_mode       = false;
            if (string.IsNullOrWhiteSpace(DocFileSourcePath))
            {
                doc_file_chosen = run_selection_dialog(out DocFileSourcePath);
            }
            else
            {
                test_mode = true;
                if (File.Exists(DocFileSourcePath))
                {
                    doc_file_chosen = true;
                }
                else
                {
                    this.Logger.WriteError("Invalid file path passed in: " + DocFileSourcePath);
                }
            }

            if (!doc_file_chosen)
            {
                this.Logger.WriteError("No document file chosen. Exiting.");
                clean_up(false);
                return;
            }
            #endregion

            #region Copy files to backend folder
            string path_DstDocFile = "";
            String name_OrgDocFile = Path.GetFileName(DocFileSourcePath);

            try
            {
                // Find the path of the current component
                String path_Comp       = ((CyPhy.Component)GetCurrentDesignElement()).GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);
                String path_CompDocDir = Path.Combine(path_Comp, "doc");
                if (Directory.Exists(path_CompDocDir) == false)
                {
                    Directory.CreateDirectory(path_CompDocDir);
                }

                path_DstDocFile = System.IO.Path.Combine(path_CompDocDir, name_OrgDocFile);

                int count = 1;
                while (File.Exists(path_DstDocFile))
                {
                    String DstFileName = String.Format("{0}_({1}){2}",
                                                       Path.GetFileNameWithoutExtension(name_OrgDocFile),
                                                       count++,
                                                       Path.GetExtension(name_OrgDocFile));

                    path_DstDocFile = System.IO.Path.Combine(path_CompDocDir, DstFileName);
                }

                System.IO.File.Copy(DocFileSourcePath, path_DstDocFile, false);
            }
            catch (Exception err_copy_file)
            {
                this.Logger.WriteError("Error copying file" + err_copy_file.Message);
                clean_up(false);
                return;
            }
            #endregion

            //- A Resource object should be created in the CyPhy Component which points to the file.
            #region Create Resource
            CyPhy.Resource ResourceObj = CyPhyClasses.Resource.Create((CyPhy.Component)GetCurrentDesignElement());
            ResourceObj.Attributes.ID   = Guid.NewGuid().ToString("B");
            ResourceObj.Attributes.Path = "doc\\" + Path.GetFileName(path_DstDocFile);
            ResourceObj.Name            = Path.GetFileName(path_DstDocFile);
            #endregion

            clean_up(true);
        }
示例#13
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;
        }
示例#14
0
        public void CopyHasInvalidPath()
        {
            // Create a new component.
            // We'll make it look like a copy, but the source (inside/outside) is not important.
            // That's because we'll give it a path that is invalid.
            // WHAT DO WE EXPECT THE ADD-ON TO DO?
            // Warn the user, and create a new folder.

            // These characters are not valid in Windows paths
            List <String> invalidCharacters = new List <String>()
            {
                "?",
                "<",
                ">",
                "\\",
                ":",
                "*",
                "|",
                " "
            };

            // Tuple structure: Component Name | Path Changed | Path Exists
            List <Tuple <String, Boolean, Boolean> > results = new List <Tuple <String, Boolean, Boolean> >();

            foreach (var invalidChar in invalidCharacters)
            {
                String org_Path = String.Format("components\\invalid{0}", invalidChar);

                var    compName = String.Format("{0}{1}", Utils.GetCurrentMethod(), invalidChar);
                string objID    = "";

                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.Path = org_Path;
                    objID             = c.ID;

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

                // Perform tests, but queue them for batch display later.
                project.PerformInTransaction(delegate
                {
                    //var c = project.GetComponentsByName(compName).FirstOrDefault();
                    var c = CyPhyClasses.Component.Cast(project.GetObjectByID(objID));
                    results.Add(new Tuple <string, bool, bool>(
                                    c.Name,
                                    org_Path != c.Attributes.Path,
                                    Directory.Exists(c.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE))
                                    ));
                });
            }

            // Did anybody not get a new path?
            var item2Failures = results.Where(r => r.Item2 == false);

            if (item2Failures.Any())
            {
                String message = "Components were not assigned a new path: ";
                foreach (var result in item2Failures)
                {
                    message += " " + result.Item1;
                }

                // Force assert failure
                Assert.False(true, message);
            }

            // Did anybody's path not exist?
            var item3Failures = results.Where(r => r.Item3 == false);

            if (item3Failures.Any())
            {
                String message = "New component folders do not exist on disk for: ";
                foreach (var result in item3Failures)
                {
                    message += " " + result.Item1;
                }

                // Force assert failure
                Assert.False(true, message);
            }
        }