Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Failure, missing arguments.");
                Console.WriteLine("galaxyBackup.exe <galaxyname> <path>");
                return;
            }

            string nodeName = Environment.MachineName;

            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[args[0]];

            if (galaxy == null)
            {
                Console.WriteLine("Failure, galaxy '{0}' does not exist", args[0]);
                return;
            }

            Process currentProc = Process.GetCurrentProcess();

            galaxy.Backup(currentProc.Id, args[1], nodeName, args[0]);
        }
Ejemplo n.º 2
0
 private void btnConnect_Click(object sender, EventArgs e)
 {
     try
     {
         galaxy     = galaxies[txtGalaxyName.Text];
         GalaxyUser = txtUser.Text.ToString();
         galaxy.Login(GalaxyUser, GalaxyPass);
         if (galaxy.CommandResult.Successful)
         {
             lblStatus.Text        = "Connected";
             lblStatus.ForeColor   = Color.Green;
             lblResMsgConnect.Text = "No Error";
             loggedIN = true;
         }
         else
         {
             lblStatus.Text        = "Dicconnected.Try again.";
             lblResMsgConnect.Text = "ID:" + galaxy.CommandResult.ID + "/nMessage:" + galaxy.CommandResult.CustomMessage.ToString();
             loggedIN = false;
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message.ToString());
     }
 }
 public void AddNeighbor(IGalaxy neighbor, bool autoAdd = true)
 {
     Neighbors.Add(neighbor.Name, neighbor);
     if (autoAdd)
     {
         neighbor.AddNeighbor(this, false);
     }
 }
Ejemplo n.º 4
0
        public PlayerGameView(Game game, int playerId)
        {
            this.game     = game;
            this.playerId = playerId;

            Galaxy  = new PlayerGalaxyView(game, playerId);
            players = game.Players.Select(Project).ToList();
        }
Ejemplo n.º 5
0
        public void TargetObject(IGalaxy galaxy, ISpaceObject target)
        {
            if (target != null)
            {
                SelectedObject = target;
                Objects        = galaxy.GetSpaceObjectsAt(target.Position).ToArray();

                OnChange();
            }
        }
Ejemplo n.º 6
0
        public void Refresh(IGalaxy galaxy)
        {
            if (SelectedObject != null)
            {
                SelectedObject = galaxy.GetSpaceObject(SelectedObject.ObjectId);

                Objects = SelectedObject != null
                                        ? galaxy.GetSpaceObjectsAt(SelectedObject.Position).ToArray()
                                        : null;

                OnChange();
            }
        }
Ejemplo n.º 7
0
 // Отключенеи от Галактики
 public void Logout()
 {
     if (_galaxy != null)
     {
         try
         {
             _galaxy.Logout();
         }
         finally
         {
             _galaxy = null;
             GC.Collect();
         }
     }
 }
Ejemplo n.º 8
0
        private void Login(string nodeName, string galaxyName, string user, string password)
        {
            try
            {
                GRAccessApp grAccess;
                try
                {
                    grAccess = new GRAccessAppClass();
                }
                catch (Exception ex)
                {
                    DispatchMessagebox("Unable to initialize GRAccess.  This can have several causes - GRAcces.dll must a registered type library.  You must have an available license - if you only have one license then you must not have the IDE open while using this tool.  On some systems, you may have to run this tool as an administrator. \n\n Exception Details:\n" + ex.ToString());
                    return;
                }

                _galaxies = grAccess.QueryGalaxies(nodeName);
                if (_galaxies == null || grAccess.CommandResult.Successful == false)
                {
                    DispatchMessagebox("Unable to query galaxies on node " + nodeName);
                    return;
                }
                IGalaxy galaxy = _galaxies[galaxyName];
                if (galaxy == null)
                {
                    DispatchMessagebox(string.Format("Couldn't find galaxy {0} on node {1}", galaxyName, nodeName));
                    return;
                }
                galaxy.Login(user, password);
                ICommandResult cmd = galaxy.CommandResult;
                if (!cmd.Successful)
                {
                    DispatchMessagebox("Login to galaxy Failed :" + cmd.Text + " : " + cmd.CustomMessage);
                }
                else
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        new MainWindow(grAccess, galaxy).Show();
                        this.Close();
                        return;
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Ejemplo n.º 9
0
        //получение Galaxy по имени
        public static IGalaxy GetGalaxy(string galaxyName, string nodeName)
        {
            if (string.IsNullOrEmpty(galaxyName))
            {
                throw new ArgumentException(nameof(galaxyName));
            }
            _grAccessApp = null;
            _grAccessApp = new GRAccessApp();
            var galaxies = _grAccessApp.QueryGalaxies(nodeName);

            GalaxyExceptions.ThrowIfNoSuccess(_grAccessApp.CommandResult);
            IGalaxy galaxy = galaxies[galaxyName];

            GalaxyExceptions.ThrowIfNoSuccess(_grAccessApp.CommandResult);
            return(galaxy == null ? throw new GalaxyObjectNotFoundException(galaxyName) : galaxy);
        }
Ejemplo n.º 10
0
        public void TargetObject(IGalaxy galaxy, Position pos)
        {
            var previous = SelectedObject;
            var target   = galaxy.ClosestSpaceObject(pos);

            if (target != null)
            {
                SelectedObject = target;
                Objects        = galaxy.GetSpaceObjectsAt(target.Position).ToArray();

                if (previous?.Position == target.Position)
                {
                    SelectedObject = Objects
                                     .SkipWhile(obj => obj.ObjectId != previous.ObjectId)
                                     .Skip(1)
                                     .FirstOrDefault();
                }

                OnChange();
            }
        }
Ejemplo n.º 11
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            galaxy = galaxies[galaxyList.SelectedItem.ToString()];
            if (checkBox1.Checked)
            {
                galaxy.Login(textBox1.Text, textBox2.Text);
            }
            else
            {
                galaxy.Login("", "");
            }

            cmdResult = galaxy.CommandResult;
            if (!cmdResult.Successful)
            {
                MessageBox.Show("Failed to login, have you set your authentication correctly?");
                _loggedIn = false;
            }
            else
            {
                _loggedIn = true;

                GetAllObjects();
                objectView.Columns.Add("original", "Original");
                objectView.Columns.Add("renamed", "Re-named");
                objectView.Columns.Add("checkedout", "Checked Out");
                objectView.Columns.Add("template", "Template");

                foreach (var item in myObjects)
                {
                    objectView.Rows.Add(item.objectName, item.objectRename, item.checkedOut, item.template);
                }

                //objectView.DataSource = myObjects;
                //objectView.Refresh();
            }
        }
Ejemplo n.º 12
0
    public void Main(IGalaxy galaxy, Transaction init)
    {
        galaxy.LogInfo ("Script running");

        // Create and send lifesign transaction to SM_A
        Transaction trans = new Transaction ();
        trans.tptf.Session = galaxy.Session;
        trans.tptf.DestComp = "SM_A";
        trans.tptf.DestFunc = "LIFE";

        // Just add some FICS data
        trans.fics.Add ("aString", "abc");
        trans.fics.Add ("anInteger", 123);

        uint id = galaxy.Send (trans);
        trans = galaxy.Wait (id);

        if (!trans.Ok) {
            trans.Dump ();
            galaxy.LogError ("Transaction failed(result = {0}", trans.tptf.Result);
        }

        galaxy.LogInfo ("Script done");
    }
Ejemplo n.º 13
0
 private void button2_Click(object sender, EventArgs e)
 {
     if (comboGalaxy.Text != "")
     {
         toolStripStatusLabel1.Text = "Attempting to login...";
         IGalaxy galaxy = galaxies[comboGalaxy.Text];
         galaxy.Login(grUser, grPass);
         if (!galaxy.CommandResult.Successful)
         {
             loggedIn = false;
             toolStripStatusLabel1.Text = "Failed to log into galaxy - " + galaxy.CommandResult.Text;
         }
         else
         {
             loggedIn = true;
             toolStripStatusLabel1.Text = "Logged in successfully";
         }
     }
     else
     {
         loggedIn = false;
         toolStripStatusLabel1.Text = "Please select a galaxy.";
     }
 }
Ejemplo n.º 14
0
 public static IEnumerable <ISpaceObject> GetSpaceObjects(this IGalaxy galaxy)
 {
     return(galaxy.Planets
            .Cast <ISpaceObject>()
            .Concat(galaxy.Fleets));
 }
Ejemplo n.º 15
0
        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();
        }
Ejemplo n.º 16
0
 public cObjectList(IGalaxy galaxy, string grNodeName)
 {
     _galaxy     = galaxy;
     _grNodeName = grNodeName;
 }
Ejemplo n.º 17
0
 public cObjectList(IGalaxy galaxy)
 {
     _galaxy = galaxy;
 }
Ejemplo n.º 18
0
 public static IPlanet ClosestPlanet(this IGalaxy galaxy, Position target)
 {
     return(galaxy.Planets
            .OrderBy(planet => target.DistanceTo(planet.Position))
            .First());
 }
Ejemplo n.º 19
0
        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();
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            string        node;
            string        galaxyName;
            string        galaxyUser;
            string        galaxyPass;
            List <string> protectedTemplates = new List <string>();
            string        line;


            Console.Write("Enter Galaxy Node name: ");
            node = Console.ReadLine();
            Console.Write("Enter Galaxy Name: ");
            galaxyName = Console.ReadLine();
            Console.Write("Enter Galaxy Username: "******"Enter Galaxy Password: "******"protectedObjects.txt");

            while ((line = file.ReadLine()) != null)
            {
                protectedTemplates.Add(line.ToLower());
            }

            try
            {
                log.Info("Attempting to connect to " + galaxyName + " using a username of " + galaxyUser);
                GRAccessApp grAccess = new GRAccessAppClass();

                IGalaxies gals = grAccess.QueryGalaxies(node);
                log.Info("Found " + gals.count + " galaxies");
                IGalaxy galaxy = gals[galaxyName];
                log.Info("Attempting to log into galaxy");
                galaxy.Login(galaxyUser, galaxyPass);

                IgObjects objs = galaxy.QueryObjects(EgObjectIsTemplateOrInstance.gObjectIsTemplate, EConditionType.NameEquals, "thisshouldnevermatch", EMatch.NotMatchCondition);

                log.Info("Found " + objs.count + " objects");

                int x = 0;
                foreach (ITemplate template in objs)
                {
                    IgObjects derivedtemplates = galaxy.QueryObjects(EgObjectIsTemplateOrInstance.gObjectIsTemplate, EConditionType.derivedOrInstantiatedFrom, template.Tagname, EMatch.MatchCondition);
                    IgObjects derivedinstances = galaxy.QueryObjects(EgObjectIsTemplateOrInstance.gObjectIsInstance, EConditionType.derivedOrInstantiatedFrom, template.Tagname, EMatch.MatchCondition);
                    log.Info("Checking " + template.Tagname + " for derived templates");
                    if (derivedtemplates.count == 0)
                    {
                        log.Info(template.Tagname + " has no derived templates, checking instances now");
                        if (derivedinstances.count == 0)
                        {
                            if (!protectedTemplates.Contains(template.Tagname.ToLower()))
                            {
                                log.Info(template.Tagname + " has no instances, this template will be removed from the galaxy");
                                x++;
                                template.DeleteTemplate();
                            }
                            else
                            {
                                log.Info(template.Tagname + " has no instances but is a protected object so will not be deleted");
                            }
                        }
                    }
                }

                galaxy.Logout();

                Console.WriteLine("Finished. {0} objects deleted, press return to exit", x.ToString());
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 21
0
 public static ISpaceObject?GetSpaceObject(this IGalaxy galaxy, string objectId)
 {
     return(galaxy.GetSpaceObjects().SingleOrDefault(obj => obj.ObjectId == objectId));
 }
Ejemplo n.º 22
0
 public static IFleet ClosestFleet(this IGalaxy galaxy, Position target)
 {
     return(galaxy.Fleets
            .OrderBy(fleet => target.DistanceTo(fleet.Position))
            .FirstOrDefault());
 }
Ejemplo n.º 23
0
 public static ISpaceObject ClosestSpaceObject(this IGalaxy galaxy, Position target)
 {
     return(galaxy.GetSpaceObjects()
            .OrderBy(obj => target.DistanceTo(obj.Position))
            .FirstOrDefault());
 }
Ejemplo n.º 24
0
 //Создание Galaxy
 public GalaxyUtils(string galaxyName, bool createIfNotExist = false, string hostname = null, string templateName = null)
 {
     _galaxy = RelateToGalaxy(galaxyName, createIfNotExist, hostname);
 }
Ejemplo n.º 25
0
 public static IEnumerable <ISpaceObject> GetSpaceObjectsAt(this IGalaxy galaxy, Position position)
 {
     return(galaxy.GetSpaceObjects()
            .Where(obj => obj.Position == position));
 }
Ejemplo n.º 26
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.º 27
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);
        }
Ejemplo n.º 28
0
 public caaExport(IGalaxy Galaxy)
 {
     this.Galaxy = Galaxy;
 }