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

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

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

            // META-2517 Explorer doesn't like paths with mixed seperators, make them all the same
            string uniformabspath = absPath.Replace("\\", "/");
            try
            {
                Process.Start(@uniformabspath);
            }
            catch (Exception ex)
            {
                Logger.WriteError("Error opening Windows Explorer: {0}", ex.Message);
                clean_up(false);
                return;
            }

            clean_up(true);
        }
 public void Dispose()
 {
     if (Logger != null)
     {
         Logger.Dispose();
         Logger = null;
     }
 }
Beispiel #3
0
        void export_component_package()
        {
            var component = this.GetCurrentComp();

            this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name);
            this.Logger.WriteDebug("Starting Component Export module...");

            // check for valid component and bail if there is not one
            try
            {
                string checkforinvalidcomponent = Path.GetDirectoryName(component.Impl.Project.ProjectConnStr.Substring("MGA=".Length));
            }
            catch(Exception)
            {
                this.Logger.WriteError("Error, No Current Componet");
                cleanup(true);
                return;
            }

            #region Prompt for Output Path
            string startupPath = Path.GetDirectoryName(component.Impl.Project.ProjectConnStr.Substring("MGA=".Length));

            // Get an output path from the user.
            String s_outPath;
            using (META.FolderBrowserDialog fbd = new META.FolderBrowserDialog()
            {
                Description = "Choose a path for the generated files.",
                //ShowNewFolderButton = true,
                SelectedPath = startupPath,
            })
            {

                DialogResult dr = fbd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    s_outPath = fbd.SelectedPath;
                }
                else
                {
                    this.Logger.WriteWarning("Component Exporter cancelled");
                    cleanup(false);
                    return;
                }
            }
            #endregion

            // FIXME: this could throw an exception (but this code is currently unreachable)
            var pkgPath = Exp.CyPhyComponentExporterInterpreter.ExportComponentPackage(component, s_outPath);
            this.Logger.WriteInfo("Component package created: {0}", pkgPath);
            cleanup(true);
        }
Beispiel #4
0
        // Event handlers for addons
        #region MgaEventSink members
        public void GlobalEvent(globalevent_enum @event)
        {
            if (@event == globalevent_enum.GLOBALEVENT_OPEN_PROJECT)
            {
                GetMetaRefs(this.addon.Project);
            }
            if (@event == globalevent_enum.GLOBALEVENT_CLOSE_PROJECT)
            {
                if (Logger != null)
                {
                    Logger.Dispose();
                    Logger = null;
                }
                Marshal.FinalReleaseComObject(addon);
                addon = null;
            }
            if (@event == globalevent_enum.APPEVENT_XML_IMPORT_BEGIN)
            {
                xmeImportInProgress = true;
                addon.EventMask     = unchecked ((uint)objectevent_enum.OBJEVENT_CREATED);
            }
            else if (@event == globalevent_enum.APPEVENT_XML_IMPORT_END)
            {
                unchecked { addon.EventMask = (uint)ComponentConfig.eventMask; }
                xmeImportInProgress = false;
            }
            else if (@event == globalevent_enum.APPEVENT_LIB_ATTACH_BEGIN)
            {
                addon.EventMask = 0;
                handleEvents    = false;
            }
            else if (@event == globalevent_enum.APPEVENT_LIB_ATTACH_END)
            {
                unchecked { addon.EventMask = (uint)ComponentConfig.eventMask; }
                handleEvents = true;
            }
            if (!componentEnabled)
            {
                return;
            }

            // TODO: Handle global events
            // MessageBox.Show(@event.ToString());
        }
        // Event handlers for addons
        #region MgaEventSink members
        public void GlobalEvent(globalevent_enum @event)
        {
            if (@event == globalevent_enum.GLOBALEVENT_OPEN_PROJECT)
            {
                GetMetaRefs(this.addon.Project);
            }
            if (@event == globalevent_enum.GLOBALEVENT_CLOSE_PROJECT)
            {
                if (Logger != null)
                {
                    Logger.Dispose();
                    Logger = null;
                }
                Marshal.FinalReleaseComObject(addon);
                addon = null;
            }
            if (@event == globalevent_enum.APPEVENT_XML_IMPORT_BEGIN)
            {
                xmeImportInProgress = true;
                addon.EventMask = unchecked((uint)objectevent_enum.OBJEVENT_CREATED);
            }
            else if (@event == globalevent_enum.APPEVENT_XML_IMPORT_END)
            {
                unchecked { addon.EventMask = (uint)ComponentConfig.eventMask; }
                xmeImportInProgress = false;
            }
            else if (@event == globalevent_enum.APPEVENT_LIB_ATTACH_BEGIN)
            {
                addon.EventMask = 0;
                handleEvents = false;
            }
            else if (@event == globalevent_enum.APPEVENT_LIB_ATTACH_END)
            {
                unchecked { addon.EventMask = (uint)ComponentConfig.eventMask; }
                handleEvents = true;
            }
            if (!componentEnabled)
            {
                return;
            }

            // TODO: Handle global events
            // MessageBox.Show(@event.ToString());
        }
Beispiel #6
0
        void open_component_folder()
        {
            this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name);

            string absPath;

            if (GetCurrentDesignElement() is CyPhy.Component)
            {
                CyPhy.Component comp = (CyPhy.Component)GetCurrentDesignElement();
                absPath = comp.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);
            }
            else
            {
                CyPhy.ComponentAssembly comp = (CyPhy.ComponentAssembly)GetCurrentDesignElement();
                absPath = comp.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);
            }


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

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

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

            clean_up(true);
        }
Beispiel #7
0
        private void LogMessage(String message, CyPhyGUIs.GMELogger.MessageType_enum type)
        {
            if (this.Logger == null)
            {
                this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name);
            }

            switch (type)
            {
            case CyPhyGUIs.SmartLogger.MessageType_enum.Error:
                this.Logger.WriteError(message);
                break;

            case CyPhyGUIs.SmartLogger.MessageType_enum.Warning:
                this.Logger.WriteWarning(message);
                break;

            default:
                this.Logger.WriteInfo(message);
                break;
            }
        }
Beispiel #8
0
        public void OctoPartDataImport_Delegate(object sender, EventArgs e)
        {
            bool allComponents = Prompt.ShowDialog("Run OctoPart Importer on all components?\n(No for only current component)\n");

            if (allComponents)
            {
                var folders = this.CurrentProj.RootFolder.ChildObjects;
                for (var i = 1; i < folders.Count; i++)
                {
                    if (String.Compare(folders[i].Name, this.CurrentObj.ParentFolder.Name) == 0)
                    {
                        var components = CyPhyClasses.Components.Cast(folders[i]);
                        foreach (var comp in components.Children.ComponentCollection)
                        {
                            this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name);
                            GetOctoPartData(comp);
                        }
                    }
                }
            }
            else
            {
                GetOctoPartData((CyPhy.Component) this.GetCurrentDesignElement());
            }

            // Close the calling dialog box if the module ran successfully
            if (Close_Dlg)
            {
                if (sender is Form)
                {
                    // the TLP is in the dialog box
                    Form parentDB = (Form)sender;
                    parentDB.Close();
                }
            }
        }
        /// <summary>
        /// Determines what action to take if a Component has been created under a Components folder.
        /// The actions are dispatched to other functions.
        /// </summary>
        /// <param name="componentFco"></param>
        private void Process(CyPhy.Component component)
        {
            var componentFco = component.Impl;
            if (Logger == null)
            {
                Logger = new CyPhyGUIs.GMELogger(componentFco.Project, this.ComponentName);
            }

            bool HasAVMID = !String.IsNullOrWhiteSpace(component.Attributes.AVMID);
            bool HasPath = !String.IsNullOrWhiteSpace(component.Attributes.Path);

            META.ComponentLibraryManager.EnsureComponentFolder(component);

            // Get all other components that have a "Components" folder as parent.
            // For the next logic tests, we'll need this list.
            var project = component.Impl.Project;
            MgaFilter filter = project.CreateFilter();
            filter.Kind = "Component";

            var otherComponents = project.AllFCOs(filter)
                                         .Cast<MgaFCO>()
                                         .Where(x => x.ParentFolder != null
                                                  && x.ParentFolder.MetaBase.Name == "Components"
                                                  && x.ID != componentFco.ID)
                                         .Select(x => CyPhyClasses.Component.Cast(x));

            //bool AVMIDCollision = HasAVMID && otherComponents.Where(c => c.Attributes.AVMID == component.Attributes.AVMID).Any();

            bool PathCollision = HasPath;
            if (HasPath)
            {
                PathCollision = false;

                string myFullPath = Path.GetFullPath(component.Attributes.Path);
                foreach (var cFullPath in otherComponents.Where(c => !String.IsNullOrWhiteSpace(c.Attributes.Path))
                                                         .Select(c => Path.GetFullPath(c.Attributes.Path)))
                {
                    if (myFullPath == cFullPath)
                        PathCollision = true;
                }
            }

            //bool PathCollision = HasPath && otherComponents.Where(c => Path.GetFullPath(c.Attributes.Path) == Path.GetFullPath(component.Attributes.Path)).Any();

            var projectPath_Absolute = component.Impl.Project.GetRootDirectoryPath();
            var lastChar = projectPath_Absolute.Last();
            if (lastChar != '\\' && lastChar != '/')
                projectPath_Absolute += '\\';

            if (HasAVMID && HasPath)
            {
                var oldCompPath_Absolute = Path.Combine(projectPath_Absolute, component.Attributes.Path);
                var folderExists = Directory.Exists(oldCompPath_Absolute);

                if (PathCollision || !folderExists)
                {
                    var newCompPath_Absolute = ComponentLibraryManager.CreateComponentFolder(component.Impl.Project);
                    var newCompPath_Relative = ComponentLibraryManager.MakeRelativePath(projectPath_Absolute, newCompPath_Absolute);

                    newCompPath_Relative = newCompPath_Relative.Replace('\\', '/') + '/';
                    var firstChars = newCompPath_Relative.Substring(0, 2);
                    if (firstChars != ".\\" && firstChars != "./")
                        newCompPath_Relative = newCompPath_Relative.Insert(0, "./");
                    component.Attributes.Path = newCompPath_Relative;

                    if (folderExists)
                    {
                        CopyComponentFiles(oldCompPath_Absolute, newCompPath_Absolute);
                    }
                    else if (component.Children.ResourceCollection.Any())
                    {
                        WarnUserAboutMissingFiles(component);
                    }
                }
            }
            else if (HasAVMID)
            {
                var newCompPath_Absolute = ComponentLibraryManager.CreateComponentFolder(component.Impl.Project);
                var newCompPath_Relative = ComponentLibraryManager.MakeRelativePath(projectPath_Absolute, newCompPath_Absolute);

                newCompPath_Relative = newCompPath_Relative.Replace('\\', '/') + '/';
                component.Attributes.Path = newCompPath_Relative;

                if (component.Children.ResourceCollection.Any())
                {
                    WarnUserAboutMissingFiles(component);
                }
            }
            else if (HasPath)
            {
                var oldCompPath_Absolute = Path.Combine(projectPath_Absolute, component.Attributes.Path);
                var folderExists = Directory.Exists(oldCompPath_Absolute);

                if (PathCollision || !folderExists)
                {
                    var newCompPath_Absolute = ComponentLibraryManager.CreateComponentFolder(component.Impl.Project);
                    var newCompPath_Relative = ComponentLibraryManager.MakeRelativePath(projectPath_Absolute, newCompPath_Absolute);

                    newCompPath_Relative = newCompPath_Relative.Replace('\\', '/') + '/';
                    var firstChars = newCompPath_Relative.Substring(0, 2);
                    if (firstChars != ".\\" && firstChars != "./")
                        newCompPath_Relative = newCompPath_Relative.Insert(0, "./");
                    component.Attributes.Path = newCompPath_Relative;

                    if (folderExists)
                    {
                        CopyComponentFiles(oldCompPath_Absolute, newCompPath_Absolute);
                    }
                    else if (component.Children.ResourceCollection.Any())
                    {
                        WarnUserAboutMissingFiles(component);
                    }
                }
            }
            else
            {
                if (component.Children.ResourceCollection.Any())
                {
                    WarnUserAboutMissingFiles(component);
                }
            }
        }
Beispiel #10
0
        public void ImportSimulinkModel(CyPhy.Component component, object sender)
        {
            Boolean ownLogger = false;

            if (Logger == null)
            {
                ownLogger = true;
                Logger    = new CyPhyGUIs.GMELogger(component.Impl.Project, "SimulinkModelImport");
            }

            // Check that the selected files are OK.
            bool needExit = false;

            if (needExit)
            {
                if (ownLogger)
                {
                    Logger.Dispose();
                    Logger = null;
                }

                return;
            }

            Form senderParentForm = null;

            if (sender is Control)
            {
                var senderControl = (Control)sender;
                senderParentForm = senderControl.FindForm();

                if (senderParentForm != null)
                {
                    senderParentForm.UseWaitCursor = true;
                }
            }

            try
            {
                var picker       = new SimulinkLibraryPicker();
                var pickerResult = picker.ShowDialog();

                if (pickerResult == DialogResult.OK)
                {
                    var selectedLibrary = picker.SelectedSimulinkLibraryName;

                    using (var browser = new SimulinkLibraryBrowser())
                    {
                        using (var simulinkConnector = new SimulinkConnector(Logger))
                        {
                            browser.BlockNames = simulinkConnector.ListSystemObjects(selectedLibrary).ToList();

                            var result = browser.ShowDialog(senderParentForm);

                            if (result == DialogResult.OK)
                            {
                                Logger.WriteInfo("Selected Block: {0}", browser.SelectedBlockName);

                                var paramNames = simulinkConnector.ListBlockParameters(browser.SelectedBlockName);

                                using (var paramPicker = new SimulinkParameterPicker())
                                {
                                    paramPicker.ParamNames = paramNames.ToList();

                                    var result2 = paramPicker.ShowDialog(senderParentForm);

                                    if (result2 == DialogResult.OK)
                                    {
                                        foreach (var param in paramPicker.SelectedParams)
                                        {
                                            Logger.WriteInfo(param);
                                        }

                                        IDictionary <string, string> inPorts;
                                        IDictionary <string, string> outPorts;

                                        simulinkConnector.ListPorts(browser.SelectedBlockName, out inPorts,
                                                                    out outPorts);

                                        AddSimulinkObjectToModel(component, browser.SelectedBlockName,
                                                                 paramPicker.SelectedParams,
                                                                 inPorts, outPorts);
                                    }
                                    else
                                    {
                                        Logger.WriteInfo("Simulink import cancelled");
                                    }
                                }
                            }
                            else
                            {
                                Logger.WriteInfo("Simulink import cancelled");
                            }

                            Logger.WriteInfo("Complete");
                        }
                    }
                }
                else
                {
                    Logger.WriteInfo("Simulink import cancelled");
                }
            }
            catch (Exception e)
            {
                Logger.WriteError("Error occurred: {0}", e.Message);

                if (ownLogger)
                {
                    Logger.Dispose();
                    Logger = null;
                }

                return;
            }
            finally
            {
                if (senderParentForm != null)
                {
                    senderParentForm.UseWaitCursor = false;
                }
            }

            // Find the visual coordinates of where the new SystemC model should be placed.
            getNewModelInitialCoordinates(component, out m_startX, out m_startY);

            if (ownLogger)
            {
                Logger.Dispose();
                Logger = null;
            }
        }
Beispiel #11
0
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // This is the main ShowNet interpreter code
            Boolean ownLogger = false;

            if (Logger == null)
            {
                ownLogger = true;
                Logger    = new CyPhyGUIs.GMELogger(project, "ShowNet");
            }
            GMEConsole.Out.WriteLine("\n======================================================================================================================================\n");
            Logger.WriteInfo("Starting ShowNet.");

            // Get RootFolder
            IMgaFolder rootFolder = project.RootFolder;
            //GMEConsole.Out.WriteLine(rootFolder.Name);

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

            if ((!done) && (null == currentobj))
            {
                done = true;
                Logger.WriteError("The current object is null.  Please select a ComponentAssembly or DesignContainer object.");
            }

            if ((!done) && (currentobj.Meta.Name != "ComponentAssembly" &&
                            currentobj.Meta.Name != "DesignContainer"))
            {
                done = true;
                Logger.WriteError("ShowNet only works on ComponentAssembly and DesignContainer objects.");
                Logger.WriteError("But, {1} is neither; it is a {0}.", currentobj.Meta.Name, currentobj.Name);
            }

            if (!done)
            {
                IEnumerable <CyPhy.PortComposition>      portCompositionChildren      = null;
                IEnumerable <CyPhy.ConnectorComposition> connectorCompositionChildren = null;

                if (currentobj.Meta.Name == "ComponentAssembly")
                {
                    var componentAssembly = ISIS.GME.Dsml.CyPhyML.Classes.ComponentAssembly.Cast(currentobj);
                    portCompositionChildren      = componentAssembly.Children.PortCompositionCollection;
                    connectorCompositionChildren = componentAssembly.Children.ConnectorCompositionCollection;
                }
                else if (currentobj.Meta.Name == "DesignContainer")
                {
                    var designContainer = ISIS.GME.Dsml.CyPhyML.Classes.DesignContainer.Cast(currentobj);
                    portCompositionChildren      = designContainer.Children.PortCompositionCollection;
                    connectorCompositionChildren = designContainer.Children.ConnectorCompositionCollection;
                }

                //=================================================================
                // Process the port connections
                //=================================================================

                NetworkManager portNetworkManager = new NetworkManager();

                foreach (CyPhy.PortComposition port in portCompositionChildren)
                {
                    Endpoint dstEndPoint = new Endpoint(port.DstEnd, port.GenericDstEndRef);
                    Endpoint srcEndPoint = new Endpoint(port.SrcEnd, port.GenericSrcEndRef);

                    //GMEConsole.Out.WriteLine("Found port: dst = '{0}' in the '{1}' {2}.",
                    //    dstEndPoint.Name,
                    //    dstEndPoint.ParentName,
                    //    dstEndPoint.ParentKind);

                    //GMEConsole.Out.WriteLine("            src = '{0}' in the '{1}' {2}.",
                    //    srcEndPoint.Name,
                    //    srcEndPoint.ParentName,
                    //    srcEndPoint.ParentKind);

                    // Create a network from the endpoints
                    List <Endpoint> nodes = new List <Endpoint>()
                    {
                        srcEndPoint, dstEndPoint
                    };
                    Network newNetwork = new Network(nodes);
                    portNetworkManager.Add(newNetwork);
                }

                //=================================================================
                // Process the connector connections
                //=================================================================

                NetworkManager connectorNetworkManager = new NetworkManager();

                foreach (CyPhy.ConnectorComposition connector in connectorCompositionChildren)
                {
                    Endpoint dstEndPoint = new Endpoint(connector.DstEnd, connector.GenericDstEndRef);
                    Endpoint srcEndPoint = new Endpoint(connector.SrcEnd, connector.GenericSrcEndRef);

                    // Create a network from the endpoints
                    List <Endpoint> nodes = new List <Endpoint>()
                    {
                        srcEndPoint, dstEndPoint
                    };
                    Network newNetwork = new Network(nodes);
                    connectorNetworkManager.Add(newNetwork);
                }

                // Make sure the network names are unique.
                NetworkNameChecker.Init();
                NetworkNameChecker.Update(ref portNetworkManager.NetworkList);
                NetworkNameChecker.Update(ref connectorNetworkManager.NetworkList);

                // Display all the networks.

                Logger.WriteInfo(string.Format("===== Found {0} port networks on {1}: =====\n",
                                               portNetworkManager.NetworkList.Count,
                                               currentobj.Name));

                foreach (Network mergedNet in portNetworkManager.NetworkList)
                {
                    using (StringReader sr = new StringReader(mergedNet.ToString()))
                    {
                        string line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            GMEConsole.Out.WriteLine(line);
                        }
                    }
                }

                Logger.WriteInfo(string.Format("===== Found {0} connector networks on {1}: =====\n",
                                               connectorNetworkManager.NetworkList.Count,
                                               currentobj.Name));

                foreach (Network mergedNet in connectorNetworkManager.NetworkList)
                {
                    using (StringReader sr = new StringReader(mergedNet.ToString()))
                    {
                        string line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            GMEConsole.Out.WriteLine(line);
                        }
                    }
                }
            }

            Logger.WriteInfo("The ShowNet interpreter has finished.");

            if (ownLogger)
            {
                Logger.Dispose();
                Logger = null;
            }
        }
        private void Process(CyPhy.ComponentAssembly componentAssembly)
        {
            if (Logger == null)
            {
                Logger = new CyPhyGUIs.GMELogger(componentAssembly.Impl.Project, this.ComponentName);
            }

            if (String.IsNullOrWhiteSpace(componentAssembly.Attributes.Path))
            {
                componentAssembly.Attributes.Path = GetRandomComponentAssemblyDir();
            }
            else
            {
                string originalPath = Path.Combine(componentAssembly.Impl.Project.GetRootDirectoryPath(), componentAssembly.Attributes.Path);
                componentAssembly.Attributes.Path = GetRandomComponentAssemblyDir();
                if (Directory.Exists(originalPath))
                {
                    try
                    {
                        CopyDirectory(originalPath, Path.Combine(componentAssembly.Impl.Project.GetRootDirectoryPath(), componentAssembly.Attributes.Path));
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteError("Exception while copying to {0}: {1}", componentAssembly.Attributes.Path, ex);
                    }
                }
            }
        }
        public void ImportSpiceModel(CyPhy.Component component, String path_SpiceFile = null)
        {
            ComponentInfo ci = new ComponentInfo();

            Boolean ownLogger = false;
            if (Logger == null)
            {
                ownLogger = true;
                Logger = new CyPhyGUIs.GMELogger(component.Impl.Project, "SpiceModelImport");
            }

            if (path_SpiceFile == null)
            {
                using (OpenFileDialog ofd = new OpenFileDialog())
                {
                    ofd.CheckFileExists = true;
                    ofd.DefaultExt = "*.cir";
                    ofd.Multiselect = false;
                    ofd.Filter = "CIR (*.cir)|*.cir|All files (*.*)|*.*";
                    DialogResult dr = ofd.ShowDialog();
                    if (dr == DialogResult.OK)
                    {
                        path_SpiceFile = ofd.FileName;
                    }
                    else
                    {
                        Logger.WriteError("No file was selected. SPICE Model Import will not complete.");

                        if (ownLogger)
                        {
                            Logger.Dispose();
                            Logger = null;
                        }

                        return;
                    }
                }
                if (String.IsNullOrWhiteSpace(path_SpiceFile))
                {
                    Logger.WriteError("SPICE Model Path of \"{0}\" isn't valid.", path_SpiceFile);

                    if (ownLogger)
                    {
                        Logger.Dispose();
                        Logger = null;
                    }

                    return;
                }
            }

            try
            {
                Parse myParse = new Parse();
                ci = myParse.ParseFile(path_SpiceFile);
            }
            catch( Exception e )
            {
                Logger.WriteError("Error parsing '{0}': {1}", path_SpiceFile, e.Message);

                if (ownLogger)
                {
                    Logger.Dispose();
                    Logger = null;
                }

                return;
            }

            //-----------------------------------------------------------------------------------
            //
            //  At this point, the SPICE model file has been parsed and component info extracted.
            //
            //  'ci' has the SPICE component information.
            //  'component' is the GME component that the SPICE info will be added to.
            //  'path_SpiceFile' is the complete path and filename of the ".CIR" file.
            //
            //------------------------------------------------------------------------------------

            //// Clean up the classifications.
            //// This doesn't really belong here; it's just temporary to fix components on 4/1/2014.
            //string[] sArray = component.Attributes.Classifications.Replace( "/", ".").Split( '.' );
            //int sArrayLength = sArray.GetLength(0);
            //string s = "";
            //for (int i = 0; i < sArrayLength; i++)
            //{
            //    string ss = sArray[i].ToLower().Trim().Replace( ' ', '_');
            //    ss = ss.Replace("(", "").Replace(")", "");
            //    s += ss.Replace( "_&_", "_and_" );
            //    if (i + 1 < sArrayLength)
            //    {
            //        s += ".";
            //    }
            //}
            //component.Attributes.Classifications = s;



            // Find the visual coordinates of where the new SPICE model should be placed.
            getNewModelInitialCoordinates(component, out m_startX, out m_startY);

            //------------- Setup the pins
            // Make a list of the preexisting schematic pins (ports) in the component, if any,
            // as well as a dictionary mapping pin names to the ports,
            // for future use when creating SPICE pins that may need to connect to the
            // schematic pins.
            List<string> schematicPins = new List<string>();
            Dictionary<string, CyPhy.Port> schematicPinNameDictionary = new Dictionary<string, CyPhy.Port>();

            // Iterate over child (schematic) ports of the component, to fill in the pin list and dictionary.
            foreach (CyPhy.Port port in component.Children.PortCollection)
            {
                Logger.WriteDebug("Child Port: {0}", GetHyperlinkStringFromComponent(port.Name, port.Impl as IMgaFCO));    // MOT-228
                schematicPins.Add(port.Name);
                try
                {
                    schematicPinNameDictionary.Add( port.Name, port );
                }
                catch( Exception e )
                {
                    // Logger.WriteDebug("Exception adding pin '{0}' to schematicPinNameDictionary: {1}", port.Name, e.Message);
                    // Include GME hyperlink in the debug message for MOT-228:
                    
                    Logger.WriteDebug("Exception adding pin '{0}' to schematicPinNameDictionary: {1}",
                        GetHyperlinkStringFromComponent(port.Name, port.Impl as IMgaFCO),
                        e.Message);
                    // Cleanup
                    Logger.WriteWarning("Unable to match any schematic pins with SPICE pins; new pins will be created.");
                    schematicPins = new List<string>();
                    schematicPinNameDictionary = new Dictionary<string, CyPhy.Port>();
                    break;
                }
            }

            // Find a mapping between the schematic pins and the SPICE pins
            string[,] matchedPins = PinMatcher.PinMatcher.GetPinMatches( schematicPins, ci.pins);

            // Show the pin matches
            if (matchedPins.GetLength(0) > 0)
            {
                Logger.WriteDebug("Pin Matches:");

                for (int row = 0; row < matchedPins.GetLength(0); row++)
                {
                    // Print out the schematic pin name and the SPICE-model pin name, for each pin match.
                    string p0 = matchedPins[row, 0];
                    string p1 = matchedPins[row, 1];

                    // Substitute hyperlinks for the schematic pin names, for MOT-228.
                    if (schematicPinNameDictionary.ContainsKey(p0))
                    {
                        p0 = GetHyperlinkStringFromComponent(p0, schematicPinNameDictionary[p0].Impl as IMgaFCO);
                    }

                    Logger.WriteDebug(@"  {0} [{1}, {2}]", row + 1, p0, p1 );
                }
            }


            //------------------ Setup the Properties
            // Make a list of the preexisting schematic properties in the component, if any,
            // as well as a dictionary mapping property names to the properties,
            // for future use when creating SPICE parameters that may need to connect to the
            // properties.
            List<string> schematicProperties = new List<string>();
            Dictionary<string, CyPhy.Property> schematicPropertyNameDictionary = new Dictionary<string, CyPhy.Property>();

            // Iterate over child (schematic) properties of the component, to fill in the schematicProperties list and dictionary.
            foreach (CyPhy.Property property in component.Children.PropertyCollection)
            {
                Logger.WriteDebug("Child Property: {0} = {1}",
                    GetHyperlinkStringFromComponent(property.Name, property.Impl as IMgaFCO),
                    property.Attributes.Value);

                schematicProperties.Add(property.Name);

                try
                {
                    schematicPropertyNameDictionary.Add(property.Name, property);
                }
                catch (Exception e)
                {
                    Logger.WriteDebug("Exception adding property '{0}' to schematicPropertyNameDictionary: {1}",
                        GetHyperlinkStringFromComponent(property.Name, property.Impl as IMgaFCO),
                        e.Message);
                    // Cleanup
                    Logger.WriteWarning("Unable to match any schematic properties with SPICE parameters; new properties will be created.");
                    schematicProperties = new List<string>();
                    schematicPropertyNameDictionary = new Dictionary<string, CyPhy.Property>();
                    break;
                }
            }

            // Get a list of the SPICE parameter names
            List<string> spiceParameters = new List<string>( ci.parameters.Keys );

            // Find a mapping between the schematic properties and the SPICE parameters
            string[,] matchedProperties = PinMatcher.PinMatcher.GetPinMatches(schematicProperties, spiceParameters);

            // Show the property matches
            if (matchedProperties.GetLength(0) > 0)
            {
                Logger.WriteDebug("Property Matches:");

                for (int row = 0; row < matchedProperties.GetLength(0); row++)
                {
                    // Print out the schematic property name and the SPICE parameter name, for each mapping.
                    string p0 = matchedProperties[row, 0];
                    string p1 = matchedProperties[row, 1];

                    // Substitute hyperlinks for the schematic property names, for MOT-228.
                    if (schematicPropertyNameDictionary.ContainsKey(p0))
                    {
                        p0 = GetHyperlinkStringFromComponent(p0, schematicPropertyNameDictionary[p0].Impl as IMgaFCO);
                    }

                    Logger.WriteDebug(@"  {0} [{1}, {2}]", row + 1, p0, p1);
                }
            }


            //------------------------------------------------------------
            // Create a SPICEModel child
            CyPhy.SPICEModel newModel = CyPhyClasses.SPICEModel.Create(component);
            newModel.Name = ci.name +"_SPICEModel";
            newModel.Attributes.Notes = "Created using SPICE Model CAT Module";
            newModel.Attributes.Class = string.Format("{0}:{1}", ci.elementType, ci.name);

            Logger.WriteInfo("Created a new SPICEModel: \"{0}\"", GetHyperlinkStringFromComponent(newModel.Name, newModel.Impl as IMgaFCO));

            // Adjust the SpiceLib model's label length to allow complete pin and property names to be seen.
            newModel.Preferences.PortLabelLength = 0;

            // Set the SPICE model's visual position.
            setFCOPosition(newModel.Impl as MgaFCO, m_startX, m_startY);

            // Create new ports within the SPICEModel, and add them to a SPICE-pin dictionary
            Dictionary<string, CyPhy.SchematicModelPort> spicePinNameDictionary = CreatePortsWithinTheSpiceModelForEachSpicePin(ci, newModel);

            // Arrange the SPICE model's pins into columns.
            Dictionary<string, int[]> spicePinRowColDictionary = ArrangeSpiceModelPinsIntoRowsAndCols(ci, spicePinNameDictionary);

            // Now the SPICE-model pins (ports) have been added to the SPICE model.
            // We need to connect them to existing schematic pins, if possible,
            // based on how the SPICE pin names matched with the schematic pin names.
            m_unconnectedSpicePinNames = new List<string>();  // Keep track of any SPICE pins that don't get connected.

            ConnectSpiceModelPortsToExistingSchematicPinsIfPossible(component, schematicPinNameDictionary, matchedPins, spicePinNameDictionary);

            CreateAndConnectSchematicPinsForUnconnectedSpicePins(component, spicePinNameDictionary, spicePinRowColDictionary, schematicPinNameDictionary);

            // Create new parameters within the SPICEModel, and add them to a SPICE parameter-name dictionary
            Dictionary<string, CyPhy.SPICEModelParameter> spiceParameterNameDictionary;
            CreateNewParametersWithinSpiceModelAndPopulateDictionary(ci, newModel, out spiceParameterNameDictionary);

            // Now the SPICE-model parameters (properties) have been added to the SPICE model.
            // We need to connect them to existing properties, if possible,
            // based on how the SPICE parameter names matched with the schematic property names.
            List<string> unconnectedSpiceParameterNames;  // Keeps track of any SPICE parameters that don't get connected.
            ConnectSpiceModelParametersToExistingPropertiesIfPossible(
                component, 
                schematicPropertyNameDictionary, 
                matchedProperties, 
                spiceParameterNameDictionary, 
                out unconnectedSpiceParameterNames);


            // Now we need to create and connect schematic properties for any SPICE parameters that are still unconnected.
            CreateAndConnectSchematicPropertiesForUnconnectedSpiceParameters(
                component, 
                ci, 
                spiceParameterNameDictionary, 
                schematicPropertyNameDictionary,
                unconnectedSpiceParameterNames);

            // Get the visual location to place the SPICE-model-file resource.
            int spiceModelfileResourceX = m_startX + 200;
            int spiceModelFileResourceY = m_startY - 100;

            string subdirectory = "Spice";  // The subdirectory where the SPICE file will be copied.

            //  - Copy the SPICE Model files into the component's back-end folder

            string verbose = "";    // String used for exception debugging.
            string destFileName = "";   // Name of the destination SPICE file after possible modification during copying.
            try
            {
                CopySpiceFile(component, path_SpiceFile, subdirectory, out destFileName, out verbose);

            }
            catch (Exception e)
            {
                Logger.WriteError("{1}Exception copying SPICE file: {0}", e.Message, verbose);
                return;
            }

            // Create the SPICE-model-file resource
            CreateSpiceModelFileResource(
                component,
                subdirectory,
                destFileName,
                path_SpiceFile,
                spiceModelfileResourceX,
                spiceModelFileResourceY,
                newModel);


            if (ownLogger)
            {
                Logger.Dispose();
                Logger = null;
            }
        }
        void import_modelica_model()
        {
            this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name);
            this.Logger.WriteDebug("Starting Import Modelica Model module...");

            var component = this.GetCurrentComp();

            Type type = Type.GetTypeFromProgID("MGA.Interpreter.ModelicaImporter");
            GME.MGA.IMgaComponentEx modelicaImporter = Activator.CreateInstance(type) as GME.MGA.IMgaComponentEx;

            modelicaImporter.Initialize(component.Impl.Project);
            var selectedFCOs = (GME.MGA.MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs"));
            modelicaImporter.InvokeEx(component.Impl.Project, component.Impl as GME.MGA.MgaFCO, selectedFCOs, 0);

            cleanup(true);
        }
Beispiel #15
0
        public void ImportCADModel(string CADpath = null)
        {
            string cadFilename = "";

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

            //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
            bool creo_installed = this.CREO_present();

            //  - 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 (creo_installed && 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;

                    // 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;
                    this.Logger.WriteDebug("Calling CADCreoParametricCreateAssembly.exe with argument string: " + argstring);

                    firstProc.Start();

                    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());
                        throw new Exception("Extract executable returned error code " + firstProc.ExitCode.ToString());
                    }
                }
                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, GetCurrentComp());
                    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 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 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(GetCurrentComp());
                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(GetCurrentComp());
                    PathforComp = GetCurrentComp().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);
                    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_name = reader.GetAttribute("Name");
                                string res_path = reader.GetAttribute("Path");
                                this.Logger.WriteDebug("Copying this file: " + res_path + "\\" + res_name);

                                // 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.ToUpper().StartsWith(res_name.ToUpper()))
                                        {
                                            string destpathandname = Path.Combine(finalPathName, latestFilename);
                                            if (!importedCADFiles.Contains(Path.Combine("CAD", Path.GetFileName(destpathandname))))
                                            {
                                                importedCADFiles.Add(Path.Combine("CAD", 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 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(GetCurrentComp());
                    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, GetCurrentComp());
                    }
                }
            }

            // 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, GetCurrentComp().Name + ".component.acm");
                CyPhyComponentExporterInterpreter.ExportToFile(GetCurrentComp(), Path.GetDirectoryName(acmPath));
            }

            // Clean up
            cleanup(tempXMLfile, (extractor_ran_success && !test_copy_and_path_only));
        }
        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 = GetCurrentComp().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(GetCurrentComp());
            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);
        }
Beispiel #17
0
        public Checker(MgaFCO model, MgaProject project, IMgaTraceability traceability = null, CyPhyGUIs.GMELogger logger = null)
        {
            Model   = model;
            Project = project;
            if (logger != null)
            {
                this.Logger = logger;
            }
            else
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
            }

            registeredRules = new ConcurrentDictionary <string, List <RuleDescriptor> >();

            if (traceability == null)
            {
                this.Traceability = new META.MgaTraceability();
            }
            else
            {
                this.Traceability = traceability;
            }
        }
        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);
        }
Beispiel #19
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);
        }
        public void Initialize(MgaProject project)
        {
            // Creating addon
            project.CreateAddOn(this, out addon);
            // Setting event mask (see ComponentConfig.eventMask)
            unchecked
            {
                addon.EventMask = (uint)ComponentConfig.eventMask;
            }

            if (Logger == null)
            {
                Logger = new CyPhyGUIs.GMELogger(project, this.ComponentName);
            }
            GetMetaRefs(project);
        }
Beispiel #21
0
 public Checker(CyPhyGUIs.IInterpreterMainParameters parameters, CyPhyGUIs.GMELogger logger)
 {
     this.Logger         = logger;
     this.mainParameters = parameters;
     this.Results        = new Dictionary <RuleDescriptor, List <RuleFeedbackBase> >();
 }
Beispiel #22
0
 public Generator(CyPhyGUIs.IInterpreterMainParameters parameters, CyPhyGUIs.GMELogger logger)
 {
     this.Logger         = logger;
     this.mainParameters = parameters;
     this.RunCommand     = "";
 }
Beispiel #23
0
 /// <summary>
 /// Gets a new instance of an elaborator based on a given context.
 /// </summary>
 /// <typeparam name="T">Specific type of elaborator</typeparam>
 /// <param name="subject">Given context</param>
 /// <param name="logger">Logger which can be used to log messages.</param>
 /// <returns>A new instance of a context aware elaborator.</returns>
 /// <exception cref="ArgumentNullException">If subject or logger null.</exception>
 /// <exception cref="NotSupportedException">If subject does not have an associated elaborator class.</exception>
 /// <exception cref="InvalidCastException">If the created elaborator cannot be casted to the requested type.</exception>
 public static T GetElaborator <T>(MgaModel subject, CyPhyGUIs.GMELogger logger, bool UnrollConnectors)
     where T : Elaborator
 {
     return((T)GetElaborator(subject, logger, UnrollConnectors));
 }
Beispiel #24
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);
        }
Beispiel #25
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;
        }
Beispiel #26
0
        /// <summary>
        /// Determines what action to take if a Component has been created under a Components folder.
        /// The actions are dispatched to other functions.
        /// </summary>
        /// <param name="componentFco"></param>
        private void Process(CyPhy.Component component)
        {
            var componentFco = component.Impl;

            if (Logger == null)
            {
                Logger = new CyPhyGUIs.GMELogger(componentFco.Project, this.ComponentName);
            }

            bool HasAVMID = !String.IsNullOrWhiteSpace(component.Attributes.AVMID);
            bool HasPath  = !String.IsNullOrWhiteSpace(component.Attributes.Path);

            META.ComponentLibraryManager.EnsureComponentFolder(component);

            // Get all other components that have a "Components" folder as parent.
            // For the next logic tests, we'll need this list.
            var       project = component.Impl.Project;
            MgaFilter filter  = project.CreateFilter();

            filter.Kind = "Component";

            var otherComponents = project.AllFCOs(filter)
                                  .Cast <MgaFCO>()
                                  .Where(x => x.ParentFolder != null &&
                                         x.ParentFolder.MetaBase.Name == "Components" &&
                                         x.ID != componentFco.ID)
                                  .Select(x => CyPhyClasses.Component.Cast(x));

            //bool AVMIDCollision = HasAVMID && otherComponents.Where(c => c.Attributes.AVMID == component.Attributes.AVMID).Any();

            bool PathCollision = HasPath;

            if (HasPath)
            {
                PathCollision = false;

                string myFullPath = Path.GetFullPath(component.Attributes.Path);
                foreach (var cFullPath in otherComponents.Where(c => !String.IsNullOrWhiteSpace(c.Attributes.Path))
                         .Select(c => Path.GetFullPath(c.Attributes.Path)))
                {
                    if (myFullPath == cFullPath)
                    {
                        PathCollision = true;
                    }
                }
            }

            //bool PathCollision = HasPath && otherComponents.Where(c => Path.GetFullPath(c.Attributes.Path) == Path.GetFullPath(component.Attributes.Path)).Any();

            var projectPath_Absolute = component.Impl.Project.GetRootDirectoryPath();
            var lastChar             = projectPath_Absolute.Last();

            if (lastChar != '\\' && lastChar != '/')
            {
                projectPath_Absolute += '\\';
            }

            if (HasAVMID && HasPath)
            {
                var oldCompPath_Absolute = Path.Combine(projectPath_Absolute, component.Attributes.Path);
                var folderExists         = Directory.Exists(oldCompPath_Absolute);

                if (PathCollision || !folderExists)
                {
                    var newCompPath_Absolute = ComponentLibraryManager.CreateComponentFolder(component.Impl.Project);
                    var newCompPath_Relative = ComponentLibraryManager.MakeRelativePath(projectPath_Absolute, newCompPath_Absolute);

                    newCompPath_Relative = newCompPath_Relative.Replace('\\', '/') + '/';
                    var firstChars = newCompPath_Relative.Substring(0, 2);
                    if (firstChars != ".\\" && firstChars != "./")
                    {
                        newCompPath_Relative = newCompPath_Relative.Insert(0, "./");
                    }
                    component.Attributes.Path = newCompPath_Relative;

                    if (folderExists)
                    {
                        CopyComponentFiles(oldCompPath_Absolute, newCompPath_Absolute);
                    }
                    else if (component.Children.ResourceCollection.Any())
                    {
                        WarnUserAboutMissingFiles(component);
                    }
                }
            }
            else if (HasAVMID)
            {
                var newCompPath_Absolute = ComponentLibraryManager.CreateComponentFolder(component.Impl.Project);
                var newCompPath_Relative = ComponentLibraryManager.MakeRelativePath(projectPath_Absolute, newCompPath_Absolute);

                newCompPath_Relative      = newCompPath_Relative.Replace('\\', '/') + '/';
                component.Attributes.Path = newCompPath_Relative;

                if (component.Children.ResourceCollection.Any())
                {
                    WarnUserAboutMissingFiles(component);
                }
            }
            else if (HasPath)
            {
                var oldCompPath_Absolute = Path.Combine(projectPath_Absolute, component.Attributes.Path);
                var folderExists         = Directory.Exists(oldCompPath_Absolute);

                if (PathCollision || !folderExists)
                {
                    var newCompPath_Absolute = ComponentLibraryManager.CreateComponentFolder(component.Impl.Project);
                    var newCompPath_Relative = ComponentLibraryManager.MakeRelativePath(projectPath_Absolute, newCompPath_Absolute);

                    newCompPath_Relative = newCompPath_Relative.Replace('\\', '/') + '/';
                    var firstChars = newCompPath_Relative.Substring(0, 2);
                    if (firstChars != ".\\" && firstChars != "./")
                    {
                        newCompPath_Relative = newCompPath_Relative.Insert(0, "./");
                    }
                    component.Attributes.Path = newCompPath_Relative;

                    if (folderExists)
                    {
                        CopyComponentFiles(oldCompPath_Absolute, newCompPath_Absolute);
                    }
                    else if (component.Children.ResourceCollection.Any())
                    {
                        WarnUserAboutMissingFiles(component);
                    }
                }
            }
            else
            {
                if (component.Children.ResourceCollection.Any())
                {
                    WarnUserAboutMissingFiles(component);
                }
            }
        }
        public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode)
        {
            // This is the main ShowNet interpreter code
            Boolean ownLogger = false;
            if (Logger == null)
            {
                ownLogger = true;
                Logger = new CyPhyGUIs.GMELogger(project, "ShowNet");
            }
            GMEConsole.Out.WriteLine("\n======================================================================================================================================\n");
            Logger.WriteInfo("Starting ShowNet.");

            // Get RootFolder
            IMgaFolder rootFolder = project.RootFolder;
            //GMEConsole.Out.WriteLine(rootFolder.Name);

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

            if ((!done) && (null == currentobj))
            {
                done = true;
                Logger.WriteError("The current object is null.  Please select a ComponentAssembly or DesignContainer object.");
            }

            if ((!done) && (currentobj.Meta.Name != "ComponentAssembly" &&
                			currentobj.Meta.Name != "DesignContainer"))
            {
                done = true;
                Logger.WriteError("ShowNet only works on ComponentAssembly and DesignContainer objects.");
                Logger.WriteError("But, {1} is neither; it is a {0}.", currentobj.Meta.Name, currentobj.Name);
            }

            if (!done)
            {
				IEnumerable<CyPhy.PortComposition> portCompositionChildren = null;
	            IEnumerable<CyPhy.ConnectorComposition> connectorCompositionChildren = null;

	            if (currentobj.Meta.Name == "ComponentAssembly")
	            {
	                var componentAssembly = ISIS.GME.Dsml.CyPhyML.Classes.ComponentAssembly.Cast(currentobj);
	                portCompositionChildren = componentAssembly.Children.PortCompositionCollection;
	                connectorCompositionChildren = componentAssembly.Children.ConnectorCompositionCollection;                    
	            }
	            else if (currentobj.Meta.Name == "DesignContainer")
	            {
	                var designContainer = ISIS.GME.Dsml.CyPhyML.Classes.DesignContainer.Cast(currentobj);
	                portCompositionChildren = designContainer.Children.PortCompositionCollection;
	                connectorCompositionChildren = designContainer.Children.ConnectorCompositionCollection;   
	            }

                //=================================================================
                // Process the port connections
                //=================================================================

                NetworkManager portNetworkManager = new NetworkManager();

            	foreach (CyPhy.PortComposition port in portCompositionChildren)
                {
                    Endpoint dstEndPoint = new Endpoint(port.DstEnd, port.GenericDstEndRef);
                    Endpoint srcEndPoint = new Endpoint(port.SrcEnd, port.GenericSrcEndRef);

                    //GMEConsole.Out.WriteLine("Found port: dst = '{0}' in the '{1}' {2}.",
                    //    dstEndPoint.Name,
                    //    dstEndPoint.ParentName,
                    //    dstEndPoint.ParentKind);

                    //GMEConsole.Out.WriteLine("            src = '{0}' in the '{1}' {2}.",
                    //    srcEndPoint.Name,
                    //    srcEndPoint.ParentName,
                    //    srcEndPoint.ParentKind);

                    // Create a network from the endpoints
                    List<Endpoint> nodes = new List<Endpoint>() { srcEndPoint, dstEndPoint };
                    Network newNetwork = new Network(nodes);
                    portNetworkManager.Add(newNetwork);
                }

                //=================================================================
                // Process the connector connections
                //=================================================================

                NetworkManager connectorNetworkManager = new NetworkManager();

            	foreach (CyPhy.ConnectorComposition connector in connectorCompositionChildren)
                {
                    Endpoint dstEndPoint = new Endpoint(connector.DstEnd, connector.GenericDstEndRef);
                    Endpoint srcEndPoint = new Endpoint(connector.SrcEnd, connector.GenericSrcEndRef);

                    // Create a network from the endpoints
                    List<Endpoint> nodes = new List<Endpoint>() { srcEndPoint, dstEndPoint };
                    Network newNetwork = new Network(nodes);
                    connectorNetworkManager.Add(newNetwork);
                }

                // Make sure the network names are unique.
                NetworkNameChecker.Init();
                NetworkNameChecker.Update(ref portNetworkManager.NetworkList);
                NetworkNameChecker.Update(ref connectorNetworkManager.NetworkList);

                // Display all the networks.

                Logger.WriteInfo(string.Format("===== Found {0} port networks on {1}: =====\n", 
                    portNetworkManager.NetworkList.Count,
                    currentobj.Name));

                foreach (Network mergedNet in portNetworkManager.NetworkList)
                {
                    using (StringReader sr = new StringReader(mergedNet.ToString()))
                    {
                        string line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            GMEConsole.Out.WriteLine(line);
                        }
                    }
                }

                Logger.WriteInfo(string.Format("===== Found {0} connector networks on {1}: =====\n", 
                    connectorNetworkManager.NetworkList.Count,
                    currentobj.Name));

                foreach (Network mergedNet in connectorNetworkManager.NetworkList)
                {
                    using (StringReader sr = new StringReader(mergedNet.ToString()))
                    {
                        string line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            GMEConsole.Out.WriteLine(line);
                        }
                    }
                }
            }

            Logger.WriteInfo("The ShowNet interpreter has finished.");

            if (ownLogger)
            {
                Logger.Dispose();
                Logger = null;
            }
        }
        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 = GetCurrentComp().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;
                    // -    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;
                try
                {
                    ResourceObj = GetCurrentComp().Children.ResourceCollection
                        .Where(p => p.Attributes.Path == ComponentLibraryManager.MakeRelativePath(GetCurrentComp().GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE), StartingCadFilename)).First();
                }
                catch (Exception ex)
                {
                    if (!test_mode_only)
                    {
                        this.Logger.WriteError("No resource found with that CAD file path", ComponentLibraryManager.MakeRelativePath(GetCurrentComp().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(GetCurrentComp().GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE), RenamedCadFilename);
                ResourceObj.Attributes.Path = new_path;

                // Step 5 - If the Resource name happens to be the filename, change it too. 
                if (ResourceObj.Name == Path.GetFileName(StartingCadFilename))
                {
                    ResourceObj.Name = Path.GetFileName(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;
                try
                {
                    ModelObj = GetCurrentComp().Children.CADModelCollection
                        .Where(p => p.Name == strip_creo_extension_off_filename(Path.GetFileName(StartingCadFilename))).First();
                }
                // check if ModelObj exists
                catch (Exception ex)
                {
                    ModelObjExists = false;
                    if (!test_mode_only)
                    {
                        this.Logger.WriteError("No model found with that CAD file name", Path.GetFileNameWithoutExtension(StartingCadFilename), ex.Message);
                    }
                }
                if (ModelObjExists)
                {
                    ModelObj.Name = Path.GetFileName(RenamedCadFilename);
                }
            }
            //cleanup
            cleanup(cad_file_chosen && !test_mode_only);
            return;
        }
Beispiel #29
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);
        }
Beispiel #30
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);
        }
        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(GetCurrentComp());
                    IconFileDestPath = GetCurrentComp().GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE);

                    // copy the selected file
                    IconFileDestName = System.IO.Path.Combine(IconFileDestPath, "Icon.png");
                    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(GetCurrentComp());
                ResourceObj.Attributes.ID = Guid.NewGuid().ToString("B");
                ResourceObj.Attributes.Path = "Icon.png";
                ResourceObj.Attributes.Notes = "Custom icon for this component";
                ResourceObj.Name = Path.GetFileName(IconFileDestName);

                String iconPath_RelativeToProjRoot = Path.Combine(GetCurrentComp().GetDirectoryPath(ComponentLibraryManager.PathConvention.REL_TO_PROJ_ROOT),
                                                                  "Icon.png");

                //- Finally, it must be set as the CyPhy Component's icon
                try
                {
                    (GetCurrentComp().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 );
        }
Beispiel #32
0
 public Checker(CyPhyGUIs.IInterpreterMainParameters parameters, CyPhyGUIs.GMELogger logger)
 {
     this.Logger = logger;
     this.mainParameters = parameters;
     this.Results = new Dictionary<RuleDescriptor, List<RuleFeedbackBase>>();
 }
        public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param)
        {
            if (!enabled)
            {
                return;
            }

            try
            {
                this.Logger = new CyPhyGUIs.GMELogger(project, this.ComponentName);

                MgaGateway = new MgaGateway(project);
                project.CreateTerritoryWithoutSink(out MgaGateway.territory);

                MgaGateway.PerformInTransaction(delegate
                {
                    Main(project, currentobj, selectedobjs, Convert(param));
                });
            }
            finally
            {
                if (this.Logger != null)
                {
                    this.Logger.Dispose();
                    this.Logger = null;
                }

                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        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 = GetCurrentComp().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(GetCurrentComp());
                    PathforComp = GetCurrentComp().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(GetCurrentComp());
                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 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 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(GetCurrentComp());
                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, GetCurrentComp());
            }
            #endregion

            // Clean up
            this.Logger.WriteDebug("Exiting Import Manufacturing Model module...");
            cleanup(mfg_file_chosen);
        }
        public void ImportCADModel(string CADpath = null)
        {
            string cadFilename = "";
            this.Logger = new CyPhyGUIs.GMELogger(CurrentProj, this.GetType().Name);

            //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
            bool creo_installed = this.CREO_present();

            //  - 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 (creo_installed && 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 = "-c \"";
                    argstring += cadFilename;
                    argstring += "\"";

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

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

                    Process firstProc = new Process();

                    // NOTE: Process class does not expand environment variables, do it manually
                    string temp = Environment.GetEnvironmentVariable("PROE_ISIS_EXTENSIONS");
                    if (temp == null)
                    {
                        this.Logger.WriteError("Please set the PROE_ISIS_EXTENSIONS environment variable");
                        cleanup(tempXMLfile, true);
                        return;
                    }
                    string path = Path.Combine(temp, "bin\\ExtractACM-XMLfromCreoModels.exe");
                    if (!File.Exists(path))
                    {
                        this.Logger.WriteError("Cannot find ExtractACM-XMLfromCreoModels.exe - Check if CAD Assembler was built and files installed to PROE_ISIS_EXTENSIONS");
                        throw new Exception("ExtractACM-XMLfromCreoModels.exe not found.");
                    }

                    firstProc.StartInfo.FileName = path;
                    firstProc.StartInfo.Arguments = argstring;
                    this.Logger.WriteDebug("Calling ExtractACM-XMLfromCreoModels.exe with argument string: " + argstring);

                    firstProc.EnableRaisingEvents = true;

                    firstProc.Start();

                    firstProc.WaitForExit();

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

                    if (firstProc.ExitCode == 0)
                    {
                        extractor_ran_success = true;
                    }
                    else
                    {
                        this.Logger.WriteDebug("ExtractACM-XMLfromCreoModels.exe returned error code " + firstProc.ExitCode.ToString());
                        throw new Exception("Extract executable returned error code " + firstProc.ExitCode.ToString());
                    }
                }
                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);

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

                // 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 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(GetCurrentComp());
                ProcessedCADModel.Name = Path.GetFileNameWithoutExtension(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(GetCurrentComp());
                    PathforComp = GetCurrentComp().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);
                    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_name = reader.GetAttribute("Name");
                                string res_path = reader.GetAttribute("Path");
                                this.Logger.WriteDebug("Copying this file: " + res_path + "\\" + res_name);

                                // 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.ToUpper().StartsWith(res_name.ToUpper()))
                                        {
                                            string destpathandname = Path.Combine(finalPathName, latestFilename);
                                            if (!importedCADFiles.Contains(Path.Combine("CAD", Path.GetFileName(destpathandname))))
                                            {
                                                importedCADFiles.Add(Path.Combine("CAD", 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 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(GetCurrentComp());
                    ResourceObj.Attributes.ID = Guid.NewGuid().ToString("B");
                    ResourceObj.Attributes.Path = cadFile;
                    ResourceObj.Attributes.Notes = "CAD Model Import tool added this resource object for the imported CAD file";
                    ResourceObj.Name = Path.GetFileName(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, GetCurrentComp());
                    }
                }
            }

            // 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,GetCurrentComp().Name + ".component.acm");
                CyPhyComponentExporterInterpreter.ExportToFile(GetCurrentComp(), Path.GetDirectoryName(acmPath));
            }

            // Clean up
            cleanup(tempXMLfile, (extractor_ran_success && !test_copy_and_path_only));
        }
        public void InvokeEx(
                MgaProject project,
                MgaFCO currentobj,
                MgaFCOs selectedobjs,
                int param)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            if (selectedobjs == null)
            {
                throw new ArgumentNullException("selectedobjs");
            }

            this.InteractiveMode = this.Convert(param) != ComponentStartMode.GME_SILENT_MODE;

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);
                project.CreateTerritoryWithoutSink(out MgaGateway.territory);

                this.GMEConsole.Clear();
                System.Windows.Forms.Application.DoEvents();

                this.InteractiveMode = this.Convert(param) != ComponentStartMode.GME_SILENT_MODE;

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

                this.Logger.GMEConsoleLoggingLevel = Properties.Settings.Default.bVerboseLogging ?
                    CyPhyGUIs.SmartLogger.MessageType_enum.Debug :
                    CyPhyGUIs.SmartLogger.MessageType_enum.Info;

                //this.Logger.WriteDebug("Hello debug");
                //this.Logger.WriteError("Hello error {0} {1} {2}", 1, "string", true);
                //this.Logger.WriteInfo("Hello info");
                //this.Logger.WriteWarning("Hello WriteWarning");
                //this.Logger.WriteFailed("Hello WriteFailed");
                //this.Logger.WriteSuccess("Hello WriteSuccess");
                //this.Logger.WriteCheckFailed("Hello WriteCheckFailed");
                //this.Logger.WriteCheckPassed("Hello WriteCheckPassed");

                this.Logger.WriteInfo("Master Interpreter 2.0");
                System.Windows.Forms.Application.DoEvents();

                this.Logger.MakeVersionInfoHeader();

                // control was held
                this.Process(currentobj);

                foreach (var filename in this.Logger.LogFilenames)
                {
                    this.Logger.WriteInfo("Log file was generated here: <a href=\"file:///{0}\" target=\"_blank\">{1}</a>", Path.GetDirectoryName(filename), filename);
                }

                this.Logger.WriteInfo("Master Interpreter 2.0 finished");
            }
            finally
            {
                this.Logger.Dispose();
                System.Windows.Forms.Application.DoEvents();

                if (MgaGateway.territory != null)
                {
                    MgaGateway.territory.Destroy();
                }
                MgaGateway = null;
                project = null;
                currentobj = null;
                selectedobjs = null;
                GMEConsole = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        public void InvokeEx(
            MgaProject project,
            MgaFCO currentobj,
            MgaFCOs selectedobjs,
            int param)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            if (selectedobjs == null)
            {
                throw new ArgumentNullException("selectedobjs");
            }

            this.InteractiveMode = this.Convert(param) != ComponentStartMode.GME_SILENT_MODE;

            try
            {
                GMEConsole = GMEConsole.CreateFromProject(project);
                MgaGateway = new MgaGateway(project);

                this.GMEConsole.Clear();
                System.Windows.Forms.Application.DoEvents();

                this.InteractiveMode = this.Convert(param) != ComponentStartMode.GME_SILENT_MODE;

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

                this.Logger.GMEConsoleLoggingLevel = Properties.Settings.Default.bVerboseLogging ?
                                                     CyPhyGUIs.SmartLogger.MessageType_enum.Debug :
                                                     CyPhyGUIs.SmartLogger.MessageType_enum.Info;

                //this.Logger.WriteDebug("Hello debug");
                //this.Logger.WriteError("Hello error {0} {1} {2}", 1, "string", true);
                //this.Logger.WriteInfo("Hello info");
                //this.Logger.WriteWarning("Hello WriteWarning");
                //this.Logger.WriteFailed("Hello WriteFailed");
                //this.Logger.WriteSuccess("Hello WriteSuccess");
                //this.Logger.WriteCheckFailed("Hello WriteCheckFailed");
                //this.Logger.WriteCheckPassed("Hello WriteCheckPassed");

                this.Logger.WriteInfo("Master Interpreter 2.0");
                System.Windows.Forms.Application.DoEvents();

                this.Logger.MakeVersionInfoHeader();

                // control was held
                this.Process(currentobj);

                foreach (var filename in this.Logger.LogFilenames)
                {
                    this.Logger.WriteInfo("Log file was generated here: " + CyPhyGUIs.SmartLogger.GetGMEConsoleFileLink(filename));
                }

                this.Logger.WriteInfo("Master Interpreter 2.0 finished");
            }
            finally
            {
                this.Logger.Dispose();
                System.Windows.Forms.Application.DoEvents();

                MgaGateway   = null;
                project      = null;
                currentobj   = null;
                selectedobjs = null;
                GMEConsole   = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }