Esempio n. 1
0
        public PersonView(ServerServiceClient serverClient,Person p)
        {
            InitializeComponent();

            person = p;
            nameBoxText.Text = p.Name;
            birthBoxText.Text = p.Birthday.ToShortDateString();
            moradaBoxText.Text = p.Address;
            textBox3.Text = p.Nif.ToString();
            TimeSpan x = DateTime.Now - p.Birthday;
            idadeBoxText.Text = (x.Days/365).ToString();

            nacioBoxText.Text = p.Birthplace;
            this.serverClient = serverClient;

            try
            {
                SampleGenericDelegate<int, Regist[]> del = new SampleGenericDelegate<int, Regist[]>(serverClient.GetRegists);

                IAsyncResult result = del.BeginInvoke(person.Nif, null, null);

                registos = del.EndInvoke(result);

                if (registos != null)
                    SetRegists();

            }
            catch (Exception e)
            {
                var info = new InfoForm();
                info.Add(e.Message);
                info.ShowDialog(this);
                info.Dispose();
            }
        }
Esempio n. 2
0
 public SuccessInfo(string message, InfoForm infoForm=InfoForm.Alert, string returnUrl="")
 {
     base.Message = message;
     base.ReturnUrl = returnUrl;
     base.InfoType = "success";
     base.InfoForm= infoForm;
 }
Esempio n. 3
0
 public FailInfo(string message, InfoForm infoForm = InfoForm.Alert, string returnUrl = "")
 {
     base.Message = message;
     base.ReturnUrl = returnUrl;
     base.InfoType = "error";
     base.InfoForm = infoForm;
 }
Esempio n. 4
0
 private void documentoToolStripMenuItem_Click_1(object sender, EventArgs e)
 {
     SetPerson();
     if (!verifyPerson())
     {
         InfoForm info = new InfoForm();
         info.Add("Aviso: Tem que prencher todos os campos pessoa primeiro");
         info.Enabled = false;
         info.Visible = true;
     }
     else {
       DocumentEditor doc = new DocumentEditor(serverClient,this.p);
       doc.Visible = true;
       doc.FormClosed += (o, even) => this.Close();
        }
 }
Esempio n. 5
0
        public string NewInfoShow(bool isAjax,ActionExecutedContext filterContext,string infoType,string message,InfoForm infoForm, string returnUrl = "")
        {
            var htmlcode = string.Empty;
            //消息形式处理
            var infoFormStr = string.Empty;
            switch (infoForm)
            {
                case InfoForm.Alert:
                    infoFormStr = "message";
                    break;
                case InfoForm.Left:
                    infoFormStr = "notify";
                    break;
            }
            if (isAjax)
            {
                var title = infoType == "error"?"": "请点击Ok继续";
                htmlcode = $"abp.{infoFormStr}.{infoType}('{title}','{message}'";
            }
            else
            {
                htmlcode = File.ReadAllText(filterContext.HttpContext.Server.MapPath("~/Views/Shared/NewInfoShow.html"));
                htmlcode = htmlcode.Replace("{infoType}", infoType);
                htmlcode = htmlcode.Replace("{title}", message);
                htmlcode = htmlcode.Replace("{form}", infoFormStr);
            }
            if (!string.IsNullOrEmpty(returnUrl))
            {
                returnUrl= returnUrl.Equals("/") ? "/Home/Index/" : returnUrl;
                if (isAjax)
                {
                    htmlcode += $"function action(){{window.location.href = '{returnUrl}'}}";
                }
                else
                {
                    htmlcode = htmlcode.Replace("{IsAction}", "true");
                    htmlcode = htmlcode.Replace("{returnUrl}", returnUrl);
                }

            }
            return isAjax? htmlcode+=")": htmlcode;
        }
Esempio n. 6
0
        private void saveButton_Click(object sender, EventArgs e)
        {
            try
            {
                regist = new Regist();
                regist.Date = dateTimePicker1.Value;
                regist.Description = richTextBox1.Text;
                regist.Code = textBox3.Text;

                SampleGenericDelegate<Regist,int> del = new SampleGenericDelegate<Regist,int>(serverClient.InsertRegist);

                IAsyncResult result = del.BeginInvoke(regist,null, null);

                regist.Id = del.EndInvoke(result);

                 SarcIntelService.PersonView.PersonEditor person = new SarcIntelService.PersonView.PersonEditor(serverClient,regist);
                 person.ShowDialog(this);

                person.Close();

            }
            catch (Exception exc)
            {
                var info = new InfoForm();
                info.Add(exc.Message);
                info.ShowDialog(this);
                info.Dispose();
            }
        }
Esempio n. 7
0
        private void SaveButton_Click(object sender, EventArgs e)
        {
            try
            {    SetPerson();

            serverClient.InsertPersonAsync(p);
             //   _regist.AddPerson(p);
                SaveButton.Enabled = false;
                Close();
            }
            catch (Exception exc)
            {
                var info = new InfoForm();
                info.Add(exc.Message);
                info.ShowDialog(this);
                info.Dispose();
            }
        }
Esempio n. 8
0
 private void buttonStatus_Click(object sender, System.EventArgs e)
 {
     if (info == null) info = new InfoForm();
     if (info.IsDisposed) info = new InfoForm();
     info.Show();
     textBoxS.Focus();
 }
Esempio n. 9
0
 private void buttonO_Click(object sender, System.EventArgs e)
 {
     if (buttonO.Tag.ToString() == "1")
     {
         if (info != null) info.Close();
         info = null;
         BaseTerm.term.Close();
         buttonO.Tag = "0";
         buttonO.Text = "Offline";
     }
     else
     {
         try
         {
             if (BaseTerm.term.Open())
             {
                 ShowMsg(">>>> ONLINE");
                 buttonO.Tag = "1";
                 buttonO.Text = "Online";
             }
             else
             {
                 ShowMsg(">>>> PORT UNAVAILABLE");
             }
         }
         catch (CommPortException ex)
         {
             ShowException(ex);
         }
     }
     textBoxS.Focus();
 }
        public static List <ToolStripItem> CreateSelectionToolStripItems(
            Func <List <WatchVariableControl> > getVars,
            WatchVariableFlowLayoutPanel panel)
        {
            Action <WatchVariableControlSettings> apply = (WatchVariableControlSettings settings) =>
            {
                if (KeyboardUtilities.IsCtrlHeld())
                {
                    WatchVariableControlSettingsManager.AddSettings(settings);
                }
                else
                {
                    getVars().ForEach(control => control.ApplySettings(settings));
                }
            };

            ToolStripMenuItem itemHighlight = new ToolStripMenuItem("Highlight...");

            ControlUtilities.AddDropDownItems(
                itemHighlight,
                new List <string>()
            {
                "Highlight", "Don't Highlight"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeHighlighted: true, newHighlighted: true)),
                () => apply(new WatchVariableControlSettings(changeHighlighted: true, newHighlighted: false)),
            });

            ToolStripMenuItem itemLock = new ToolStripMenuItem("Lock...");

            ControlUtilities.AddDropDownItems(
                itemLock,
                new List <string>()
            {
                "Lock", "Don't Lock"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeLocked: true, newLocked: true)),
                () => apply(new WatchVariableControlSettings(changeLocked: true, newLocked: false)),
            });

            ToolStripMenuItem itemCopy = new ToolStripMenuItem("Copy...");
            Action <List <WatchVariableControl>, string> copyValues =
                (List <WatchVariableControl> controls, string separator) =>
            {
                Clipboard.SetText(
                    String.Join(separator, controls.ConvertAll(
                                    control => control.GetValue(false))));
            };

            ControlUtilities.AddDropDownItems(
                itemCopy,
                new List <string>()
            {
                "Copy with Commas", "Copy with Tabs", "Copy with Line Breaks"
            },
                new List <Action>()
            {
                () => copyValues(getVars(), ","),
                () => copyValues(getVars(), "\t"),
                () => copyValues(getVars(), "\r\n"),
            });

            ToolStripMenuItem itemPaste = new ToolStripMenuItem("Paste");

            itemPaste.Click += (sender, e) =>
            {
                List <string> stringList            = ParsingUtilities.ParseStringList(Clipboard.GetText());
                List <WatchVariableControl> varList = getVars();
                if (stringList.Count != varList.Count)
                {
                    return;
                }

                Config.Stream.Suspend();
                for (int i = 0; i < stringList.Count; i++)
                {
                    varList[i].SetValue(stringList[i]);
                }
                Config.Stream.Resume();
            };

            ToolStripMenuItem itemRoundTo        = new ToolStripMenuItem("Round to...");
            ToolStripMenuItem itemRoundToDefault = new ToolStripMenuItem("Default");

            itemRoundToDefault.Click += (sender, e) =>
                                        apply(new WatchVariableControlSettings(
                                                  changeRoundingLimit: true, changeRoundingLimitToDefault: true));
            ToolStripMenuItem itemRoundToNoRounding = new ToolStripMenuItem("No Rounding");

            itemRoundToNoRounding.Click += (sender, e) =>
                                           apply(new WatchVariableControlSettings(
                                                     changeRoundingLimit: true, newRoundingLimit: -1));
            List <ToolStripMenuItem> itemsRoundToNumDecimalPlaces = new List <ToolStripMenuItem>();

            for (int i = 0; i <= 10; i++)
            {
                int index = i;
                itemsRoundToNumDecimalPlaces.Add(new ToolStripMenuItem(index + " decimal place(s)"));
                itemsRoundToNumDecimalPlaces[index].Click += (sender, e) =>
                                                             apply(new WatchVariableControlSettings(
                                                                       changeRoundingLimit: true, newRoundingLimit: index));
            }
            itemRoundTo.DropDownItems.Add(itemRoundToDefault);
            itemRoundTo.DropDownItems.Add(itemRoundToNoRounding);
            itemsRoundToNumDecimalPlaces.ForEach(setAllRoundingLimitsNumberItem =>
            {
                itemRoundTo.DropDownItems.Add(setAllRoundingLimitsNumberItem);
            });

            ToolStripMenuItem itemDisplayAsHex = new ToolStripMenuItem("Display as Hex...");

            ControlUtilities.AddDropDownItems(
                itemDisplayAsHex,
                new List <string>()
            {
                "Default", "Hex", "Decimal"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeDisplayAsHex: true, changeDisplayAsHexToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeDisplayAsHex: true, newDisplayAsHex: true)),
                () => apply(new WatchVariableControlSettings(changeDisplayAsHex: true, newDisplayAsHex: false)),
            });

            ToolStripMenuItem itemAngleSigned = new ToolStripMenuItem("Angle: Signed...");

            ControlUtilities.AddDropDownItems(
                itemAngleSigned,
                new List <string>()
            {
                "Default", "Unsigned", "Signed"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeAngleSigned: true, changeAngleSignedToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeAngleSigned: true, newAngleSigned: false)),
                () => apply(new WatchVariableControlSettings(changeAngleSigned: true, newAngleSigned: true)),
            });

            ToolStripMenuItem itemAngleUnits        = new ToolStripMenuItem("Angle: Units...");
            ToolStripMenuItem itemAngleUnitsDefault = new ToolStripMenuItem("Default");

            itemAngleUnitsDefault.Click += (sender, e) =>
                                           apply(new WatchVariableControlSettings(
                                                     changeAngleUnits: true, changeAngleUnitsToDefault: true));
            List <ToolStripMenuItem> itemsAngleUnitsValue = new List <ToolStripMenuItem>();

            foreach (AngleUnitType angleUnitType in Enum.GetValues(typeof(AngleUnitType)))
            {
                AngleUnitType     angleUnitTypeFixed  = angleUnitType;
                ToolStripMenuItem itemAngleUnitsValue = new ToolStripMenuItem(angleUnitTypeFixed.ToString());
                itemAngleUnitsValue.Click += (sender, e) =>
                                             apply(new WatchVariableControlSettings(
                                                       changeAngleUnits: true, newAngleUnits: angleUnitTypeFixed));
                itemsAngleUnitsValue.Add(itemAngleUnitsValue);
            }
            itemAngleUnits.DropDownItems.Add(itemAngleUnitsDefault);
            itemsAngleUnitsValue.ForEach(setAllAngleUnitsValuesItem =>
            {
                itemAngleUnits.DropDownItems.Add(setAllAngleUnitsValuesItem);
            });

            ToolStripMenuItem itemAngleTruncateToMultipleOf16 = new ToolStripMenuItem("Angle: Truncate to Multiple of 16...");

            ControlUtilities.AddDropDownItems(
                itemAngleTruncateToMultipleOf16,
                new List <string>()
            {
                "Default", "Truncate to Multiple of 16", "Don't Truncate to Multiple of 16"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeAngleTruncateToMultipleOf16: true, changeAngleTruncateToMultipleOf16ToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeAngleTruncateToMultipleOf16: true, newAngleTruncateToMultipleOf16: true)),
                () => apply(new WatchVariableControlSettings(changeAngleTruncateToMultipleOf16: true, newAngleTruncateToMultipleOf16: false)),
            });

            ToolStripMenuItem itemAngleConstrainToOneRevolution = new ToolStripMenuItem("Angle: Constrain to One Revolution...");

            ControlUtilities.AddDropDownItems(
                itemAngleConstrainToOneRevolution,
                new List <string>()
            {
                "Default", "Constrain to One Revolution", "Don't Constrain to One Revolution"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeAngleConstrainToOneRevolution: true, changeAngleConstrainToOneRevolutionToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeAngleConstrainToOneRevolution: true, newAngleConstrainToOneRevolution: true)),
                () => apply(new WatchVariableControlSettings(changeAngleConstrainToOneRevolution: true, newAngleConstrainToOneRevolution: false)),
            });

            ToolStripMenuItem itemAngleDisplayAsHex = new ToolStripMenuItem("Angle: Display as Hex...");

            ControlUtilities.AddDropDownItems(
                itemAngleDisplayAsHex,
                new List <string>()
            {
                "Default", "Hex", "Decimal"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeAngleDisplayAsHex: true, changeAngleDisplayAsHexToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeAngleDisplayAsHex: true, newAngleDisplayAsHex: true)),
                () => apply(new WatchVariableControlSettings(changeAngleDisplayAsHex: true, newAngleDisplayAsHex: false)),
            });

            ToolStripMenuItem itemShowVariableXml = new ToolStripMenuItem("Show Variable XML");

            itemShowVariableXml.Click += (sender, e) =>
            {
                InfoForm infoForm = new InfoForm();
                infoForm.SetText(
                    "Variable Info",
                    "Variable XML",
                    String.Join("\r\n", getVars().ConvertAll(control => control.ToXml(true))));
                infoForm.Show();
            };

            ToolStripMenuItem itemShowVariableInfo = new ToolStripMenuItem("Show Variable Info");

            itemShowVariableInfo.Click += (sender, e) =>
            {
                InfoForm infoForm = new InfoForm();
                infoForm.SetText(
                    "Variable Info",
                    "Variable Info",
                    String.Join("\t",
                                WatchVariableWrapper.GetVarInfoLabels()) +
                    "\r\n" +
                    String.Join(
                        "\r\n",
                        getVars().ConvertAll(control => control.GetVarInfo())
                        .ConvertAll(infoList => String.Join("\t", infoList))));
                infoForm.Show();
            };

            ToolStripMenuItem itemMove = new ToolStripMenuItem("Move...");

            ControlUtilities.AddDropDownItems(
                itemMove,
                new List <string>()
            {
                "Start Move", "End Move", "Clear Move"
            },
                new List <Action>()
            {
                () => panel.NotifyOfReorderingStart(getVars()),
                () => panel.NotifyOfReorderingEnd(getVars()),
                () => panel.NotifyOfReorderingClear(),
            });

            ToolStripMenuItem itemRemove = new ToolStripMenuItem("Remove");

            itemRemove.Click += (sender, e) => panel.RemoveVariables(getVars());

            ToolStripMenuItem itemEnableCustomization = new ToolStripMenuItem("Enable Customization");

            itemEnableCustomization.Click += (sender, e) => apply(new WatchVariableControlSettings(enableCustomization: true));

            ToolStripMenuItem itemOpenController = new ToolStripMenuItem("Open Controller");

            itemOpenController.Click += (sender, e) =>
            {
                List <WatchVariableControl> vars          = getVars();
                VariableControllerForm      varController =
                    new VariableControllerForm(
                        vars.ConvertAll(control => control.VarName),
                        vars.ConvertAll(control => control.WatchVarWrapper),
                        vars.ConvertAll(control => control.FixedAddressList));
                varController.Show();
            };

            ToolStripMenuItem itemOpenPopOut = new ToolStripMenuItem("Open Pop Out");

            itemOpenPopOut.Click += (sender, e) =>
            {
                VariablePopOutForm form = new VariablePopOutForm();
                form.Initialize(getVars().ConvertAll(control => control.CreateCopy()));
                form.ShowForm();
            };

            ToolStripMenuItem itemAddToTab = new ToolStripMenuItem("Add to Tab...");

            itemAddToTab.Click += (sender, e) => SelectionForm.ShowDataManagerSelectionForm(getVars());

            ToolStripMenuItem itemAddToCustomTab = new ToolStripMenuItem("Add to Custom Tab");

            itemAddToCustomTab.Click += (sender, e) => WatchVariableControl.AddVarsToTab(getVars(), Config.CustomManager);

            return(new List <ToolStripItem>
            {
                itemHighlight,
                itemLock,
                itemCopy,
                itemPaste,
                new ToolStripSeparator(),
                itemRoundTo,
                itemDisplayAsHex,
                new ToolStripSeparator(),
                itemAngleSigned,
                itemAngleUnits,
                itemAngleTruncateToMultipleOf16,
                itemAngleConstrainToOneRevolution,
                itemAngleDisplayAsHex,
                new ToolStripSeparator(),
                itemShowVariableXml,
                itemShowVariableInfo,
                new ToolStripSeparator(),
                itemMove,
                itemRemove,
                itemEnableCustomization,
                itemOpenController,
                itemOpenPopOut,
                itemAddToTab,
                itemAddToCustomTab,
            });
        }
Esempio n. 11
0
 public UpdateInfo(string message, InfoForm infoForm = InfoForm.Alert, string returnUrl = "")
 {
     base.Message = message;
     base.ReturnUrl = returnUrl;
     base.InfoType = "info";
     base.InfoForm = infoForm;
 }
Esempio n. 12
0
        private void infoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InfoForm form = new InfoForm();

            form.Show();
        }
Esempio n. 13
0
        public static void RunBotWithParameters(Action <ISession, StatisticsAggregator> onBotStarted, string[] args)
        {
            var ioc = TinyIoC.TinyIoCContainer.Current;

            //Setup Logger for API
            APIConfiguration.Logger = new APILogListener();

            //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 Loading";
            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 options = new Options();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                // Values are available here
                if (options.Init)
                {
                    settings.GenerateAccount(options.IsGoogle, options.Template, options.Start, options.End, options.Password);
                }
            }
            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]);
                    //If lastcoord is snipe coord, bot start from default location

                    if (LocationUtils.CalculateDistanceInMeters(lat, lng, settings.LocationConfig.DefaultLatitude, settings.LocationConfig.DefaultLongitude) < 2000)
                    {
                        settings.LocationConfig.DefaultLatitude  = lat;
                        settings.LocationConfig.DefaultLongitude = lng;
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }

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

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

            TinyIoC.TinyIoCContainer.Current.Register <ITranslation>(translation);

            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() == DialogResult.OK)
                {
                    settings.Auth.APIConfig = form.Config;
                }
            }
            else
            {
                var apiCfg = settings.Auth.APIConfig;

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

                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                    try
                    {
                        HttpClient client = new HttpClient();
                        client.DefaultRequestHeaders.Add("X-AuthToken", apiCfg.AuthAPIKey);
                        var maskedKey = apiCfg.AuthAPIKey.Substring(0, 4) + "".PadLeft(apiCfg.AuthAPIKey.Length - 8, 'X') + apiCfg.AuthAPIKey.Substring(apiCfg.AuthAPIKey.Length - 4, 4);
                        HttpResponseMessage response = client.PostAsync("https://pokehash.buddyauth.com/api/v133_1/hash", null).Result;

                        string   AuthKey             = response.Headers.GetValues("X-AuthToken").FirstOrDefault();
                        string   MaxRequestCount     = response.Headers.GetValues("X-MaxRequestCount").FirstOrDefault();
                        DateTime AuthTokenExpiration = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(Convert.ToDouble(response.Headers.GetValues("X-AuthTokenExpiration").FirstOrDefault()));
                        TimeSpan Expiration          = AuthTokenExpiration - DateTime.UtcNow;
                        string   Result = $"Key: {maskedKey} RPM: {MaxRequestCount} Expiration Date: {AuthTokenExpiration.Month}/{AuthTokenExpiration.Day}/{AuthTokenExpiration.Year} ({Expiration.Days} Days {Expiration.Hours} Hours {Expiration.Minutes} Minutes)";
                        Logger.Write(Result, LogLevel.Info, ConsoleColor.Green);
                        AuthKey         = null;
                        MaxRequestCount = null;
                        Expiration      = new TimeSpan();
                        Result          = null;
                    }
                    catch
                    {
                        Logger.Write("The HashKey is invalid or has expired, please press any key to exit and correct you auth.json, \r\n The Pogodev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer", LogLevel.Error);
                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                }
                else if (apiCfg.UseLegacyAPI)
                {
                    Logger.Write(
                        "You bot will start after 15 seconds, You are running bot with Legacy API (0.45), but it will increase your risk of being banned and triggering captchas. Config Captchas in config.json to auto-resolve them",
                        LogLevel.Warning
                        );

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

            _session = new Session(settings,
                                   new ClientSettings(settings, elevationService), logicSettings, elevationService,
                                   translation
                                   );
            ioc.Register <ISession>(_session);

            Logger.SetLoggerContext(_session);

            MultiAccountManager accountManager = new MultiAccountManager(settings, logicSettings.Bots);
            ioc.Register(accountManager);

            if (boolNeedsSetup)
            {
                StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile);
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    var fileName = Assembly.GetEntryAssembly().Location;

                    Process.Start(fileName);
                    Environment.Exit(0);
                }

                //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);

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = _session.RuntimeStatistics;

            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);
            onBotStarted?.Invoke(_session, aggregator);

            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 +=
                (session, lat, lng, speed) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng, Speed = speed
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += LoadSaveState.SaveLocationToDisk;

            ProgressBar.Fill(100);

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

            var bot = accountManager.GetStartUpAccount();

            _session.ReInitSessionWithNextBot(bot);

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

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

            Logger.Write(
                $"(Start-Up Stats) User: {bot.Username} | XP: {bot.CurrentXp} | SD: {bot.Stardust}",
                LogLevel.Info, ConsoleColor
                .Magenta
                );

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

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

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


            if (_session.LogicSettings.DataSharingConfig.EnableSyncData)
            {
                BotDataSocketClient.StartAsync(_session, Properties.Resources.EncryptKey);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, certificate, chain, sslPolicyErrors) => true;
                //temporary disable MSniper connection because site under attacking.
                //MSniperServiceTask.ConnectToService();
                //_session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }

            // jjskuld - Don't await the analytics service since it starts a worker thread that never returns.
#pragma warning disable 4014
            _session.AnalyticsService.StartAsync(_session, _session.CancellationTokenSource.Token);
#pragma warning restore 4014
            _session.EventDispatcher.EventReceived += evt => AnalyticsService.Listen(evt, _session);

            var trackFile = Path.GetTempPath() + "\\necrobot2.io";

            if (!File.Exists(trackFile) || File.GetLastWriteTime(trackFile) < DateTime.Now.AddDays(-1))
            {
                Thread.Sleep(10000);
                Thread mThread = new Thread(delegate()
                {
                    var infoForm = new InfoForm();
                    infoForm.ShowDialog();
                });
                File.WriteAllText(trackFile, DateTime.Now.Ticks.ToString());
                mThread.SetApartmentState(ApartmentState.STA);

                mThread.Start();
            }

            QuitEvent.WaitOne();
        }
Esempio n. 14
0
        public static void TestSomething3()
        {
            List <DataManager> dataManagerList = Config.GetDataManagers();

            InfoForm.ShowValue(String.Join("\r\n\r\n", dataManagerList));
        }
        public static List <ToolStripItem> CreateSelectionToolStripItems(
            Func <List <WatchVariableControl> > getVars,
            WatchVariableFlowLayoutPanel panel)
        {
            Action <WatchVariableControlSettings, List <WatchVariableControl> > apply2 =
                (WatchVariableControlSettings settings, List <WatchVariableControl> vars) =>
            {
                if (KeyboardUtilities.IsCtrlHeld())
                {
                    WatchVariableControlSettingsManager.AddSettings(settings);
                }
                else
                {
                    vars.ForEach(control => control.ApplySettings(settings));
                }
            };

            Action <WatchVariableControlSettings> apply = (WatchVariableControlSettings settings) => apply2(settings, getVars());

            ToolStripMenuItem itemHighlight = new ToolStripMenuItem("Highlight...");

            ControlUtilities.AddDropDownItems(
                itemHighlight,
                new List <string>()
            {
                "Highlight", "Don't Highlight"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeHighlighted: true, newHighlighted: true)),
                () => apply(new WatchVariableControlSettings(changeHighlighted: true, newHighlighted: false)),
            });
            ToolStripMenuItem itemHighlightColor = new ToolStripMenuItem("Color...");

            ControlUtilities.AddDropDownItems(
                itemHighlightColor,
                new List <string>()
            {
                "Red",
                "Orange",
                "Yellow",
                "Green",
                "Blue",
                "Purple",
                "Pink",
                "Brown",
                "Black",
                "White",
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Red)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Orange)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Yellow)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Green)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Blue)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Purple)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Pink)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Brown)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.Black)),
                () => apply(new WatchVariableControlSettings(changeHighlightColor: true, newHighlightColor: Color.White)),
            });
            itemHighlight.DropDownItems.Add(itemHighlightColor);

            ToolStripMenuItem itemLock = new ToolStripMenuItem("Lock...");

            ControlUtilities.AddDropDownItems(
                itemLock,
                new List <string>()
            {
                "Lock", "Don't Lock"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeLocked: true, newLocked: true)),
                () => apply(new WatchVariableControlSettings(changeLocked: true, newLocked: false)),
            });

            ToolStripMenuItem itemFixAddress = new ToolStripMenuItem("Fix Address...");

            ControlUtilities.AddDropDownItems(
                itemFixAddress,
                new List <string>()
            {
                "Default", "Fix Address", "Fix Address Special", "Don't Fix Address"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeFixedAddress: true, changeFixedAddressToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeFixedAddress: true, newFixedAddress: true)),
                () => apply(new WatchVariableControlSettings(doFixAddressSpecial: true)),
                () => apply(new WatchVariableControlSettings(changeFixedAddress: true, newFixedAddress: false)),
            });

            ToolStripMenuItem itemCopy = new ToolStripMenuItem("Copy...");

            CopyUtilities.AddDropDownItems(itemCopy, getVars);

            ToolStripMenuItem itemPaste = new ToolStripMenuItem("Paste");

            itemPaste.Click += (sender, e) => PasteUtilities.Paste(getVars());

            ToolStripMenuItem itemRoundTo        = new ToolStripMenuItem("Round to...");
            ToolStripMenuItem itemRoundToDefault = new ToolStripMenuItem("Default");

            itemRoundToDefault.Click += (sender, e) =>
                                        apply(new WatchVariableControlSettings(
                                                  changeRoundingLimit: true, changeRoundingLimitToDefault: true));
            ToolStripMenuItem itemRoundToNoRounding = new ToolStripMenuItem("No Rounding");

            itemRoundToNoRounding.Click += (sender, e) =>
                                           apply(new WatchVariableControlSettings(
                                                     changeRoundingLimit: true, newRoundingLimit: -1));
            List <ToolStripMenuItem> itemsRoundToNumDecimalPlaces = new List <ToolStripMenuItem>();

            for (int i = 0; i <= 10; i++)
            {
                int index = i;
                itemsRoundToNumDecimalPlaces.Add(new ToolStripMenuItem(index + " decimal place(s)"));
                itemsRoundToNumDecimalPlaces[index].Click += (sender, e) =>
                                                             apply(new WatchVariableControlSettings(
                                                                       changeRoundingLimit: true, newRoundingLimit: index));
            }
            itemRoundTo.DropDownItems.Add(itemRoundToDefault);
            itemRoundTo.DropDownItems.Add(itemRoundToNoRounding);
            itemsRoundToNumDecimalPlaces.ForEach(setAllRoundingLimitsNumberItem =>
            {
                itemRoundTo.DropDownItems.Add(setAllRoundingLimitsNumberItem);
            });

            ToolStripMenuItem itemDisplayAsHex = new ToolStripMenuItem("Display as Hex...");

            ControlUtilities.AddDropDownItems(
                itemDisplayAsHex,
                new List <string>()
            {
                "Default", "Hex", "Decimal"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeDisplayAsHex: true, changeDisplayAsHexToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeDisplayAsHex: true, newDisplayAsHex: true)),
                () => apply(new WatchVariableControlSettings(changeDisplayAsHex: true, newDisplayAsHex: false)),
            });

            ToolStripMenuItem itemAngleSigned = new ToolStripMenuItem("Angle: Signed...");

            ControlUtilities.AddDropDownItems(
                itemAngleSigned,
                new List <string>()
            {
                "Default", "Unsigned", "Signed"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeAngleSigned: true, changeAngleSignedToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeAngleSigned: true, newAngleSigned: false)),
                () => apply(new WatchVariableControlSettings(changeAngleSigned: true, newAngleSigned: true)),
            });

            ToolStripMenuItem itemAngleUnits        = new ToolStripMenuItem("Angle: Units...");
            ToolStripMenuItem itemAngleUnitsDefault = new ToolStripMenuItem("Default");

            itemAngleUnitsDefault.Click += (sender, e) =>
                                           apply(new WatchVariableControlSettings(
                                                     changeAngleUnits: true, changeAngleUnitsToDefault: true));
            List <ToolStripMenuItem> itemsAngleUnitsValue = new List <ToolStripMenuItem>();

            foreach (AngleUnitType angleUnitType in Enum.GetValues(typeof(AngleUnitType)))
            {
                AngleUnitType angleUnitTypeFixed = angleUnitType;
                string        stringValue        = angleUnitTypeFixed.ToString();
                if (stringValue == AngleUnitType.InGameUnits.ToString())
                {
                    stringValue = "In-Game Units";
                }
                ToolStripMenuItem itemAngleUnitsValue = new ToolStripMenuItem(stringValue);
                itemAngleUnitsValue.Click += (sender, e) =>
                                             apply(new WatchVariableControlSettings(
                                                       changeAngleUnits: true, newAngleUnits: angleUnitTypeFixed));
                itemsAngleUnitsValue.Add(itemAngleUnitsValue);
            }
            itemAngleUnits.DropDownItems.Add(itemAngleUnitsDefault);
            itemsAngleUnitsValue.ForEach(setAllAngleUnitsValuesItem =>
            {
                itemAngleUnits.DropDownItems.Add(setAllAngleUnitsValuesItem);
            });

            ToolStripMenuItem itemAngleTruncateToMultipleOf16 = new ToolStripMenuItem("Angle: Truncate to Multiple of 16...");

            ControlUtilities.AddDropDownItems(
                itemAngleTruncateToMultipleOf16,
                new List <string>()
            {
                "Default", "Truncate to Multiple of 16", "Don't Truncate to Multiple of 16"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeAngleTruncateToMultipleOf16: true, changeAngleTruncateToMultipleOf16ToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeAngleTruncateToMultipleOf16: true, newAngleTruncateToMultipleOf16: true)),
                () => apply(new WatchVariableControlSettings(changeAngleTruncateToMultipleOf16: true, newAngleTruncateToMultipleOf16: false)),
            });

            ToolStripMenuItem itemAngleConstrainToOneRevolution = new ToolStripMenuItem("Angle: Constrain to One Revolution...");

            ControlUtilities.AddDropDownItems(
                itemAngleConstrainToOneRevolution,
                new List <string>()
            {
                "Default", "Constrain to One Revolution", "Don't Constrain to One Revolution"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeAngleConstrainToOneRevolution: true, changeAngleConstrainToOneRevolutionToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeAngleConstrainToOneRevolution: true, newAngleConstrainToOneRevolution: true)),
                () => apply(new WatchVariableControlSettings(changeAngleConstrainToOneRevolution: true, newAngleConstrainToOneRevolution: false)),
            });

            ToolStripMenuItem itemAngleReverse = new ToolStripMenuItem("Angle: Reverse...");

            ControlUtilities.AddDropDownItems(
                itemAngleReverse,
                new List <string>()
            {
                "Default", "Reverse", "Don't Reverse"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeAngleReverse: true, changeAngleReverseToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeAngleReverse: true, newAngleReverse: true)),
                () => apply(new WatchVariableControlSettings(changeAngleReverse: true, newAngleReverse: false)),
            });

            ToolStripMenuItem itemAngleDisplayAsHex = new ToolStripMenuItem("Angle: Display as Hex...");

            ControlUtilities.AddDropDownItems(
                itemAngleDisplayAsHex,
                new List <string>()
            {
                "Default", "Hex", "Decimal"
            },
                new List <Action>()
            {
                () => apply(new WatchVariableControlSettings(changeAngleDisplayAsHex: true, changeAngleDisplayAsHexToDefault: true)),
                () => apply(new WatchVariableControlSettings(changeAngleDisplayAsHex: true, newAngleDisplayAsHex: true)),
                () => apply(new WatchVariableControlSettings(changeAngleDisplayAsHex: true, newAngleDisplayAsHex: false)),
            });

            ToolStripMenuItem itemShowVariableXml = new ToolStripMenuItem("Show Variable XML");

            itemShowVariableXml.Click += (sender, e) =>
            {
                InfoForm infoForm = new InfoForm();
                infoForm.SetText(
                    "Variable Info",
                    "Variable XML",
                    String.Join("\r\n", getVars().ConvertAll(control => control.ToXml(true))));
                infoForm.Show();
            };

            ToolStripMenuItem itemShowVariableInfo = new ToolStripMenuItem("Show Variable Info");

            itemShowVariableInfo.Click += (sender, e) =>
            {
                InfoForm infoForm = new InfoForm();
                infoForm.SetText(
                    "Variable Info",
                    "Variable Info",
                    String.Join("\t",
                                WatchVariableWrapper.GetVarInfoLabels()) +
                    "\r\n" +
                    String.Join(
                        "\r\n",
                        getVars().ConvertAll(control => control.GetVarInfo())
                        .ConvertAll(infoList => String.Join("\t", infoList))));
                infoForm.Show();
            };

            void createBinaryMathOperationVariable(BinaryMathOperation operation)
            {
                List <WatchVariableControl> controls = getVars();

                if (controls.Count % 2 == 1)
                {
                    controls.RemoveAt(controls.Count - 1);
                }

                for (int i = 0; i < controls.Count / 2; i++)
                {
                    WatchVariableControl control1 = controls[i];
                    WatchVariableControl control2 = controls[i + controls.Count / 2];
                    string specialType            = WatchVariableSpecialUtilities.AddBinaryMathOperationEntry(control1, control2, operation);
                    string name = string.Format("{0} {1} {2}", control1.VarName, MathOperationUtilities.GetSymbol(operation), control2.VarName);

                    WatchVariable watchVariable =
                        new WatchVariable(
                            name: name,
                            memoryTypeName: null,
                            specialType: specialType,
                            baseAddressType: BaseAddressTypeEnum.None,
                            offsetUS: null,
                            offsetJP: null,
                            offsetSH: null,
                            offsetEU: null,
                            offsetDefault: null,
                            mask: null,
                            shift: null,
                            handleMapping: true);
                    WatchVariableControlPrecursor precursor =
                        new WatchVariableControlPrecursor(
                            name: name,
                            watchVar: watchVariable,
                            subclass: WatchVariableSubclass.Number,
                            backgroundColor: null,
                            displayType: null,
                            roundingLimit: null,
                            useHex: null,
                            invertBool: null,
                            isYaw: null,
                            coordinate: null,
                            groupList: new List <VariableGroup>()
                    {
                        VariableGroup.Custom
                    });
                    WatchVariableControl control = precursor.CreateWatchVariableControl();
                    panel.AddVariable(control);
                }
            }

            void createAggregateMathOperationVariable(AggregateMathOperation operation)
            {
                List <WatchVariableControl> controls = getVars();

                if (controls.Count == 0)
                {
                    return;
                }
                string        specialType   = WatchVariableSpecialUtilities.AddAggregateMathOperationEntry(controls, operation);
                string        name          = operation.ToString();
                WatchVariable watchVariable =
                    new WatchVariable(
                        name: name,
                        memoryTypeName: null,
                        specialType: specialType,
                        baseAddressType: BaseAddressTypeEnum.None,
                        offsetUS: null,
                        offsetJP: null,
                        offsetSH: null,
                        offsetEU: null,
                        offsetDefault: null,
                        mask: null,
                        shift: null,
                        handleMapping: true);
                WatchVariableControlPrecursor precursor =
                    new WatchVariableControlPrecursor(
                        name: name,
                        watchVar: watchVariable,
                        subclass: WatchVariableSubclass.Number,
                        backgroundColor: null,
                        displayType: null,
                        roundingLimit: null,
                        useHex: null,
                        invertBool: null,
                        isYaw: null,
                        coordinate: null,
                        groupList: new List <VariableGroup>()
                {
                    VariableGroup.Custom
                });
                WatchVariableControl control = precursor.CreateWatchVariableControl();

                panel.AddVariable(control);
            }

            void createDistanceMathOperationVariable(bool use3D)
            {
                List <WatchVariableControl> controls = getVars();
                bool satisfies2D = !use3D && controls.Count >= 4;
                bool satisfies3D = use3D && controls.Count >= 6;

                if (!satisfies2D && !satisfies3D)
                {
                    return;
                }
                string specialType = WatchVariableSpecialUtilities.AddDistanceMathOperationEntry(controls, use3D);
                string name        = use3D ?
                                     string.Format(
                    "({0},{1},{2}) to ({3},{4},{5})",
                    controls[0].VarName,
                    controls[1].VarName,
                    controls[2].VarName,
                    controls[3].VarName,
                    controls[4].VarName,
                    controls[5].VarName) :
                                     string.Format(
                    "({0},{1}) to ({2},{3})",
                    controls[0].VarName,
                    controls[1].VarName,
                    controls[2].VarName,
                    controls[3].VarName);
                WatchVariable watchVariable =
                    new WatchVariable(
                        name: name,
                        memoryTypeName: null,
                        specialType: specialType,
                        baseAddressType: BaseAddressTypeEnum.None,
                        offsetUS: null,
                        offsetJP: null,
                        offsetSH: null,
                        offsetEU: null,
                        offsetDefault: null,
                        mask: null,
                        shift: null,
                        handleMapping: true);
                WatchVariableControlPrecursor precursor =
                    new WatchVariableControlPrecursor(
                        name: name,
                        watchVar: watchVariable,
                        subclass: WatchVariableSubclass.Number,
                        backgroundColor: null,
                        displayType: null,
                        roundingLimit: null,
                        useHex: null,
                        invertBool: null,
                        isYaw: null,
                        coordinate: null,
                        groupList: new List <VariableGroup>()
                {
                    VariableGroup.Custom
                });
                WatchVariableControl control = precursor.CreateWatchVariableControl();

                panel.AddVariable(control);
            }

            void createRealTimeVariable()
            {
                List <WatchVariableControl> controls = getVars();

                for (int i = 0; i < controls.Count; i++)
                {
                    WatchVariableControl control = controls[i];
                    string specialType           = WatchVariableSpecialUtilities.AddRealTimeEntry(control);
                    string name = string.Format("{0} Real Time", control.VarName);

                    WatchVariable watchVariable =
                        new WatchVariable(
                            name: name,
                            memoryTypeName: null,
                            specialType: specialType,
                            baseAddressType: BaseAddressTypeEnum.None,
                            offsetUS: null,
                            offsetJP: null,
                            offsetSH: null,
                            offsetEU: null,
                            offsetDefault: null,
                            mask: null,
                            shift: null,
                            handleMapping: true);
                    WatchVariableControlPrecursor precursor =
                        new WatchVariableControlPrecursor(
                            name: name,
                            watchVar: watchVariable,
                            subclass: WatchVariableSubclass.String,
                            backgroundColor: null,
                            displayType: null,
                            roundingLimit: null,
                            useHex: null,
                            invertBool: null,
                            isYaw: null,
                            coordinate: null,
                            groupList: new List <VariableGroup>()
                    {
                        VariableGroup.Custom
                    });
                    WatchVariableControl control2 = precursor.CreateWatchVariableControl();
                    panel.AddVariable(control2);
                }
            }

            void createActionDescriptionVariable()
            {
                List <WatchVariableControl> controls = getVars();

                for (int i = 0; i < controls.Count; i++)
                {
                    WatchVariableControl control = controls[i];
                    string specialType           = WatchVariableSpecialUtilities.AddActionDescriptionEntry(control);
                    string name = string.Format("{0} Description", control.VarName);

                    WatchVariable watchVariable =
                        new WatchVariable(
                            name: name,
                            memoryTypeName: null,
                            specialType: specialType,
                            baseAddressType: BaseAddressTypeEnum.None,
                            offsetUS: null,
                            offsetJP: null,
                            offsetSH: null,
                            offsetEU: null,
                            offsetDefault: null,
                            mask: null,
                            shift: null,
                            handleMapping: true);
                    WatchVariableControlPrecursor precursor =
                        new WatchVariableControlPrecursor(
                            name: name,
                            watchVar: watchVariable,
                            subclass: WatchVariableSubclass.String,
                            backgroundColor: null,
                            displayType: null,
                            roundingLimit: null,
                            useHex: null,
                            invertBool: null,
                            isYaw: null,
                            coordinate: null,
                            groupList: new List <VariableGroup>()
                    {
                        VariableGroup.Custom
                    });
                    WatchVariableControl control2 = precursor.CreateWatchVariableControl();
                    panel.AddVariable(control2);
                }
            }

            void createDereferencedVariable(string typeString)
            {
                List <WatchVariableControl> controls = getVars();
                uint?offset = null;

                if (KeyboardUtilities.IsCtrlHeld())
                {
                    string offsetString = DialogUtilities.GetStringFromDialog(labelText: "Enter Offset in Hex:");
                    if (offsetString != null)
                    {
                        offset = ParsingUtilities.ParseHexNullable(offsetString);
                    }
                }
                for (int i = 0; i < controls.Count; i++)
                {
                    WatchVariableControl control = controls[i];
                    string specialType           = WatchVariableSpecialUtilities.AddDereferencedEntry(control, typeString, offset);
                    string name = string.Format("{0}{1} Deref", control.VarName, offset.HasValue ? " + " + HexUtilities.FormatValue(offset.Value) : "");

                    WatchVariable watchVariable =
                        new WatchVariable(
                            name: name,
                            memoryTypeName: null,
                            specialType: specialType,
                            baseAddressType: BaseAddressTypeEnum.None,
                            offsetUS: null,
                            offsetJP: null,
                            offsetSH: null,
                            offsetEU: null,
                            offsetDefault: null,
                            mask: null,
                            shift: null,
                            handleMapping: true);
                    WatchVariableControlPrecursor precursor =
                        new WatchVariableControlPrecursor(
                            name: name,
                            watchVar: watchVariable,
                            subclass: WatchVariableSubclass.Number,
                            backgroundColor: null,
                            displayType: null,
                            roundingLimit: null,
                            useHex: null,
                            invertBool: null,
                            isYaw: null,
                            coordinate: null,
                            groupList: new List <VariableGroup>()
                    {
                        VariableGroup.Custom
                    });
                    WatchVariableControl control2 = precursor.CreateWatchVariableControl();
                    panel.AddVariable(control2);
                }
            }

            ToolStripMenuItem itemAddDereferencedVariable = new ToolStripMenuItem("Dereferenced...");

            foreach (string typeString in TypeUtilities.InGameTypeList)
            {
                ToolStripMenuItem typeItem = new ToolStripMenuItem(typeString);
                itemAddDereferencedVariable.DropDownItems.Add(typeItem);
                typeItem.Click += (sender, e) =>
                {
                    createDereferencedVariable(typeString);
                };
            }
            ToolStripMenuItem itemAddVariables = new ToolStripMenuItem("Add Variable(s)...");

            ControlUtilities.AddDropDownItems(
                itemAddVariables,
                new List <string>()
            {
                "Addition",
                "Subtraction",
                "Multiplication",
                "Division",
                "Modulo",
                "Non-Negative Modulo",
                "Exponent",
                null,
                "Mean",
                "Median",
                "Min",
                "Max",
                "Sum",
                null,
                "2D Distance",
                "3D Distance",
                null,
                "Real Time",
                "Action Description",
            },
                new List <Action>()
            {
                () => createBinaryMathOperationVariable(BinaryMathOperation.Add),
                () => createBinaryMathOperationVariable(BinaryMathOperation.Subtract),
                () => createBinaryMathOperationVariable(BinaryMathOperation.Multiply),
                () => createBinaryMathOperationVariable(BinaryMathOperation.Divide),
                () => createBinaryMathOperationVariable(BinaryMathOperation.Modulo),
                () => createBinaryMathOperationVariable(BinaryMathOperation.NonNegativeModulo),
                () => createBinaryMathOperationVariable(BinaryMathOperation.Exponent),
                () => { },
                () => createAggregateMathOperationVariable(AggregateMathOperation.Mean),
                () => createAggregateMathOperationVariable(AggregateMathOperation.Median),
                () => createAggregateMathOperationVariable(AggregateMathOperation.Min),
                () => createAggregateMathOperationVariable(AggregateMathOperation.Max),
                () => createAggregateMathOperationVariable(AggregateMathOperation.Sum),
                () => { },
                () => createDistanceMathOperationVariable(use3D: false),
                () => createDistanceMathOperationVariable(use3D: true),
                () => { },
                () => createRealTimeVariable(),
                () => createActionDescriptionVariable(),
            });
            itemAddVariables.DropDownItems.Add(itemAddDereferencedVariable);

            ToolStripMenuItem itemSetCascadingValues = new ToolStripMenuItem("Set Cascading Values");

            itemSetCascadingValues.Click += (sender, e) =>
            {
                List <WatchVariableControl> controls = getVars();
                object value1 = DialogUtilities.GetStringFromDialog(labelText: "Base Value:");
                object value2 = DialogUtilities.GetStringFromDialog(labelText: "Offset Value:");
                if (value1 == null || value2 == null)
                {
                    return;
                }
                double?number1 = ParsingUtilities.ParseDoubleNullable(value1);
                double?number2 = ParsingUtilities.ParseDoubleNullable(value2);
                if (!number1.HasValue || !number2.HasValue)
                {
                    return;
                }
                List <Func <object, bool, bool> > setters = controls.SelectMany(control => control.GetSetters()).ToList();
                for (int i = 0; i < setters.Count; i++)
                {
                    setters[i](number1.Value + i * number2.Value, true);
                }
            };

            List <string> backgroundColorStringList = new List <string>();
            List <Action> backgroundColorActionList = new List <Action>();

            backgroundColorStringList.Add("Default");
            backgroundColorActionList.Add(
                () => apply(new WatchVariableControlSettings(changeBackgroundColor: true, changeBackgroundColorToDefault: true)));
            foreach (KeyValuePair <string, string> pair in ColorUtilities.ColorToParamsDictionary)
            {
                Color  color       = ColorTranslator.FromHtml(pair.Value);
                string colorString = pair.Key;
                if (colorString == "LightBlue")
                {
                    colorString = "Light Blue";
                }
                backgroundColorStringList.Add(colorString);
                backgroundColorActionList.Add(
                    () => apply(new WatchVariableControlSettings(changeBackgroundColor: true, newBackgroundColor: color)));
            }
            backgroundColorStringList.Add("Control (No Color)");
            backgroundColorActionList.Add(
                () => apply(new WatchVariableControlSettings(changeBackgroundColor: true, newBackgroundColor: SystemColors.Control)));
            backgroundColorStringList.Add("Custom Color");
            backgroundColorActionList.Add(
                () =>
            {
                List <WatchVariableControl> vars = getVars();
                Color?newColor = ColorUtilities.GetColorFromDialog(SystemColors.Control);
                if (newColor.HasValue)
                {
                    apply2(new WatchVariableControlSettings(changeBackgroundColor: true, newBackgroundColor: newColor.Value), vars);
                    ColorUtilities.LastCustomColor = newColor.Value;
                }
            });
            backgroundColorStringList.Add("Last Custom Color");
            backgroundColorActionList.Add(
                () => apply(new WatchVariableControlSettings(changeBackgroundColor: true, newBackgroundColor: ColorUtilities.LastCustomColor)));
            ToolStripMenuItem itemBackgroundColor = new ToolStripMenuItem("Background Color...");

            ControlUtilities.AddDropDownItems(
                itemBackgroundColor,
                backgroundColorStringList,
                backgroundColorActionList);

            ToolStripMenuItem itemMove = new ToolStripMenuItem("Move...");

            ControlUtilities.AddDropDownItems(
                itemMove,
                new List <string>()
            {
                "Start Move", "End Move", "Clear Move"
            },
                new List <Action>()
            {
                () => panel.NotifyOfReorderingStart(getVars()),
                () => panel.NotifyOfReorderingEnd(getVars()),
                () => panel.NotifyOfReorderingClear(),
            });

            ToolStripMenuItem itemRemove = new ToolStripMenuItem("Remove");

            itemRemove.Click += (sender, e) => panel.RemoveVariables(getVars());

            ToolStripMenuItem itemRename = new ToolStripMenuItem("Rename...");

            itemRename.Click += (sender, e) =>
            {
                List <WatchVariableControl> watchVars = getVars();
                string template = DialogUtilities.GetStringFromDialog("$");
                if (template == null)
                {
                    return;
                }
                foreach (WatchVariableControl control in watchVars)
                {
                    control.VarName = template.Replace("$", control.VarName);
                }
            };

            ToolStripMenuItem itemOpenController = new ToolStripMenuItem("Open Controller");

            itemOpenController.Click += (sender, e) =>
            {
                List <WatchVariableControl> vars          = getVars();
                VariableControllerForm      varController =
                    new VariableControllerForm(
                        vars.ConvertAll(control => control.VarName),
                        vars.ConvertAll(control => control.WatchVarWrapper),
                        vars.ConvertAll(control => control.FixedAddressListGetter()));
                varController.Show();
            };

            ToolStripMenuItem itemOpenTripletController = new ToolStripMenuItem("Open Triplet Controller");

            itemOpenTripletController.Click += (sender, e) =>
            {
                VariableTripletControllerForm form = new VariableTripletControllerForm();
                form.Initialize(getVars().ConvertAll(control => control.CreateCopy()));
                form.ShowForm();
            };

            ToolStripMenuItem itemOpenPopOut = new ToolStripMenuItem("Open Pop Out");

            itemOpenPopOut.Click += (sender, e) =>
            {
                VariablePopOutForm form = new VariablePopOutForm();
                form.Initialize(getVars().ConvertAll(control => control.CreateCopy()));
                form.ShowForm();
            };

            ToolStripMenuItem itemAddToTab = new ToolStripMenuItem("Add to Tab...");

            ControlUtilities.AddDropDownItems(
                itemAddToTab,
                new List <string>()
            {
                "Regular", "Fixed", "Grouped by Base Address", "Grouped by Variable"
            },
                new List <Action>()
            {
                () => SelectionForm.ShowDataManagerSelectionForm(getVars(), AddToTabTypeEnum.Regular),
                () => SelectionForm.ShowDataManagerSelectionForm(getVars(), AddToTabTypeEnum.Fixed),
                () => SelectionForm.ShowDataManagerSelectionForm(getVars(), AddToTabTypeEnum.GroupedByBaseAddress),
                () => SelectionForm.ShowDataManagerSelectionForm(getVars(), AddToTabTypeEnum.GroupedByVariable),
            });

            ToolStripMenuItem itemAddToCustomTab = new ToolStripMenuItem("Add to Custom Tab...");

            ControlUtilities.AddDropDownItems(
                itemAddToCustomTab,
                new List <string>()
            {
                "Regular", "Fixed", "Grouped by Base Address", "Grouped by Variable"
            },
                new List <Action>()
            {
                () => WatchVariableControl.AddVarsToTab(getVars(), Config.CustomManager, AddToTabTypeEnum.Regular),
                () => WatchVariableControl.AddVarsToTab(getVars(), Config.CustomManager, AddToTabTypeEnum.Fixed),
                () => WatchVariableControl.AddVarsToTab(getVars(), Config.CustomManager, AddToTabTypeEnum.GroupedByBaseAddress),
                () => WatchVariableControl.AddVarsToTab(getVars(), Config.CustomManager, AddToTabTypeEnum.GroupedByVariable),
            });

            return(new List <ToolStripItem>()
            {
                itemHighlight,
                itemLock,
                itemFixAddress,
                itemCopy,
                itemPaste,
                new ToolStripSeparator(),
                itemRoundTo,
                itemDisplayAsHex,
                new ToolStripSeparator(),
                itemAngleSigned,
                itemAngleUnits,
                itemAngleTruncateToMultipleOf16,
                itemAngleConstrainToOneRevolution,
                itemAngleReverse,
                itemAngleDisplayAsHex,
                new ToolStripSeparator(),
                itemShowVariableXml,
                itemShowVariableInfo,
                new ToolStripSeparator(),
                itemAddVariables,
                itemSetCascadingValues,
                new ToolStripSeparator(),
                itemBackgroundColor,
                itemMove,
                itemRemove,
                itemRename,
                itemOpenController,
                itemOpenTripletController,
                itemOpenPopOut,
                itemAddToTab,
                itemAddToCustomTab,
            });
        }
Esempio n. 16
0
        private void infoButton_Click(object sender, EventArgs e)
        {
            InfoForm frm = new InfoForm();

            frm.Show();
        }
 public MainForm()     // constructor
 {
     InitializeComponent();
     this.forwardForm = new InfoForm(this);
 }
        private void ShowInfo(object sender, EventArgs e)
        {
            InfoForm infoForm = new InfoForm();

            infoForm.ShowDialog();
        }
Esempio n. 19
0
        public static void RunBotWithParameters(Action <ISession, StatisticsAggregator> onBotStarted, string[] args)
        {
            var ioc = TinyIoC.TinyIoCContainer.Current;

            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
                }
            }

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

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

            TinyIoC.TinyIoCContainer.Current.Register <ITranslation>(translation);

            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() == 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
                );
            ioc.Register <ISession>(_session);

            Logger.SetLoggerContext(_session);

            if (boolNeedsSetup)
            {
                StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile);
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    var fileName = Assembly.GetExecutingAssembly().Location;
                    Process.Start(fileName);
                    Environment.Exit(0);
                }

                //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   = _session.RuntimeStatistics;

            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);
            if (onBotStarted != null)
            {
                onBotStarted(_session, aggregator);
            }

            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 +=
                (session, lat, lng, speed) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng, Speed = speed
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += LoadSaveState.SaveLocationToDisk;

            ProgressBar.Fill(100);

            var accountManager = new MultiAccountManager(logicSettings.Bots);

            var mainAccount = accountManager.Add(settings.Auth.AuthConfig);

            ioc.Register <MultiAccountManager>(accountManager);



            var bot = accountManager.GetStartUpAccount();

            _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)
            {
                // jjskuld - Ignore CS4014 warning for now.
                #pragma warning disable 4014
                HumanWalkSnipeTask.StartFastPokemapAsync(_session,
                                                         _session.CancellationTokenSource.Token); // that need to keep data live
                #pragma warning restore 4014
            }

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

            if (_session.LogicSettings.ActivateMSniper)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, certificate, chain, sslPolicyErrors) => true;
                //temporary disable MSniper connection because site under attacking.
                //MSniperServiceTask.ConnectToService();
                //_session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }
            var trackFile = Path.GetTempPath() + "\\necrobot2.io";

            if (!File.Exists(trackFile) || File.GetLastWriteTime(trackFile) < DateTime.Now.AddDays(-1))
            {
                Thread.Sleep(10000);
                Thread mThread = new Thread(delegate()
                {
                    var infoForm = new InfoForm();
                    infoForm.ShowDialog();
                });
                File.WriteAllText(trackFile, DateTime.Now.Ticks.ToString());
                mThread.SetApartmentState(ApartmentState.STA);

                mThread.Start();
            }

            QuitEvent.WaitOne();
        }
 //------ Info Form ------
 private void CreateInfo()
 {
     InfoForm info = new InfoForm();
     info.Show();
 }
Esempio n. 21
0
        /// <summary>
        /// This menu command allows the user to multi-select a handful of gesture XML files from a directory, and 
        /// to produce an output file containing the recognition results for everything in the directory.
        /// </summary>
        /// <param name="sender">The sender of this event.</param>
        /// <param name="e">The arguments for this event.</param>
        /// <remarks>
        /// The gestures loaded must conform to a naming convention where each example of a particular gesture is named 
        /// with the same string, followed by a numerical identifier for that example. As in:
        ///
        ///     circle01.xml        // circle gestures
        ///     circle02.xml
        ///     circle03.xml
        ///     square01.xml        // square gestures
        ///     square02.xml
        ///     square03.xml
        ///     triangle01.xml      // triangle gestures
        ///     triangle02.xml
        ///     triangle03.xml
        ///
        /// The same number of examples should be read in for each gesture category. The testing procedure will load a 
        /// random subset of each gesture and test on the remaining gestures.
        /// 
        /// <b>Warning.</b> This process will throw an exception if the number of gesture examples for each gesture is 
        /// unbalanced.
        /// </remarks>
        private void TestBatch_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Gestures (*.xml)|*.xml";
            dlg.Title = "Load Gesture Batch";
            dlg.Multiselect = true;
            dlg.RestoreDirectory = false;

            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                InfoForm ifrm = new InfoForm();
                if (ifrm.ShowDialog(this) == DialogResult.OK)
                {
                    prgTesting.Visible = true;
                    lblRecognizing.Visible = true;
                    Application.DoEvents();

                    // each slot in the list contains a gesture Category, which contains a list of gesture prototypes.
                    List<Category> categories = _rec.AssembleBatch(dlg.FileNames);

                    if (categories != null)
                    {
                        string[] rstr = _rec.TestBatch(
                            ifrm.Subject.ToString(),
                            ifrm.Speed, 
                            categories, 
                            dlg.FileName.Substring(0, dlg.FileName.LastIndexOf('\\')),
                            _protractor
                            );
                        if (rstr != null)
                        {
                            MessageBox.Show(this, "Testing complete.", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            MessageBox.Show(this, "There was an error writing the output file during testing.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else // error assembling batch
                    {
                        MessageBox.Show(this, "Unreadable files, or unbalanced number of gestures in categories.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    lblRecognizing.Visible = false;
                    prgTesting.Visible = false;
                }
            }
        }