/// <summary>
        ///     Add a Global Hotkey
        /// </summary>
        /// <param name="hotkey">Hotkey</param>
        /// <returns>True on success</returns>
        public bool Add(Hotkey hotkey)
        {
            var id = 0;

            // Add hotkey to settings
            try
            {
                Settings.Default.HotKeys.Add(hotkey);
                Logger.Instance.WriteGlobal("Register hotkey: {0} - {1}+{2}", hotkey.Name,
                                            hotkey.Modifier.ToString().Replace(", ", "+"), hotkey.Key);
                id            = _keyboardHook.RegisterHotKey(hotkey.Modifier, hotkey.Key);
                hotkey.HookId = id;

                foreach (var action in hotkey.Actions)
                {
                    Debug.WriteLine("Initialize Hotkey: {0} {1}", action.Name, action.Version);
                    ActionContainer.GetAction(action.Name, action.Version).OnInitialize(hotkey);
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.WriteGlobal("Failed to register hotkey with message: " + ex.Message);
                DebugHelper.Exception(ex);
            }
            return(id >= 1);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates a new user account
        /// </summary>
        /// <param name="name">User login name</param>
        /// <param name="password">User password</param>
        /// <param name="fullName">User full name</param>
        /// <param name="isAdmin">flag as admin</param>
        /// <returns>returns true when user is successfully created</returns>
        public static bool Create(string name, string password, string fullName = "", bool isAdmin = false)
        {
            try
            {
                var dirEntry = new DirectoryEntry("WinNT://localhost");
                var entries  = dirEntry.Children;
                var newUser  = entries.Add(name, "user");
                newUser.Properties["FullName"].Add(fullName);
                newUser.Invoke("SetPassword", password);
                newUser.CommitChanges();

                // Remove the if condition along with the else to create user account in "user" group.
                DirectoryEntry grp;
                grp = dirEntry.Children.Find(UserGroup, "group");
                grp.Invoke("Add", new object[] { newUser.Path });

                if (isAdmin)
                {
                    grp = dirEntry.Children.Find(AdminGroup, "group");
                    grp.Invoke("Add", new object[] { newUser.Path });
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.WriteGlobal("Failed to add new user: {0}", name);
                DebugHelper.Exception(ex);
                return(false);
            }

            return((isAdmin && ExistsAsAdmin(name)) || (Exists(name)));
        }
Ejemplo n.º 3
0
        public void CrashCheck()
        {
            if (Proc.HasExited)
            {
                return;
            }

            if (Proc.Responding)
            {
                _lastRepsonse = DateTime.Now;
            }

            if (DateTime.Now.Subtract(_lastRepsonse).TotalSeconds > 90)
            {
                Logger.Instance.Write(Parent, "Demonbuddy:{0}: Is unresponsive for more than 30 seconds", Proc.Id);
                Logger.Instance.Write(Parent, "Demonbuddy:{0}: Killing process", Proc.Id);
                try
                {
                    if (Proc != null && !Proc.HasExited)
                    {
                        Proc.CloseMainWindow();
                    }
                    //Proc.Kill();
                }
                catch (Exception ex)
                {
                    Logger.Instance.Write(Parent, "Failed to kill process", ex.Message);
                    DebugHelper.Exception(ex);
                }
            }
        }
Ejemplo n.º 4
0
 private void button1_Click(object sender, EventArgs e)
 { // UP
     if (dataGridView1.SelectedCells.Count <= 0 && dataGridView1.SelectedCells[0].RowIndex <= 0)
     {
         return;
     }
     try
     {
         var index = dataGridView1.SelectedCells[0].RowIndex;
         var test  = Settings.Default.AutoPosScreens.FirstOrDefault(x => x.Name == (string)dataGridView1.Rows[index].Cells["Name"].Value && x.Order > 0);
         if (test != null)
         {
             test.Order--;
             index--;
             test = Settings.Default.AutoPosScreens.FirstOrDefault(x => index >= 0 && x.Name == (string)dataGridView1.Rows[index].Cells["Name"].Value && x.Order >= 0);
             if (test != null)
             {
                 test.Order++;
             }
         }
         // Sort and update list
         Settings.Default.AutoPosScreens.Sort((s1, s2) => s1.Order.CompareTo(s2.Order));
         updateGridView();
     }
     catch (Exception ex)
     {
         DebugHelper.Exception(ex);
     }
 }
Ejemplo n.º 5
0
 private void updateMainformLabel(System.Windows.Forms.Label label, string value)
 {
     if (Program.Mainform == null || label == null)
     {
         return;
     }
     try
     {
         Program.Mainform.Invoke(new Action(() =>
         {
             try
             {
                 label.Text = value;
             }
             catch (Exception ex)
             {
                 DebugHelper.Exception(ex);
             }
         }));
     }
     catch (Exception ex)
     {
         DebugHelper.Exception(ex);
     }
 }
Ejemplo n.º 6
0
 public static bool WindowsAutoStartDel()
 {
     try
     {
         RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
         if (key == null)
         {
             Logger.Instance.WriteGlobal(
                 "Failed to get registry key \"Software\\Microsoft\\Windows\\CurrentVersion\\Run\"");
             return(false);
         }
         if (key.GetValue("YetAnotherRelogger") != null)
         {
             key.DeleteValue("YetAnotherRelogger");
         }
         key.Close();
         return(true);
     }
     catch (Exception ex)
     {
         Logger.Instance.WriteGlobal("Failed to delete registry key: {0}", ex.Message);
         DebugHelper.Exception(ex);
         return(false);
     }
 }
Ejemplo n.º 7
0
        public void CrashCheck()
        {
            if (Proc.HasExited)
            {
                return;
            }

            if (Proc.Responding)
            {
                _lastRepsonse = DateTime.Now;
                Parent.Status = "Monitoring";
            }
            else
            {
                Parent.Status = string.Format("Diablo is unresponsive ({0} secs)", DateTime.Now.Subtract(_lastRepsonse).TotalSeconds);
            }

            if (DateTime.Now.Subtract(_lastRepsonse).TotalSeconds > 120)
            {
                Logger.Instance.Write("Diablo:{0}: Is unresponsive for more than 120 seconds", Proc.Id);
                Logger.Instance.Write("Diablo:{0}: Killing process", Proc.Id);
                try
                {
                    if (Proc != null && !Proc.HasExited)
                    {
                        Proc.Kill();
                    }
                }
                catch (Exception ex)
                {
                    DebugHelper.Exception(ex);
                }
            }
        }
Ejemplo n.º 8
0
 protected virtual void OnPropertyChanged(string propertyName)
 {
     try
     {
         if (Program.Mainform == null)
         {
             return;
         }
         Program.Mainform.Invoke(new Action(() =>
         {
             try
             {
                 PropertyChangedEventHandler handler = PropertyChanged;
                 if (handler != null)
                 {
                     handler(this, new PropertyChangedEventArgs(propertyName));
                 }
             }
             catch (Exception ex)
             {
                 DebugHelper.Exception(ex);
             }
         }));
     }
     catch (Exception ex)
     {
         DebugHelper.Exception(ex);
     }
 }
Ejemplo n.º 9
0
        private void ApocD3Starter()
        {
            Parent.Status = "D3Starter: Starting Diablo"; // Update Status
            var d3StarterSuccess = false;

            try
            {
                var starter = new Process
                {
                    StartInfo =
                    {
                        FileName               = Settings.Default.D3StarterPath,
                        WorkingDirectory       = Path.GetDirectoryName(Settings.Default.D3StarterPath),
                        Arguments              = string.Format("\"{0}\" 1",                            Location2),
                        UseShellExecute        = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow         = true,
                        WindowStyle            = ProcessWindowStyle.Hidden
                    }
                };
                starter.StartInfo = UserAccount.ImpersonateStartInfo(starter.StartInfo, Parent);
                starter.Start();

                Match m;
                while (!starter.HasExited)
                {
                    var l = starter.StandardOutput.ReadLine();
                    if (l == null)
                    {
                        continue;
                    }

                    Logger.Instance.Write("D3Starter: " + l);
                    if ((m = Regex.Match(l, @"Process ID (\d+) started.")).Success)
                    {
                        Proc = Process.GetProcessById(Convert.ToInt32(m.Groups[1].Value));
                    }
                    if (Regex.Match(l, @"\d game instances started! All done!").Success)
                    {
                        d3StarterSuccess = true;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.Write("D3Starter Error: {0}", ex.Message);
                DebugHelper.Exception(ex);
            }

            if (!d3StarterSuccess)
            {
                Logger.Instance.Write("D3Starter failed!");
                Parent.Stop();
                Parent.Status = "D3Starter Failed!";
            }
        }
Ejemplo n.º 10
0
        private void CreateChartStats(BotClass bot, Chart graph, ChartValueType valueType = ChartValueType.Auto)
        {
            if (Program.Mainform != null && graph != null)
            {
                try
                {
                    Program.Mainform.Invoke(new Action(() =>
                    {
                        try
                        {
                            if (bot.IsRunning)
                            {
                                Series serie = graph.Series.FirstOrDefault(x => x.Name == bot.Name);
                                if (serie == null)
                                {
                                    // Add Series
                                    graph.Series.Add(bot.Name);
                                    graph.Series[bot.Name].ChartType = SeriesChartType.FastLine;
                                    graph.Series[bot.Name].Points.Add(0);
                                    graph.Series[bot.Name].YAxisType       = AxisType.Primary;
                                    graph.Series[bot.Name].YValueType      = valueType;
                                    graph.Series[bot.Name].IsXValueIndexed = false;

                                    graph.Series[bot.Name].Color = Color.Black;
                                    foreach (
                                        Color color in
                                        ChartColors.Where(color => graph.Series.All(x => x.Color != color))
                                        )
                                    {
                                        graph.Series[bot.Name].Color = color;
                                    }
                                    graph.Series[bot.Name].Name = bot.Name;
                                }
                            }
                            else
                            {
                                Series serie = graph.Series.FirstOrDefault(x => x.Name == bot.Name);
                                if (serie != null)
                                {
                                    graph.Series.Remove(serie);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            DebugHelper.Exception(ex);
                        }
                    }));
                }
                catch (Exception ex)
                {
                    DebugHelper.Exception(ex);
                }
            }
        }
Ejemplo n.º 11
0
 public static void Stop()
 {
     try
     {
         mutex.ReleaseMutex();
     }
     catch (Exception ex)
     {
         DebugHelper.Exception(ex);
     }
 }
        private static void UpdateMainformGraph(Chart graph, string serie, double value, int limit = 120, string legend = null,
                                                bool autoscale = false)
        {
            if (Program.Mainform == null || graph == null)
            {
                return;
            }
            try
            {
                Program.Mainform.Invoke(new Action(() =>
                {
                    try
                    {
                        if (legend != null)
                        {
                            graph.Series[serie].LegendText = legend;
                        }

                        while (graph.Series[serie].Points.Count < limit)
                        {
                            graph.Series[serie].Points.Add(0);
                        }

                        if (value > 0)
                        {
                            graph.Series[serie].Points.Add(value);
                        }
                        else
                        {
                            graph.Series[serie].Points.Add(0);
                        }

                        while (graph.Series[serie].Points.Count > limit)
                        {
                            graph.Series[serie].Points.RemoveAt(0);
                        }
                        if (autoscale)
                        {
                            graph.ChartAreas[0].AxisY.Minimum = double.NaN;
                            graph.ChartAreas[0].AxisY.Maximum = double.NaN;
                            graph.ChartAreas[0].RecalculateAxesScale();
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugHelper.Exception(ex);
                    }
                }));
            }
            catch (Exception ex)
            {
                DebugHelper.Exception(ex);
            }
        }
Ejemplo n.º 13
0
        private void prepareMainGraphConnections()
        {
            if (Program.Mainform == null || Program.Mainform.CommConnections == null)
            {
                return;
            }
            try
            {
                Program.Mainform.Invoke(new Action(() =>
                {
                    try
                    {
                        // Clear mainform stats
                        var graph = Program.Mainform.CommConnections;
                        graph.Series.Clear();
                        graph.Palette = ChartColorPalette.Pastel;
                        graph.Titles.Clear();
                        graph.Titles.Add("Communicator Open Connections");
                        // Add Series
                        graph.Series.Add("Connections");
                        graph.Series["Connections"].ChartType = SeriesChartType.FastLine;
                        graph.Series["Connections"].Points.Add(0);
                        graph.Series["Connections"].YAxisType       = AxisType.Primary;
                        graph.Series["Connections"].YValueType      = ChartValueType.Int32;
                        graph.Series["Connections"].IsXValueIndexed = false;
                        graph.Series["Connections"].Color           = Color.DarkSlateBlue;

                        graph.Series.Add("Failed");
                        graph.Series["Failed"].ChartType = SeriesChartType.FastLine;
                        graph.Series["Failed"].Points.Add(0);
                        graph.Series["Failed"].YAxisType       = AxisType.Secondary;
                        graph.Series["Failed"].YValueType      = ChartValueType.Int32;
                        graph.Series["Failed"].IsXValueIndexed = false;
                        graph.Series["Failed"].Color           = Color.Red;

                        graph.ResetAutoValues();
                        graph.ChartAreas[0].AxisY.Maximum          = 255; //Max Y
                        graph.ChartAreas[0].AxisY.Minimum          = 0;
                        graph.ChartAreas[0].AxisX.Enabled          = AxisEnabled.False;
                        graph.ChartAreas[0].AxisY.IntervalAutoMode = IntervalAutoMode.VariableCount;
                    }
                    catch (Exception ex)
                    {
                        DebugHelper.Exception(ex);
                    }
                }));
            }
            catch (Exception ex)
            {
                DebugHelper.Exception(ex);
            }
        }
Ejemplo n.º 14
0
        public static bool ChangeRegion(string region)
        {
            try
            {
                var key = Registry.CurrentUser.CreateSubKey(@"Software\Blizzard Entertainment\Battle.net\D3\");
                if (key == null)
                {
                    Logger.Instance.Write("Failed to get registry key for changing region!");
                    return(false);
                }

                string regionUrl;

                switch (region)
                {
                case "Beta":
                    regionUrl = "beta.actual.battle.net";
                    break;

                case "Europe":
                    regionUrl = "eu.actual.battle.net";
                    break;

                case "America":
                    regionUrl = "us.actual.battle.net";
                    break;

                case "Asia":
                    regionUrl = "kr.actual.battle.net";
                    break;

                case "China":
                    regionUrl = "cn.actual.battle.net";
                    break;

                default:
                    Logger.Instance.Write("Unknown region ({0}) using Europe as our default region", region);
                    regionUrl = "eu.actual.battle.net";
                    break;
                }
                Logger.Instance.Write("Region set: {0} : {1}", region, regionUrl);
                key.SetValue("RegionUrl", regionUrl);
                key.Close();
                return(true);
            }
            catch (Exception ex)
            {
                Logger.Instance.Write("Changing Region Failed!");
                DebugHelper.Exception(ex);
                return(false);
            }
        }
Ejemplo n.º 15
0
        public void CrashCheck()
        {
            if (Proc.HasExited)
            {
                return;
            }

            if (Proc.Responding)
            {
                _lastRepsonse = DateTime.UtcNow;
            }

            if (DateTime.UtcNow.Subtract(Proc.StartTime).TotalMilliseconds < (90 * 1000))
            {
                return;
            }

            if (Settings.Default.AllowKillDemonbuddy && DateTime.UtcNow.Subtract(_lastRepsonse).TotalSeconds > 90)
            {
                Logger.Instance.Write(Parent, "Demonbuddy:{0}: Is unresponsive for more than 120 seconds", Proc.Id);
                Logger.Instance.Write(Parent, "Demonbuddy:{0}: Killing process", Proc.Id);
                try
                {
                    Proc.Kill();
                }
                catch (Exception ex)
                {
                    Logger.Instance.Write(Parent, "Failed to kill process", ex.Message);
                    DebugHelper.Exception(ex);
                }
            }

            else if (Settings.Default.AllowKillDemonbuddy && DateTime.UtcNow.Subtract(_lastRepsonse).TotalSeconds > 90)
            {
                Logger.Instance.Write(Parent, "Demonbuddy:{0}: Is unresponsive for more than 90 seconds", Proc.Id);
                Logger.Instance.Write(Parent, "Demonbuddy:{0}: Closing process", Proc.Id);
                try
                {
                    if (Proc != null && !Proc.HasExited)
                    {
                        Proc.CloseMainWindow();
                    }
                    //Proc.Kill();
                }
                catch (Exception ex)
                {
                    Logger.Instance.Write(Parent, "Failed to kill process", ex.Message);
                    DebugHelper.Exception(ex);
                }
            }
        }
Ejemplo n.º 16
0
 public static Int64 GetTotalMemory()
 {
     try
     {
         var pi = new PerformanceInformation();
         if (GetPerformanceInfo(out pi, Marshal.SizeOf(pi)))
         {
             return(Convert.ToInt64((pi.PhysicalTotal.ToInt64() * pi.PageSize.ToInt64())));
         }
     }
     catch (Exception ex)
     {
         DebugHelper.Exception(ex);
     }
     return(-1);
 }
Ejemplo n.º 17
0
        private void prepareMainGraphGold()
        {
            if (Program.Mainform == null || Program.Mainform.GoldStats == null)
            {
                return;
            }
            try
            {
                Program.Mainform.Invoke(new Action(() =>
                {
                    try
                    {
                        // Clear mainform stats
                        var graph = Program.Mainform.GoldStats;
                        graph.Series.Clear();
                        graph.Palette = ChartColorPalette.Pastel;
                        graph.Titles.Clear();
                        graph.Titles.Add("Gold Statistics");
                        // Add Series
                        graph.Series.Add("Gph");
                        graph.Series["Gph"].ChartType = SeriesChartType.FastLine;
                        graph.Series["Gph"].Points.Add(0);
                        graph.Series["Gph"].YAxisType       = AxisType.Primary;
                        graph.Series["Gph"].YValueType      = ChartValueType.Auto;
                        graph.Series["Gph"].IsXValueIndexed = false;
                        graph.Series["Gph"].Color           = Color.DarkSlateBlue;

                        graph.ResetAutoValues();
                        graph.ChartAreas[0].AxisY.Minimum          = 0;
                        graph.ChartAreas[0].AxisX.Enabled          = AxisEnabled.False;
                        graph.ChartAreas[0].AxisY.IntervalAutoMode = IntervalAutoMode.VariableCount;
                    }
                    catch (Exception ex)
                    {
                        DebugHelper.Exception(ex);
                    }
                }));
            }
            catch (Exception ex)
            {
                DebugHelper.Exception(ex);
            }
        }
Ejemplo n.º 18
0
        public static void AgentKiller()
        {
            foreach (var p in Process.GetProcessesByName("Agent"))
            {
                try
                {
                    if (!p.MainModule.FileVersionInfo.ProductName.Equals("Battle.net Update Agent"))
                    {
                        continue;
                    }

                    Logger.Instance.Write("Killing Agent.exe:{0}", p.Id);
                    p.Kill();
                }
                catch (Exception ex)
                {
                    DebugHelper.Exception(ex);
                }
            }
        }
Ejemplo n.º 19
0
        void GenerateSchedule()
        {
            int  x       = 0;  // start at X-Axis
            int  y       = 14; // start at Y-Axis
            int  n       = 0;  // box number
            bool bHeader = false;

            try
            {
                for (int d = 1; d <= 7; d++)
                {
                    for (int h = 0; h <= 23; h++)
                    {
                        if (!bHeader)
                        {
                            var l = new Label();
                            l.Location  = new Point(x + 1, 0);
                            l.Margin    = new Padding(0);
                            l.Name      = "lbl" + n;
                            l.Text      = n.ToString("D2"); // add leading zero when needed (2 digits)
                            l.Size      = new Size(20, 13);
                            l.TextAlign = ContentAlignment.MiddleCenter;
                            this.Invoke(new Action(() => this.BoxPanel.Controls.Add(l)));
                        }
                        ScheduleBox[n] = new ClickBox("box" + n, x, y);

                        this.Invoke(new Action(() => this.BoxPanel.Controls.Add(ScheduleBox[n].box)));
                        n++;
                        x += 20; // X-Axis
                    }
                    bHeader = true;
                    y      += 20; // Y-Axis
                    x       = 0;  // X-Axis
                }
            }
            catch (Exception ex)
            {
                DebugHelper.Exception(ex);
            }
            isDone = true;
        }
Ejemplo n.º 20
0
 public static bool WindowsAutoStartAdd()
 {
     try
     {
         var key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
         if (key == null)
         {
             Logger.Instance.WriteGlobal("Failed to get registry key \"Software\\Microsoft\\Windows\\CurrentVersion\\Run\"");
             return(false);
         }
         key.SetValue("YetAnotherRelogger", string.Format("\"{0}\" -winstart", Application.ExecutablePath));
         key.Close();
         return(true);
     }
     catch (Exception ex)
     {
         Logger.Instance.WriteGlobal("Failed to add/change registry key: {0}", ex.Message);
         DebugHelper.Exception(ex);
         return(false);
     }
 }
Ejemplo n.º 21
0
 public static bool ChangeLocale(string Language)
 {
     try
     {
         var locale = Tools.General.GetLocale(Language);
         var key    = Registry.CurrentUser.CreateSubKey(@"Software\Blizzard Entertainment\D3");
         if (key == null)
         {
             Logger.Instance.Write("Failed to get registry key for changing locale!");
             return(false);
         }
         Logger.Instance.Write("Language set: {0} : {1}", Language, locale);
         key.SetValue("Locale", locale);
         key.Close();
         return(true);
     }
     catch (Exception ex)
     {
         Logger.Instance.Write("Failed to change locale!");
         DebugHelper.Exception(ex);
         return(false);
     }
 }
Ejemplo n.º 22
0
        private void ReloggerWorker()
        {
            // Check if we are launched by windows RUN
            if (CommandLineArgs.WindowsAutoStart && !_autoStartDone)
            {
                _autoStartDone = true;
                Logger.Instance.WriteGlobal("Windows auto start delaying with {0} seconds", Settings.Default.StartDelay);
                Thread.Sleep((int)Settings.Default.StartDelay * 1000);
                foreach (BotClass bot in BotSettings.Instance.Bots.Where(c => c.IsEnabled))
                {
                    bot.AntiIdle.Reset(freshstart: true); // Reset AntiIdle
                    bot.IsStarted = true;
                    bot.Status    = "Auto Start...";
                }
            }
            // Check if we are launched with the autostart
            if (CommandLineArgs.AutoStart && !_autoStartDone)
            {
                _autoStartDone = true;
                foreach (BotClass bot in BotSettings.Instance.Bots.Where(c => c.IsEnabled))
                {
                    bot.AntiIdle.Reset(freshstart: true); // Reset AntiIdle
                    bot.IsStarted = true;
                    bot.Status    = "Auto Start...";
                }
            }

            DebugHelper.Write("Relogger Thread Starting!");
            while (true)
            {
                try
                {
                    if (_isStopped)
                    {
                        return;
                    }

                    // Paused
                    if (Program.Pause)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }

                    List <Process> blizzardErrorProcs =
                        (from p in Process.GetProcessesByName("BlizzardError.exe")
                         select p).ToList();
                    if (blizzardErrorProcs.Any())
                    {
                        try
                        {
                            foreach (var p in blizzardErrorProcs)
                            {
                                Logger.Instance.Write("Killing BlizzardError.exe with PID {0}", p.Id);
                                p.Kill();
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Instance.Write("Exception killing BlizzardError.exe: " + ex);
                        }
                    }

                    if (DateTime.UtcNow.Subtract(_lastSaveSettings).TotalSeconds > 10)
                    {
                        _lastSaveSettings = DateTime.UtcNow;
                        Settings.Default.Save();
                        BotSettings.Instance.Save();
                    }

                    // Check / validate internet connection
                    if (!ConnectionCheck.IsConnected || !ConnectionCheck.ValidConnection)
                    {
                        Debug.WriteLine("Internet validation failed looping until success");
                        Thread.Sleep(1000);
                        continue;
                    }

                    foreach (BotClass bot in BotSettings.Instance.Bots.Where(bot => bot != null).ToList())
                    {
                        if (Program.Pause)
                        {
                            break;
                        }

                        DateTime time = DateTime.UtcNow; // set current time to calculate sleep time at end of loop
                        CurrentBot = bot;
                        //Debug.WriteLine(bot.Name + ":" + ":" + bot.IsRunning);
                        //Debug.WriteLine("State=" + bot.AntiIdle.State);
                        if (bot.IsRunning && bot.IsStarted && !bot.Week.ShouldRun(bot.IsRunning))
                        {
                            // We need to stop
                            Logger.Instance.Write("We are scheduled to stop");
                            bot.Week.NextSchedule(true);
                            bot.IsRunning = false;
                            bot.Demonbuddy.Stop();
                            bot.Diablo.Stop();
                            bot.Status = "Scheduled stop!";
                        }
                        else if (!bot.IsRunning && bot.IsStarted && bot.Week.ShouldRun(bot.IsRunning))
                        {
                            // we need to start
                            Logger.Instance.Write("We are scheduled to start");
                            bot.Week.NextSchedule(false);
                            bot.IsRunning = true;
                            bot.StartTime = DateTime.UtcNow;
                            StartBoth(bot);
                        }
                        else if (!bot.IsStandby && bot.IsRunning)
                        {
                            // Check if process is responding
                            bot.Diablo.CrashCheck();
                            if (bot.AntiIdle.IsInitialized)
                            {
                                bot.Demonbuddy.CrashCheck();
                            }

                            if (!bot.Diablo.IsRunning)
                            {
                                if (bot.Diablo.Proc != null)
                                {
                                    Logger.Instance.Write("Diablo:{0}: Process is not running", bot.Diablo.Proc.Id);
                                }
                                //if (bot.Demonbuddy.IsRunning && bot.Demonbuddy.Proc != null)
                                //{
                                //    Logger.Instance.Write("Demonbuddy:{0}: Closing db", bot.Demonbuddy.Proc.Id);
                                //    bot.Demonbuddy.Stop();
                                //}
                                if (bot.Demonbuddy.IsRunning && bot.Demonbuddy.Proc != null)
                                {
                                    Logger.Instance.Write("Demonbuddy:{0}: Waiting for Demonbuddy to self close", bot.Demonbuddy.Proc.Id);
                                }
                                else
                                {
                                    StartBoth(bot);
                                }
                            }
                            else if (!bot.Demonbuddy.IsRunning)
                            {
                                Logger.Instance.Write("Demonbuddy: Process is not running");
                                bot.Demonbuddy.Start();
                            }
                            else if (Settings.Default.AntiIdleStatsDuration > 0 && bot.AntiIdle.State != IdleState.Initialize && General.DateSubtract(bot.AntiIdle.LastStats) >
                                     (double)Settings.Default.AntiIdleStatsDuration)
                            {
                                Logger.Instance.Write("We did not recieve any stats during 300 seconds!");
                                bot.Restart();
                            }
                            else if (bot.AntiIdle.IsInitialized)
                            {
                                if (bot.ProfileSchedule.IsDone)
                                {
                                    Logger.Instance.Write("Profile: \"{0}\" Finished!", bot.ProfileSchedule.Current.Name);
                                    bot.AntiIdle.State = IdleState.NewProfile;
                                }
                            }
                        }
                        else
                        {
                            //Logger.Instance.Write("Bot Standby={0} Running={1} D3Running={2} DBRunning={3}", bot.IsStandby, bot.IsRunning, bot.Diablo.IsRunning, bot.Demonbuddy.IsRunning);
                            bot.StartTime = DateTime.UtcNow;
                        }
                        // calculate sleeptime
                        var sleep = (int)(Program.Sleeptime - DateTime.UtcNow.Subtract(time).TotalMilliseconds);
                        if (sleep > 0)
                        {
                            Thread.Sleep(sleep);
                        }
                    }
                } // try
                catch (InvalidOperationException)
                {
                    // Catch error when bot is edited while in a loop
                    //Logger.Instance.WriteGlobal(iox.Message);
                    continue;
                }
                catch (Exception ex)
                {
                    if (_isStopped)
                    {
                        return;
                    }
                    Logger.Instance.WriteGlobal("Relogger Crashed! with message {0}", ex.Message);
                    DebugHelper.Exception(ex);
                    Logger.Instance.WriteGlobal("Waiting 10 seconds and try again!");
                    Thread.Sleep(10000);
                    continue;
                }
                Thread.Sleep(1000);
            } // while
        }     // private void reloggerWorker()
        public void StatsUpdaterWorker()
        {
            // Wait here till mainform is up
            while (Program.Mainform == null || !Program.Mainform.IsHandleCreated)
            {
                Thread.Sleep(100);
            }

            var usages   = new CpuRamUsage();
            var totalRam = PerformanceInfo.GetTotalMemory();

            PrepareMainGraphCpu();
            PrepareMainGraphMemory();
            PrepareMainGraphGold();
            while (true)
            {
                // Update Cpu/Ram Usage
                usages.Update();

                double diabloCpuUsage     = 0;
                long   diabloRamUsage     = 0;
                double demonbuddyCpuUsage = 0;
                long   demonbuddyRamUsage = 0;
                double goldPerHour        = 0;
                double totalGold          = 0;
                lock (BotSettings.Instance)
                {
                    foreach (var bot in BotSettings.Instance.Bots.ToList())
                    {
                        var chartStats = bot.ChartStats;
                        // Update bot uptime
                        bot.RunningTime = bot.IsRunning
                            ? DateTime.UtcNow.Subtract(bot.StartTime).ToString(@"hh\hmm\mss\s")
                            : "";

                        // Update bot specific Chart stats
                        CreateChartStats(bot, Program.Mainform.GoldStats, ChartValueType.Double);

                        if (bot.IsRunning)
                        {
                            #region Calculate System Usage

                            if (bot.Diablo.IsRunning)
                            {
                                // Calculate total Cpu/Ram usage for Diablo
                                try
                                {
                                    var usage = usages.GetUsageById(bot.Diablo.Proc.Id);
                                    diabloCpuUsage += usage.Cpu;
                                    diabloRamUsage += usage.Memory;
                                }
                                catch (Exception)
                                {
                                }
                            }

                            if (bot.Demonbuddy.IsRunning)
                            {
                                // Calculate total Cpu/Ram usage for Demonbuddy
                                try
                                {
                                    var usage = usages.GetUsageById(bot.Demonbuddy.Proc.Id);
                                    demonbuddyCpuUsage += usage.Cpu;
                                    demonbuddyRamUsage += usage.Memory;
                                }
                                catch (Exception)
                                {
                                }
                            }

                            #endregion

                            #region Gold Stats

                            chartStats.GoldStats.Update(bot); // Update Current bot

                            // Calculate total gold for all bots
                            goldPerHour += chartStats.GoldStats.GoldPerHour;
                            totalGold   += chartStats.GoldStats.LastCoinage;

                            var serie = Program.Mainform.GoldStats.Series.FirstOrDefault(x => x.Name == bot.Name);
                            if (serie != null)
                            {
                                UpdateMainformGraph(Program.Mainform.GoldStats, serie.Name,
                                                    Math.Round(chartStats.GoldStats.GoldPerHour), (int)Settings.Default.StatsGphHistory,
                                                    autoscale: true);
                            }

                            #endregion
                        }
                    }
                }
                try
                {
                    // add to Cpu graph
                    var graph    = Program.Mainform.CpuUsage;
                    var allusage = diabloCpuUsage + demonbuddyCpuUsage;
                    UpdateMainformGraph(graph, "All Usage", allusage,
                                        legend: $"All usage: {allusage,11:000.0}%",
                                        limit: (int)Settings.Default.StatsCPUHistory);
                    UpdateMainformGraph(graph, "Diablo", diabloCpuUsage,
                                        legend: $"Diablo: {diabloCpuUsage,16:000.0}%",
                                        limit: (int)Settings.Default.StatsCPUHistory);
                    UpdateMainformGraph(graph, "Demonbuddy", demonbuddyCpuUsage,
                                        legend: $"Demonbuddy: {demonbuddyCpuUsage,4:000.0}%",
                                        limit: (int)Settings.Default.StatsCPUHistory);
                    UpdateMainformGraph(graph, "Total System", Math.Round(usages.TotalCpuUsage, 2),
                                        legend: $"Total System: {usages.TotalCpuUsage,2:000.0}%",
                                        limit: (int)Settings.Default.StatsCPUHistory);

                    // add to Memory graph
                    graph    = Program.Mainform.MemoryUsage;
                    allusage = (double)(diabloRamUsage + demonbuddyRamUsage) / totalRam * 100;
                    var diablousage     = (double)diabloRamUsage / totalRam * 100;
                    var demonbuddyusage = (double)demonbuddyRamUsage / totalRam * 100;
                    UpdateMainformGraph(graph, "All Usage", allusage,
                                        legend:
                                        $"All usage: {((double)(diabloRamUsage + demonbuddyRamUsage) / totalRam * 100),11:000.0}%",
                                        limit: (int)Settings.Default.StatsMemoryHistory);
                    UpdateMainformGraph(graph, "Diablo", diablousage,
                                        legend: $"Diablo: {diablousage,16:000.0}%",
                                        limit: (int)Settings.Default.StatsMemoryHistory);
                    UpdateMainformGraph(graph, "Demonbuddy", demonbuddyusage,
                                        legend: $"Demonbuddy: {demonbuddyusage,4:000.0}%",
                                        limit: (int)Settings.Default.StatsMemoryHistory);
                    var mem = (double)PerformanceInfo.GetPhysicalUsedMemory() / totalRam * 100;
                    UpdateMainformGraph(graph, "Total System", mem,
                                        legend: $"Total System: {mem,2:000.0}%",
                                        limit: (int)Settings.Default.StatsMemoryHistory);

                    // add to Gold Graph
                    UpdateMainformGraph(Program.Mainform.GoldStats, "Gph", Math.Round(goldPerHour),
                                        legend: $"Gph {Math.Round(goldPerHour)}", autoscale: true,
                                        limit: (int)Settings.Default.StatsGphHistory);
                    UpdateMainformLabel(Program.Mainform.CashPerHour,
                                        $"{(goldPerHour / 1000000 * (double)Settings.Default.StatsGoldPrice):C2}");
                    UpdateMainformLabel(Program.Mainform.CurrentCash,
                                        $"{(totalGold / 1000000 * (double)Settings.Default.StatsGoldPrice):C2}");
                    UpdateMainformLabel(Program.Mainform.TotalGold, $"{totalGold:N0}");
                }
                catch (Exception ex)
                {
                    DebugHelper.Exception(ex);
                }
                Thread.Sleep((int)Settings.Default.StatsUpdateRate);
            }
        }
Ejemplo n.º 24
0
        public void Start()
        {
            if (!Parent.IsStarted)
            {
                return;
            }

            if (!File.Exists(Location))
            {
                Logger.Instance.Write("File not found: {0}", Location);
                return;
            }

            _isStopped = false;
            // Ping check
            while (Settings.Default.ConnectionCheckPing && !ConnectionCheck.PingCheck() && !_isStopped)
            {
                Parent.Status = "Wait on internet connection";
                Logger.Instance.WriteGlobal("PingCheck: Waiting 10 seconds and trying again!");
                Thread.Sleep(10000);
            }

            // Check valid host
            while (Settings.Default.ConnectionCheckIpHost && !ConnectionCheck.CheckValidConnection() && !_isStopped)
            {
                Parent.Status = "Wait on host validation";
                Logger.Instance.WriteGlobal("ConnectionValidation: Waiting 10 seconds and trying again!");
                Thread.Sleep(10000);
            }

            // Check if we need to create a Diablo clone
            if (Parent.UseDiabloClone)
            {
                DiabloClone.Create(Parent);
            }

            Parent.Status = "Prepare Diablo"; // Update Status

            General.AgentKiller();            // Kill all Agent.exe processes

            // Prepare D3 for launch
            var agentDBPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\Battle.net\Agent\agent.db";

            if (File.Exists(agentDBPath))
            {
                Logger.Instance.Write("Deleting: {0}", agentDBPath);
                try
                {
                    File.Delete(agentDBPath);
                }
                catch (Exception ex)
                {
                    Logger.Instance.Write("Failed to delete! Exception: {0}", ex.Message);
                    DebugHelper.Exception(ex);
                }
            }

            // Copy D3Prefs
            if (!string.IsNullOrEmpty(Parent.D3PrefsLocation))
            {
                D3Prefs();
            }

            // Registry Changes
            RegistryClass.ChangeLocale(Parent.Diablo.Language); // change language
            RegistryClass.ChangeRegion(Parent.Diablo.Region);   // change region

            if (UseIsBoxer)
            {
                IsBoxerStarter();
            }
            else if (Settings.Default.UseD3Starter)
            {
                ApocD3Starter();
            }
            else
            {
                try
                {
                    var arguments = "-launch";
                    var pi        = new ProcessStartInfo(Location2, arguments)
                    {
                        WorkingDirectory = Path.GetDirectoryName(Location2)
                    };
                    pi = UserAccount.ImpersonateStartInfo(pi, Parent);
                    // Set working directory to executable location
                    Parent.Status = "Starting Diablo"; // Update Status
                    Proc          = Process.Start(pi);
                }
                catch (Exception ex)
                {
                    Parent.Stop();
                    DebugHelper.Exception(ex);
                    return;
                }
            }

            if (!UseIsBoxer) // Don't want to fight with isboxer
            {
                if (CpuCount != Environment.ProcessorCount)
                {
                    ProcessorAffinity = AllProcessors; // set it to all ones
                    CpuCount          = Environment.ProcessorCount;
                }
                Proc.ProcessorAffinity = (IntPtr)ProcessorAffinity;
            }


            if (_isStopped)
            {
                return;             // Halt here when bot is stopped while we where waiting for it to become active
            }
            // Wait for d3 to fully load
            var state    = (Settings.Default.UseD3Starter || UseIsBoxer ? 0 : 2);
            var handle   = IntPtr.Zero;
            var timedout = false;

            LimitStartTime(true); // reset startup time
            while ((!Proc.HasExited && state < 4))
            {
                if (timedout)
                {
                    return;
                }
                //Debug.WriteLine("Splash: " + FindWindow.FindWindowClass("D3 Splash Window Class", Proc.Id) + " Main:" + FindWindow.FindWindowClass("D3 Main Window Class", Proc.Id));
                switch (state)
                {
                case 0:
                    handle = FindWindow.FindWindowClass("D3 Splash Window Class", Proc.Id);
                    if (handle != IntPtr.Zero)
                    {
                        Logger.Instance.Write("Diablo:{0}: Found D3 Splash Window ({1})", Proc.Id, handle);
                        state++;
                        LimitStartTime(true);     // reset startup time
                    }
                    timedout = LimitStartTime();
                    break;

                case 1:
                    handle = FindWindow.FindWindowClass("D3 Splash Window Class", Proc.Id);
                    if (handle == IntPtr.Zero)
                    {
                        Logger.Instance.Write("Diablo:{0}: D3 Splash Window Closed ({1})", Proc.Id, handle);
                        state++;
                        LimitStartTime(true);     // reset startup time
                    }
                    timedout = LimitStartTime();
                    break;

                case 2:
                    handle = FindWindow.FindWindowClass("D3 Main Window Class", Proc.Id);
                    if (handle != IntPtr.Zero)
                    {
                        Logger.Instance.Write("Diablo:{0}: Found D3 Main Window ({1})", Proc.Id, handle);
                        state++;
                        LimitStartTime(true);     // reset startup time
                    }
                    timedout = LimitStartTime();
                    break;

                case 3:
                    if (CrashChecker.IsResponding(handle))
                    {
                        MainWindowHandle = handle;
                        state++;
                        LimitStartTime(true);     // reset startup time
                    }
                    timedout = LimitStartTime();
                    break;
                }
                Thread.Sleep(500);
            }
            if (timedout)
            {
                return;
            }

            if (Program.IsRunAsAdmin)
            {
                Proc.PriorityClass = General.GetPriorityClass(Priority);
            }
            else
            {
                Logger.Instance.Write(Parent, "Failed to change priority (No admin rights)");
            }
            // Continue after launching stuff
            Logger.Instance.Write("Diablo:{0}: Waiting for process to become ready", Proc.Id);

            var timeout = DateTime.Now;

            while (true)
            {
                if (General.DateSubtract(timeout) > 30)
                {
                    Logger.Instance.Write("Diablo:{0}: Failed to start!", Proc.Id);
                    Parent.Restart();
                    return;
                }
                Thread.Sleep(500);
                try
                {
                    Proc.Refresh();
                    if (Proc.WaitForInputIdle(100) || CrashChecker.IsResponding(MainWindowHandle))
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    DebugHelper.Exception(ex);
                }
            }

            if (!IsRunning)
            {
                return;
            }

            _lastRepsonse = DateTime.Now;

            Thread.Sleep(1500);
            if (NoFrame)
            {
                AutoPosition.RemoveWindowFrame(MainWindowHandle, true);          // Force remove window frame
            }
            if (ManualPosSize)
            {
                AutoPosition.ManualPositionWindow(MainWindowHandle, X, Y, W, H, Parent);
            }
            else if (Settings.Default.UseAutoPos)
            {
                AutoPosition.PositionWindows();
            }

            Logger.Instance.Write("Diablo:{0}: Process is ready", Proc.Id);

            // Demonbuddy start delay
            if (Settings.Default.DemonbuddyStartDelay > 0)
            {
                Logger.Instance.Write("Demonbuddy start delay, waiting {0} seconds", Settings.Default.DemonbuddyStartDelay);
                Thread.Sleep((int)Settings.Default.DemonbuddyStartDelay * 1000);
            }
        }
Ejemplo n.º 25
0
        private void ForegroundCheckerWorker()
        {
            try
            {
                while (true)
                {
                    BindingList <BotClass> bots = BotSettings.Instance.Bots;
                    IntPtr hwnd = WinAPI.GetForegroundWindow();

                    if (_lastDemonbuddy != hwnd && _lastDiablo != hwnd)
                    {
                        _lastDemonbuddy = _lastDiablo = IntPtr.Zero;
                        foreach (BotClass bot in bots)
                        {
                            DateTime time = DateTime.Now;
                            if (!bot.IsStarted || !bot.IsRunning || !bot.Diablo.IsRunning || !bot.Demonbuddy.IsRunning)
                            {
                                continue;
                            }
                            if (bot.Diablo.Proc.MainWindowHandle != hwnd)
                            {
                                continue;
                            }

                            _lastDiablo     = bot.Diablo.MainWindowHandle;
                            _lastDemonbuddy = bot.Demonbuddy.MainWindowHandle;
                            Logger.Instance.WriteGlobal(
                                "<{0}> Diablo:{1}: has focus. Bring attached Demonbuddy to front", bot.Name,
                                bot.Diablo.Proc.Id);

                            // Bring demonbuddy to front
                            WinAPI.ShowWindow(_lastDemonbuddy, WinAPI.WindowShowStyle.ShowNormal);
                            WinAPI.SetForegroundWindow(_lastDemonbuddy);
                            DateTime timeout = DateTime.Now;
                            while (WinAPI.GetForegroundWindow() != _lastDemonbuddy)
                            {
                                if (General.DateSubtract(timeout, false) > 500)
                                {
                                    WinAPI.ShowWindow(_lastDemonbuddy, WinAPI.WindowShowStyle.ForceMinimized);
                                    Thread.Sleep(300);
                                    WinAPI.ShowWindow(_lastDemonbuddy, WinAPI.WindowShowStyle.ShowNormal);
                                    Thread.Sleep(300);
                                    WinAPI.SetForegroundWindow(_lastDemonbuddy);
                                    if (WinAPI.GetForegroundWindow() != _lastDemonbuddy)
                                    {
                                        Logger.Instance.WriteGlobal("<{0}> Failed to bring Demonbuddy to front",
                                                                    bot.Name);
                                    }
                                    break;
                                }
                                Thread.Sleep(100);
                            }

                            // Switch back to diablo
                            WinAPI.ShowWindow(_lastDiablo, WinAPI.WindowShowStyle.ShowNormal);
                            WinAPI.SetForegroundWindow(_lastDiablo);
                            while (WinAPI.GetForegroundWindow() != _lastDiablo)
                            {
                                if (General.DateSubtract(timeout, false) > 500)
                                {
                                    WinAPI.ShowWindow(_lastDiablo, WinAPI.WindowShowStyle.ForceMinimized);
                                    Thread.Sleep(300);
                                    WinAPI.ShowWindow(_lastDiablo, WinAPI.WindowShowStyle.ShowNormal);
                                    Thread.Sleep(300);
                                    WinAPI.SetForegroundWindow(_lastDiablo);
                                    break;
                                }
                                Thread.Sleep(100);
                            }

                            // calculate sleeptime
                            var sleep = (int)(Program.Sleeptime - DateTime.Now.Subtract(time).TotalMilliseconds);
                            if (sleep > 0)
                            {
                                Thread.Sleep(sleep);
                            }
                        }
                    }
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                DebugHelper.Exception(ex);
                Thread.Sleep(5000);
                ForegroundCheckerWorker();
            }
        }
Ejemplo n.º 26
0
        public void StatsUpdaterWorker()
        {
            // Wait here till mainform is up
            while (Program.Mainform == null)
            {
                Thread.Sleep(100);
            }

            var usages   = new CpuRamUsage();
            var totalRam = PerformanceInfo.GetTotalMemory();

            prepareMainGraphCpu();
            prepareMainGraphMemory();
            prepareMainGraphConnections();
            prepareMainGraphGold();
            while (true)
            {
                // Update Cpu/Ram Usage
                usages.Update();

                double diabloCpuUsage     = 0;
                long   diabloRamUsage     = 0;
                int    diabloCount        = 0;
                double demonbuddyCpuUsage = 0;
                long   demonbuddyRamUsage = 0;
                int    demonbuddyCount    = 0;
                double goldPerHour        = 0;
                double totalGold          = 0;
                foreach (var bot in BotSettings.Instance.Bots)
                {
                    var chartStats = bot.ChartStats;
                    // Update bot uptime
                    bot.RunningTime = bot.IsRunning ? DateTime.Now.Subtract(bot.StartTime).ToString(@"hh\hmm\mss\s") : "";

                    // Update bot specific Chart stats
                    CreateChartStats(bot, Program.Mainform.GoldStats, ChartValueType.Double);

                    if (bot.IsRunning)
                    {
                        #region Calculate System Usage
                        if (bot.Diablo.IsRunning)
                        {
                            // Calculate total Cpu/Ram usage for Diablo
                            try
                            {
                                var usage = usages.GetUsageById(bot.Diablo.Proc.Id);
                                diabloCpuUsage += usage.Cpu;
                                diabloRamUsage += usage.Memory;
                                diabloCount++;
                            }
                            catch
                            {
                            }
                        }

                        if (bot.Demonbuddy.IsRunning)
                        {
                            // Calculate total Cpu/Ram usage for Demonbuddy
                            try
                            {
                                var usage = usages.GetUsageById(bot.Demonbuddy.Proc.Id);
                                demonbuddyCpuUsage += usage.Cpu;
                                demonbuddyRamUsage += usage.Memory;
                                demonbuddyCount++;
                            }
                            catch
                            {
                            }
                        }
                        #endregion
                        #region Gold Stats
                        chartStats.GoldStats.Update(bot); // Update Current bot

                        // Calculate total gold for all bots
                        goldPerHour += chartStats.GoldStats.GoldPerHour;
                        totalGold   += chartStats.GoldStats.LastCoinage;

                        var serie = Program.Mainform.GoldStats.Series.FirstOrDefault(x => x.Name == bot.Name);
                        if (serie != null)
                        {
                            updateMainformGraph(Program.Mainform.GoldStats, serie.Name, Math.Round(chartStats.GoldStats.GoldPerHour), limit: (int)Properties.Settings.Default.StatsGphHistory, autoscale: true);
                        }
                        #endregion
                    }
                    else
                    {
                    }
                }
                try
                {
                    // add to Cpu graph
                    var graph    = Program.Mainform.CpuUsage;
                    var allusage = diabloCpuUsage + demonbuddyCpuUsage;
                    updateMainformGraph(graph, "All Usage", allusage, legend: string.Format("All usage: {0,11}%", allusage.ToString("000.0")), limit: (int)Properties.Settings.Default.StatsCPUHistory);
                    updateMainformGraph(graph, "Diablo", diabloCpuUsage, legend: string.Format("Diablo: {0,16}%", diabloCpuUsage.ToString("000.0")), limit: (int)Properties.Settings.Default.StatsCPUHistory);
                    updateMainformGraph(graph, "Demonbuddy", demonbuddyCpuUsage, legend: string.Format("Demonbuddy: {0,4}%", demonbuddyCpuUsage.ToString("000.0")), limit: (int)Properties.Settings.Default.StatsCPUHistory);
                    updateMainformGraph(graph, "Total System", Math.Round(usages.TotalCpuUsage, 2), legend: string.Format("Total System: {0,2}%", usages.TotalCpuUsage.ToString("000.0")), limit: (int)Properties.Settings.Default.StatsCPUHistory);

                    // add to Memory graph
                    graph    = Program.Mainform.MemoryUsage;
                    allusage = (double)(diabloRamUsage + demonbuddyRamUsage) / totalRam * 100;
                    var diablousage     = (double)diabloRamUsage / totalRam * 100;
                    var demonbuddyusage = (double)demonbuddyRamUsage / totalRam * 100;
                    updateMainformGraph(graph, "All Usage", allusage, legend: string.Format("All usage: {0,11}%", ((double)(diabloRamUsage + demonbuddyRamUsage) / totalRam * 100).ToString("000.0")), limit: (int)Properties.Settings.Default.StatsMemoryHistory);
                    updateMainformGraph(graph, "Diablo", diablousage, legend: string.Format("Diablo: {0,16}%", diablousage.ToString("000.0")), limit: (int)Properties.Settings.Default.StatsMemoryHistory);
                    updateMainformGraph(graph, "Demonbuddy", demonbuddyusage, legend: string.Format("Demonbuddy: {0,4}%", demonbuddyusage.ToString("000.0")), limit: (int)Properties.Settings.Default.StatsMemoryHistory);
                    var mem = (double)PerformanceInfo.GetPhysicalUsedMemory() / totalRam * 100;
                    updateMainformGraph(graph, "Total System", mem, legend: string.Format("Total System: {0,2}%", mem.ToString("000.0")), limit: (int)Properties.Settings.Default.StatsMemoryHistory);

                    // add to Connection graph
                    updateMainformGraph(Program.Mainform.CommConnections, "Connections", Communicator.StatConnections, legend: string.Format("Connections {0}", Communicator.StatConnections), autoscale: true, limit: (int)Properties.Settings.Default.StatsConnectionsHistory);
                    updateMainformGraph(Program.Mainform.CommConnections, "Failed", Communicator.StatFailed, legend: string.Format("Failed {0}", Communicator.StatFailed), autoscale: true, limit: (int)Properties.Settings.Default.StatsConnectionsHistory);
                    Communicator.StatConnections = 0;
                    Communicator.StatFailed      = 0;

                    // add to Gold Graph
                    updateMainformGraph(Program.Mainform.GoldStats, "Gph", Math.Round(goldPerHour), legend: string.Format("Gph {0}", Math.Round(goldPerHour)), autoscale: true, limit: (int)Properties.Settings.Default.StatsGphHistory);
                    updateMainformLabel(Program.Mainform.CashPerHour, string.Format("{0:C2}", (goldPerHour / 1000000 * (double)Properties.Settings.Default.StatsGoldPrice)));
                    updateMainformLabel(Program.Mainform.CurrentCash, string.Format("{0:C2}", (totalGold / 1000000 * (double)Properties.Settings.Default.StatsGoldPrice)));
                    updateMainformLabel(Program.Mainform.TotalGold, string.Format("{0:N0}", totalGold));
                }
                catch (Exception ex)
                {
                    DebugHelper.Exception(ex);
                }
                Thread.Sleep((int)Properties.Settings.Default.StatsUpdateRate);
            }
        }
Ejemplo n.º 27
0
        private void prepareMainGraphMemory()
        {
            if (Program.Mainform == null || Program.Mainform.MemoryUsage == null)
            {
                return;
            }
            try
            {
                Program.Mainform.Invoke(new Action(() =>
                {
                    try
                    {
                        // Clear mainform stats
                        var graph = Program.Mainform.MemoryUsage;
                        graph.Series.Clear();
                        graph.Palette = ChartColorPalette.Pastel;
                        graph.Titles.Clear();
                        graph.Titles.Add("Memory Usage");
                        // Add Series
                        graph.Series.Add("All Usage");
                        graph.Series["All Usage"].ChartType = SeriesChartType.FastLine;
                        graph.Series["All Usage"].Points.Add(0);
                        graph.Series["All Usage"].YAxisType       = AxisType.Primary;
                        graph.Series["All Usage"].YValueType      = ChartValueType.Double;
                        graph.Series["All Usage"].IsXValueIndexed = false;
                        graph.Series["All Usage"].Color           = Color.DarkSlateBlue;

                        graph.Series.Add("Demonbuddy");
                        graph.Series["Demonbuddy"].ChartType = SeriesChartType.FastLine;
                        graph.Series["Demonbuddy"].Points.Add(0);
                        graph.Series["Demonbuddy"].YAxisType       = AxisType.Primary;
                        graph.Series["Demonbuddy"].YValueType      = ChartValueType.Double;
                        graph.Series["Demonbuddy"].IsXValueIndexed = false;
                        graph.Series["Demonbuddy"].Color           = Color.Red;

                        graph.Series.Add("Diablo");
                        graph.Series["Diablo"].ChartType = SeriesChartType.FastLine;
                        graph.Series["Diablo"].Points.Add(0);
                        graph.Series["Diablo"].YAxisType       = AxisType.Primary;
                        graph.Series["Diablo"].YValueType      = ChartValueType.Double;
                        graph.Series["Diablo"].IsXValueIndexed = false;
                        graph.Series["Diablo"].Color           = Color.Green;

                        graph.Series.Add("Total System");
                        graph.Series["Total System"].ChartType = SeriesChartType.FastLine;
                        graph.Series["Total System"].Points.Add(0);
                        graph.Series["Total System"].YAxisType       = AxisType.Primary;
                        graph.Series["Total System"].YValueType      = ChartValueType.Double;
                        graph.Series["Total System"].IsXValueIndexed = false;
                        graph.Series["Total System"].Color           = Color.SpringGreen;

                        graph.ResetAutoValues();

                        graph.ChartAreas[0].AxisY.Maximum          = 100; //Max Y
                        graph.ChartAreas[0].AxisY.Minimum          = 0;
                        graph.ChartAreas[0].AxisX.Enabled          = AxisEnabled.False;
                        graph.ChartAreas[0].AxisY.IntervalAutoMode = IntervalAutoMode.VariableCount;
                    }
                    catch (Exception ex)
                    {
                        DebugHelper.Exception(ex);
                    }
                }));
            }
            catch (Exception ex)
            {
                DebugHelper.Exception(ex);
            }
        }
Ejemplo n.º 28
0
        public void Start(bool noprofile = false, string profilepath = null, bool crashtenderstart = false)
        {
            if (!Parent.IsStarted || !Parent.Diablo.IsRunning || (_crashTenderRestart && !crashtenderstart))
            {
                return;
            }
            if (!File.Exists(Location))
            {
                Logger.Instance.Write("File not found: {0}", Location);
                return;
            }

            while (Parent.IsStarted && Parent.Diablo.IsRunning)
            {
                // Get Last login time and kill old session
                if (GetLastLoginTime)
                {
                    BuddyAuth.Instance.KillSession(Parent);
                }

                _isStopped = false;

                // Reset AntiIdle;
                Parent.AntiIdle.Reset(true);

                var arguments = "-pid=" + Parent.Diablo.Proc.Id;
                arguments += " -key=" + Key;
                arguments += " -autostart";
                arguments += string.Format(" -routine=\"{0}\"", CombatRoutine);
                arguments += string.Format(" -bnetaccount=\"{0}\"", Parent.Diablo.Username);
                arguments += string.Format(" -bnetpassword=\"{0}\"", Parent.Diablo.Password);

                if (profilepath != null)
                {
                    // Check if current profile path is Kickstart
                    var file = Path.GetFileName(profilepath);
                    if (file == null || (file.Equals("YAR_Kickstart.xml") || file.Equals("YAR_TMP_Kickstart.xml")))
                    {
                        profilepath = Parent.ProfileSchedule.Current.Location;
                    }

                    var profile = new Profile()
                    {
                        Location = profilepath
                    };
                    var path = ProfileKickstart.GenerateKickstart(profile);
                    Logger.Instance.Write("Using Profile {0}", path);
                    arguments += string.Format(" -profile=\"{0}\"", path);
                }
                else if (Parent.ProfileSchedule.Profiles.Count > 0 && !noprofile)
                {
                    var path = Parent.ProfileSchedule.GetProfile;
                    Logger.Instance.Write("Using Scheduled Profile {0}", path);
                    if (File.Exists(path))
                    {
                        arguments += string.Format(" -profile=\"{0}\"", path);
                    }
                }
                else if (!noprofile)
                {
                    Logger.Instance.Write("Warning: Launching Demonbuddy without a starting profile (Add a profile to the profilescheduler for this bot)");
                }

                if (NoFlash)
                {
                    arguments += " -noflash";
                }
                if (AutoUpdate)
                {
                    arguments += " -autoupdate";
                }
                if (NoUpdate)
                {
                    arguments += " -noupdate";
                }

                if (ForceEnableAllPlugins)
                {
                    arguments += " -YarEnableAll";
                }

                Debug.WriteLine("DB Arguments: {0}", arguments);

                var p = new ProcessStartInfo(Location, arguments)
                {
                    WorkingDirectory = Path.GetDirectoryName(Location)
                };
                p = UserAccount.ImpersonateStartInfo(p, Parent);

                // Check/Install latest Communicator plugin
                var plugin = string.Format("{0}\\Plugins\\YAR\\Plugin.cs", p.WorkingDirectory);
                if (!PluginVersionCheck.Check(plugin))
                {
                    PluginVersionCheck.Install(plugin);
                }


                DateTime timeout;
                try                                        // Try to start Demonbuddy
                {
                    Parent.Status = "Starting Demonbuddy"; // Update Status
                    Proc          = Process.Start(p);

                    if (Program.IsRunAsAdmin)
                    {
                        Proc.PriorityClass = General.GetPriorityClass(Priority);
                    }
                    else
                    {
                        Logger.Instance.Write(Parent, "Failed to change priority (No admin rights)");
                    }


                    // Set affinity
                    if (CpuCount != Environment.ProcessorCount)
                    {
                        ProcessorAffinity = AllProcessors; // set it to all ones
                        CpuCount          = Environment.ProcessorCount;
                    }
                    Proc.ProcessorAffinity = (IntPtr)ProcessorAffinity;


                    Logger.Instance.Write(Parent, "Demonbuddy:{0}: Waiting for process to become ready", Proc.Id);

                    timeout = DateTime.Now;
                    while (true)
                    {
                        if (General.DateSubtract(timeout) > 30)
                        {
                            Logger.Instance.Write(Parent, "Demonbuddy:{0}: Failed to start!", Proc.Id);
                            Parent.Restart();
                            return;
                        }
                        Thread.Sleep(500);
                        try
                        {
                            Proc.Refresh();
                            if (Proc.WaitForInputIdle(100) || CrashChecker.IsResponding(MainWindowHandle))
                            {
                                break;
                            }
                        }
                        catch
                        {
                        }
                    }

                    if (_isStopped)
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                    DebugHelper.Exception(ex);
                    Parent.Stop();
                }

                timeout = DateTime.Now;
                while (!FindMainWindow())
                {
                    if (General.DateSubtract(timeout) > 30)
                    {
                        MainWindowHandle = Proc.MainWindowHandle;
                        break;
                    }
                    Thread.Sleep(500);
                }

                // Window postion & resizing
                if (ManualPosSize)
                {
                    AutoPosition.ManualPositionWindow(MainWindowHandle, X, Y, W, H, Parent);
                }
                Logger.Instance.Write(Parent, "Demonbuddy:{0}: Process is ready", Proc.Id);

                // Wait for demonbuddy to be Initialized (this means we are logged in)
                // If we don't wait here the Region changeing for diablo fails!
                Logger.Instance.Write(Parent, "Demonbuddy:{0}: Waiting for demonbuddy to log into Diablo", Proc.Id);
                while (!IsInitialized && !_isStopped)
                {
                    Thread.Sleep(1000);
                }
                // We made to many attempts break here
                if (Parent.AntiIdle.FailedInitCount > 3)
                {
                    break;
                }
                if (!Parent.AntiIdle.IsInitialized)
                {
                    continue;                                 // Retry
                }
                // We are ready to go
                Logger.Instance.Write(Parent, "Demonbuddy:{0}: Initialized! We are ready to go", Proc.Id);
                Parent.AntiIdle.FailedInitCount = 0; // only reset counter
                break;
            } // while (Parent.IsStarted && Parent.Diablo.IsRunning)
        }