Start() private method

private Start ( ) : void
return void
Exemplo n.º 1
0
        /// <summary>
        /// Handle the user logging in
        /// </summary>
        private void HandleLogin()
        {
            try
            {
                // if the value for HasProgressBar is true
                if (HasProgressBar)
                {
                    // Set ShowProgress to true
                    ShowProgress = true;

                    // Reset just in case this is being run again
                    LoginProcessed = false;
                    LoginComplete  = false;

                    // Start the Progressbar timer
                    progressBar.Start();
                }
            }
            catch (Exception error)
            {
                // for debugging only
                DebugHelper.WriteDebugError("HandleLogin", "Login.cs", error);
            }
            finally
            {
                // Refresh the UI
                StateHasChanged();
            }
        }
        private static async Task <bool> Download(DownloadModel model, int c = 0)
        {
            ProgressBar.Init(false);

            Downloader downloader = new Downloader(model.DestinationPath, model.Url);

            downloader.DownloadChanged += Downloader_DownloadChanged;

            ProgressBar.Start();

            bool ok = await downloader.StartSync();

            downloader.DownloadChanged -= Downloader_DownloadChanged;

            ProgressBar.Stop();

            if (ok && model.PostAction != null)
            {
                ProgressBar.Init(true, model.PostActionDescription);
                await Task.Run(() => model.PostAction.Invoke());
            }

            if (!ok && c < MaxTries)
            {
                return(await Download(model, ++c));
            }
            return(ok);
        }
Exemplo n.º 3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //ProgressBar.Start(1);
                //for (int i = 0; i < 1000; i++)
                //{
                //    ProgressBar.Roll("共发布" + 1000 + "条信息,正在发布" + (i + 1) + "条。", ((i + 1) * 100 / 1000));
                //}

                //  ProgressBar.Start(2);
                //  int j = 0;
                BLL.contents.article bll = new BLL.contents.article();


                //列表
                DataTable dt = bll.GetList(0, "category_id=" + this.category_id, "sort_id asc,add_time desc,id desc").Tables[0];
                if (dt.Rows != null && dt.Rows.Count > 0)
                {
                    ProgressBar.Start(1);
                    CreatePageHtml(category_id, "/article_list.aspx?category_id=" + category_id, "../../html/list-" + category_id, dt.Rows.Count, 2);
                    ProgressBar.Start(2);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        CreateIndexHtml("/detail.aspx?category_id=" + category_id + "&id=" + dt.Rows[i]["id"], "../../html/detail-" + category_id + "-" + dt.Rows[i]["id"] + ".html");
                        ProgressBar.Roll("共发布详情" + dt.Rows.Count + "条信息,正在发布" + (i + 1) + "条。", ((i + 1) * 100 / dt.Rows.Count));
                    }
                    ////ProgressBar.Roll("发布信息成功,成功" + j + "个,失败" + (dt.Rows.Count - j) + "条。", 100);
                }
            }
        }
        public void ProgressBarSmokeCheck()
        {
            var progress = new ProgressBar();

            progress.Start(0, "test");
            progress.Tick("next");
            progress.Ticks().ShouldBe(1);
            progress.Stop();

            progress.Dispose();
            progress.Ticks().ShouldBe(-1);
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            var progressBar = new ProgressBar(20, "スタート", "エンド");

            progressBar.Start();
            foreach (var i in Enumerable.Range(0, 20))
            {
                progressBar.ShowMessage(i.ToString());
                progressBar.Step();
                Thread.Sleep(500);
            }
            progressBar.Finish();
        }
        protected override void OnDraw(Canvas canvas)
        {
            base.OnDraw(canvas);

            if (!AnimationInProgress && _isRunning)
            {
                if (_progressBar == null)
                {
                    _progressBar = new ProgressBar(this);
                    SetupProgressBarBounds();
                    _progressBar.SetColorScheme(_color1, _color2, _color3, _color4);
                    _progressBar.Start();
                }

                _progressBar.Draw(canvas);
            }
        }
        public void Test1()
        {
            const string start       = "さあ、始まりました!";
            const string end         = "あーっと、ここで終了です!";
            var          progressBar = new ProgressBar(20, start, end);

            progressBar.Start();
            Thread.Sleep(1000);
            progressBar.Step();
            Thread.Sleep(1000);
            progressBar.Step();
            Thread.Sleep(1000);
            progressBar.ShowMessage("ワッショイワッショイ");
            progressBar.Step();
            progressBar.Finish();
            Assert.Equal(1, 1);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Called when a Ok button is pressed
        /// </summary>
        /// <param name="sender">   Sender object</param>
        /// <param name="e">        Event argument</param>
        private void butOk_Click(object sender, RoutedEventArgs e)
        {
            string strHostName;
            int    iPortNumber;
            string strUserName;
            string strPassword;

            strHostName            = HostName;
            iPortNumber            = PortNumber;
            strUserName            = UserName;
            strPassword            = Password;
            ProgressBar.Visibility = Visibility.Visible;
            ProgressBar.Start();
            butOk.IsEnabled     = false;
            butCancel.IsEnabled = false;
            System.Threading.Tasks.Task.Factory.StartNew(() => { InitializeConnection(strHostName, iPortNumber, strUserName, strPassword); });
        }
Exemplo n.º 9
0
 private void UserLogin()
 {
     try
     {
         if (string.IsNullOrEmpty(txtUserName.Text) || string.IsNullOrEmpty(txtPassword.Text))
         {
             MessageBox.Show("Login Fail", "Duo Dialer", MessageBoxButtons.OK, MessageBoxIcon.Error);
             return;
         }
         button_login.Enabled = false;
         ProgressBar.Start();
         ProgressBar.Show();
         var isSuccess = AgentProfile.Instance.Login(txtUserName.Text.Trim(), txtPassword.Text.Trim());
         if (isSuccess)
         {
             new Thread(MonitorRestApiHandler.MapResourceToVeery).Start();
             Hide();
             new FormDialPad().ShowDialog(this);
             this.Close();
             Environment.Exit(0);
         }
         else
         {
             Logger.Instance.LogMessage(Logger.LogAppender.DuoDefault, "Login Fail", Logger.LogLevel.Error);
             MessageBox.Show("Login Fail", "Duo Dialer", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
         button_login.Enabled = true;
         txtPassword.Text     = string.Empty;
         ProgressBar.Stop();
         ProgressBar.Hide();
     }
     catch (Exception exception)
     {
         this.Invoke(new MethodInvoker(delegate
         {
             button_login.Enabled = true;
             //ProgressBar.Stop();
             //ProgressBar.Hide();
             txtPassword.Text = string.Empty;
         }));
         Logger.Instance.LogMessage(Logger.LogAppender.DuoDefault, "Login fail", exception, Logger.LogLevel.Error);
         MessageBox.Show("Login Fail", "Duo Dialer", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
        public async Task <IEnumerable <StashTab> > GetStashTabsAsync(string league, CancellationToken cancellationToken = default)
        {
            ProgressBar progress = new ProgressBar("Downloading stash data...");

            progress.Start();
            progress.Update(0);

            // prepare request
            Log.Debug("Requesting stash tabs info for account {Account} in league {League}", AccountName, league);
            Dictionary <string, object> query = new Dictionary <string, object>(5)
            {
                { "accountName", this.AccountName },
                { "league", league },
                { "realm", this.Realm },
                { "tabs", 1 }
            };
            string url = $"https://www.pathofexile.com/character-window/get-stash-items?" +
                         string.Join('&', query.Select(pair => $"{pair.Key}={pair.Value}"));

            using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);

            // send
            using HttpResponseMessage response = await SendAsync(request, cancellationToken).ConfigureAwait(false);

            response.EnsureSuccessStatusCode();

            // read content
            Log.Verbose("Parsing stash info");
            JObject data = JObject.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(false));

            StashTab[] tabs = data["tabs"].ToObject <StashTab[]>(SerializationHelper.DefaultSerializer);
            for (int i = 0; i < tabs.Length; i++)
            {
                progress.Update(i, tabs.Length);
                StashTab tab   = tabs[i];
                JToken   items = await GetStashTabContentsInternalAsync(league, tab.Index, cancellationToken).ConfigureAwait(false);

                items.PopulateObject(tab);
            }
            progress.Update(tabs.Length, tabs.Length, "Stash data download complete.");
            Log.Verbose("Done parsing stash info");
            return(tabs);
        }
Exemplo n.º 11
0
        private static void Main(string[] args)
        {
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };
            if (args.Length > 0)
            {
                _subPath = args[0];
            }

            Logger.SetLogger(new ConsoleLogger(LogLevel.LevelUp), _subPath);

            if (CheckKillSwitch())
            {
                return;
            }

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                // If the current program is not the latest version, ensure we skip saving the file after loading
                // This is to prevent saving the file with new options at their default values so we can check for differences
                settings = GlobalSettings.Load(_subPath, !VersionCheckState.IsLatest());
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }

            if (args.Length > 1)
            {
                var crds = args[1].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    ).OrderBy(pt => pt.Distance).FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }

            _session = new Session(new ClientSettings(settings), logicSettings, translation);

            if (boolNeedsSetup)
            {
                Logger.SetLoggerContext(_session);
                if (GlobalSettings.PromptForSetup(_session.Translation))
                {
                    _session = GlobalSettings.SetupSettings(_session, settings, configFile);

                    var fileName = Assembly.GetExecutingAssembly().Location;
                    Process.Start(fileName);
                    Environment.Exit(0);
                }
                else
                {
                    GlobalSettings.Load(_subPath);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            _session.Client.ApiFailure = new ApiFailureStrategy(_session);
            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = new Statistics();

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(3);

            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();

            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            Logger.SetLoggerContext(_session);
            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (lat, lng) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += SaveLocationToDisk;
            UseNearbyPokestopsTask.UpdateTimeStampsPokestop      += SaveTimeStampsPokestopToDisk;
            CatchPokemonTask.UpdateTimeStampsPokemon             += SaveTimeStampsPokemonToDisk;

            ProgressBar.Fill(100);

            machine.AsyncStart(new VersionCheckState(), _session, _subPath);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.UseSnipeLocationServer || _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }

            settings.checkProxy(_session.Translation);

            QuitEvent.WaitOne();
        }
Exemplo n.º 12
0
 /// <summary>
 /// Called when the windows is loaded
 /// </summary>
 /// <param name="sender">   Sender object</param>
 /// <param name="e">        Event arguments</param>
 private void WndPGNParsing_Loaded(object sender, RoutedEventArgs e)
 {
     ProgressBar.Start();
     StartProcessing();
 }
Exemplo n.º 13
0
        private static void Main(string[] args)
        {
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    _ignoreKillSwitch = false;
                    break;

                case "false":
                    _ignoreKillSwitch = true;
                    break;
                }
            }

            bool excelConfigAllow = false;

            if (commandLine["provider"] != null && commandLine["provider"] == "excel")
            {
                excelConfigAllow = true;
            }

            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            if (!_ignoreKillSwitch && CheckKillSwitch() || CheckMKillSwitch())
            {
                return;
            }

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");
            var excelConfigFile   = Path.Combine(profileConfigPath, "config.xlsm");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                settings = GlobalSettings.Load(_subPath, _enableJsonValidation);
                if (excelConfigAllow)
                {
                    if (!File.Exists(excelConfigFile))
                    {
                        Logger.Write("Migrating existing json confix to excel config, please check the config.xlsm in your config folder");

                        ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                    }
                    else
                    {
                        settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile);
                    }

                    Logger.Write("Bot will run with your excel config, loading excel config");
                }
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }
            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    ).OrderBy(pt => pt.Distance).FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }
            IElevationService elevationService = new ElevationService(settings);

            _session = new Session(new ClientSettings(settings, elevationService), logicSettings, elevationService, translation);
            Logger.SetLoggerContext(_session);

            if (boolNeedsSetup)
            {
                if (GlobalSettings.PromptForSetup(_session.Translation))
                {
                    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                    var fileName = Assembly.GetExecutingAssembly().Location;
                    Process.Start(fileName);
                    Environment.Exit(0);
                }
                else
                {
                    GlobalSettings.Load(_subPath, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = new Statistics();

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);

            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();

            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (lat, lng) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += SaveLocationToDisk;

            ProgressBar.Fill(100);

            if (_session.LogicSettings.AllowMultipleBot && _session.LogicSettings.MultipleBotConfig.SelectAccountOnStartUp)
            {
                byte index = 0;
                Console.WriteLine();
                Console.WriteLine();
                Logger.Write("PLEASE SELECT AN ACCOUNT TO START.");
                List <Char> availableOption = new List <char>();
                foreach (var item in _session.Accounts)
                {
                    var ch = (char)(index + 65);
                    availableOption.Add(ch);
                    Logger.Write($"{ch}. {item.GoogleUsername}{item.PtcUsername}");
                    index++;
                }
                ;

                char select = ' ';
                do
                {
                    select = Console.ReadKey(true).KeyChar;
                    Console.WriteLine(select);
                    select = Char.ToUpper(select);
                }while (!availableOption.Contains(select));

                var bot = _session.Accounts[select - 65];

                _session.ResetSessionToWithNextBot(bot);
            }
            machine.AsyncStart(new VersionCheckState(), _session, _subPath, excelConfigAllow);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }

            if (_session.LogicSettings.EnableHumanWalkingSnipe && _session.LogicSettings.HumanWalkingSnipeUseFastPokemap)
            {
                HumanWalkSnipeTask.StartFastPokemapAsync(_session, _session.CancellationTokenSource.Token);// that need to keep data  live
            }

            if (_session.LogicSettings.DataSharingEnable)
            {
                BotDataSocketClient.StartAsync(_session);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                MSniperServiceTask.ConnectToService();
                _session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }
            QuitEvent.WaitOne();
        }
Exemplo n.º 14
0
 /// <summary>
 /// Start the progress bar
 /// </summary>
 public void StartProgressBar()
 {
     ProgressBar.Visibility = Visibility.Visible;
     ProgressBar.Start();
 }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            var dir      = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var filePath = Path.Combine(dir, @"Maps\Tomsk.osm");

            if (!File.Exists(filePath))
            {
                Console.WriteLine($"Файл {filePath} не найден");
                Console.ReadKey();
                return;
            }


            using (_db = new TransportContext())
            {
                // очистка площадей и полигонов перед пересчетом
                //_db.Buildings.ToList().ForEach(b =>
                //{
                //    b.Square = 0.0;
                //    b.Polygon = null;
                //});
                //_db.SaveChanges();

                var correpStreetNamesFile = new FileStream(@"Dic\correspStreet.txt", FileMode.OpenOrCreate);
                using (var reader = new StreamReader(correpStreetNamesFile))
                {
                    _correspondenceStreetNames = GetCorrespondenceDictionary(reader.ReadToEnd());
                }
                _correspStrCount = _correspondenceStreetNames.Count;

                var correspAddrFile = new FileStream(@"Dic\correspAddr.txt", FileMode.OpenOrCreate);
                using (var reader = new StreamReader(correspAddrFile))
                {
                    _correspondenceAddresses = GetCorrespondenceDictionary(reader.ReadToEnd());
                }
                _correspAddrCount = _correspondenceAddresses.Count;

                try
                {
                    using (var xmlReader = XmlReader.Create(filePath))
                    {
                        var doc   = new XPathDocument(xmlReader);
                        var xpath = doc.CreateNavigator();
                        var nodes = xpath.Select("//node");
                        var ways  = xpath.Select("//way[tag/@k='building']");

                        var progress = new ProgressBar(ways.Count, "Получение площадей зданий...");
                        while (ways.MoveNext())
                        {
                            // изменение ProgressBar'a
                            progress.Report(ways.CurrentPosition);

                            // Получение названия улицы из osm-файла
                            var osmStreetName = GetTagNodeAttributeValue(ways.Current, "addr:street");
                            if (osmStreetName == string.Empty)
                            {
                                continue;
                            }
                            // Очистка навания улицы в соответствии с правилами
                            osmStreetName = CleanStreetName(osmStreetName);

                            // Получение номера дома из osm-файла
                            var osmHouseNumber = GetTagNodeAttributeValue(ways.Current, "addr:housenumber");
                            if (osmHouseNumber == string.Empty)
                            {
                                continue;
                            }
                            // Очистка номера дома в соответствии с правилами
                            osmHouseNumber = CleanHouseNumber(osmHouseNumber);

                            // Получение идентификаторов узлов, входящих в текущее здание
                            var ids = GetNodesIds(ways.Current.Select("nd/@ref"));
                            // Получение полигона по найденнымидентификаторам узлов
                            DbGeography polygon;
                            try
                            {
                                polygon = GetPolygonFromNodesIds(nodes, ids);
                            }
                            catch (Exception)
                            {
                                continue;
                            }


                            var repeatSearch       = true;  // повтор поиска, если не найдено
                            var skipAddress        = false; // пропуск адреса по нажатию на Esc
                            var exactAddress       = new Address();
                            var needSaveStreetName = false;
                            var needSaveAddress    = false;

                            // Адрес уже был найден и хранится в словаре
                            if (!_correspondenceAddresses.ContainsKey($"{osmStreetName},{osmHouseNumber}"))
                            {
                                var gisStreetNames = new List <string>(); // похожие названия улицы в 2gis
                                // Название улицы уже было найдено и хранится в словаре
                                if (!_correspondenceStreetNames.ContainsKey(osmStreetName))
                                {
                                    var gisStreetName = osmStreetName;
                                    // поиск названия улицы
                                    do
                                    {
                                        var addressesByStreet =
                                            _db.Addresses.Where(a => a.Street.Contains(gisStreetName));
                                        if (addressesByStreet.Any())
                                        {
                                            // Есть улицы с таким названием
                                            // Выбираем все названия
                                            var searchResults = addressesByStreet.Select(a => a.Street).Distinct();
                                            if (searchResults.Count() < MaxFoundedStreetsInQuery)
                                            {
                                                gisStreetNames = searchResults.ToList();
                                                repeatSearch   = false;
                                            }
                                            else
                                            {
                                                progress.Pause();
                                                Console.Write(
                                                    $"\r\n***\r\nВыполняется поиск адреса {osmStreetName}, {osmHouseNumber}" +
                                                    $"По названию улицы \"{gisStreetName}\" найдено слишком большее количество совпадений." +
                                                    "Уточните запрос, либо пропустите адрес (Esc): ");
                                                gisStreetName      = ConsoleReadLineWithSkip();
                                                needSaveStreetName = true;
                                                if (gisStreetName == null)
                                                {
                                                    skipAddress = true;
                                                    break;
                                                }
                                                if (gisStreetName == string.Empty)
                                                {
                                                    gisStreetName      = osmStreetName;
                                                    needSaveStreetName = false;
                                                }

                                                progress.Start();
                                            }
                                        }
                                        else
                                        {
                                            // Не найдено улицы с таким названием
                                            progress.Pause();
                                            Console.WriteLine("\r\n****");
                                            Console.WriteLine(
                                                $"Выполняется поиск адреса {osmStreetName}, {osmHouseNumber}");
                                            Console.Write(
                                                $"Улица \"{gisStreetName}\" не найдена. (Esc - пропуск) \r\nНовое название: ");

                                            gisStreetName      = ConsoleReadLineWithSkip();
                                            needSaveStreetName = true;
                                            if (gisStreetName == null)
                                            {
                                                skipAddress = true;
                                                break;
                                            }
                                            if (gisStreetName == string.Empty)
                                            {
                                                gisStreetName      = osmStreetName;
                                                needSaveStreetName = false;
                                            }
                                            progress.Start();
                                        }
                                    } while (repeatSearch);
                                }
                                else
                                {
                                    // Добавляем в результирующий список один элемент из словаря
                                    gisStreetNames.Add(_correspondenceStreetNames[osmStreetName]);
                                }

                                repeatSearch = true;
                                if (skipAddress)
                                {
                                    continue;
                                }

                                var gisHouseNumber = osmHouseNumber;
                                // поиск полного адреса
                                do
                                {
                                    var addressByStreetAndHouse =
                                        _db.Addresses.Where(
                                            a => gisStreetNames.Contains(a.Street) && a.Number == gisHouseNumber);

                                    if (addressByStreetAndHouse.Count() == 1)
                                    {
                                        // Если найден точный адрес
                                        exactAddress = addressByStreetAndHouse.First();
                                        repeatSearch = false;
                                    }
                                    else
                                    {
                                        // Если точный адрес не найден - требуется уточнить запрос
                                        progress.Pause();
                                        Console.Write(
                                            $"\r\n****\r\nВыполняется поиск адреса {osmStreetName}, {osmHouseNumber}" +
                                            "\r\nТочный результат не найден.");
                                        // получаем базовый номер дома для поиска вариантов
                                        var baseHouseNumber = GetBaseHouseNumber(osmHouseNumber);

                                        // выбираем адреса с базовым номером дома
                                        var searchResults =
                                            _db.Addresses.Where(
                                                a => gisStreetNames.Contains(a.Street) &&
                                                a.Number.StartsWith(baseHouseNumber));

                                        var matchesSearchResult =
                                            searchResults.AsEnumerable()
                                            .Where(a => Regex.IsMatch(a.Number, $@"^{baseHouseNumber}($|\D)"))
                                            .ToList();

                                        Console.Write(matchesSearchResult.Any() ? " Варианты:\r\n" : " Введите адрес: ");

                                        var resultsArray = matchesSearchResult.ToArray();
                                        for (var i = 0; i < resultsArray.Length; i++)
                                        {
                                            Console.WriteLine(
                                                $"{i + 1}. {resultsArray[i].Street}, {resultsArray[i].Number}");
                                        }

                                        // обработка пропуска адреса (нажатия Esc)
                                        var gisHouseNumberOrIndex = ConsoleReadLineWithSkip();
                                        needSaveAddress = true;
                                        if (gisHouseNumberOrIndex == null)
                                        {
                                            skipAddress = true;
                                            break;
                                        }
                                        if (gisHouseNumberOrIndex == string.Empty)
                                        {
                                            gisHouseNumber  = osmHouseNumber;
                                            needSaveAddress = false;
                                        }
                                        else
                                        {
                                            // обработка выбранного варианта из предложеных
                                            int selectedIndx;
                                            if (int.TryParse(gisHouseNumberOrIndex, NumberStyles.Integer,
                                                             CultureInfo.InvariantCulture, out selectedIndx) &&
                                                selectedIndx - 1 >= 0 && resultsArray.Length > selectedIndx - 1)
                                            {
                                                exactAddress = resultsArray[selectedIndx - 1];
                                                repeatSearch = false;
                                            }
                                            else
                                            {
                                                var sn = gisHouseNumberOrIndex.Split(new[] { "," },
                                                                                     StringSplitOptions.RemoveEmptyEntries);
                                                if (sn.Length == 2)
                                                {
                                                    gisStreetNames.Clear();
                                                    gisStreetNames.Add(sn[0].Trim());
                                                    gisHouseNumber = sn[1].Trim();
                                                }
                                                else
                                                {
                                                    gisHouseNumber  = osmHouseNumber;
                                                    needSaveAddress = false;
                                                }
                                            }
                                        }
                                        progress.Start();
                                    }
                                } while (repeatSearch);
                            }
                            else
                            {
                                var sn = _correspondenceAddresses[$"{osmStreetName},{osmHouseNumber}"]
                                         .Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                                exactAddress.Street = sn[0];
                                exactAddress.Number = sn[1];
                            }

                            if (skipAddress)
                            {
                                continue;
                            }

                            // если был найден объект точного адреса, то поиск посуществлять не требуется
                            var address = exactAddress.AddressId != 0
                                ? exactAddress
                                : _db.Addresses.FirstOrDefault(
                                a => a.Street == exactAddress.Street && a.Number == exactAddress.Number);

                            // если найденный адрес отличается от исходного (были переименования)
                            // то предлагается сохранить соответствие
                            if (needSaveStreetName)
                            {
                                progress.Pause();
                                Console.WriteLine(
                                    $"\r\n****\r\nСохраниь соответствие названий улицы: \"{osmStreetName}\" - \"{exactAddress.Street}\" (Y/N)?");
                                if (Console.ReadKey().Key == ConsoleKey.Y)
                                {
                                    _correspondenceStreetNames.Add(osmStreetName, exactAddress.Street);
                                }
                            }
                            if (needSaveAddress)
                            {
                                progress.Pause();
                                Console.WriteLine(
                                    $"\r\n****\r\nСохраниь соответствие адресов: \"{osmStreetName}, {osmHouseNumber}\" - \"{exactAddress.Street}, {exactAddress.Number}\" (Y/N)?");
                                if (Console.ReadKey().Key == ConsoleKey.Y)
                                {
                                    _correspondenceAddresses.Add($"{osmStreetName},{osmHouseNumber}",
                                                                 $"{exactAddress.Street},{exactAddress.Number}");
                                }
                            }

                            progress.Start();
                            var building = _db.Buildings.Find(address?.BuildingId);

                            if (building != null)
                            {
                                var square = polygon.Area ?? 0;

                                if (building.Polygon != null)
                                {
                                    square += building.Square;
                                    polygon = polygon.Union(building.Polygon);
                                }

                                building.Polygon = polygon;
                                building.Square  = square;
                            }
                        }
                        progress.Pause();
                    }
                    Console.WriteLine("Выполнено");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Произошла ошибка: {e.Message}");
                }
                finally
                {
                    SaveCurrentResults();
                }
            }

            Console.ReadKey(true);
        }
Exemplo n.º 16
0
        private static void Main(string[] args)
        {
            System.Windows.Forms.Application.EnableVisualStyles();
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    //_ignoreKillSwitch = false;
                    break;

                case "false":
                    //_ignoreKillSwitch = true;
                    break;
                }
            }

            bool excelConfigAllow = false;

            if (commandLine["provider"] != null && commandLine["provider"] == "excel")
            {
                excelConfigAllow = true;
            }

            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");
            var excelConfigFile   = Path.Combine(profileConfigPath, "config.xlsm");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                settings = GlobalSettings.Load(_subPath, _enableJsonValidation);
                if (excelConfigAllow)
                {
                    if (!File.Exists(excelConfigFile))
                    {
                        Logger.Write("Migrating existing json confix to excel config, please check the config.xlsm in your config folder");

                        ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                    }
                    else
                    {
                        settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile);
                    }

                    Logger.Write("Bot will run with your excel config, loading excel config");
                }
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }
            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            //Only check killswitch if use legacyAPI
            //if (settings.Auth.APIConfig.UseLegacyAPI  && (!_ignoreKillSwitch && CheckKillSwitch() || CheckMKillSwitch()))
            //    return;

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    ).OrderBy(pt => pt.Distance).FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }
            IElevationService elevationService = new ElevationService(settings);

            //validation auth.config
            if (boolNeedsSetup)
            {
                AuthAPIForm form = new AuthAPIForm(true);
                if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    settings.Auth.APIConfig = form.Config;
                }
            }
            else
            {
                var apiCfg = settings.Auth.APIConfig;

                if (apiCfg.UsePogoDevAPI)
                {
                    if (string.IsNullOrEmpty(apiCfg.AuthAPIKey))
                    {
                        Logger.Write("You select pogodev API but not provide API Key, please press any key to exit and correct you auth.json, \r\n The Pogodev API key call be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer", LogLevel.Error);

                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                    //TODO - test api call to valida auth key
                }
                else
                if (apiCfg.UseLegacyAPI)
                {
                    Logger.Write("You bot will start after 15 second, You are running bot with  Legacy API (0.45) it will increase your risk to be banned and trigger captcha. Config captcha in config.json to auto resolve them", LogLevel.Warning);

                    #if RELEASE
                    Thread.Sleep(15000);
                    #endif
                }
                else
                {
                    Logger.Write("At least 1 authentication method is selected, please correct your auth.json, ", LogLevel.Error);
                    Console.ReadKey();
                    Environment.Exit(0);
                }
            }

            _session = new Session(new ClientSettings(settings, elevationService), logicSettings, elevationService, translation);
            Logger.SetLoggerContext(_session);

            if (boolNeedsSetup)
            {
                if (GlobalSettings.PromptForSetup(_session.Translation))
                {
                    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                    var fileName = Assembly.GetExecutingAssembly().Location;
                    Process.Start(fileName);
                    Environment.Exit(0);
                }
                else
                {
                    GlobalSettings.Load(_subPath, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            ProgressBar.Fill(20);


            var machine = new StateMachine();
            var stats   = new Statistics();

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);
            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);
            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();
            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (lat, lng) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += SaveLocationToDisk;

            ProgressBar.Fill(100);

            if (_session.LogicSettings.AllowMultipleBot && _session.LogicSettings.MultipleBotConfig.SelectAccountOnStartUp)
            {
                byte index = 0;
                Console.WriteLine();
                Console.WriteLine();
                Logger.Write("PLEASE SELECT AN ACCOUNT TO START. AUTO START AFTER 30 SEC");
                List <Char> availableOption = new List <char>();
                foreach (var item in _session.Accounts)
                {
                    var ch = (char)(index + 65);
                    availableOption.Add(ch);
                    int day  = (int)item.RuntimeTotal / 1440;
                    int hour = (int)(item.RuntimeTotal - (day * 1400)) / 60;
                    int min  = (int)(item.RuntimeTotal - (day * 1400) - hour * 60);

                    var runtime = $"{day:00}:{hour:00}:{min:00}:00";

                    Logger.Write($"{ch}. {item.GoogleUsername}{item.PtcUsername} \t\t{runtime}");
                    index++;
                }
                ;

                char     select       = ' ';
                DateTime timeoutvalue = DateTime.Now.AddSeconds(30);

                while (DateTime.Now < timeoutvalue && !availableOption.Contains(select))
                {
                    if (Console.KeyAvailable)
                    {
                        ConsoleKeyInfo cki = Console.ReadKey();
                        select = cki.KeyChar;
                        select = Char.ToUpper(select);
                        if (!availableOption.Contains(select))
                        {
                            Console.Out.WriteLine("Please select an account from list");
                        }
                    }
                    else
                    {
                        Thread.Sleep(100);
                    }
                }

                if (availableOption.Contains(select))
                {
                    var bot = _session.Accounts[select - 65];
                    _session.ReInitSessionWithNextBot(bot);
                }
                else
                {
                    var bot = _session.Accounts.OrderBy(p => p.RuntimeTotal).First();
                    _session.ReInitSessionWithNextBot(bot);
                }
            }

            machine.AsyncStart(new VersionCheckState(), _session, _subPath, excelConfigAllow);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }

            if (_session.LogicSettings.EnableHumanWalkingSnipe && _session.LogicSettings.HumanWalkingSnipeUseFastPokemap)
            {
                HumanWalkSnipeTask.StartFastPokemapAsync(_session, _session.CancellationTokenSource.Token);// that need to keep data  live
            }

            if (_session.LogicSettings.DataSharingEnable)
            {
                BotDataSocketClient.StartAsync(_session);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                MSniperServiceTask.ConnectToService();
                _session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }

            Thread.Sleep(10000);
            Thread mThread = new Thread(delegate()
            {
                var infoForm = new InfoForm();
                infoForm.ShowDialog();
            });

            mThread.SetApartmentState(ApartmentState.STA);

            mThread.Start();

            QuitEvent.WaitOne();
        }