Beispiel #1
0
//INTERFACE
    /// <summary>
    /// Load statistics configuration from given file.
    /// Creates gatheres writing configuration to files.
    /// </summary>
    /// <param name="statisticsFileName">Name of file to read configuration from.</param>
    public static void Load(string statisticsFileName)
    {
        string progressText = string.Format("Reading statistics gatherers from {0}.", Configuration.Files.StatisticsFile);

        ProgressLogger.Starting(progressText);
        gatherers = new List <Gatherer>();
        XmlDocument document = new XmlDocument();

        document.Load(statisticsFileName);
        XmlNode main = document[statisticsTag];

        foreach (XmlNode node in main.ChildNodes)
        {
            switch (node.Name)
            {
            case Gatherer.GathererTag:
                gatherers.Add(Gatherer.Create(node));
                break;

            default:
                throw new ArgumentException("Unknown XML node: " + node.Name);
            }
        }
        ProgressLogger.Finished(progressText);
    }
Beispiel #2
0
//HELPERS
    static void loadElements()
    {
        string progressText = string.Format("Loading network elements from {0}.", Configuration.Files.NetworkFile);

        ProgressLogger.Starting(progressText);
        XmlDocument document = new XmlDocument();

        document.Load(Configuration.Files.NetworkFile);
        XmlNode network = XmlParser.GetChildNode(document, networkTag);

        foreach (XmlNode element in network.ChildNodes)
        {
            switch (element.Name)
            {
            case Node.NodeTag:
                new Node(element);
                break;

            case Link.LinkTag:
                new Link(element);
                break;

            default:
                XmlParser.ThrowUnknownNode(element);
                break;
            }
        }
        ProgressLogger.Finished(progressText);
    }
Beispiel #3
0
        // This method is used to login using the credentials captured from UI after assigning the account
        public bool LogInUsingCredsAfterAssignAccount(ProgressLogger logger, string userName, string userPassword)
        {
            bool flag = false;

            try
            {
                UserSetFunctions.EnterText(GenericUtils.WaitForElementPresence(driver, userLoginName, 15), userName);
                UserSetFunctions.EnterText(GenericUtils.WaitForElementPresence(driver, userLoginPassword, 15), userPassword);
                UserSetFunctions.Click(GenericUtils.WaitForElementPresence(driver, userLoginButton, 15));
                if (driver.Title.ToLower().Equals(apexWebTitle.ToLower()))
                {
                    flag = true;
                }

                if (flag)
                {
                    logger.LogCheckPoint(String.Format(LogMessage.VerifyLoginAfterAssignAccountPassed, userName));
                    Thread.Sleep(2000);
                    LogOut();
                }
                else
                {
                    logger.LogCheckPoint(String.Format(LogMessage.VerifyLoginAfterAssignAccountFailed, userName));
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(flag);
        }
Beispiel #4
0
 private string UserLogin(ProgressLogger logger, string userName, string userServerName, bool changeServerOnly = false)
 {
     try
     {
         string defaultSelectedServer;
         username = data.UserPortal.Users[userName].UserName;
         password = data.UserPortal.Users[userName].Password;
         IWebElement   serverWebElement = driver.FindElement(selectServer);
         SelectElement selectObj        = new SelectElement(serverWebElement);
         defaultSelectedServer = selectObj.SelectedOption.Text;
         Thread.Sleep(1000);
         if (!(userServerName.Equals(defaultSelectedServer)))
         {
             UserSetFunctions.SelectDropdown(serverWebElement, userServerName);
         }
         Thread.Sleep(1000);
         if (changeServerOnly)
         {
             return(null);
         }
         UserSetFunctions.EnterText(GenericUtils.WaitForElementPresence(driver, userLoginName, 15), username);
         UserSetFunctions.EnterText(GenericUtils.WaitForElementPresence(driver, userLoginPassword, 15), password);
         UserSetFunctions.Click(GenericUtils.WaitForElementPresence(driver, userLoginButton, 15));
         Assert.Equal(driver.Title.ToLower(), apexWebTitle.ToLower());
         logger.LogCheckPoint(string.Format(LogMessage.UserLoggedInSuccessfully, username));
         Thread.Sleep(2000);
         return(username);
     }
     catch (Exception)
     {
         throw;
     }
 }
Beispiel #5
0
    /// <summary>
    /// Runs event loop till either current time is greater than passed endTime or there are no more scheduled events.
    /// </summary>
    /// <param name="endTime">Simulation time indicating when to stop simulation.</param>
    public static void Run()
    {
        whenStarted = DateTime.Now;
        const string progressText = "Simulating.";
        ProgressLogger.Starting(progressText);
        ProgressLogger.Progress();
        lastShown = DateTime.Now;
        while(events.Count>0 && currentTime <= simulationTime)
        {
            //show progress
            if (lastShown + showingDelay < DateTime.Now)
            {
                ProgressLogger.Progress();
                lastShown = DateTime.Now;
            }
            ++loopNumber;

            //next event;

            TimerEntryImplementation entry = events.DeleteMin();
            currentTime = entry.Time;
            entry.Method(entry);
        }
        if (events.Count == 0)
        {
            Console.WriteLine("No more events to handle.");
        }
        if (currentTime > simulationTime)
        {
            Console.WriteLine("Simulation came to its end time.");
        }
        ProgressLogger.Finished(progressText);
    }
        //This method will login to admin portal
        public void AdminLogIn(ProgressLogger logger, string userName = Const.ADMIN1)
        {
            try
            {
                username = data.AdminPortal.Users[userName].UserName;
                password = data.AdminPortal.Users[userName].Password;
                string userUrl        = data.AdminPortal.PortalUrl;
                string userServerName = data.AdminPortal.PortalServerUrl;

                driver.Navigate().GoToUrl(userUrl);
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
                driver.Manage().Window.Size = new Size(1366, 768);

                UserSetFunctions.EnterText(AdminUserName(), username);
                UserSetFunctions.EnterText(AdminUserPassword(), password);
                UserSetFunctions.Click(AdminSignIn());
                Assert.Equal(driver.Title.ToLower(), Const.AdminLoginTitle.ToLower());
                logger.LogCheckPoint(String.Format(LogMessage.AdminLoginSuccessfullMsg, userName));
                Thread.Sleep(2000);
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #7
0
        // This method is used to login using the credentials captured from UI after unassigning the account
        public bool LogInUsingCredsAfterUnassignAccount(ProgressLogger logger, string userName, string userPassword)
        {
            bool flag = false;

            try
            {
                UserSetFunctions.EnterText(GenericUtils.WaitForElementPresence(driver, userLoginName, 15), userName);
                UserSetFunctions.EnterText(GenericUtils.WaitForElementPresence(driver, userLoginPassword, 15), userPassword);
                UserSetFunctions.Click(GenericUtils.WaitForElementPresence(driver, userLoginButton, 15));

                //When trying to login using credential after unassigining the account then page is showing blank
                //So in case we have used below condition to check login.
                //Once login failed error messges shows then use below comment code in if condition
                //LoginErrorMsg().Text.Equals(Const.LoginErrroMsg)
                if (driver.Title.ToLower().Equals(apexWebTitle.ToLower()))
                {
                    flag = true;
                }

                if (flag)
                {
                    logger.LogCheckPoint(String.Format(LogMessage.VerifyLoginAfterUnassignAccountPassed, userName));
                }
                else
                {
                    logger.LogCheckPoint(String.Format(LogMessage.VerifyLoginAfterUnassignAccountFailed, userName));
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(flag);
        }
Beispiel #8
0
    public static void ShutDown()
    {
        const string progressText = "Shutting down network.";

        ProgressLogger.Starting(progressText);
        identificables.Clear();
        ProgressLogger.Finished(progressText);
    }
Beispiel #9
0
//INTERFACE
    /// <summary>
    /// Some parameters can be passed in console command. Analyze them here before moving to reading configuration from XML files.
    /// </summary>
    /// <param name="arguments">Aguments passed to Main method.</param>
    public static void AnalyzeConsoleInput(string[] arguments)
    {
        const string progressText = "Analyzing console arguments.";

        ProgressLogger.Starting(progressText);
        Files.AnalyzeConsoleArguments(arguments);
        ProgressLogger.Finished(progressText);
    }
Beispiel #10
0
//HELPERS
    static void Main(string[] arguments)
    {
        try
        {
            //set some console parameters and write a big "Welcome" :)
            Console.ForegroundColor = ConsoleColor.White;
            Console.BackgroundColor = ConsoleColor.Black;
            Console.WriteLine("Welcome to {0}!", programName);
            Console.WriteLine();
            //the default color of displayed informations is green
            Console.ForegroundColor = ConsoleColor.Green;

            string progressText = "Running application.";
            ProgressLogger.Starting(progressText);

            //load all services
            Configuration.AnalyzeConsoleInput(arguments);
            Configuration.Load(Configuration.Files.ConfigurationFile);
            Timer.SimulationTime = Configuration.Simulation.SimulationTime;
            Logger.Initialize(Configuration.Files.LogFile);
            Network.Load(Configuration.Files.NetworkFile);
            Statistics.Load(Configuration.Files.StatisticsFile);

            //run simulation
            Timer.Run();

            //shut down all services
            Statistics.ShutDown();
            Network.ShutDown();
            Logger.ShutDown();

            //log end
            ProgressLogger.Finished(progressText);
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Bye!");
        }
#if (!DEBUG)
        catch (Exception exception)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("An exception occured:");
            Console.WriteLine();
            Console.WriteLine(exception.Message);
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine(exception.StackTrace);
            Logger.ShutDown();
        }
#endif
        finally
        {
            //reset console to normal state
            Console.ResetColor();
        }
    }
Beispiel #11
0
    public static void Initialize(string logFileName)
    {
        const string progressText = "Initializing logging.";

        ProgressLogger.Starting(progressText);
        logFile           = new StreamWriter(logFileName, false);
        logFile.AutoFlush = true;
        ProgressLogger.Finished(progressText);
    }
 /// <summary>
 /// Writes the limits to the sdf file
 /// </summary>
 /// <param name="log">logger to write messages to</param>
 /// <param name="writer">the writer to write the file with</param>
 protected override void WriteLimits(ProgressLogger log, XmlWriter writer)
 {
     writer.WriteStartElement("limit");
     {
         SDFExporter.writeSDFElement(writer, "upper", (UpperLimit*ThreadPitch).ToString());
         SDFExporter.writeSDFElement(writer, "lower", (LowerLimit*ThreadPitch).ToString());
         SDFExporter.writeSDFElement(writer, "effort", EffortLimit.ToString());
     }
     writer.WriteEndElement();
 }
Beispiel #13
0
//INTERFACE
    public static void Load(string networkFileName)
    {
        const string progressText = "Loading network.";

        ProgressLogger.Starting(progressText);
        loadElements();
        connectElements();
        configureElements();
        ProgressLogger.Finished(progressText);
    }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (disposing)
            {
                if (_logger != null)
                    _logger.Dispose();
                _logger = null;
            }
        }
        // Login with a user and cancell all placed orders
        public static void LoginAndCancelAllOrders(ProgressLogger logger, IWebDriver driver, string instrument, string loginUser)
        {
            UserFunctions userFunctions = new UserFunctions(logger);

            userFunctions.LogIn(logger, loginUser);
            Thread.Sleep(2000);
            DashBoardMenuButton(driver);
            SelectAnExchange(driver);
            SelectInstrumentFromExchange(instrument, driver);
            CancelAllOrders(driver);
        }
Beispiel #16
0
        public static void PrintUpdateInfo()
        {
            try
            {
//                ProgramLog.Log ("Attempting to retreive Build Info...");

                var buildInfo = String.Empty;
                using (var ctx = new WebClient())
                {
                    using (var prog = new ProgressLogger(100, "Downloading build information..."))
                    {
                        var signal = new System.Threading.AutoResetEvent(false);

                        ctx.DownloadProgressChanged += (sender, args) =>
                        {
                            prog.Value = args.ProgressPercentage;
                        };

                        ctx.DownloadStringCompleted += (sender, args) =>
                        {
                            var arg = args as DownloadStringCompletedEventArgs;
                            buildInfo = arg.Result;

                            signal.Set();
                        };

                        ctx.DownloadStringAsync(new Uri(UpdateInfo));

                        signal.WaitOne();
                    }
                }

                if (String.IsNullOrEmpty(buildInfo))
                {
                    ProgramLog.Log("Failed to download build information.");
                    return;
                }

                var toString = "comments: ";
                //if (buildInfo.ToLower().Contains(toString))
                var index = buildInfo.ToLower().IndexOf(toString);
                if (index != -1)
                {
                    buildInfo = buildInfo.Remove(0, index + toString.Length).Trim();
                    foreach (var pair in BuildInfoReplacements)
                    {
                        buildInfo = buildInfo.Replace(pair.Key, pair.Value);
                    }

                    ProgramLog.Log("Build Comments: \n\t " + buildInfo);
                }
            }
            catch (Exception) { }
        }
Beispiel #17
0
    static void connectElements()
    {
        const string progressText = "Connecting network elements.";

        ProgressLogger.Starting(progressText);
        foreach (IConnectable connectable in connectables)
        {
            connectable.Connect();
        }
        connectables = null;//free memory
        ProgressLogger.Finished(progressText);
    }
Beispiel #18
0
    /// <summary>
    /// Shuts down all gatheres (saves data in buffers).
    /// </summary>
    public static void ShutDown()
    {
        const string progressText = "Shutting down statistics gatherers.";

        ProgressLogger.Starting(progressText);
        foreach (Gatherer gatherer in gatherers)
        {
            gatherer.Close();
        }
        gatherers = null;
        ProgressLogger.Finished(progressText);
    }
Beispiel #19
0
    public static void ShutDown()
    {
        const string progressText = "Shutting down logging.";

        ProgressLogger.Starting(progressText);
        if (logFile != null)
        {
            logFile.Close();
            logFile = null;
        }
        ProgressLogger.Finished(progressText);
    }
Beispiel #20
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (disposing)
            {
                if (_logger != null)
                {
                    _logger.Dispose();
                }
                _logger = null;
            }
        }
        /*public static BackupResult LoadWorld(string Name)
         * {
         *  WorldIO.LoadWorld(null, null, Statics.WorldPath + Path.DirectorySeparatorChar + Name);
         *  if (WorldModify.loadFailed && !WorldModify.loadSuccess)
         *  {
         *      return BackupResult.LOAD_FAIL;
         *  }
         *  return BackupResult.SUCCESS;
         * }*/

        public static BackupResult Compress(string worldPath)
        {
//            Stopwatch stopwatch = new Stopwatch();
//            stopwatch.Start();
//
//            ProgramLog.Log("Compressing backup...");

            if (!File.Exists(worldPath))
            {
                ProgramLog.Error.Log("File not Found: " + worldPath);
                return(BackupResult.LOAD_FAIL);
            }

            using (var pg = new ProgressLogger(1, "Compressing backup"))
            {
                FileInfo world       = new FileInfo(worldPath);
                String   archivePath = String.Concat(worldPath, ".zip");

                using (FileStream inStream = world.OpenRead())
                {
                    using (FileStream outStream = File.Create(archivePath))
                    {
                        using (GZipStream alg = new GZipStream(outStream, CompressionMode.Compress))
                        {
                            // copy the input file into the compression stream
                            inStream.CopyTo(alg);
                        }
                    }
                }

                if (File.Exists(archivePath))
                {
                    if (File.Exists(worldPath))
                    {
                        File.Delete(worldPath);
                    }
                    //                    stopwatch.Stop();

                    pg.Value = 1;
//                    ProgramLog.Log("Compression duration: " + stopwatch.Elapsed.Seconds + " Second(s)");
                    return(BackupResult.SUCCESS);
                }
            }
//                else
//                {
//                    stopwatch.Stop();
            ProgramLog.Error.Log("Compression Failed!");
            return(BackupResult.SAVE_FAIL);
//                }
        }
 //This method returns the Success and Failure messages
 public static string GetTextOfMessage(IWebDriver driver, ProgressLogger logger)
 {
     try
     {
         IWebElement msgWebElement = GenericUtils.WaitForElementVisibility(driver, messageDisplayed, 10);
         string      messageText   = msgWebElement.Text;
         return(messageText);
     }
     catch (Exception e)
     {
         logger.Error(LogMessage.FailedToRetrieveMessage, e);
         logger.Error(e.StackTrace);
         throw;
     }
 }
 //This method closes the Advanced Order Section
 public static void CloseAdvancedOrderSection(IWebDriver driver, ProgressLogger logger)
 {
     try
     {
         IWebElement closeAdvanced = GenericUtils.WaitForElementVisibility(driver, closeIconAdvancedOrder, 30);
         UserSetFunctions.Click(closeAdvanced);
         Thread.Sleep(2000);
     }
     catch (Exception e)
     {
         logger.Error(LogMessage.CloseAdvanceOrderSectFailureMsg, e);
         logger.Error(e.StackTrace);
         throw;
     }
 }
 //This method returns the text of toast message in Admin
 public static string GetTextOfToastMessageInAdmin(IWebDriver driver, ProgressLogger logger)
 {
     try
     {
         IWebElement msgWebElement = GenericUtils.WaitForElementPresence(driver, toastMessageAdmin, 20);
         string      messageText   = msgWebElement.Text;
         return(messageText);
     }
     catch (Exception e)
     {
         logger.Error(LogMessage.FailedToRetrieveMessage, e);
         logger.Error(e.StackTrace);
         throw;
     }
 }
Beispiel #25
0
    static void configureElements()
    {
        const string progressText = "Configuring network elements.";

        ProgressLogger.Starting(progressText);
        foreach (Identificable identificable in identificables.Values)
        {
            IConfigurable configurable = identificable as IConfigurable;
            if (configurable != null)
            {
                Logger.Log(identificable, "Configuring.");
                configurable.Configure();
            }
        }
        ProgressLogger.Finished(progressText);
    }
Beispiel #26
0
        //This method is used for User Login
        //If the user is already logged in, then this method logs out user and then logs in
        public string LogIn(ProgressLogger logger, string userName = Const.USER5, bool changeServerOnly = false)
        {
            string username = null;

            apexWebTitle = TestData.GetData("HomePageTitle");
            string userUrl        = data.UserPortal.PortalUrl;
            string userServerName = data.UserPortal.PortalServerUrl;

            driver.Navigate().GoToUrl(userUrl);
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
            driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(20);
            driver.Manage().Window.Size = new Size(1366, 768);
            Thread.Sleep(1000);
            if (driver.Url.EndsWith(Const.LoginText))
            {
                try
                {
                    username = UserLogin(logger, userName, userServerName, changeServerOnly);
                }
                catch (Exception e)
                {
                    logger.TakeScreenshot();
                    logger.Error(Const.UserLoginFailed, e);
                    throw e;
                }
            }
            else
            {
                try
                {
                    driver.Navigate().Refresh();
                    Thread.Sleep(2000);
                    UserSetFunctions.Click(GenericUtils.WaitForElementVisibility(driver, loggedInUserName, 30));
                    UserSetFunctions.Click(GenericUtils.WaitForElementVisibility(driver, userSignOutButton, 30));
                    Thread.Sleep(2000);
                    username = UserLogin(logger, userName, userServerName, changeServerOnly);
                }

                catch (Exception e)
                {
                    logger.Error(Const.UserLogoutFailed, e);
                    throw e;
                }
            }
            return(username);
        }
        public static BackupResult SaveWorld(string path)
        {
            if (Terraria.WorldGen.saveLock)
            {
                return(BackupResult.SAVE_LOCK);                            //Please wait for the current operation to finish.
            }
            try
            {
                using (var pg = new ProgressLogger(1, "Backing up world"))
                {
                    if (CopyBackups)
                    {
                        var copyFrom = Terraria.Main.ActiveWorldFileData.Path;
                        if (File.Exists(copyFrom))
                        {
                            File.Copy(copyFrom, path);
                        }
                    }
                    else
                    {
                        lock (OTA.Callbacks.WorldFileCallback.SavePathLock)
                        {
                            OTA.Callbacks.WorldFileCallback.SavePath = path;
                            Terraria.IO.WorldFile.saveWorld();
                            OTA.Callbacks.WorldFileCallback.SavePath = null; //Reset
                        }
                    }
                    pg.Value = 1;
                }

                if (CompressBackups)
                {
                    Compress(path); // it just adds ".zip" to the timestamp+".wld"
                }
                return(BackupResult.SUCCESS);
            }
            catch (Exception e)
            {
                ProgramLog.Log(e, "Error during the save process.");
            }

            return(BackupResult.SAVE_FAIL);
        }
        /// <summary>
        /// Exports the .stl model for one link
        /// The model must already be switched to the correct configuration and all parts must be hidden before this method is called
        /// </summary>
        /// <param name="link">Link to be exported</param>
        /// <param name="configuration">The configuration that this link should be exported from</param>
        /// <param name="path">The path to save the .stl file</param>
        /// <param name="log">The logger to write messages to</param>
        public void ExportLink(Link link ,ModelConfiguration configuration, String path, ProgressLogger log)
        {
            log.WriteMessage("Exporting link " + link.Name + " as an STL. Configuration: " + ((ModelConfiguration.ModelConfigType)configuration.Type) + "; Path: " + path, false);

            int errors = 0;
            int warnings = 0;

            ModelDoc2 ActiveDoc = (ModelDoc2)asm;

            IsolateLink(link, configuration);

            int saveOptions = (int)swSaveAsOptions_e.swSaveAsOptions_Silent;

            ActiveDoc.Extension.SaveAs(path, (int)swSaveAsVersion_e.swSaveAsCurrentVersion, saveOptions, null, ref errors, ref warnings);

            HideLink(link);

            log.WriteMessage("Correcting STL header");
            CorrectSTLMesh(path);
            log.WriteMessage("Finished exporting STL.");
        }
Beispiel #29
0
    /// <summary>
    /// Main configuraiton is read from an XML file.
    /// All variables have their default values that can be overwritten by values found in configuration.
    /// No XML nodes are obligatory(except the main node), all are analyzed when found.
    /// </summary>
    /// <param name="configurationFileName">Name of file to read configuration from.</param>
    public static void Load(string configurationFileName)
    {
        string progressText = string.Format("Reading configuration from {0}.", configurationFileName);

        ProgressLogger.Starting(progressText);

        XmlDocument xmlDocument = new XmlDocument();

        xmlDocument.Load(configurationFileName);
        XmlNode configuration = XmlParser.GetChildNode(xmlDocument, configurationTag);

        //find intresting elements and pass XML nodes to them
        XmlNode files = configuration[Files.FilesTag];

        if (files != null)
        {
            Files.Configure(files);
        }
        XmlNode protocols = configuration[Protocols.ProtocolsTag];

        if (protocols != null)
        {
            Protocols.Configure(protocols);
        }
        XmlNode network = configuration[Network.NetworkTag];

        if (network != null)
        {
            Network.Configure(network);
        }

        XmlNode simulation = configuration[Simulation.SimulationTag];

        if (simulation != null)
        {
            Simulation.Configre(simulation);
        }

        ProgressLogger.Finished(progressText);
    }
        public static void AutoPurge(string worldName)
        {
            if (!ExpirationsEnabled)
            {
                return;
            }

//            ProgramLog.Log("Performing backup purge...");
            var backups = GetBackups(worldName);

            if (backups != null && backups.Length > 0)
            {
                using (var pg = new ProgressLogger(backups.Length, "Purging old backups"))
                {
                    var expired = (from x in backups
                                   where (DateTime.Now - File.GetCreationTime(x)).TotalMinutes >= BackupExpiryMinutes
                                   select x).ToArray();
                    //var deleted = 0;
                    foreach (var file in expired)
                    {
                        try
                        {
                            File.Delete(file);
                            //deleted++;
                        }
                        catch
                        {
                        }
                    }
                }
            }
            else
            {
                ProgramLog.Log("No backups to be purged.");
            }
        }
Beispiel #31
0
        internal static void OnUpdate()
        {
            if ((DateTime.Now - _lastSave).TotalMinutes >= SaveIntervalMinutes)
            {
                _lastSave = DateTime.Now;

                try
                {
                    lock (OTA.Callbacks.WorldFileCallback.SavePathLock)
                    {
                        using (var pg = new ProgressLogger(1, "Saving world"))
                        {
                            OTA.Callbacks.WorldFileCallback.SavePath = null; //Clear, and use the default
                            Terraria.IO.WorldFile.saveWorld();
                            pg.Value = 1;
                        }
                    }
                }
                catch (Exception e)
                {
                    ProgramLog.Log(e, "Error during the world save process");
                }
            }
        }
 /// <summary>
 /// Verifies that everything is good in the attachment
 /// </summary>
 /// <param name="log">Logger to output messages to</param>
 /// <returns>true if successfully verified</returns>
 public override bool Verify(ProgressLogger log)
 {
     log.WriteMessage("Verifying " + Name);
     return true;
 }
        private static string[] InstallUpdate(string path)
        {
            //Extract ZIP's into a seperate folder
            //Install everything else as a plugin

            var info = new FileInfo(path);

            var ext = info.Extension.ToLower();
            if (ext == ".zip")
            {
                //Extract into a temporary directory incase of zip exceptions that could potentially corrupt our installation
                var tmp = ExtractZip(info);
                if (!String.IsNullOrEmpty(tmp))
                {
                    //Read package
                    var pkgFile = Path.Combine(tmp, "package.json");
                    if (File.Exists(pkgFile))
                    {
                        var pkg = Newtonsoft.Json.JsonConvert.DeserializeObject<UpdatePackage>(File.ReadAllText(pkgFile));
                        if (pkg != null && pkg.Instructions != null && pkg.Instructions.Length > 0)
                        {
                            //Verify first then install
                            using (var logger = new ProgressLogger(pkg.Instructions.Length, "Verifying package"))
                            {
                                foreach (var ins in pkg.Instructions)
                                {
                                    if (String.IsNullOrEmpty(ins.PackageFileName)) throw new RepositoryError("Invalid source file");
                                    if (String.IsNullOrEmpty(ins.DestinationFileName)) ins.DestinationFileName = ins.PackageFileName; //If not provided then it means it's the same

                                    var relPath = ins.PackageFileName.Split(ins.DirectorySeperator);
                                    relPath = new string[] { tmp }.Concat(relPath).ToArray();
                                    var from = Path.Combine(relPath);

                                    if (!File.Exists(from)) throw new RepositoryError("Source file {0} does not exist", ins.PackageFileName);

                                    var toPath = ins.PackageFileName.Split(ins.DirectorySeperator);
                                    toPath = new string[] { Environment.CurrentDirectory }.Concat(toPath).ToArray();
                                    var to = Path.Combine(toPath);

                                    if (IsChild(to) == null) throw new RepositoryError("Destination file {0} is not within the TDSM install directory", ins.DestinationFileName);
                                }
                            }

                            using (var logger = new ProgressLogger(pkg.Instructions.Length, "Installing package"))
                            {
                                foreach (var ins in pkg.Instructions)
                                {
                                    var relPath = ins.PackageFileName.Split(ins.DirectorySeperator);
                                    relPath = new string[] { tmp }.Concat(relPath).ToArray();
                                    var from = Path.Combine(relPath);

                                    var toPath = ins.PackageFileName.Split(ins.DirectorySeperator);
                                    toPath = new string[] { Environment.CurrentDirectory }.Concat(toPath).ToArray();
                                    var to = IsChild(Path.Combine(toPath));

                                    if (File.Exists(to)) File.Delete(to);
                                    File.Move(from, to);
                                }
                            }

                            ProgramLog.Admin.Log("Cleaning up");
                            Directory.Delete(tmp, true);
                            File.Delete(path);

                            return pkg.PluginsToLoad;
                        }
                        else
                        {
                            throw new RepositoryError("No install instructions");
                        }
                    }
                    else
                    {
                        throw new RepositoryError("package.json is missing");
                    }
                }
                else
                {
                    throw new RepositoryError("Failed to extract package");
                }
            }
            else if (ext == ".lua" || ext == ".dll")
            {
                //Move and replace targets
                var dest = Path.Combine(Globals.PluginPath, info.Name);
                if (File.Exists(dest)) File.Delete(dest);
                File.Move(info.FullName, dest);

                return new string[] { dest };
            }
            else throw new RepositoryError("No package support for {0}", ext ?? "<unknown>");
        }
 /// <summary>
 /// Verifies that the joint is valid to export
 /// </summary>
 /// <param name="logger">The logger to write messages to</param>
 /// <returns>Returns true if succesfully verified</returns>
 protected override bool VerifySpecifics(ProgressLogger logger)
 {
     Axis1.Verify(joint.Name + " Axis1", logger);
     RobotInfo.WriteToLogFile("Successfully Verified Single Axis Joint");
     return true;
 }
 public override void WriteSensor(ProgressLogger log, XmlWriter output)
 {
 }
        /// <summary>
        /// Writes the Attachment to the URDF file
        /// </summary>
        /// <param name="log">Logger to write messages to</param>
        /// <param name="owner">The XMLWriter to use to write the values</param>
        public override void WriteElements(ProgressLogger log, XmlWriter owner)
        {
            owner.WriteStartElement("gazebo");
            owner.WriteStartElement("plugin");
            owner.WriteAttributeString("name", Name);
            owner.WriteAttributeString("filename", "libpotentiometer.so");

            owner.WriteStartElement("joint");
            owner.WriteString(Joint.Name);
            owner.WriteEndElement();

            owner.WriteStartElement("topic");
            owner.WriteString("/gazebo/frc/simulator/analog/" + AnalogChannel.ToString());
            owner.WriteEndElement();

            owner.WriteStartElement("units");
            owner.WriteString("degrees");
            owner.WriteEndElement();
            owner.WriteEndElement();
            owner.WriteEndElement();
        }
Beispiel #37
0
 public ProgressWebClient(string message)
 {
     _logger = new ProgressLogger(1, message);
 }
 /// <summary>
 /// Writes the Attachment to the SDF file
 /// </summary>
 /// <param name="log"></param>
 /// <param name="owner"></param>
 public override void WritePlugins(ProgressLogger log, XmlWriter owner)
 {
     owner.WriteStartElement("plugin");
     {
         owner.WriteAttributeString("name", Joint.Name + "_encoder");
         owner.WriteAttributeString("filename", "libencoder.so");
         SDFExporter.writeSDFElement(owner, "joint", Joint.Name.Replace(" ", "_"));
         SDFExporter.writeSDFElement(owner, "topic", "/gazebo/frc/simulator/dio/" + DioPinA.ToString() + "/" + DioPinB.ToString());
         SDFExporter.writeSDFElement(owner, "units", "degrees");
     }
     owner.WriteEndElement();
 }
        /// <summary>
        /// Exports the robot
        /// </summary>
        /// <param name="log"> Logger to be used to write messeges </param>
        /// <param name="path"> File path to export robot to </param>
        public override void Export(ProgressLogger log, String path)
        {
            this.log = log;
            path += "\\" + robot.Name +"_Exported";
            folderPath = path + "\\" + robot.Name;
            tempFilePath = folderPath +  "\\";
            visualSTLPath = folderPath + "\\visualSTL\\";
            collisionSTLPath = folderPath + "\\collisionSTL\\";
            if (Directory.Exists(path))
                Directory.Delete(path, true);
            Directory.CreateDirectory(path);
            Directory.CreateDirectory(folderPath);
            Directory.CreateDirectory(visualSTLPath);
            Directory.CreateDirectory(collisionSTLPath);
            try
            {
                log.WriteMessage("Setting up exporter", false);

                //Export STLs
                log.WriteMessage("Starting STL exports", false);
                ModelDoc2 ActiveDoc = (ModelDoc2)asm;
                //switchs to the visual configuration and hides all components
                Configuration currentConfig = ActiveDoc.ConfigurationManager.ActiveConfiguration;
                ActiveDoc.ShowConfiguration2(robot.VisualConfig);
                STLExporter meshMaker = new STLExporter(iSwApp, asm);
                Component2[] hiddenComps = meshMaker.HideAllComponents();
                //exports each Link's visual models
                foreach (Link L in robot.GetLinksAsArray())
                {
                    if (!robot.ContinueExport)
                    {
                        meshMaker.UnhideComponents(hiddenComps);
                        meshMaker.close();
                        ActiveDoc.ShowConfiguration2(currentConfig.Name);
                        return;
                    }
                    meshMaker.ExportLink(L, robot.VisualConfig, visualSTLPath + L.Name + ".stl", log);

                }
                //unhides all components, switches to collision configuration, then hides all components
                meshMaker.UnhideComponents(hiddenComps);
                ActiveDoc.ShowConfiguration2(robot.CollisionConfig);
                hiddenComps = meshMaker.HideAllComponents();
                //exports each Link's collision model
                foreach (Link L in robot.GetLinksAsArray())
                {
                    if (!robot.ContinueExport)
                    {
                        meshMaker.UnhideComponents(hiddenComps);
                        meshMaker.close();
                        ActiveDoc.ShowConfiguration2(currentConfig.Name);
                        return;
                    }
                    meshMaker.ExportLink(L, robot.CollisionConfig, collisionSTLPath + L.Name + ".stl", log);
                }
                //restores the model to its original configuration
                meshMaker.UnhideComponents(hiddenComps);
                ActiveDoc.ShowConfiguration(currentConfig.Name);
                meshMaker.close();
                log.WriteMessage("Finished exporting STL files", false);

                //Make URDF
                log.WriteMessage("Creating URDF file", false);
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Encoding = new UTF8Encoding(false);
                settings.Indent = true;
                settings.NewLineOnAttributes = false;
                XmlWriter URDFwriter = XmlWriter.Create(tempFilePath+robot.Name+".URDF", settings);
                URDFwriter.WriteStartDocument();
                WriteURDF(URDFwriter);
                URDFwriter.WriteEndDocument();
                URDFwriter.Close();
                log.WriteMessage("URDF file complete");
                CreateConfigFile();
                log.WriteMessage("Config file complete");
                log.WriteMessage("Export Complete");
            }
            catch (Exception e)
            {
                log.WriteError("Unhandled Exception thrown when exporting robot: "+e.Message);
            }
        }
 /// <summary>
 /// Writes the Attachment to the SDF file
 /// </summary>
 /// <param name="log"></param>
 /// <param name="owner"></param>
 public override void WritePlugins(ProgressLogger log, XmlWriter owner)
 {
     owner.WriteStartElement("plugin");
     {
         owner.WriteAttributeString("name", Joint.Name + "_motor");
         owner.WriteAttributeString("filename", "libdc_motor.so");
         SDFExporter.writeSDFElement(owner, "joint", Joint.Name.Replace(" ", "_"));
         SDFExporter.writeSDFElement(owner, "topic", "/gazebo/frc/simulator/pwm/" + this.PwmChannel.ToString());
         SDFExporter.writeSDFElement(owner, "multiplier", Multiplier.ToString());
     }
     owner.WriteEndElement();
 }
        /// <summary>
        /// Writes the Attachment to the URDF file
        /// </summary>
        /// <param name="log">Logger to write messages to</param>
        /// <param name="owner">The XMLWriter to use to write the values</param>
        public override void WriteElements(ProgressLogger log, XmlWriter owner)
        {
            owner.WriteStartElement("gazebo");
            owner.WriteStartElement("plugin");
            owner.WriteAttributeString("name", Name);
            owner.WriteAttributeString("filename", "libdc_motor.so");

            owner.WriteStartElement("joint");
            owner.WriteString(Joint.Name);
            owner.WriteEndElement();

            owner.WriteStartElement("topic");
            owner.WriteString("/gazebo/frc/simulator/pwm/" + PwmChannel.ToString());
            owner.WriteEndElement();

            owner.WriteStartElement("multiplier");
            owner.WriteString(Multiplier.ToString());
            owner.WriteEndElement();

            owner.WriteEndElement();
            owner.WriteEndElement();
        }
 /// <summary>
 /// Writes this joint to the SDF file
 /// </summary>
 /// <param name="log">The logger to write messages to</param>
 /// <param name="writer">The writer to use to write the SDF file</param>
 public override void WriteSDF(ProgressLogger log, XmlWriter writer)
 {
     Axes[0].WriteSDF(log, writer, 1);
     Axes[1].WriteSDF(log, writer, 2);
 }
 /// <summary>
 /// Verifies that the joint is valid for export
 /// </summary>
 /// <param name="log"></param>
 /// <returns></returns>
 protected override bool VerifySpecifics(ProgressLogger log)
 {
     Axes[0].Verify(joint.Name + " Axis1", log);
     Axes[1].Verify(joint.Name + " Axis2", log);
     RobotInfo.WriteToLogFile("Successfully Verified both Double Axis");
     return true;
 }
        /// <summary>
        /// Writes the Attachment to the URDF file
        /// </summary>
        /// <param name="log">Logger to write messages to</param>
        /// <param name="owner">The XMLWriter to use to write the values</param>
        public override void WriteElements(ProgressLogger log, XmlWriter owner)
        {
            owner.WriteStartElement("gazebo");
            owner.WriteStartElement("plugin");
            owner.WriteAttributeString("name", ChildLink.Name + " extlimit");
            owner.WriteAttributeString("filename", "liblimit_switch.so");

            owner.WriteStartElement("topic");
            owner.WriteString("/gazebo/frc/simulator/dio/" + dioChannel.ToString());
            owner.WriteEndElement();

            owner.WriteStartElement("type");
            owner.WriteString("external");
            owner.WriteEndElement();

            owner.WriteStartElement("sensor");
            owner.WriteString(ChildLink.Name);
            owner.WriteEndElement();

            owner.WriteEndElement();
            owner.WriteEndElement();

            base.WriteElements(log, owner);
        }
 /// <summary>
 /// Verifies that everything is good in the attachment
 /// </summary>
 /// <param name="log">Logger to output messages to</param>
 /// <returns>true if successfully verified</returns>
 public override bool Verify(ProgressLogger log)
 {
     log.WriteMessage("Verifying " + Name);
     if (TicksPerRev == 0)
         log.WriteWarning("Tick number not specified in " + Name);
     if (Joint == null)
         log.WriteError(Name + " must be associated with a joint.");
     return true;
 }
 /// <summary>
 /// Verifies the attachment
 /// </summary>
 /// <param name="log">Logger to print messages to</param>
 /// <returns>returns true if verified successfully</returns>
 public abstract bool Verify(ProgressLogger log);
        /// <summary>
        /// Writes the Attachment to the URDF file
        /// </summary>
        /// <param name="log">Logger to write messages to</param>
        /// <param name="owner">The XMLWriter to use to write the values</param>
        public override void WriteElements(ProgressLogger log, XmlWriter owner)
        {
            owner.WriteStartElement("gazebo");
            owner.WriteStartElement("plugin");
            owner.WriteAttributeString("name", Name);
            owner.WriteAttributeString("filename", "libencoder.so");

            owner.WriteStartElement("joint");
            owner.WriteString(Joint.Name);
            owner.WriteEndElement();

            owner.WriteStartElement("topic");
            owner.WriteString("/gazebo/frc/simulator/dio/" + DioPinA.ToString() + "/" + DioPinB.ToString());
            owner.WriteEndElement();

            owner.WriteStartElement("units");
            owner.WriteString("degrees");
            owner.WriteEndElement();
            owner.WriteEndElement();
            owner.WriteEndElement();
        }
 /// <summary>
 /// Writes the Attachment to the URDF file
 /// </summary>
 /// <param name="log">Logger to write messages to</param>
 /// <param name="output">The XMLWriter to use to write the values</param>
 public abstract void WriteElements(ProgressLogger log, XmlWriter output);
 public ProgressWebClient(string message)
 {
     _logger = new ProgressLogger(1, message);
 }
 public abstract void WritePlugins(ProgressLogger log, XmlWriter output);
 public override void Verify(string axisName, ProgressLogger log)
 {
     base.Verify(axisName, log);
     if (!IsContinuous && LowerLimit >= 0 && UpperLimit <= 0)
         log.WriteWarning("No movement defined in joint " + axisName);
 }
 public abstract void WriteSensor(ProgressLogger log, XmlWriter output);
 /// <summary>
 /// Writes the Attachment to the SDF file
 /// </summary>
 /// <param name="log"></param>
 /// <param name="owner"></param>
 public override void WritePlugins(ProgressLogger log, XmlWriter owner)
 {
     owner.WriteStartElement("plugin");
     {
         owner.WriteAttributeString("name", Joint.Name + "_pot");
         owner.WriteAttributeString("filename", "libpotentiometer.so");
         SDFExporter.writeSDFElement(owner, "joint", Joint.Name.Replace(" ","_"));
         SDFExporter.writeSDFElement(owner, "topic", "/gazebo/frc/simulator/analog/" + AnalogChannel.ToString());
         SDFExporter.writeSDFElement(owner, "units", "degrees");
     }
     owner.WriteEndElement();
 }
 /// <summary>
 /// Verifies that everything is good in the attachment
 /// </summary>
 /// <param name="log">Logger to output messages to</param>
 /// <returns>true if successfully verified</returns>
 public override bool Verify(ProgressLogger log)
 {
     log.WriteMessage("Verifying " + Name);
     if (Multiplier == 0)
         log.WriteWarning("No multiplier in " + Name);
     if (Joint == null)
         log.WriteError(Name + " must be associated with a joint.");
     return true;
 }
Beispiel #55
0
        public static bool PerformUpdate(string DownloadLink, string savePath, string backupPath, string myFile, int Update, int MaxUpdates, string header = "update ")
        {
            if (File.Exists(savePath))
            {
                try
                {
                    File.Delete(savePath);
                }
                catch (Exception e)
                {
                    ProgramLog.Log(e, "Error deleting old file");
                    return(false);
                }
            }

            if (File.Exists(myFile) && !MoveFile(myFile, backupPath))
            {
                ProgramLog.Log("Error moving current file!");
                return(false);
            }

            var       download = new System.Net.WebClient();
            Exception error    = null;

            string downloadText = "";

            if (MaxUpdates > 1)
            {
                downloadText = "Downloading " + header + Update.ToString() + "/" + MaxUpdates.ToString() + " from server";
            }
            else
            {
                downloadText = "Downloading " + header + "from server";
            }

            using (var prog = new ProgressLogger(100, downloadText))
            {
                var signal = new System.Threading.AutoResetEvent(false);

                download.DownloadProgressChanged += (sender, args) =>
                {
                    prog.Value = args.ProgressPercentage;
                };

                download.DownloadFileCompleted += (sender, args) =>
                {
                    error = args.Error;
                    signal.Set();
                };

                download.DownloadFileAsync(new Uri(DownloadLink), savePath);

                signal.WaitOne();
            }

            if (error != null)
            {
                ProgramLog.Log(error, "Error downloading update");
                return(false);
            }

            //Program.tConsole.Write("Finishing Update...");

            if (!MoveFile(savePath, myFile))
            {
                ProgramLog.Log("Error moving updated file!");
                return(false);
            }

            return(true);
        }
Beispiel #56
0
 /// <summary>
 /// Verifies that the joint is ready for export
 /// </summary>
 /// <returns>Returns true if succesfully verified</returns>
 public bool Verify(ProgressLogger log)
 {
     return jointSpecifics.Verify(log);
 }
 /// <summary>
 /// Writes this joint to the SDF file
 /// </summary>
 /// <param name="log">The logger to write messages to</param>
 /// <param name="writer">The writer to use to write the SDF file</param>
 public override void WriteSDF(ProgressLogger log, XmlWriter writer)
 {
     Axis1.WriteSDF(log,writer,1);
 }
Beispiel #58
0
 /// <summary>
 /// Writes the SDF file for the joint
 /// </summary>
 /// <param name="log">The logger to write messages to</param>
 /// <param name="writer">The XMLwriter to write the sdf tags to</param>
 public void WriteSDF(ProgressLogger log, XmlWriter writer)
 {
     jointSpecifics.WriteJointSDF(log, writer);
 }
        public override void WriteSensor(ProgressLogger log, XmlWriter owner)
        {
            owner.WriteStartElement("sensor");
            {
                owner.WriteAttributeString("name", ChildLink.Name.Replace(" ", "_") + "_contact");
                owner.WriteAttributeString("type", "contact");

                SDFExporter.writeSDFElement(owner, "always_on", "1");
                //SDFExporter.writeSDFElement(owner, "visualize", "true");

                owner.WriteStartElement("contact");
                {
                    SDFExporter.writeSDFElement(owner, "collision", ChildLink.Name.Replace(" ", "_")+"_collision");
                }
                owner.WriteEndElement();
            }
            owner.WriteEndElement();
        }
 /// <summary>
 /// Writes the Attachment to the SDF file
 /// </summary>
 /// <param name="log"></param>
 /// <param name="owner"></param>
 public override void WritePlugins(ProgressLogger log, XmlWriter owner)
 {
     owner.WriteStartElement("plugin");
     {
         owner.WriteAttributeString("name", ChildLink.Name + "_extlimit");
         owner.WriteAttributeString("filename", "liblimit_switch.so");
         SDFExporter.writeSDFElement(owner, "topic", "/gazebo/frc/simulator/dio/" + dioChannel.ToString());
         SDFExporter.writeSDFElement(owner, "type", "external");
         SDFExporter.writeSDFElement(owner, "sensor", ChildLink.Name.Replace(" ", "_") + "_contact");
     }
     owner.WriteEndElement();
 }