// Возвращает IgObjects коллекцию по списку имен public IgObjects GetTemplates(string[] tagNames) { var objects = _galaxy.QueryObjectsByName(EgObjectIsTemplateOrInstance.gObjectIsTemplate, ref tagNames); GalaxyExceptions.ThrowIfNoSuccess(CommandResult); return(objects); }
/// <summary> /// Return an empty set of GObjects so we can simply add to it /// </summary> /// <returns></returns> private IgObjects GetEmptyIgObjects() { string[] DummyStringRef; try { DummyStringRef = new string[1]; DummyStringRef[0] = "-"; return(_galaxy.QueryObjectsByName(EgObjectIsTemplateOrInstance.gObjectIsInstance, ref DummyStringRef)); } catch (Exception ex) { log.Error(ex.ToString()); return(null); } }
void workerImport_DoWork(object sender, DoWorkEventArgs e) { DateTime t0 = DateTime.Now; int createSuccessCount = 0; int recreateSuccessCount = 0; int updateSuccessCount = 0; int faultCount = 0; int delay = 50; UpdateType updateType = UpdateType.Update; int index = 0; double progress = 0; int count = 0; try { //string nodeName = Environment.MachineName; string nodeName = Global.Default.varXml.SystemPlatform.NodeName; string galaxyName = Global.Default.varXml.SystemPlatform.GalaxyName; // create GRAccessAppClass object GRAccessApp grAccess = new GRAccessAppClass(); Report(string.Format("Подключение к Galaxy ({0}/{1})...\r\n", nodeName, galaxyName)); // try to get galaxy IGalaxies gals = grAccess.QueryGalaxies(nodeName); if (gals == null || grAccess.CommandResult.Successful == false) { Report(string.Format("Error!\r\nCustomMessage - {0}\r\nCommandResult - {1}\r\n", grAccess.CommandResult.CustomMessage, grAccess.CommandResult.Text)); return; } else { Report("Подключен.\r\n"); } IGalaxy galaxy = gals[galaxyName]; string login = Global.Default.varXml.SystemPlatform.Login; string password = Global.Default.varXml.SystemPlatform.Password; Report(string.Format("Авторизация {0}/{1}...\r\n", login, password)); // log in galaxy.Login(login, password); ICommandResult cmd; cmd = galaxy.CommandResult; if (!cmd.Successful) { Report("Ошибка авторизации:" + cmd.Text + " : " + cmd.CustomMessage + "\r\n"); return; } else { Report("Авторизован.\r\n"); } XPCollection <ObjectTypeAddonCollection> importFields = new XPCollection <ObjectTypeAddonCollection>(); XPCollection <ObjectType> objTypes2 = new XPCollection <ObjectType>(); ObjectType objType = (ObjectType)_dbInterface1.GetCurrentObject(); ObjectType objTypeThreadSafe = null; foreach (ObjectTypeAddonCollection addon in importFields) { if (addon.ObjectTypeOwner.Oid == objType.Oid) { objTypeThreadSafe = addon.ObjectTypeOwner; break; } } if (objTypeThreadSafe != null) { string templateName = ""; IgObjects queryResult; string[] tagnames = new string[1]; // Почему-то не работает стандартная выборка. //importFields.Filter = CriteriaOperator.Parse("[ObjectTypeOwner] == {0}", objTypeThreadSafe); importFields.Criteria = new BinaryOperator("ObjectTypeOwner", objTypeThreadSafe); importFields.Filter = CriteriaOperator.Parse("[ArchestrAImport]"); count = importFields.Count; templateName = objType.ArchestrATemplate; tagnames[0] = templateName; queryResult = galaxy.QueryObjectsByName(EgObjectIsTemplateOrInstance.gObjectIsInstance, ref tagnames); // get the $UserDefined template tagnames[0] = objType.ArchestrATemplate; queryResult = galaxy.QueryObjectsByName( EgObjectIsTemplateOrInstance.gObjectIsTemplate, ref tagnames); cmd = galaxy.CommandResult; if (!cmd.Successful) { Report("Ошибка инициализации шаблона:" + cmd.Text + " : " + cmd.CustomMessage + "\r\n"); } ITemplate template = (ITemplate)queryResult[1]; Report(string.Format("Обновляем шаблон {0}...\r\n", objType.ArchestrATemplate)); Thread.Sleep(delay); template.CheckOut(); foreach (ObjectTypeAddonCollection field in importFields) { index++; try { if (!string.IsNullOrEmpty(field.AttributeAddon)) { IAttribute att = template.Attributes[field.AttributeAddon]; MxDataType type = GetDataType(field.DataType); if (att == null) { updateType = UpdateType.Create; createSuccessCount++; template.AddUDA(field.AttributeAddon, type, MxAttributeCategory.MxCategoryWriteable_USC_Lockable, MxSecurityClassification.MxSecurityOperate); } else { if (att.DataType == type) { updateType = UpdateType.Update; updateSuccessCount++; } else { updateType = UpdateType.Recreate; recreateSuccessCount++; template.DeleteUDA(field.AttributeAddon); template.AddUDA(field.AttributeAddon, type, MxAttributeCategory.MxCategoryWriteable_USC_Lockable, MxSecurityClassification.MxSecurityOperate); } } att = template.Attributes[field.AttributeAddon]; att.Description = field.Comment; string fieldValue = field.ArchestrAValue; if (!string.IsNullOrEmpty(fieldValue)) { MxValue mxValue = new MxValueClass(); PutMxValue(ref mxValue, type, fieldValue); att.SetValue(mxValue); } progress = ((double)index / count * 1000); progressPossition = (int)Math.Round(progress); switch (updateType) { case UpdateType.Update: Report(string.Format("Поле {0} ({1} / {2}) обновлено удачно.\r\n", field.AttributeAddon, type, fieldValue)); break; case UpdateType.Create: Report(string.Format("Поле {0} ({1} / {2}) создано удачно.\r\n", field.AttributeAddon, type, fieldValue)); break; case UpdateType.Recreate: Report(string.Format("Поле {0} ({1} / {2}) пересоздано удачно.\r\n", field.AttributeAddon, type, fieldValue)); break; } } } catch (Exception ex) { Report(string.Format("У поля {0} есть проблема создания :( [{1} -> {2}] \r\n", templateName, ex.Message, ex.InnerException)); faultCount++; } } template.Save(); template.CheckIn("Check in after adding."); Report(string.Format("Обновлен.\r\n")); galaxy.Logout(); Thread.Sleep(delay); Report(string.Format("Отключение от галактики выполнено. \r\n")); Thread.Sleep(delay); } } catch (Exception ex) { meResultArchestrA.Text = ex.Message + "->" + ex.InnerException + "\r\n"; } TimeSpan diff = DateTime.Now - t0; Report(string.Format("Было потрачено времени: {0} c.\r\n", diff.ToString())); Thread.Sleep(delay); Report(string.Format("Среднее время на один объект: {0:0.#} c.\r\n", diff.TotalSeconds / count)); Thread.Sleep(delay); Report(string.Format("Удачно созданных: {0}.\r\n", createSuccessCount)); Thread.Sleep(delay); Report(string.Format("Удачно обновленных: {0}.\r\n", updateSuccessCount)); Thread.Sleep(delay); Report(string.Format("Удачно пересозданных: {0}.\r\n", recreateSuccessCount)); Thread.Sleep(delay); Report(string.Format("Неудачно выполненных команд: {0}. \r\n", faultCount)); Thread.Sleep(delay); }
static void Main(string[] args) { string nodeName = Environment.MachineName; string galaxyName = args[0]; string template = args[1]; string attribute = args[2]; string username = ""; string password = ""; if (args.Length >= 4) { username = args[3]; } if (args.Length >= 5) { password = args[4]; } GRAccessApp grAccess = new GRAccessAppClass(); IGalaxies gals = grAccess.QueryGalaxies(nodeName); if (gals == null || grAccess.CommandResult.Successful == false) { Console.WriteLine(grAccess.CommandResult.CustomMessage + grAccess.CommandResult.Text); return; } IGalaxy galaxy = gals[galaxyName]; ICommandResult cmd; if (galaxy == null) { Console.WriteLine("Galaxy '" + galaxyName + "' does not exist"); Console.WriteLine("Press return key to exit."); Console.ReadLine(); return; } galaxy.Login(username, password); cmd = galaxy.CommandResult; if (!cmd.Successful) { Console.WriteLine("Login to galaxy Example1 Failed :" + cmd.Text + " : " + cmd.CustomMessage); return; } string[] tagnames = { template }; IgObjects queryResult = galaxy.QueryObjectsByName( EgObjectIsTemplateOrInstance.gObjectIsTemplate, ref tagnames); ITemplate myTemplate = (ITemplate)queryResult[1]; myTemplate.CheckOut(); IAttributes myAttributes = myTemplate.Attributes; IAttribute myAttribute = myAttributes[attribute]; myAttribute.SetLocked(MxPropertyLockedEnum.MxUnLocked); myTemplate.Save(); myTemplate.CheckIn(); galaxy.Logout(); Console.WriteLine("The attribute should have been unlocked"); Console.WriteLine("Press return to exit"); Console.ReadLine(); }
static void Main(string[] args) { GRAccessApp grAccess = new GRAccessAppClass(); string machineName = Environment.MachineName; Console.Write("Enter Galaxy name:"); string galaxyName = Console.ReadLine(); IGalaxies gals = grAccess.QueryGalaxies(machineName); IGalaxy galaxy = gals[galaxyName]; if (galaxy == null) { Console.WriteLine("That galaxy does not exist"); Console.WriteLine("Press return to exit."); Console.ReadLine(); return; } Console.Write("Enter username, press return for blank:"); string galaxyUser = Console.ReadLine(); Console.Write("Enter password, press return for blank:"); string galaxyPass = Console.ReadLine(); galaxy.Login(galaxyUser, galaxyPass); if (!galaxy.CommandResult.Successful) { Console.WriteLine("Those login credentials are invalid"); Console.WriteLine("Press return to exit."); Console.ReadLine(); return; } string[] tagnames = new string[1]; Console.Write("Please enter the template name you wish to modify, please ensure it starts with $:"); tagnames[0] = Console.ReadLine(); IgObjects queryResult = galaxy.QueryObjectsByName(EgObjectIsTemplateOrInstance.gObjectIsTemplate, ref tagnames); ITemplate myTemplate = (ITemplate)queryResult[1]; myTemplate.CheckOut(); string udaName = string.Format("uda_{0:yyyyMMddhhmmss}", DateTime.Now); myTemplate.AddUDA(udaName, MxDataType.MxBoolean, MxAttributeCategory.MxCategoryWriteable_USC_Lockable, MxSecurityClassification.MxSecurityOperate, false, null); myTemplate.Save(); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); try { myTemplate.CheckIn(); } catch { Console.WriteLine("Caught Error"); if (stopWatch.IsRunning) { stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("RunTime " + elapsedTime); } Console.ReadLine(); } stopWatch.Stop(); TimeSpan ts2 = stopWatch.Elapsed; string elapsedTime2 = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts2.Hours, ts2.Minutes, ts2.Seconds, ts2.Milliseconds / 10); Console.WriteLine("RunTime " + elapsedTime2); galaxy.Logout(); Console.WriteLine("Process has completed"); Console.ReadLine(); }
void workerImport_DoWork(object sender, DoWorkEventArgs e) { DateTime t0 = DateTime.Now; int createSuccessCount = 0; int updateSuccessCount = 0; int faultCount = 0; int delay = 50; bool isUpdating = false; int index = 0; double progress = 0; int count = 0; try { //string nodeName = Environment.MachineName; string nodeName = Global.Default.varXml.SystemPlatform.NodeName; string galaxyName = Global.Default.varXml.SystemPlatform.GalaxyName; // create GRAccessAppClass object GRAccessApp grAccess = new GRAccessAppClass(); Report(string.Format("Подключение к Galaxy ({0}/{1})...\r\n", nodeName, galaxyName)); // try to get galaxy IGalaxies gals = grAccess.QueryGalaxies(nodeName); if (gals == null || grAccess.CommandResult.Successful == false) { Report(string.Format("Error!\r\nCustomMessage - {0}\r\nCommandResult - {1}\r\n", grAccess.CommandResult.CustomMessage, grAccess.CommandResult.Text)); return; } else { Report("Подключен.\r\n"); } IGalaxy galaxy = gals[galaxyName]; string login = Global.Default.varXml.SystemPlatform.Login; string password = Global.Default.varXml.SystemPlatform.Password; Report(string.Format("Авторизация {0}/{1}...\r\n", login, password)); // log in galaxy.Login(login, password); ICommandResult cmd; cmd = galaxy.CommandResult; if (!cmd.Successful) { Report("Ошибка авторизации:" + cmd.Text + " : " + cmd.CustomMessage + "\r\n"); return; } else { Report("Авторизован.\r\n"); } string instanceName = ""; IgObjects queryResult; string[] tagnames = new string[1]; XPCollection <Object> objects = new XPCollection <Object>(); objects.Criteria = CriteriaOperator.Parse("[ArchestrAImport]"); count = objects.Count; foreach (Object obj in objects) { index++; try { if (obj.ObjectTypeID != null) { if (!string.IsNullOrEmpty(obj.ObjectTypeID.ArchestrATemplate)) { instanceName = obj.Attribute; tagnames[0] = instanceName; queryResult = galaxy.QueryObjectsByName( EgObjectIsTemplateOrInstance.gObjectIsInstance, ref tagnames); IInstance instance = null; cmd = galaxy.CommandResult; try { instance = (IInstance)queryResult[1]; isUpdating = true; } catch { isUpdating = false; } if (isUpdating) { updateSuccessCount++; } else { // get the $UserDefined template tagnames[0] = obj.ObjectTypeID.ArchestrATemplate; queryResult = galaxy.QueryObjectsByName( EgObjectIsTemplateOrInstance.gObjectIsTemplate, ref tagnames); cmd = galaxy.CommandResult; if (!cmd.Successful) { meResultArchestrA.Text = "Ошибка инициализации шаблона:" + cmd.Text + " : " + cmd.CustomMessage + "\r\n"; } ITemplate userDefinedTemplate = (ITemplate)queryResult[1]; // create an instance instance = userDefinedTemplate.CreateInstance(instanceName, true); createSuccessCount++; isUpdating = false; } instance.CheckOut(); MxValue mxName = new MxValueClass(); mxName.PutString(obj.Chart); instance.Attributes[Global.Default.varXml.SystemPlatform.NameField].SetValue(mxName); MxValue mxDescription = new MxValueClass(); mxDescription.PutString(obj.Comment); instance.Attributes[Global.Default.varXml.SystemPlatform.DescriptionField].SetValue(mxDescription); if (obj.ObjectTypeID.IsRealType) { MxValue mxPointNum = new MxValueClass(); mxPointNum.PutInteger(obj.PointNum); instance.Attributes[Global.Default.varXml.SystemPlatform.PointNumField].SetValue(mxPointNum); MxValue mxUnit = new MxValueClass(); mxUnit.PutString(obj.Unit); instance.Attributes[Global.Default.varXml.SystemPlatform.UnitField].SetValue(mxUnit); } instance.Save(); instance.CheckIn("Check in after adding."); progress = ((double)index / objects.Count * 1000); progressPossition = (int)Math.Round(progress); if (!isUpdating) { Report(string.Format("Объект {0} создан удачно.\r\n", instanceName)); } else { Report(string.Format("Объект {0} обновлен удачно.\r\n", instanceName)); } } } } catch (Exception ex) { Report(string.Format("У объекта {0} есть проблема создания :( [{1} -> {2}] \r\n", instanceName, ex.Message, ex.InnerException)); faultCount++; } } galaxy.Logout(); Thread.Sleep(delay); Report(string.Format("Отключение от галактики выполнено. \r\n")); Thread.Sleep(delay); } catch (Exception ex) { meResultArchestrA.Text = ex.Message + "->" + ex.InnerException + "\r\n"; } TimeSpan diff = DateTime.Now - t0; Report(string.Format("Было потрачено времени: {0} c.\r\n", diff.ToString())); Thread.Sleep(delay); Report(string.Format("Среднее время на один объект: {0:0.#} c.\r\n", diff.TotalSeconds / count)); Thread.Sleep(delay); Report(string.Format("Удачно созданных: {0}.\r\n", createSuccessCount)); Thread.Sleep(delay); Report(string.Format("Удачно обновленных: {0}.\r\n", updateSuccessCount)); Thread.Sleep(delay); Report(string.Format("Неудачно выполненных команд: {0}. \r\n", faultCount)); Thread.Sleep(delay); }
/// <summary> /// Backup GObjects to multiple files in a single folder /// </summary> /// <param name="ExportType"></param> /// <param name="GalaxyObjects"></param> /// <param name="BackupFolderName"></param> /// <returns></returns> public int BackupToFolder(EExportType ExportType, IgObjects GalaxyObjects, String BackupFolderName) { String[] SingleItemName = new String[1]; IgObjects SingleObject; String BackupFileName; String Extension; String ConfigVersion; try { // first verify connection if (!this.Connected) { throw new Exception("Galaxy not connected"); } // Get Extension Extension = CorrectExtension(ExportType); //Create the Backup FOlder if it doesn't exist if (!System.IO.Directory.Exists(BackupFolderName)) { System.IO.Directory.CreateDirectory(BackupFolderName); } // Double check that we have the folder. If it's missing then error out if (!System.IO.Directory.Exists(BackupFolderName)) { throw new Exception("Missing Directory " + BackupFolderName); } //Need to iterate through the the objects foreach (IgObject Item in GalaxyObjects) { // Populate the single item array with the item's tagname SingleItemName[0] = Item.Tagname; //Default Config Version Text to Blank ConfigVersion = ""; //If we require config version in the filename then figure it out then add it if (_includeConfigVersion) { ConfigVersion = "-v" + Item.ConfigVersion.ToString(); } // Calculate the appropriate backup filename BackupFileName = BackupFolderName + "\\" + Item.Tagname + ConfigVersion + Extension; // Check for file exists. Bail if the file already exists and we don't want to overwrite // In this section it is actually a bit redundant but we don't want to perform the Galaxy query if not necessary if (CheckandLogFileExists(BackupFileName)) { continue; } // Figure out if we're dealing with a Template or Instance if (Item.Tagname.Substring(0, 1) == "$") { //Template SingleObject = _galaxy.QueryObjectsByName(EgObjectIsTemplateOrInstance.gObjectIsTemplate, ref SingleItemName); } else { // Instance SingleObject = _galaxy.QueryObjectsByName(EgObjectIsTemplateOrInstance.gObjectIsInstance, ref SingleItemName); } // Make sure we have an actual object in the collection if (SingleObject.count > 0) { // Perform the actual backup BackupToFile(ExportType, SingleObject, BackupFileName); } } return(0); } catch (Exception ex) { log.Error(ex.ToString()); return(-1); } }