public void CopyMgaAndRunDesignImporter(string asmName) { //proj.Save(proj.ProjectConnStr + asmName + ".mga", true); File.Copy(proj.ProjectConnStr.Substring("MGA=".Length), (proj.ProjectConnStr + asmName + ".mga").Substring("MGA=".Length), true); MgaProject proj2 = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject")); proj2.OpenEx(proj.ProjectConnStr + asmName + ".mga", "CyPhyML", null); proj2.BeginTransactionInNewTerr(); try { MgaFCO componentAssembly = (MgaFCO)proj2.RootFolder.GetObjectByPathDisp("/@" + FolderName + "/@" + asmName); Assert.NotNull(componentAssembly); componentAssembly.DestroyObject(); var importer = new CyPhyDesignImporter.AVMDesignImporter(null, proj2); avm.Design design; using (StreamReader streamReader = new StreamReader(Path.Combine(AdmPath, asmName + ".adm"))) design = CyPhyDesignImporter.CyPhyDesignImporterInterpreter.DeserializeAvmDesignXml(streamReader); var ret = (ISIS.GME.Dsml.CyPhyML.Interfaces.DesignEntity)importer.ImportDesign(design, "ComponentAssemblies" == FolderName ? CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_CAS : CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_DS); } finally { proj2.CommitTransaction(); if (Debugger.IsAttached) { proj2.Save(null, true); } proj2.Close(true); } }
public void CopyMgaAndRunImporter(string tbName) { //proj.Save(proj.ProjectConnStr + asmName + ".mga", true); File.Copy(proj.ProjectConnStr.Substring("MGA=".Length), (proj.ProjectConnStr + tbName + ".mga").Substring("MGA=".Length), true); MgaProject proj2 = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject")); proj2.OpenEx(proj.ProjectConnStr + tbName + ".mga", "CyPhyML", null); proj2.BeginTransactionInNewTerr(); try { MgaFCO oldTestBench = (MgaFCO)proj2.RootFolder.GetObjectByPathDisp("/@" + FolderName + "/@" + tbName + "|kind=TestBench"); Assert.NotNull(oldTestBench); oldTestBench.DestroyObject(); CyPhyML.TestBenchType testBench; using (StreamReader streamReader = new StreamReader(Path.Combine(AtmPath, tbName + ".atm"))) { avm.TestBench avmTestBench = OpenMETA.Interchange.AvmXmlSerializer.Deserialize <avm.TestBench>(streamReader); testBench = CyPhy2TestBenchInterchange.TestBenchInterchange2CyPhy.Convert(avmTestBench, proj2); } } finally { proj2.CommitTransaction(); if (Debugger.IsAttached) { proj2.Save(null, true); } proj2.Close(true); } }
private void RunInTransaction(Action <MgaProject> action) { MgaProject project = m_Input.designContainer.Impl.Project; project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); try { action(project); project.CommitTransaction(); } catch (Exception) { try { project.AbortTransaction(); } catch { } throw; } }
public void LibraryAttach() { var mgaReference = "MGA=" + mgaFile; MgaProject project = new MgaProject(); project.EnableAutoAddOns(true); project.OpenEx(mgaReference, "CyPhyML", null); try { Assert.Contains("MGA.Addon.CyPhyDecoratorAddon", project.AddOnComponents.Cast <IMgaComponentEx>().Select(addon => addon.ComponentProgID)); MgaFolder lib; project.BeginTransactionInNewTerr(); try { project.RootFolder.AttachLibrary(project.ProjectConnStr, out lib); } finally { project.CommitTransaction(); } } finally { project.Close(true); } Assert.True(File.Exists(mgaReference.Substring("MGA=".Length))); }
public void Import(IEnumerable <string> lbrFiles) { project.Create("MGA=" + Path.GetFullPath(Path.Combine(".", "ComponentCreator", "Components")) + ".mga", "CyPhyML"); IMgaComponent signalBlocksAddon = (IMgaComponent)Activator.CreateInstance(Type.GetTypeFromProgID("MGA.Addon.CyPhySignalBlocksAddOn")); signalBlocksAddon.Initialize(project); project.Notify(globalevent_enum.GLOBALEVENT_OPEN_PROJECT_FINISHED); System.Windows.Forms.Application.DoEvents(); // let CyPhySignalBlocksAddOn create libs project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); try { MgaMetaFolder componentsMeta = (MgaMetaFolder)project.RootMeta.RootFolder.DefinedFolderByName["Components", false]; var components = project.RootFolder.CreateFolder(componentsMeta); components.Name = componentsMeta.Name; } finally { project.CommitTransaction(); } foreach (string eagleFilePath in lbrFiles) { //Console.WriteLine(eagleFilePath); //Console.WriteLine(string.Join(" ", CyPhyComponentAuthoring.Modules.EDAModelImport.GetDevicesInEagleModel(eagleFilePath).ToArray())); foreach (string deviceName in CyPhyComponentAuthoring.Modules.EDAModelImport.GetDevicesInEagleModel(eagleFilePath)) { try { CreateNewComponentMga(eagleFilePath, deviceName); Console.WriteLine("Imported {0} {1}", eagleFilePath, deviceName); } catch (Exception e) { MessageBox.Show("Import failed: " + e.ToString()); } } } project.Save("", true); project.Close(true); }
public void CreatedObjectWithDefaultNamesShouldNotHaveSpaces() { var mgaReference = "MGA=" + mgaFile; MgaProject project = new MgaProject(); project.EnableAutoAddOns(true); project.OpenEx(mgaReference, "CyPhyML", null); List <IMgaObject> createdObjects = new List <IMgaObject>(); try { var terr = project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); // turn off CyPhySignalBlocksAddOn var addons = project.AddOnComponents.Cast <IMgaComponentEx>().Where(x => x.ComponentName == "CyPhySignalBlocksAddOnAddon"); foreach (var addon in addons) { try { addon.Enable(false); } catch (Exception ex) { // if one fails keep trying the other ones. } } // Use default names empty suffix createdObjects = this.CreateObjectHierarchy(project, ""); project.CommitTransaction(); project.BeginTransaction(terr, transactiontype_enum.TRANSACTION_NON_NESTED); // check renames foreach (var obj in createdObjects) { // this will fail on the first one // FIXME: should we collect everything and print a detailed message about failures? Assert.False(obj.Name.Contains(' '), string.Format("Name contains space, but it should not contain any spaces. {0} [{1}]", obj.Name, obj.MetaBase.DisplayedName)); } project.AbortTransaction(); } finally { project.Close(false); } Assert.True(File.Exists(mgaReference.Substring("MGA=".Length))); }
protected string CopyMgaAndRunDesignImporter(string asmName, Action <ISIS.GME.Dsml.CyPhyML.Interfaces.ComponentAssembly> caTest) { string testrunDir = Path.Combine(Path.GetDirectoryName(proj.ProjectConnStr.Substring("MGA=".Length)), "testrun"); try { Directory.Delete(testrunDir, true); } catch (DirectoryNotFoundException) { } Directory.CreateDirectory(testrunDir); string importMgaPath = Path.Combine(testrunDir, Path.GetFileNameWithoutExtension(proj.ProjectConnStr.Substring("MGA=".Length)) + asmName + ".mga"); //proj.Save(proj.ProjectConnStr + asmName + ".mga", true); File.Copy(proj.ProjectConnStr.Substring("MGA=".Length), importMgaPath, true); MgaProject proj2 = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject")); proj2.OpenEx("MGA=" + importMgaPath, "CyPhyML", null); proj2.BeginTransactionInNewTerr(); try { MgaFCO componentAssembly = (MgaFCO)proj2.RootFolder.GetObjectByPathDisp("/@" + FolderName + "/@" + asmName); Assert.NotNull(componentAssembly); componentAssembly.DestroyObject(); var importer = new CyPhyDesignImporter.AVMDesignImporter(null, proj2); avm.Design design; var adpPath = Path.Combine(fixture.AdmPath, asmName + ("ComponentAssemblies" == FolderName ? ".adp" : ".adm")); var ret = importer.ImportFile(adpPath, "ComponentAssemblies" == FolderName ? CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_CAS : CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_DS); if (caTest != null) { caTest((ISIS.GME.Dsml.CyPhyML.Interfaces.ComponentAssembly)ret); } } finally { proj2.CommitTransaction(); if (Debugger.IsAttached) { proj2.Save(null, true); } proj2.Close(true); } return(importMgaPath); }
public void ComponentLibraryManagerAddonRelativeProjectPathURI() { var mgaReference = "MGA=" + mgaFile; MgaProject project = new MgaProject(); project.EnableAutoAddOns(true); project.OpenEx(mgaReference, "CyPhyML", null); try { var terr = project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); // turn off CyPhySignalBlocksAddOn var addons = project.AddOnComponents.Cast <IMgaComponentEx>().Where(x => x.ComponentName == "CyPhySignalBlocksAddOnAddon"); foreach (var addon in addons) { try { addon.Enable(false); } catch (Exception ex) { // if one fails keep trying the other ones. } } var components = project.RootFolder.CreateFolder(project.RootMeta.RootFolder.LegalChildFolderByName["Components"]); components.Name = "ComponentLibraryManagerAddonProjectPathURITest"; var component = components.CreateRootObject(project.RootMeta.RootFolder.DefinedFCOByName["Component", false]); component.Name = "ComponentLibraryManagerAddonProjectPathURITest"; project.CommitTransaction(); } finally { project.Close(false); } }
public void Test_CyPhyPET_unit_matcher() { var project = new MgaProject(); project.OpenEx("MGA=" + this.mgaFile, "CyPhyML", null); try { project.BeginTransactionInNewTerr(); try { var wrapper = project.RootFolder.ObjectByPath["/@Testing/@ParametricExploration/@TestPython/@PythonWrapper"]; var pythonBlock = ISIS.GME.Dsml.CyPhyML.Classes.PythonWrapper.Cast(wrapper); var binDir = Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(Workflow_PET_Test)).CodeBase.Substring("file:///".Length)); var path = Path.GetFullPath(binDir + "/../../paraboloid.py"); var pet = CyPhyPET.CyPhyPETInterpreter.GetParamsAndUnknownsForPythonOpenMDAO(path, pythonBlock); // "{\"unknowns\": {\"f_xy\": {\"units\": \"m**3\", \"gme_unit_id\": \"id-0065-00000179\", \"shape\": 1, \"val\": 0.0, \"size\": 1}}, \"params\": {\"x\": {\"units\": \"m\", \"gme_unit_id\": \"id-0066-00000014\", \"shape\": 1, \"val\": 0.0, \"size\": 1}, \"y\": {\"units\": \"m**3\", \"gme_unit_id\": \"id-0065-00000179\", \"shape\": 1, \"val\": 0.0, \"size\": 1}}}" var unknowns = pet["unknowns"]; var params_ = pet["params"]; var x = params_["x"]; var y = params_["y"]; var f_xy = unknowns["f_xy"]; Assert.Equal("Meter", project.GetFCOByID((string)x["gme_unit_id"]).Name); Assert.Equal("Cubic Meter", project.GetFCOByID((string)y["gme_unit_id"]).Name); Assert.Equal("Cubic Meter", project.GetFCOByID((string)f_xy["gme_unit_id"]).Name); } finally { project.CommitTransaction(); } } finally { project.Close(abort: true); } }
private void ExecuteInTransaction(MgaProject project, Action doWork) { if (project == null || doWork == null) { throw new ArgumentNullException(); } var terr = project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); try { doWork(); project.CommitTransaction(); project.FlushUndoQueue(); } catch (Exception) { try { project.AbortTransaction(); } catch { } throw; } }
private void CleanUpTempMgaProject(string outputFile) { var newProject = new MgaProject(); bool ro_mode; // open the copied temporary mga file newProject.Open("MGA=" + outputFile, out ro_mode); IMgaTerritory terr = null; try { // create a new transaction terr = newProject.BeginTransactionInNewTerr(); // get the sot object on which the job manager will operate var sot = newProject.GetObjectByID(sotConfig.SoTID); if (sot != null) { // if the sot object exists in the project GME.MGA.Meta.objtype_enum objtype; MgaObject parent; // get the parent folder of which this SoT belongs to. sot.GetParent(out parent, out objtype); if (objtype == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER) { // if it is really a folder cast it var parentSoTFolder = parent as MgaFolder; // get all SoT objects in the folder except the one we operate on // mark them for deletion var sotsToDelete = parentSoTFolder .ChildFCOs .Cast <MgaFCO>() .Where(x => x.ID != sotConfig.SoTID) .ToList(); try { // destroy all SoTs that are not used by this sot run sotsToDelete.ForEach(x => x.DestroyObject()); } catch { // ok } // get all not null test bench objects that this sot run uses. var referredTBsInSot = sot .ChildObjects .OfType <MgaReference>() .Where(x => x.Meta.Name == typeof(CyPhy.TestBenchRef).Name && x.Referred != null) .Select(x => x.Referred) .Cast <MgaModel>() .ToList(); foreach (var tb in referredTBsInSot) { GME.MGA.Meta.objtype_enum tbParentObjtype; MgaObject tbParent; // get the parent folder where the referenced test bench located tb.GetParent(out tbParent, out tbParentObjtype); if (tbParentObjtype == GME.MGA.Meta.objtype_enum.OBJTYPE_FOLDER) { var parentTBFolder = tbParent as MgaFolder; // get all test benches that are not used by the sot // WARNING: sometimes COM object comparison can fail this code is not the safest. var tbsToDelete = parentTBFolder .ChildFCOs .OfType <MgaModel>() .Where(x => referredTBsInSot.Contains(x) == false) .ToList(); try { // delete test benches that sot does not use tbsToDelete.ForEach(x => x.DestroyObject()); } catch { // ok } } } } } // commit changes if everything is successful newProject.CommitTransaction(); } catch { // abort all changes if exception occured newProject.AbortTransaction(); } finally { if (terr != null) { // destroy the territory we were working in if it is not null terr.Destroy(); } } // close the project AND save all changes newProject.Close(); }
private void AttachLibrary(LibraryInfo libraryInfo) { string mgaPath = metaPath + "\\" + libraryInfo.MgaName + ".mga"; if ((project.ProjectStatus & PROJECT_STATUS_OPEN) == PROJECT_STATUS_OPEN) { if (!File.Exists(mgaPath)) { GMEConsole.Error.WriteLine("Path '" + mgaPath + "' does not exist. Cannot attach " + libraryInfo.MgaName); return; } project.Notify(globalevent_enum.APPEVENT_LIB_ATTACH_BEGIN); try { project.BeginTransaction(project.ActiveTerritory); IMgaFolder oldLibFolder = project.RootFolder.ChildFolders.Cast <IMgaFolder>() .Where(x => string.IsNullOrWhiteSpace(x.LibraryName) == false && (x.Name.Contains(libraryInfo.DisplayName) || x.Name.Contains(libraryInfo.DisplayName))).FirstOrDefault(); bool needAttach; if (oldLibFolder == null) { needAttach = true; if (libraryPaths.Contains(Path.GetFullPath(project.ProjectConnStr.Substring("MGA=".Length)))) { // Don't attach libraries to themselves needAttach = false; } } else { DateTime oldModTime; long loldModTime; if (long.TryParse(oldLibFolder.RegistryValue["modtime"], out loldModTime)) { oldModTime = DateTime.FromFileTimeUtc(loldModTime); } else { oldModTime = DateTime.MinValue; } needAttach = File.GetLastWriteTimeUtc(mgaPath).CompareTo(oldModTime) > 0; if (!needAttach) { GMEConsole.Info.WriteLine("Library is up-to-date: embedded library modified " + oldModTime.ToString() + ", " + libraryInfo.MgaName + " modified " + File.GetLastWriteTimeUtc(mgaPath).ToString()); } } if (needAttach) { MgaProject proj = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject")); int mgaVersion; string paradigmName; string paradigmVersion; object paradigmGuid; bool readOnly; proj.QueryProjectInfo("MGA=" + mgaPath, out mgaVersion, out paradigmName, out paradigmVersion, out paradigmGuid, out readOnly); Guid guidP1 = ConvertToGUID(paradigmGuid); Guid guidP2 = ConvertToGUID(project.RootMeta.GUID); bool guidsEqual = guidP1.Equals(guidP2); if (paradigmName != project.MetaName || !guidsEqual) { GMEConsole.Info.WriteLine("Skipping refresh of " + libraryInfo.DisplayName + " because it uses a different metamodel version than the current project."); project.AbortTransaction(); // not true, but don't try again libraryInfo.attachedLibrary = true; return; } // GMEConsole.Info.WriteLine("Attaching library " + mgaPath); RootFolder newLibFolder = Common.Classes.RootFolder.GetRootFolder(project).AttachLibrary("MGA=" + mgaPath); DateTime modtime = File.GetLastWriteTimeUtc(mgaPath); ((newLibFolder as ISIS.GME.Common.Classes.RootFolder).Impl as GME.MGA.IMgaFolder).RegistryValue["modtime"] = modtime.ToFileTimeUtc().ToString(); if (oldLibFolder != null) { ReferenceSwitcher.Switcher sw = new ReferenceSwitcher.Switcher(oldLibFolder, newLibFolder.Impl, null); sw.UpdateSublibrary(); oldLibFolder.DestroyObject(); } ((newLibFolder as ISIS.GME.Common.Classes.RootFolder).Impl as GME.MGA.IMgaFolder).LibraryName = libraryInfo.DisplayName; GMEConsole.Info.WriteLine((oldLibFolder == null ? "Attached " : "Refreshed ") + libraryInfo.MgaName + ".mga library."); } project.CommitTransaction(); } catch (Exception e) { GMEConsole.Error.WriteLine("Error refreshing library: " + SecurityElement.Escape(e.Message)); project.AbortTransaction(); } finally { project.Notify(globalevent_enum.APPEVENT_LIB_ATTACH_END); } libraryInfo.attachedLibrary = true; } }
private void ExecuteInTransaction(MgaProject project, Action doWork, bool abort = false, transactiontype_enum type = transactiontype_enum.TRANSACTION_NON_NESTED) { if (project == null || doWork == null) { throw new ArgumentNullException(); } bool inTx = (project.ProjectStatus & 8) != 0; if (inTx) { doWork(); return; } project.BeginTransactionInNewTerr(type); try { doWork(); if (abort) { project.AbortTransaction(); } else { project.CommitTransaction(); } project.FlushUndoQueue(); } catch (Exception) { try { project.AbortTransaction(); } catch { } throw; } }
void TestSubTreeMergeModel() { string mgaFileCopy = mgaFile + "copy.mga"; File.Copy(mgaFile, mgaFile + "copy.mga", true); MgaProject project = new MgaProject(); project.OpenEx("MGA=" + this.mgaFile, "CyPhyML", null); try { project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); try { string mergeMeModelPath = "/@ComponentAssemblies/@MergeMe"; MgaFCO mergeMe = (MgaFCO)project.ObjectByPath[mergeMeModelPath]; int startingDescendantFCOs = ((MgaModel)mergeMe).GetDescendantFCOs(mergeMe.Project.CreateFilter()).Count; var fcos = ((MgaModel)mergeMe).GetDescendantFCOs(project.CreateFilter()).Cast <MgaFCO>().Select( x => x.AbsPath).ToList(); foreach (MgaObject obj in mergeMe.ChildObjects) { if (obj.MetaBase.Name != "Connector" && obj.MetaBase.Name != "Axis" && /* keep these, since they have refport connections*/ obj.Status == (int)objectstatus_enum.OBJECT_EXISTS /* connections may be deleted when their endpoints are */) { obj.DestroyObject(); } } var subTreeMerge = new SubTreeMerge.SubTreeMerge(); subTreeMerge.merge(mergeMe, mgaFileCopy); Assert.Equal(SubTreeMerge.SubTreeMerge.Errors.NoError, subTreeMerge.exitStatus); MgaFCO newMergeMe = (MgaFCO)project.ObjectByPath[mergeMeModelPath]; Assert.Equal(newMergeMe.ID, ((MgaReference)project.ObjectByPath["/@ComponentAssemblies/@AsmWithRef/@MergeMe"]).Referred.ID); Assert.Equal(newMergeMe.ID, ((MgaReference)project.ObjectByPath["/@Testing/@TestBench/@MergeMe"]).Referred.ID); Assert.Equal(2, ((MgaReference)project.ObjectByPath["/@ComponentAssemblies/@AsmWithRef/@MergeMe"]).UsedByConns.Count); Assert.Equal(2, ((MgaReference)project.ObjectByPath["/@Testing/@TestBench/@MergeMe"]).UsedByConns.Count); //Debugging: //var fcos2 = ((MgaModel)newMergeMe).GetDescendantFCOs(project.CreateFilter()).Cast<MgaFCO>().Select(x => x.AbsPath) // .Where(x => fcos.Contains(x) == false); //HashSet<string> originalObjects = new HashSet<string>(); //foreach (string abspath in fcos) // originalObjects.Add(abspath); //foreach (string abspath in ((MgaModel)newMergeMe).GetDescendantFCOs(project.CreateFilter()).Cast<IMgaFCO>().Select(x => x.AbsPath)) // originalObjects.Remove(abspath); // Console.Out.WriteLine(string.Join("\n", originalObjects)); Assert.Equal(startingDescendantFCOs, ((MgaModel)newMergeMe).GetDescendantFCOs(project.CreateFilter()).Count); } finally { project.CommitTransaction(); } } finally { if (System.Diagnostics.Debugger.IsAttached) { project.Save(project.ProjectConnStr + "_testoutput.mga", true); } project.Close(true); } }