Ejemplo n.º 1
0
        public async Task TestEditedEncounters()
        {
            var(game, config) = await this.GetGameAndConfigAsync();

            var whitelist = await this.GetOriginalNullEncounters();

            var randomizer = Randomization.Common.Randomizer.GetRandomizer(game, config, 407643609);
            var progress   = new ProgressNotifier();

            //await randomizer.RandomizeEncounters( progress, CancellationToken.None );

            var encounters = await game.GetEncounterData(false);

            var zoneNames = (await game.GetTextFile(TextNames.EncounterZoneNames)).Lines;

            foreach (var(iEnc, encounter) in encounters.Pairs())
            {
                var name = zoneNames[encounter.ZoneId];

                foreach (var(iEnt, entry) in encounter.GetAllEntries().Pairs())
                {
                    var key = $"{iEnc}:{iEnt}";

                    if (whitelist.Contains(key))
                    {
                        continue;
                    }

                    Assert.That(entry, Is.Not.Null, $"Encounter entry {key} was null");
                    Assert.That(entry.Species, Is.Not.Zero, $"Encounter entry {key} had a species of \"0\"");
                }
            }
        }
Ejemplo n.º 2
0
        public static void GetAll
        (
            [Required] string fileStorageName,
            [Required] string fileExtension
        )
        {
            try
            {
                var startDateTime    = DateTime.Now;
                var progressNotifier = new ProgressNotifier("RetrieveAll");
                var dataIdentifiers  = FileStorageFacade.GetAllDataIdentifiersBasedUponFileStorageIndexFile(fileStorageName, new FileStorageHandler.ExposeProgressDelegate(progressNotifier.ShowProgress));

                Console.WriteLine("Dumping ...");
                foreach (var currentdataIdentifier in dataIdentifiers)
                {
                    var outputFile = currentdataIdentifier + "." + fileExtension;
                    FileStorageFacade.ExportToFile(fileStorageName, currentdataIdentifier, outputFile, ExportFileBehaviour.ThrowExceptionWhenAlreadyExists);
                    Console.Write(".");
                }
                Console.WriteLine("[Finished]");
                Console.WriteLine(string.Format("{0} files found", dataIdentifiers.LongCount()));
                var timeSpan = DateTime.Now - startDateTime;
                Console.WriteLine(string.Format("This operation took {0} msecs", (Int64)timeSpan.TotalMilliseconds));
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("An error occured; {0}", e.Message));
            }
        }
Ejemplo n.º 3
0
        public void testGame(ProgressNotifier pn)
        {
            try
            {
                pn.Progress = .2f;

                cleanProject();
                pn.Progress = .3f;

                CompileManager.Instance.compile();
                DirectoryCopy(PathLib, PathBuildLib, true);
                DirectoryCopy(PathMedia, PathBuildMedia, true);

                InstanceManager.Instance.Levels.ForEach(l => InstanceManager.Instance.convertToGobs(FileGameDataLibrary, l));


                pn.Progress = .6f;

                pn.Progress = .7f;

                DirectoryCopy(ResourceFiles.CompileLib, PathBuildLib, true);
                DirectoryCopy(ResourceFiles.CompileMedia, PathBuildMedia, true);
                File.Copy(ResourceFiles.LibExe, FileBuildGameExePath);
                File.Copy(PATH_COMPILE_EXE_CONFIG, FileBuildGameConfigPath);
                createGameSettings();

                pn.Progress = .8f;
                runGame();
                pn.Progress = 1;
            }
            catch (WhiskeyException we)
            {
                we.displayMessageBox();
            }
        }
Ejemplo n.º 4
0
        void Init(ProgressNotifier notifier, String applicationAdminUser, String applicationAdminPassword, CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            notifier.OnInitProgress(55, CoreTranslations.InitDbAdmin);
            var user = this.Users.FirstOrDefault(u => u.UserName.Equals(applicationAdminUser, StringComparison.OrdinalIgnoreCase));

            if (user == null)
            {
                user = this.Users.Add(new Users.DbUser(this)
                {
                    UserName = applicationAdminUser
                });
            }
            user.LogicallyDeleted    = false;
            user.AllowMultipleLogins = false;
            user.NeedChangePassword  = false;
            user.SetPassword(applicationAdminPassword);
            this.SetCurrentUser(user);
            token.ThrowIfCancellationRequested();
            this.SaveChanges();

            notifier.OnInitProgress(60, CoreTranslations.InitDbFill);
            DoInitWindows(null);
            token.ThrowIfCancellationRequested();
            this.SaveChanges();

            notifier.OnInitProgress(70, CoreTranslations.InitDbAdmin);
            SetUserAsAdmin(user);
            token.ThrowIfCancellationRequested();
            this.SaveChanges();
        }
Ejemplo n.º 5
0
        private void findPreviouslyImportedTickets()
        {
            previouslyImported = new ConcurrentDictionary <string, WorkItem>();
            var workItemStore = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));

            var query        = string.Format("Select [ID] From WorkItems where [Team Project] = '{0}' AND [Hyperlink Count] > 0", project);
            var queryResults = workItemStore.Query(query);

            if (queryResults.Count > 0)
            {
                var externalRef     = externalReferenceTag + " [";
                var progressNotifer = new ProgressNotifier(OnPercentComplete, queryResults.Count);
                foreach (WorkItem workItem in queryResults)
                {
                    var hyperLinks = workItem.Links.OfType <Hyperlink>();
                    foreach (var link in hyperLinks)
                    {
                        if (link.Comment.IndexOf(externalRef, StringComparison.Ordinal) == 0)
                        {
                            var toExtract = (link.Comment.Length - externalRef.Length) - 1;
                            var sourceId  = link.Comment.Substring(externalRef.Length, toExtract);
                            onDetailedProcessing(string.Format("Retrieving previously imported tickets ({0}).", sourceId));
                            previouslyImported[sourceId] = workItem;
                            break;
                        }
                        progressNotifer.UpdateProgress();
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public static void Defrag
        (
            [Required] string sourceFileStorageName,
            [Required] string destinationFileStorageName,
            [Required] string sqlTable,
            [Required] string sqlColumn
        )
        {
            try
            {
                var startDateTime          = DateTime.Now;
                var progressNotifierPhase1 = new ProgressNotifier("Reading indexes");
                var progressNotifierPhase2 = new ProgressNotifier("Writing");

                FileStorageFacade.DefragDataIdentifiers(sourceFileStorageName, destinationFileStorageName, sqlTable, sqlColumn, progressNotifierPhase1.ShowProgress, progressNotifierPhase2.ShowProgress);
                Console.WriteLine();
                var timeSpan = DateTime.Now - startDateTime;
                Console.WriteLine(string.Format("File storage optimization finished"));
                Console.WriteLine(string.Format("This operation took {0} msecs", (Int64)timeSpan.TotalMilliseconds));
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("An error occured; {0}", e.Message));
            }
        }
Ejemplo n.º 7
0
        public static void Replicate
        (
            [Required] string sourcefileStorageName,
            [Required] string destinationfileStorageName
        )
        {
            try
            {
                Console.WriteLine(string.Format("[Source {0}]", sourcefileStorageName));
                Console.WriteLine(string.Format("[Destination {0}]", destinationfileStorageName));
                Console.WriteLine();
                Console.WriteLine("Press enter to replicate ... ");
                Console.ReadLine();

                var progressNotifierPhase1 = new ProgressNotifier("Reading indexes");
                var progressNotifierPhase2 = new ProgressNotifier("Writing");

                var startDateTime = DateTime.Now;
                FileStorageFacade.Replicate(sourcefileStorageName, destinationfileStorageName, ReplicateBehaviour.ReplicateToNewStorage, AddFileBehaviour.ThrowExceptionWhenAlreadyExists, new FileStorageHandler.ExposeProgressDelegate(progressNotifierPhase1.ShowProgress), new FileStorageHandler.ExposeProgressDelegate(progressNotifierPhase2.ShowProgress));

                var timeSpan = DateTime.Now - startDateTime;
                Console.WriteLine(string.Format("This operation took {0} msecs", (Int64)timeSpan.TotalMilliseconds));
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("An error occured; {0}", e.Message));
            }
        }
Ejemplo n.º 8
0
        public void StartImport()
        {
            setCurrentAction("Preparing to import");
            FailedTickets = new List <IFailedTicket>();
            passedTickets = new List <Ticket>();
            var okToImport = ticketTarget.StartImport(ticketSource.Source);

            if (okToImport)
            {
                ticketSource.PreferHtml = ticketTarget.SupportsHtml;

                setCurrentAction(String.Format("Validating {0} tickets against {1}", ticketSource.Source, ticketTarget.Target));

                foreach (var sourceTicket in ticketSource.Tickets(ticketTarget.GetAvailableTicketTypes()))
                {
                    IFailedTicket failedTicket;
                    if (ticketTarget.CheckTicket(sourceTicket, out failedTicket))
                    {
                        passedTickets.Add(sourceTicket);
                    }
                    else
                    {
                        FailedTickets.Add(failedTicket);
                    }
                }

                if (FailedTickets.Count == 0)
                {
                    setCurrentAction(String.Format("Creating {0} tickets", ticketTarget.Target));
                    var progressNotifer = new ProgressNotifier(onPercentComplete, passedTickets.Count);
                    foreach (var passedTicket in passedTickets)
                    {
                        if (includeAttachments)
                        {
                            clearDownloadFolder();
                            ticketSource.DownloadAttachments(passedTicket, downloadFolder);
                        }
                        else
                        {
                            passedTicket.Attachments.Clear();
                        }
                        ticketTarget.AddTicket(passedTicket);
                        progressNotifer.UpdateProgress();
                    }

                    setCurrentAction(String.Format("Updating {0} tickets", ticketTarget.Target));
                    ticketTarget.EndImport();

                    if (includeAttachments)
                    {
                        clearDownloadFolder();
                        Directory.Delete(downloadFolder);
                    }

                    setCurrentAction("Import complete.");
                }
            }
        }
Ejemplo n.º 9
0
        public async Task TestRandomizer()
        {
            var(game, config) = await this.GetGameAndConfigAsync();

            var randomizer = Randomization.Common.Randomizer.GetRandomizer(game, config);
            var progress   = new ProgressNotifier();

            await randomizer.RandomizeAll(progress, CancellationToken.None);
        }
Ejemplo n.º 10
0
 public override void save(ProgressNotifier pn)
 {
     Invoke(new NoArgFunction(() =>
     {
         Project.Name           = control.ProjectName;
         Project.GameStartScene = control.StartScene;
         Project.IsFullScreen   = control.IsFullScreen;
         Project.CloseOnExit    = control.CloseOnExit;
         base.save(pn);
     }));
 }
Ejemplo n.º 11
0
        public override void save(ProgressNotifier pn)
        {
            pn.Progress = .3f;
            //State state = Descriptor.Level.getInstanceLevelState();
            Descriptor.save();
            pn.Progress = .9f;

            //State.serialize(state, Descriptor.FilePath);
            pn.Progress = 1;
            base.save(pn);
        }
Ejemplo n.º 12
0
 public static Task InitDatabaseAsync(String serverName, String databaseName,
                                      String sqlServerUser, String sqlServerPassword,
                                      String applicationAdminUser, String applicationAdminPassword,
                                      WhatToDo whatToDo, ProgressNotifier notifier = null, CancellationToken?token = null)
 {
     return(BaseContext.InitDatabaseAsync(serverName, databaseName, PROJECT_NAME,
                                          sqlServerUser, sqlServerPassword, applicationAdminUser, applicationAdminPassword,
                                          whatToDo,
                                          cnString => new ClimbingContext2(cnString),
                                          cnString => new ClimbingContext2(cnString, false, false, null, null),
                                          notifier, token ?? CancellationToken.None));
 }
Ejemplo n.º 13
0
 protected static Task <BaseContext> InitContextOnExistingDBAsync(string contextConnectionString, WhatToDo whatToDo,
                                                                  Func <String, BaseContext> contextInitConstructor,
                                                                  Func <String, BaseContext> contextJobConstructor,
                                                                  String applicationAdminUser, String applicationAdminPassword,
                                                                  ProgressNotifier notifier, CancellationToken token)
 {
     if (whatToDo == WhatToDo.CreateNew || whatToDo == WhatToDo.DropAndCreate)
     {
         throw new ArgumentOutOfRangeException("whatToDo", whatToDo, "Value not supported");
     }
     if (notifier == null)
     {
         notifier = new ProgressNotifier();
     }
     return(Task <BaseContext> .Factory.StartNew(() =>
     {
         notifier.OnInitProgress(10, CoreTranslations.InitDbCreation);
         using (var result = contextInitConstructor(contextConnectionString))
         {
             if (whatToDo == WhatToDo.LeaveAsIs)
             {
                 result.SetInitializer(WhatToDo.LeaveAsIs);
             }
             else
             {
                 result.SetInitializer(WhatToDo.CreateOrUpdate);
             }
             result.Database.ExecuteSqlCommand("select top 1 * from sys.tables");
         }
         BaseContext context = null;
         try
         {
             context = contextJobConstructor(contextConnectionString);
             context.CreateCreateNewIidProc();
             context.Init(notifier, applicationAdminUser, applicationAdminPassword, token);
             return context;
         }
         catch
         {
             if (context != null)
             {
                 context.Dispose();
             }
             throw;
         }
     }, token));
 }
Ejemplo n.º 14
0
        public async Task Run(Random masterRandom, CancellationToken token)
        {
            int cur = 0;

            foreach (var task in this.tasks)
            {
                int thisTask = cur;

                if (token.IsCancellationRequested)
                {
                    this.ProgressNotifier.NotifyUpdate(ProgressUpdate.Cancelled());
                }

                if (this.ProgressNotifier.IsCancelled || this.ProgressNotifier.IsFailed)
                {
                    break;
                }

                ProgressNotifier subNotifier = new ProgressNotifier();

                subNotifier.ProgressUpdated += (s, u) => {
                    if (u.Progress < 0)
                    {
                        this.ProgressNotifier.NotifyUpdate(u);
                    }
                    else
                    {
                        double progWithSub = (thisTask + subNotifier.Progress) / this.tasks.Count;
                        this.ProgressNotifier.NotifyUpdate(ProgressUpdate.Update(u.Status, progWithSub));
                    }
                };

                try
                {
                    var taskRandom = new Random(masterRandom.Next());

                    await task(taskRandom, subNotifier, token);
                }
                catch (Exception e)
                {
                    this.ProgressNotifier?.NotifyFailure(e);
                    throw;
                }

                this.ProgressNotifier.NotifyUpdate(ProgressUpdate.Update(this.ProgressNotifier.Status ?? string.Empty, ++cur / (double)this.tasks.Count));
            }
        }
Ejemplo n.º 15
0
        public override void save(ProgressNotifier pn)
        {
            string       code       = editor.Text;
            FileStream   fileStream = File.Create(desc.FilePath);
            StreamWriter writer     = new StreamWriter(fileStream);

            writer.WriteLine(code);
            writer.Flush();
            writer.Close();
            fileStream.Close();

            lastText = editor.Text;



            base.save(pn);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Convert a datatable to a soils XML file. Can handle multiple soils in the table.
        /// </summary>
        public static XmlNode TableToSoilXML(DataTable Table, ProgressNotifier Notifier = null)
        {
            XmlDocument Doc       = new XmlDocument();
            XmlNode     SoilsNode = Doc.CreateElement("folder");

            Doc.AppendChild(SoilsNode);
            XmlHelper.SetName(SoilsNode, "Soils");
            XmlHelper.SetAttribute(SoilsNode, "version", APSIMChangeTool.CurrentVersion.ToString());

            Soil[] Soils = TableToSoils(Table, Notifier);
            foreach (Soil Soil in Soils)
            {
                AddSoilToXML(Soil, SoilsNode);
            }

            return(Doc.DocumentElement);
        }
Ejemplo n.º 17
0
        private void RunScenario(string scenarioName, string label, IEnumerable <Step> steps)
        {
            ProgressNotifier.NotifyScenarioStart(scenarioName, label);
            var stepsToExecute = steps.ToArray();

            try
            {
                foreach (var step in stepsToExecute)
                {
                    PerformStep(step, stepsToExecute.Length);
                }
            }
            finally
            {
                var result = new ScenarioResult(scenarioName, stepsToExecute.Select(s => s.Result), label);
                _result.AddScenario(result);
                ProgressNotifier.NotifyScenarioFinished(result.Status, result.StatusDetails);
            }
        }
Ejemplo n.º 18
0
        public override async Task RandomizeEggMoves(ProgressNotifier progressNotifier, CancellationToken token)
        {
            progressNotifier?.NotifyUpdate(ProgressUpdate.StatusOnly("Randomizing egg moves..."));

            var config       = this.ValidateAndGetConfig().EggMoves;
            var eggMovesList = await this.Game.GetEggMoves();

            var speciesInfo = await this.Game.GetPokemonInfo(edited : true);

            var moves     = (await this.Game.GetMoves()).ToList();
            var pokeNames = (await this.Game.GetTextFile(TextNames.SpeciesNames)).Lines;

            for (var i = 0; i < eggMovesList.Length; i++)
            {
                string name = pokeNames[speciesInfo.GetSpeciesForEntry(i)];
                progressNotifier?.NotifyUpdate(ProgressUpdate.Update($"Randomizing egg moves...\n{name}", i / (double)eggMovesList.Length));

                var  species        = speciesInfo[i];
                var  eggMoves       = eggMovesList[i];
                var  chooseFrom     = moves.ToList();
                bool preferSameType = config.FavorSameType && this.rand.Next(2) == 0;

                if (eggMoves.Empty || eggMoves.Count == 0)
                {
                    continue;
                }

                if (preferSameType)
                {
                    chooseFrom = chooseFrom.Where(m => species.Types.Any(t => t == m.Type)).ToList();
                }

                for (int m = 0; m < eggMoves.Count; m++)
                {
                    var move = chooseFrom.GetRandom(this.rand);
                    eggMoves.Moves[m] = (ushort)moves.IndexOf(move);
                }

                eggMovesList[i] = eggMoves;
            }

            await this.Game.SaveEggMoves(eggMovesList);
        }
Ejemplo n.º 19
0
        public IEnumerable <short[, ]> Run()
        {
            if (Format.Channels <= 0)
            {
                yield break;
            }

            if (ProgressNotifier != null)
            {
                ProgressNotifier.Reset();
            }

            RawStream.Seek(0, SeekMode.Origin);
            uint decodedSize = 0;

            while (decodedSize < RawStream.Length)
            {
                // Calculate the size of the block
                int blockLen = 0x2000;
                if (decodedSize + blockLen > RawStream.Length)
                {
                    blockLen = (int)(RawStream.Length - decodedSize);
                }

                // Decode
                yield return(DecodeBlock(blockLen));

                // Increase decoded size
                decodedSize += (uint)blockLen;

                // Show progress
                if (ProgressNotifier != null)
                {
                    ProgressNotifier.Update((int)decodedSize, RawStream.Length);
                }
            }

            if (ProgressNotifier != null)
            {
                ProgressNotifier.End();
            }
        }
Ejemplo n.º 20
0
        public async Task RandomizeAll(ProgressNotifier progress, CancellationToken token)
        {
            var runner = new TaskRunner {
                this.RandomizeAbilities,
                this.RandomizeEggMoves,
                this.RandomizeEncounters,
                this.RandomizeLearnsets,
                this.RandomizeStarters,
                this.RandomizeTrainers,
            };

            if (progress != null)
            {
                runner.ProgressNotifier.ProgressUpdated += (s, u) => progress.NotifyUpdate(u);
            }

            await runner.Run(token);

            progress?.NotifyUpdate(ProgressUpdate.Completed());
        }
Ejemplo n.º 21
0
        public bool HeavyProc(int p1, string p2)
        {
            int n = 40;

            for (int i = 0; i < n; i++)
            {
                ProgressNotifier.ThrowIfCancellationRequested();

                Thread.Sleep(50);
                ProgressNotifier.Report(new Progress(i * 100 / n));
                ProgressNotifier.Report(new Progress(string.Format("Processing... {0}%", i * 100 / n)));

                ProgressNotifier.ThrowIfCancellationRequested();
            }

            ProgressNotifier.Report(new Progress(n * 100 / n));
            ProgressNotifier.Report(new Progress(string.Format("Processing... {0}%", n * 100 / n)));

            return(true);
        }
Ejemplo n.º 22
0
        public static void Count
        (
            [Required] string fileStorageName
        )
        {
            try
            {
                ProgressNotifier progressNotifier = new ProgressNotifier("Count");

                DateTime    startDateTime   = DateTime.Now;
                List <Guid> dataIdentifiers = FileStorageFacade.GetAllDataIdentifiersBasedUponFileStorageIndexFile(fileStorageName, new FileStorageHandler.ExposeProgressDelegate(progressNotifier.ShowProgress));
                Console.WriteLine(string.Format("{0} files found", dataIdentifiers.LongCount()));
                TimeSpan timeSpan = DateTime.Now - startDateTime;
                Console.WriteLine(string.Format("This operation took {0} msecs", (Int64)timeSpan.TotalMilliseconds));
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("An error occured; {0}", e.Message));
            }
        }
Ejemplo n.º 23
0
        private async Task <TransferResults> InternalTransit(bool dryRun, TextStatusNotifier progress, CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            var transitChannel = Channel.CreateBounded <List <ReplaceOneModel <BsonDocument> > >(_options.Workers);

            var(filter, count) = await _preparationHandler.PrepareCollectionAsync(_options.IterativeTransferOptions, progress, token);

            if (count == 0)
            {
                _logger.Information("Collection {Collection} is up-to date, skipping transit", _options.Collection);
                return(TransferResults.Empty);
            }

            var notifier = new ProgressNotifier(count);

            _manager.Attach(_options.Collection, notifier);

            var writer = _documentsWriterFactory.Create(transitChannel, notifier, dryRun);

            var sw = new Stopwatch();

            sw.Start();

            var writeHandler = writer.WriteAsync(token);

            await _source.ReadDocumentsAsync(filter, transitChannel, _options.BatchSize,
                                             _options.KeyFields ?? Array.Empty <string>(), _options.Upsert,
                                             _options.FetchKeyFromDestination?_destination : null, token);

            var results = await writeHandler;

            sw.Stop();

            _logger.Debug("Transfer was completed in {Elapsed}", sw.Elapsed);

            _logger.Information("Transferred {S}; Retried {R}; Failed {F};", results.Processed, results.Retried,
                                results.Failed);

            return(results);
        }
Ejemplo n.º 24
0
        private static void ProcessAccount(Account account, ILogger logger)
        {
            logger.Trace("Reading nodes from the folder {0}", account.LocalRoot);
            var itemListFromFileSystem = GenerateListFromLocalFolder(account.LocalRoot, account.LocalRoot);

            MegaApiClient client = new MegaApiClient();

            client.Login(account.Username, account.Password);

            var itemListFromMegaNz = GenerateListFromMegaNz(client).ToList();

            var commandGenerator = new CommandGenerator(account.LocalRoot);
            var commandList      = commandGenerator.GenerateCommandList(itemListFromFileSystem, itemListFromMegaNz);

            if (!commandList.Any())
            {
                logger.Trace("Nothing to do here. Exiting.....");
                return;
            }

            // Showing the commands and asking if continue
            ShowCommandList(commandList);
            if (commandList.OfType <DeleteFileCommand>().Any())
            {
                Console.WriteLine("There are some files to delete. Continue? (y/n)");
                var continueAnswer = Console.ReadLine();
                if (continueAnswer.ToLower() != "y")
                {
                    logger.Trace("Exiting...");
                }
            }

            // Executing the commands in the list
            var fileManager      = new FileManager();
            var progressNotifier = new ProgressNotifier(new ConsoleWrapper());
            var executor         = new CommandExecutor(client, logger);

            var megaNzItemCollection = new MegaNzItemCollection(itemListFromMegaNz);

            executor.Execute(commandList, megaNzItemCollection, fileManager, progressNotifier);
        }
Ejemplo n.º 25
0
        public async Task RandomizeAll(ProgressNotifier progress, CancellationToken token)
        {
            await this.LogAsync($"Randomizer started. Using seed: {this.RandomSeed}{Environment.NewLine}");

            var runner = new TaskRunner(this.GetRandomizationTasks());

            if (progress != null)
            {
                runner.ProgressNotifier.ProgressUpdated += (s, u) => progress.NotifyUpdate(u);
            }

            await runner.Run(this.Random, token);

            progress?.NotifyUpdate(ProgressUpdate.Completed());
            await this.LogAsync("Randomization has finished.");

            if (this.Logger != null)
            {
                await this.Logger.FlushAsync();
            }
        }
Ejemplo n.º 26
0
        public override void save(ProgressNotifier pn)
        {
            string       code       = editor.Text;
            FileStream   fileStream = File.Create(desc.FilePath);
            StreamWriter writer     = new StreamWriter(fileStream);

            writer.WriteLine(code);
            writer.Flush();
            writer.Close();
            fileStream.Close();

            lastText = editor.Text;


            ShaderBuilder sb = new ShaderBuilder();

            sb.buildShader(desc.FilePath, desc.FilePath.Replace(".hlsl", ".mgfx"));
            desc.ShouldBeLoadedAgain = true;

            base.save(pn);
        }
Ejemplo n.º 27
0
        public string Go(List <string> FilesToRun, ProgressNotifier Notifier)
        {
            if (Notifier != null)
            {
                Notifier(0, "Initialising");
            }

            WorkingFolder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(WorkingFolder);
            foreach (string file in Directory.GetFiles(WorkingFolder, "*.*"))
            {
                File.Delete(file);
            }

            // The XML document that we use for everything.
            XmlDocument jobDoc = new XmlDocument();

            jobDoc.LoadXml("<apsimfiles/>");

            AddFiles(jobDoc.DocumentElement, FilesToRun, Notifier);

            if (Notifier != null)
            {
                Notifier(99, "Creating batch files");
            }
            CreateSubmitFile(jobDoc);

            StreamWriter fp = new StreamWriter(Path.Combine(WorkingFolder, "CondorApsim.xml"));

            jobDoc.Save(fp);
            fp.Close();

            if (Notifier != null)
            {
                Notifier(100, "Zipping up");
            }
            string localzip = zipUp();

            return(null);
        }
Ejemplo n.º 28
0
        public static void RestoreIndexFile
        (
            [Required] string fileStorageName
        )
        {
            try
            {
                var startDateTime = DateTime.Now;

                var progressNotifier = new ProgressNotifier("RestoreIndexFile");
                FileStorageFacade.RestoreIndexFile(fileStorageName, AddFileBehaviour.OverrideWhenAlreadyExists, new FileStorageHandler.ExposeProgressDelegate(progressNotifier.ShowProgress));

                var timeSpan = DateTime.Now - startDateTime;
                Console.WriteLine(string.Format("This operation took {0} msecs", (Int64)timeSpan.TotalMilliseconds));

                Console.WriteLine("[Index is restored succesfully]");
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("An error occured; {0}", e.Message));
            }
        }
Ejemplo n.º 29
0
        public void testLevel(LevelDescriptor level, ProgressNotifier pn)
        {
            try
            {
                string origStartScene = GameStartScene;
                pn.Progress = .2f;

                cleanProject();
                pn.Progress = .3f;

                CompileManager.Instance.compile();
                DirectoryCopy(PathLib, PathBuildLib, true);
                DirectoryCopy(PathMedia, PathBuildMedia, true);

                pn.Progress = .6f;

                string statePath = InstanceManager.Instance.convertToGobs(FileGameDataLibrary, level.Level);
                GameStartScene = level.Name;

                pn.Progress = .7f;

                DirectoryCopy(ResourceFiles.CompileLib, PathBuildLib, true);
                DirectoryCopy(ResourceFiles.CompileMedia, PathBuildMedia, true);
                File.Copy(ResourceFiles.LibExe, FileBuildGameExePath);
                File.Copy(PATH_COMPILE_EXE_CONFIG, FileBuildGameConfigPath);
                createGameSettings();

                pn.Progress = .8f;
                runGame();
                pn.Progress = 1;

                GameStartScene = origStartScene;
            }
            catch (WhiskeyException we)
            {
                we.displayMessageBox();
            }
        }
        public override async Task RandomizeStarters(ProgressNotifier progressNotifier, CancellationToken token)
        {
            progressNotifier?.NotifyUpdate(ProgressUpdate.StatusOnly("Randomizing starter Pokémon..."));

            var config   = this.ValidateAndGetConfig().Starters;
            var starters = await this.Game.GetStarters();

            var species = Species.ValidSpecies.ToList();
            var chosen  = new List <SpeciesType>(starters.Generations.Count() * 3);

            if (config.StartersOnly)
            {
                species = species.Intersect(Starters.AllStarters)
                          .ToList();
            }

            if (!config.AllowLegendaries)
            {
                species = species.Except(Legendaries.AllLegendaries)
                          .ToList();
            }

            for (int i = 0; i < chosen.Capacity; i++)
            {
                var ret = this.GetRandomSpecies(species.Except(chosen));

                chosen.Add(ret);
            }

            starters.Generations.ForEach((gen, genIndex) => {
                for (int i = 0; i < 3; i++)
                {
                    starters[gen][i] = (ushort)chosen[genIndex * 3 + i];
                }
            });

            await this.Game.SaveStarters(starters);
        }