Ejemplo n.º 1
0
        public static void UpdateMxString(bool whatif, string objName, IAttribute attribute, Operation op, string newValue, string findString = "")
        {
            if (attribute.DataType != MxDataType.MxString)
            {
                _log.Error(string.Format("Attribute data type {0} is not supported by function {1}", attribute.DataType.ToString(), nameof(UpdateMxString)));
            }
            string newString = attribute.value.GetString();

            findString = findString.Replace("~%obj", objName);
            newValue   = newValue.Replace("~%obj", objName);

            switch (op)
            {
            case Operation.FindReplace:
                if (newString.Contains(findString))
                {
                    newString = newString.Replace(findString, newValue);
                }
                break;

            case Operation.FindUpdate:
                if (newString == findString)
                {
                    newString = newValue;
                }
                else
                {
                    return;
                }
                break;

            case Operation.Update:
                newString = newValue;
                break;

            default:
                _log.Error(string.Format("{0} opertation is not supported by function {1}", op.ToString(), nameof(UpdateMxString)));
                return;
            }
            if (attribute.value.GetString() == newString)
            {
                return;
            }

            _log.Info(string.Format("Updating attribute [{0}] on object [{1}] from [{2}] to [{3}]", attribute.Name, objName, attribute.value.GetString(), newString));

            if (!whatif)
            {
                MxValue mxval = new MxValueClass();
                mxval.PutString(newString);
                attribute.SetValue(mxval);
                ICommandResult cmd = attribute.CommandResult;
                if (!cmd.Successful)
                {
                    _log.Warn(string.Format("{0} Failed:{1}:{2}", nameof(UpdateMxString), cmd.Text, cmd.CustomMessage));
                }
            }
        }
Ejemplo n.º 2
0
        public static void UpdateMxBool(bool whatif, string objName, IAttribute attribute, Operation op, bool newValue, bool findBool = false)
        {
            if (attribute.DataType != MxDataType.MxBoolean)
            {
                _log.Error(string.Format("Attribute data type {0} is not supported by function {1}", attribute.DataType.ToString(), nameof(UpdateMxBool)));
            }
            bool newBool = attribute.value.GetBoolean();

            switch (op)
            {
            case Operation.FindUpdate:
                if (newBool == findBool)
                {
                    newBool = newValue;
                }
                else
                {
                    return;
                }
                break;

            case Operation.Update:
                newBool = newValue;
                break;

            default:
                _log.Error(string.Format("{0} opertation is not supported by function {1}", op.ToString(), nameof(UpdateMxBool)));
                return;
            }

            _log.Info(string.Format("Updating attribute [{0}] on object [{1}] from [{2}] to [{3}]", attribute.Name, objName, attribute.value.GetString(), newBool));

            if (!whatif)
            {
                MxValue mxval = new MxValueClass();
                mxval.PutBoolean(newBool);
                attribute.SetValue(mxval);

                ICommandResult cmd = attribute.CommandResult;
                if (!cmd.Successful)
                {
                    _log.Warn(string.Format("{0} Failed:{1}:{2}", nameof(UpdateMxBool), cmd.Text, cmd.CustomMessage));
                }
            }
        }
Ejemplo n.º 3
0
        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);
        }
Ejemplo n.º 4
0
        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);
        }