Example #1
0
        public static void Main(string[] args)
        {
            //On Console exit make sure we also exit the proxy
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            Console.Write("Do you want to monitor HTTPS? (Y/N):");

            if(Console.ReadLine().Trim().ToLower()=="y" )
            {
                controller.EnableSSL = true;

            }

            Console.Write("Do you want to set this as a System Proxy? (Y/N):");

            if (Console.ReadLine().Trim().ToLower() == "y")
            {
                controller.SetAsSystemProxy = true;

            }

            //Start proxy controller
            controller.StartProxy();

            Console.WriteLine("Hit any key to exit..");
            Console.WriteLine();
            Console.Read();

            controller.Stop();
        }
Example #2
0
        static void Main(string[] args)
        {
            //Setup console events
            consoleHandler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(consoleHandler, true);

            //Setup forms stuff, to possibly be used if an error occurs and a dialog needs to be opened
            System.Windows.Forms.Application.EnableVisualStyles();
            System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);

            Console.Title = title;

            //Only show error screen in release builds
            #if DEBUG
                Server = new Server();
                Server.Run();
            #else
                try
                {
                    Server = new Server();
                    Server.Run();
                }
                catch (Exception e)
                {
                    //Open all exceptions in an error dialog
                   System.Windows.Forms.Application.Run(new Bricklayer.Common.ExceptionForm(e));
            }
            #endif
        }
Example #3
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            var ser = new Service1();

            if (Environment.UserInteractive)
            {
                _handler = (eventType) =>
                {
                    //only 5 seconds so run important code first
                    if (eventType == 2)
                    {
                        ser.Stop();
                        LogManager.Logger.Debug("Exiting");
                    }
                    return false;
                };

                SetConsoleCtrlHandler(_handler, true);

                ser.Start(null);
                Thread.Sleep(Timeout.Infinite);
            }
            else
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    ser
                };
                ServiceBase.Run(ServicesToRun);
            }
        }
Example #4
0
 static void Main(string[] args)
 {
     _starter = new Starter();
     _starter.Start();
     handler = new ConsoleEventDelegate(ConsoleEventCallback);
     SetConsoleCtrlHandler(handler, true);
     Console.ReadLine();
 }
 static bool ConsoleEventCallback(int eventType)
 {
     if (eventType == 2)
     {
         ConsoleClose(null, EventArgs.Empty);
     }
     ConsoleClose= null;
     _handler = null;
     return false;
 }
Example #6
0
        static void Main(string[] args)
        {
            var handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            c = new Checker();
            c.Initialize();
            c.Start();

            Console.Read();
        }
        static void Main(string[] args)
        {
            Start(args);

            consoleEventCallbackHandler = ConsoleEventCallback;
            SetConsoleCtrlHandler(consoleEventCallbackHandler, true);

            System.Console.WriteLine("Press any key to stop...");
            System.Console.ReadKey(true);

            Stop();
        }
Example #8
0
        static void Main()
        {
            #region This region is only for use in this console example as ending the console will leave VLC running
            handler = ConsoleEventCallback;
            var osver = Environment.OSVersion;
            switch (osver.Platform)
            {
                case PlatformID.Win32NT:
                    SetConsoleCtrlHandler(handler, true);
                    break;
            }

            #endregion

            var input = new FileInfo(@"c:\Temp\inputVideo.avi");
            var output = new FileInfo(@"c:\Temp\outputVideo.mpg");

            if (!input.Exists)
            {
                throw new FileNotFoundException("Example app needs a file to convert", input.FullName);
            }

            var driver = new VlcDriver();
            //driver.VlcExePath = new FileInfo("/usr/bin/vlc"); - Only on Non Windows environments
            Job = driver.CreateVideoJob();
            Job.InputFile = input;
            Job.OutputFile = output;
            Job.VideoConfiguration.Format = VideoConfiguration.VlcVideoFormat.Mpeg2;
            Job.AudioConfiguration.Format = AudioConfiguration.ConversionFormats.Mpg;

            driver.StartJob(Job);

            while (Job.State != VlcJob.JobState.Finished)
            {
                Job.UpdateProgress();
                Console.Clear();
                Console.SetCursorPosition(0,0);
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("{0}% Complete. Remaining {1}", string.Format("{0:0.0#}", Job.PercentComplete * 100), Job.EstimatedTimeToCompletion.ToString(@"h\h\:m\m\:s\s", System.Globalization.CultureInfo.InvariantCulture));
                Thread.Sleep(1000);
            }
        }
Example #9
0
        // Mouse start point range 0-65535
        //private static int pos_x = 32768;
        //private static int pos_y = 49151;

        static void Main(string[] args)
        {
            // Exit handler
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            // Mapping keylayout
            InitLayout();

            // Connect to target Android
            and1 = new Adb("192.168.0.105");

            
            // Thread to get constant stream of event in target Android
            eventing = new Thread(new ThreadStart(and1.AdbReadEvents));
            eventing.Start();
            while (!eventing.IsAlive) ;
            Thread.Sleep(10);

            // event execution loop
            while (eventing.IsAlive)
            {
                try
                {
                    if (and1.GetEvents().Count() > 0)
                    {
                        ParseEvent(and1.GetEvents()[0]);
                        and1.Remove(0);
                    }
                    else
                    {
                        Thread.Sleep(1);
                    }
                }
                catch (NullReferenceException)
                {
                    Thread.Sleep(1);
                    continue;
                }

            }
        }
Example #10
0
        internal static void Subscribe()
        {
            #if WINDOWS
            handler = new ConsoleEventDelegate((type) =>
            {
                if (type == 2)
                {
                    if (SystemExit != null)
                        SystemExit(true);
                }
                return false;
            });
            SetConsoleCtrlHandler(handler, true);
            #endif

            #if UNIX
            signal_thread = new Thread(() =>
            {
                while (isRunning)
                {
                    int index = UnixSignal.WaitAny(signals, -1);

                    Mono.Unix.Native.Signum signal = signals[index].Signum;
                    if (SystemExit != null)
                        SystemExit(true);

                    isRunning = false;
                }
            });
            signal_thread.Start();
            #endif

            AppDomain.CurrentDomain.ProcessExit += (sender, args) =>
                {
                    if (SystemExit != null)
                        SystemExit(false);
                };
        }
Example #11
0
        static void Main(string[] args)
        {
            Console.CancelKeyPress += delegate
            {
                core.Kill();
            }; 
            handler = ConsoleEventCallback;
            SetConsoleCtrlHandler(handler, true);

            Console.Title = "MBCon - Connected";
            Console.OutputEncoding = Encoding.UTF8;
            core = new Core();
            try
            {
                core.Run(args);
            }
            catch (CoreException ex)
            {
                core.Kill();
                AppConsole.Log(String.Format("ERROR: {0}", ex.Message), ConsoleColor.Red);
                Thread.Sleep(5000);
            }
        }
Example #12
0
        static void Main(string[] args)
        {
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            Console.SetWindowSize(150, 50);
            Console.BackgroundColor = ConsoleColor.White;
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("Azure DarkOrbit(DO) EMULATOR");
            Console.WriteLine("THANKS TO Eliaz for the packets");
            Console.WriteLine("THE FREE OPEN-SOURCE DARKORBIT EMULATOR");
            Console.WriteLine("COPYRIGHT <C> 2013 BY XDR");
            Console.WriteLine("FOR MORE DETAILS CHECK UPDATE.TXT");
            Console.WriteLine("");
            Console.WriteLine("BUILD");
            Console.WriteLine(" CORE: AZURE 0.2 on C#.NET 4.5");
            Console.WriteLine(" CLIENT VERSION: 4.1");
            Console.WriteLine(" SERVER VERSION: 0.5");
            Console.WriteLine("______________________________________________________");
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine("");
            Out.WriteLine("Starting up DarkOrbit Emulator for " + Environment.MachineName + "...", "Azure.Boot");
            Task.Factory.StartNew(Server);

            while (true)
            {
                string Command = Console.ReadLine();
                string[] SubCommands = (Command.Contains(' ')) ? Command.Split(' ') : null;

                if (Command == "close")
                {
                    ConsoleEventCallback(2);
                    Environment.Exit(0);
                }
            }
        }
Example #13
0
        internal static void Main(string[] args)
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            _configuration = (RadiumBotConfigurationSection) config.GetSection("radiumBot");

            _noHipChat = _configuration.NoHipChat ?? false;
            _noPagerDuty = _configuration.NoPagerDuty ?? true;

            if (_configuration.NotifyOnShutdown == true)
            {
                _handler = ConsoleEventCallback;
                SetConsoleCtrlHandler(_handler, true);
            }

            var pods = _configuration.Alerts.Select(x => new AlertingMetric(x.Name, x.ConnectionString)
            {
                LowWatermark = x.LowWatermark ?? 500,
                HipChatApiKey = x.HipChat?.HipChatApiKey,
                HipChatRoomName = x.HipChat?.HipChatRoomName,
                LastPagerDutyAlert = null,
                PagerDutyServiceApiKey = x.PagerDuty?.GenericServiceApiKey,
                PagerDutyMessage = x.PagerDuty?.MessageOnAlert,
                RealtimeUpdates = x.RealtimeUpdates ?? false
            })
                .ToArray();

            if (_configuration.NotifyOnStartup == true)
                foreach (var hc in pods.Select(p => new {p.HipChatApiKey, p.HipChatRoomName}).Where(p => !string.IsNullOrWhiteSpace(p.HipChatApiKey)).Distinct())
                    HipChatClient.SendMessage(hc.HipChatApiKey, hc.HipChatRoomName, "RadiumBot", "RadiumBot has started", true,
                        HipChatClient.BackgroundColor.purple);

            var threads = new List<Thread>(pods.Length);
            threads.AddRange(pods.Select(podClosure => new Thread(() => MonitorPod(podClosure))));
            foreach (var thread in threads)
                thread.Start();
        }
Example #14
0
        static void Main(string[] args)
        {
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            var form = new NeuralForm(NeuralNetwork);

            form.Show();

            var r = new Random(1);

            if (!File.Exists("neural.net"))
            {
                var ii = 0;
                while (ii++ <= 100000)
                {
                    var input = new double[8];

                    for (int i = 0; i < input.Length; i++)
                    {
                        input[i] = r.Next(100) > 50 ? 1 : 0;
                    }

                    var output = new double[input.Length];

                    for (int i = 0; i < input.Length; i++)
                    {
                        output[i] = input[i] == 1 ? 0 : 1;
                    }

                    NeuralNetwork.Train(input, output);



                    var networkOutput = new double[input.Length];
                    for (int j = 0; j < NeuralNetwork.Layers.Last().Neurons.Count; j++)
                    {
                        var neuron = NeuralNetwork.Layers.Last().Neurons[j];
                        networkOutput[j] = neuron.Value;
                    }

                    for (int j = 0; j < output.Length; j++)
                    {
                        if (experienceList.Count > 999)
                        {
                            experienceList.Remove(experienceList.First());
                        }
                        experienceList.Add(output[j] == Math.Round(networkOutput[j]) ? 1 : 0);
                    }

                    double temp = 0;
                    foreach (var exp in experienceList)
                    {
                        temp += exp;
                    }

                    double loss = 100 - ((temp / experienceList.Count) * 100);



                    if (ii % 100 == 0)
                    {
                        Console.CursorTop  = 0;
                        Console.CursorLeft = 0;
                        Console.WriteLine($"Iteration: {ii}  ");
                        form.UpdateNeural(NeuralNetwork, $"Loss: {loss:##.###}%");
                    }
                }
            }
            else
            {
                NeuralNetwork.Load("neural.net");
                form.Hide();
                form = new NeuralForm(NeuralNetwork);
                form.Show();
            }



            while (true)
            {
                Console.Clear();

                var input         = new double[8];
                var networkOutput = new double[8];
                var output        = new double[8];

                for (int i = 0; i < input.Length; i++)
                {
                    input[i] = r.Next(100) > 50 ? 1 : 0;
                }

                for (int i = 0; i < input.Length; i++)
                {
                    output[i] = input[i] == 1 ? 0 : 1;
                }

                var response = NeuralNetwork.Run(input);

                for (int i = 0; i < response.Length; i++)
                {
                    networkOutput[i] = Math.Round(response[i]);
                }
                DrawMap(input, networkOutput);

                for (int i = 0; i < 10; i++)
                {
                    NeuralNetwork.Train(input, output);
                }



                for (int j = 0; j < output.Length; j++)
                {
                    if (experienceList.Count > 999)
                    {
                        experienceList.Remove(experienceList.First());
                    }
                    experienceList.Add(output[j] == Math.Round(networkOutput[j]) ? 1 : 0);
                }

                double temp = 0;
                foreach (var exp in experienceList)
                {
                    temp += exp;
                }

                double loss = 100 - ((temp / experienceList.Count) * 100);



                form.UpdateNeural(NeuralNetwork, $"Loss: {loss:##.###}%");
                //Thread.Sleep(300);
            }
        }
Example #15
0
        static void Main(string[] args)
        {
            Console.WriteLine("Log location; " + logFilePath);

            void ActualMain()
            {
                //AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                SetupDataFolder();
                if (File.Exists(logFilePath))
                {
                    try {
                        File.WriteAllText(logFilePath, string.Empty);
                    } catch {
                        // Don't let this being DENIED crash the software
                    }
                }
                else
                {
                    Console.WriteLine("Trying to create log");
                    CreateLogFile();
                }

                //Check if software already runs, if so kill this instance
                var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull));

                if (otherACCs.Length > 1)
                {
                    //Try kill the _other_ process instead
                    foreach (Process p in otherACCs)
                    {
                        if (p.Id != Process.GetCurrentProcess().Id)
                        {
                            try {
                                p.Kill();
                                DoDebug("Other ACC instance was running. Killed it.");
                            } catch {
                                DoDebug("Could not kill other process of ACC; access denied");
                            }
                        }
                    }
                }

                Application.EnableVisualStyles();

                DoDebug("[ACC begun (v" + softwareVersion + ")]");
#if (HasAnalyticsClass)
                AnalyticsSettings.SetupAnalytics();
#endif

                if (Properties.Settings.Default.CheckForUpdates)
                {
                    if (HasInternet())
                    {
                        new Thread(() => {
                            new ACC_Updater().Check();
                        }).Start();
                    }
                    else
                    {
                        DoDebug("Couldn't check for new update as PC does not have access to the internet");
                    }
                }

                //On console close: hide NotifyIcon
                Application.ApplicationExit += new EventHandler(OnApplicationExit);
                handler = new ConsoleEventDelegate(ConsoleEventCallback);
                SetConsoleCtrlHandler(handler, true);

                //Check if software starts with Windows
                if (!Properties.Settings.Default.StartWithWindows)
                {
                    sysIcon.AddOpenOnStartupMenu();
                }

                //Create shortcut folder if doesn't exist
                if (!Directory.Exists(shortcutLocation))
                {
                    Directory.CreateDirectory(shortcutLocation);
                }
                if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt")))
                {
                    //Create example-file
                    try {
                        using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
                            sw.WriteLine("This is an example file.");
                            sw.WriteLine("If you haven't already, make your assistant open this file!");
                        }
                    } catch {
                        DoDebug("Could not create or write to example file");
                    }
                }

                //Delete all old action files
                if (Directory.Exists(CheckPath()))
                {
                    foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension))
                    {
                        ClearFile(file);
                    }
                }

                //SetupListener();
                watcher = new FileSystemWatcher()
                {
                    Path         = CheckPath(),
                    NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                   | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                    Filter = "*." + Properties.Settings.Default.ActionFileExtension,
                    EnableRaisingEvents = true
                };
                watcher.Changed += new FileSystemEventHandler(ActionChecker.FileFound);
                watcher.Created += new FileSystemEventHandler(ActionChecker.FileFound);

                DoDebug("\n[" + messageBoxTitle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions");

                sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon;

                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                if (Registry.GetValue(key.Name + "\\AssistantComputerControl", "FirstTime", null) == null)
                {
                    key.CreateSubKey("AssistantComputerControl");
                    key = key.OpenSubKey("AssistantComputerControl", true);
                    key.SetValue("FirstTime", false);

                    Properties.Settings.Default.HasCompletedTutorial = true;
                    Properties.Settings.Default.Save();

                    ShowGettingStarted();

                    DoDebug("Starting setup guide");
                }
                else
                {
                    if (!Properties.Settings.Default.HasCompletedTutorial)
                    {
                        ShowGettingStarted();
                        DoDebug("Didn't finish setup guide last time, opening again");
                    }
                }
                SetRegKey("ActionFolder", CheckPath());
                SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension);

                if (gettingStarted is null && !Properties.Settings.Default.AnalyticsInformed)
                {
                    //"Getting started" not shown but user hasn't been told about analytics gathering yet
                    ShowGettingStarted(3);
                }

                //If newly updated
                if (Properties.Settings.Default.LastKnownVersion != softwareVersion)
                {
                    //Up(or down)-grade, display version notes
                    if (gettingStarted != null)
                    {
                        DoDebug("'AboutVersion' window awaits, as 'Getting Started' is showing");
                        aboutVersionAwaiting = true;
                    }
                    else
                    {
                        Properties.Settings.Default.LastKnownVersion = softwareVersion;
                        new NewVersion().Show();
                        Properties.Settings.Default.Save();
                    }
                }

                SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //On wake up from sleep
                Application.Run();
            }

            hasAnalyticsClass = Type.GetType("AssistantComputerControl.AnalyticsSettings") != null;

            string sentryToken = "super_secret";

            if (hasAnalyticsClass)
            {
#if (HasAnalyticsClass)
                sentryToken = AnalyticsSettings.sentryToken;
#endif
            }

            if (sentryToken != "super_secret")
            {
                //Tracking issues with Sentry.IO - not forked from GitHub (official version)
                bool sentryOK = false;
                try {
                    if (Properties.Settings.Default.UID != "")
                    {
                        SentrySdk.ConfigureScope(scope => {
                            scope.User = new Sentry.Protocol.User {
                                Id = Properties.Settings.Default.UID
                            };
                        });
                    }

                    using (SentrySdk.Init(sentryToken)) {
                        sentryOK = true;
                    }
                } catch {
                    //Sentry failed. Error sentry's side or invalid key - don't let this stop the app from running
                    DoDebug("Sentry initiation failed");
                    ActualMain();
                }

                if (sentryOK)
                {
                    using (SentrySdk.Init(sentryToken)) {
                        DoDebug("Sentry initiated");
                        ActualMain();
                    }
                }
            }
            else
            {
                //Code is (most likely) forked - skip issue tracking
                ActualMain();
            }
        }
Example #16
0
        static async Task Main(string[] args)
        {
            try
            {
                var handle = GetConsoleWindow();
                ShowWindow(handle, SW_HIDE);
                VerifyIfGameDirectory();
                StartGame();
                SetupMapFileWatcher();
                await ExecutePreCommandAsync();

                while (Process.GetProcessesByName("ge").FirstOrDefault() == null)
                {
                    await Task.Delay(100);
                }
                var postTask = ExecutePostCommandAsync();
                procmon = new System.Timers.Timer
                {
                    Interval = 300
                };
                procmon.Elapsed += Procmon_WatchDog;
                procmon.Start();

                handler = new ConsoleEventDelegate(ConsoleEventCallback);
                SetConsoleCtrlHandler(handler, true);
                Process GameProcess = Process.GetProcessesByName("ge").FirstOrDefault();
                if (GameProcess == null)
                {
                    Environment.Exit(0);
                }
                VAMemory vam = new VAMemory("ge");
                vam.ReadInt32(GameProcess.MainModule.BaseAddress);
                DiscordRPC.EventHandlers handlers = new DiscordRPC.EventHandlers
                {
                    readyCallback        = HandleReadyCallback,
                    errorCallback        = HandleErrorCallback,
                    disconnectedCallback = HandleDisconnectedCallback
                };
                DiscordRPC.Initialize("720242655103156235", ref handlers, true, null);
                var presence = new DiscordRPC.RichPresence
                {
                    largeImageKey = "gicon",
                };
                presence.startTimestamp = ToUtcUnixTime(DateTime.Now);//DateTimeOffset.Now.
                presence.largeImageText = "https://github.com/Desz01ate/Andromida-GE-Tracker/releases";
                string latestMap = string.Empty;
                await  postTask;
                while (true)
                {
                    var familyName = GetFamilyName(vam);
                    var currentMap = GetCurrentMap(vam);
                    presence.details = familyName;
                    presence.state   = GetMapDescription(currentMap);
                    if (latestMap != currentMap)
                    {
                        latestMap = currentMap;
                        presence.startTimestamp = ToUtcUnixTime(DateTime.Now);
                    }
                    DiscordRPC.UpdatePresence(presence);
                    await Task.Delay(1000);
                }
            }
            catch (Exception ex)
            {
                AppendLog(ex);
            }
        }
Example #17
0
        public Program(string[] args)
        {
            var myExePath     = Path.GetFullPath(Environment.GetCommandLineArgs()[0]);
            var myExeFileName = Path.GetFileName(myExePath);
            var cfgFile       = myExeFileName + ".config";

            //var cfg = new XMLConfig(cfgFile);


            try
            {
                this.args = args;
                if (args.Length >= 1 && (args[0] == "help" || args[0] == "?"))
                {
                    printHelp = true;
                }

                Param("serverPort");
                Param("updateProcessInfoEveryMiliseconds");
                Param("numberOfProcessInfoSamplesToAverage");
                Param("updateNetworkInfoEveryMiliseconds");
                Param("secondsToKeepNetworkInfoSamples");
                Param("secondsToKeepWatchingProcessWithNoRequests");
                Param("secondsToClosePIDPortsWithNoRequests");
                Param("secondsToUpdatePidToPortsTable");


                if (printHelp)
                {
                    PrintGeneralHelp();
                }
                if (!printHelp && allPassed)
                {
                    Console.WriteLine("Starting ...");
                    Start();
                    Console.WriteLine("Started");

                    AppDomain.CurrentDomain.ProcessExit += (sender, a) =>
                    {
                        Stop();
                    };

                    var handler = new ConsoleEventDelegate((int eventType) =>
                    {
                        if (eventType == 2)
                        {
                            Stop();
                        }
                        return(true);
                    });
                    SetConsoleCtrlHandler(handler, true);

                    //Console.WriteLine("Press enter to quit ...");
                    while (Thread.CurrentThread.ThreadState == ThreadState.Running)
                    {
                        Thread.Sleep(100);
                    }

                    Console.WriteLine("Stopping, this may take a while ...");
                    Stop();
                    Console.WriteLine("Stopped");
                }
            }
            catch (Exception e)
            {
                PrintGeneralHelp();
                Console.WriteLine();
                Console.WriteLine(e);
            }
        }
Example #18
0
 private static extern void SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add); // SetConsoleCtrlHandler is a function from kernel32.dll
Example #19
0
        static void StartUp()
        {
            RunningOnCI    = !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("CI_SERVER"));
            RunningOnLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);

            if (RunningOnLinux)
            {
                ConsoleWrapper.WriteLine("Linux Environment detected!");
            }

            Directory.SetCurrentDirectory(Path.GetDirectoryName(ExePath));

            if (RunningOnCI)
            {
                ConsoleWrapper.WriteLine("CI Environment detected!");
            }
            else
            {
                if (runConfig == "Debug")
                {
                    Console.Title = "MEE7 - DEBUG";
                }
                else
                {
                    Console.Title = "MEE7";
                }
                //if (!RunningOnLinux)
                //    ShowWindow(GetConsoleWindow(), 2);
                Thread.CurrentThread.Name = "Main";
                Console.ForegroundColor   = ConsoleColor.White;
                Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;

                handler = new ConsoleEventDelegate(ConsoleEventCallback);
                if (!RunningOnLinux)
                {
                    SetConsoleCtrlHandler(handler, true);
                }
            }

            LoadBuildDate();
            //UpdateYTDL();

            var config = new DiscordSocketConfig()
            {
                GatewayIntents      = GatewayIntents.All,
                AlwaysDownloadUsers = true,
            };

            client = new DiscordSocketClient(config);
            SetClientEvents();

            Login();

            CreateCommandInstances();

            while (!ClientReady || client.ConnectionState != ConnectionState.Connected)
            {
                Thread.Sleep(50);
            }

            SetState();

            CurrentChannel = (ISocketMessageChannel)client.GetChannel(473991188974927884);
            Thread.Sleep(1000);
            Master = client.GetUser(300699566041202699);

            DiscordNETWrapper.SendText(logStartupMessage, (IMessageChannel)GetChannelFromID(logChannel)).Wait();
            Config.Load();

            BuildHelpMenu();

            StartAutosaveLoop();

            Task.Run(() => BootTwitterModule());
            CallOnConnected();
        }
Example #20
0
        /// <summary>
        /// Now we're defenitely admin and can start everything.
        /// </summary>
        private static void MyMain()
        {
            StartRuralCafe();

            // for adding a list of URLs to the index
            //CacheIndexer.IndexSquidLog("urls.txt");

            // for analyzing search result pages
            //AnalysisTools.CountEmbeddedObjects();

            // Register our handler as event handler when the console exits
            // Like this we can do cleanup stuff before closing
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);
        }
 public static void Init()
 {
     handler = new ConsoleEventDelegate(ConsoleEventCallback);
     SetConsoleCtrlHandler(handler, true);
 }
        static ConsoleEventDelegate _handler; // Keeps it from getting garbage collected

        #endregion Fields

        #region Constructors

        static ConsoleUtils()
        {
            _handler = ConsoleEventCallback;
            SetConsoleCtrlHandler(_handler, true);
        }
Example #23
0
        //Fragt nach Namen und Schreibt wenn unter den ersten 20 die Punkte in das Hihscore-File an der Richtigen Stelle
        //bei gleichen Punkten werden die Punkte über dem Alten Punktestand gespeichert
        public void writeHighscore()
        {
            bool nameExist = false;
            bool replaced = false;
            string name;
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            do
            {
                nameExist = false;
                Console.Clear();
                Console.WriteLine(program.getPoints());
                Console.Write("Spielername (min 3 oder max 7 Zeichen und kein\"-\"): ");
                name = Console.ReadLine().Trim();

                if (name.Length > 7 || name.Length < 3 || name.Equals(""))
                {
                    Console.WriteLine("Der Name ist zu kurz oder zu lang!");
                    Console.ReadKey();
                    nameExist = true;
                }
                if (name.Contains("-"))
                {
                    Console.WriteLine("No \" - \"");
                    Console.ReadKey();
                    nameExist = true;
                }

            } while (nameExist == true);

            for (int i = 0; i < playerHolders.Count; i++)
            {
                if (!(Convert.ToInt32(program.getPoints()) < Convert.ToInt32(playerHolders[i].getAttribut("Punkte"))) && replaced != true)
                {
                    for (int x = 19; x >= (i + 1); x--)
                    {
                        playerHolders[x].removeAttribut("Name");
                        playerHolders[x].removeAttribut("Punkte");
                        playerHolders[x].setAttribut("Name", playerHolders[(x - 1)].getAttribut("Name"));
                        playerHolders[x].setAttribut("Punkte", playerHolders[(x - 1)].getAttribut("Punkte"));
                    }
                    playerHolders[i].getHighscore().Replace(playerHolders[i].getHighscore(), program.getPoints());
                    playerHolders[i].removeAttribut("Name");
                    playerHolders[i].setAttribut("Name", name);
                    playerHolders[i].removeAttribut("Punkte");
                    playerHolders[i].setAttribut("Punkte", program.getPoints());
                    replaced = true;
                }
                if (Convert.ToInt32(program.getPoints()) < Convert.ToInt32(playerHolders[19].getAttribut("Punkte")))
                {
                    Console.WriteLine("Deine Punkte sind zu niedrig für die obersten Top 20!");
                    Console.ReadKey();
                    break;
                }
            }

            removeFileSave();
            StreamWriter sw = new StreamWriter(@getPath());
            sw.WriteLine("|Platz|Name|Punkte|");
            for (int i = 0; i < 20; i++)
            {
                playerHolders[i].removeAttribut("Platz");
                playerHolders[i].setAttribut("Platz", Convert.ToString((i + 1)));
                sw.WriteLine("|" + playerHolders[i].getAttribut("Platz") + "|" + playerHolders[i].getAttribut("Name") + "|" + playerHolders[i].getAttribut("Punkte") + "|");
            }
            sw.Close();
            setFileSave();
        }
 static void Main(string[] args)
 {
     handler = new ConsoleEventDelegate(ConsoleEventCallback);
     SetConsoleCtrlHandler(handler, true);
     Console.ReadLine();
 }
Example #25
0
        static void Main(string[] args)
        {
            Console.WriteLine("Log location; " + logFilePath);
            CheckSettings();

            var config  = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile")
            {
                FileName = logFilePath
            };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;

            void ActualMain()
            {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                //Upgrade settings
                if (Properties.Settings.Default.UpdateSettings)
                {
                    /* Copy old setting-files in case the Evidence type and Evidence Hash has changed (which it does sometimes) - easier than creating a whole new settings system */
                    try {
                        Configuration accConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
                        string        currentFolder    = new DirectoryInfo(accConfiguration.FilePath).Parent.Parent.FullName;
                        string[]      directories      = Directory.GetDirectories(new DirectoryInfo(currentFolder).Parent.FullName);

                        foreach (string dir in directories)
                        {
                            if (dir != currentFolder.ToString())
                            {
                                var directoriesInDir = Directory.GetDirectories(dir);
                                foreach (string childDir in directoriesInDir)
                                {
                                    string checkPath = Path.Combine(currentFolder, Path.GetFileName(childDir));
                                    if (!Directory.Exists(checkPath))
                                    {
                                        string checkFile = Path.Combine(childDir, "user.config");
                                        if (File.Exists(checkFile))
                                        {
                                            bool xmlHasError = false;
                                            try {
                                                XmlDocument xml = new XmlDocument();
                                                xml.Load(checkFile);

                                                xml.Validate(null);
                                            } catch {
                                                xmlHasError = true;
                                                DoDebug("XML document validation failed (is invalid): " + checkFile);
                                            }

                                            if (!xmlHasError)
                                            {
                                                Directory.CreateDirectory(checkPath);
                                                File.Copy(checkFile, Path.Combine(checkPath, "user.config"), true);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        Console.WriteLine("Error getting settings from older versions of ACC" + e.Message);
                    }
                    /* End "copy settings" */

                    try {
                        Properties.Settings.Default.Upgrade();
                        Properties.Settings.Default.UpdateSettings = false;
                        Properties.Settings.Default.Save();
                    } catch {
                        DoDebug("Failed to upgrade from old settings file.");
                    }

                    Console.WriteLine("Upgraded settings to match last version");
                }

                if (Properties.Settings.Default.LastUpdated == DateTime.MinValue)
                {
                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                }

                //Translator
                string tempDir = Path.Combine(currentLocation, "Translations");

                if (Directory.Exists(tempDir))
                {
                    Translator.translationFolder = Path.Combine(currentLocation, "Translations");
                    Translator.languagesArray    = Translator.GetLanguages();
                }
                else
                {
                    MessageBox.Show("Missing the translations folder. Reinstall the software to fix this issue.", messageBoxTitle);
                }

                string lang = Properties.Settings.Default.ActiveLanguage;

                if (Array.Exists(Translator.languagesArray, element => element == lang))
                {
                    DoDebug("ACC running with language \"" + lang + "\"");

                    Translator.SetLanguage(lang);
                }
                else
                {
                    DoDebug("Invalid language chosen (" + lang + ")");

                    Properties.Settings.Default.ActiveLanguage = "English";
                    Translator.SetLanguage("English");
                }
                //End translator
                sysIcon = new SysTrayIcon();

                Properties.Settings.Default.TimesOpened += 1;
                Properties.Settings.Default.Save();

                SetupDataFolder();
                if (File.Exists(logFilePath))
                {
                    try {
                        File.WriteAllText(logFilePath, string.Empty);
                    } catch {
                        // Don't let this being DENIED crash the software
                        Console.WriteLine("Failed to empty the log");
                    }
                }
                else
                {
                    Console.WriteLine("Trying to create log");
                    CreateLogFile();
                }

                //Check if software already runs, if so kill this instance
                var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull));

                if (otherACCs.Length > 1)
                {
                    //Try kill the _other_ process instead
                    foreach (Process p in otherACCs)
                    {
                        if (p.Id != Process.GetCurrentProcess().Id)
                        {
                            try {
                                p.Kill();
                                DoDebug("Other ACC instance was running. Killed it.");
                            } catch {
                                DoDebug("Could not kill other process of ACC; access denied");
                            }
                        }
                    }
                }

                Application.EnableVisualStyles();

                DoDebug("[ACC begun (v" + softwareVersion + ")]");

                if (Properties.Settings.Default.CheckForUpdates)
                {
                    if (HasInternet())
                    {
                        new Thread(() => {
                            new SoftwareUpdater().Check();
                        }).Start();
                    }
                    else
                    {
                        DoDebug("Couldn't check for new update as PC does not have access to the internet");
                    }
                }

                //On console close: hide NotifyIcon
                Application.ApplicationExit += new EventHandler(OnApplicationExit);
                handler = new ConsoleEventDelegate(ConsoleEventCallback);
                SetConsoleCtrlHandler(handler, true);

                //Check if software starts with Windows
                if (!ACCStartsWithWindows())
                {
                    sysIcon.AddOpenOnStartupMenu();
                }

                //Create shortcut folder if doesn't exist
                if (!Directory.Exists(shortcutLocation))
                {
                    Directory.CreateDirectory(shortcutLocation);
                }
                if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt")))
                {
                    //Create example-file
                    try {
                        using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
                            sw.WriteLine("This is an example file.");
                            sw.WriteLine("If you haven't already, make your assistant open this file!");
                        }
                    } catch {
                        DoDebug("Could not create or write to example file");
                    }
                }

                //Delete all old action files
                if (Directory.Exists(CheckPath()))
                {
                    DoDebug("Deleting all files in action folder");
                    foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension))
                    {
                        int timeout = 0;

                        if (File.Exists(file))
                        {
                            while (ActionChecker.FileInUse(file) && timeout < 5)
                            {
                                timeout++;
                                Thread.Sleep(500);
                            }
                            if (timeout >= 5)
                            {
                                DoDebug("Failed to delete file at " + file + " as file appears to be in use (and has been for 2.5 seconds)");
                            }
                            else
                            {
                                try {
                                    File.Delete(file);
                                } catch (Exception e) {
                                    DoDebug("Failed to delete file at " + file + "; " + e.Message);
                                }
                            }
                        }
                    }
                    DoDebug("Old action files removed - moving on...");
                }

                //SetupListener();
                watcher = new FileSystemWatcher()
                {
                    Path         = CheckPath(),
                    NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                   | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                    Filter = "*." + Properties.Settings.Default.ActionFileExtension,
                    EnableRaisingEvents = true
                };
                watcher.Changed += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Created += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Renamed += new RenamedEventHandler(new ActionChecker().FileFound);
                watcher.Deleted += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Error   += delegate { DoDebug("Something wen't wrong TEST"); };

                DoDebug("\n[" + messageBoxTitle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions");

                sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon_light;

                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);

                if (Registry.GetValue(key.Name + @"\AssistantComputerControl", "FirstTime", null) == null)
                {
                    key.CreateSubKey("AssistantComputerControl");
                    key = key.OpenSubKey("AssistantComputerControl", true);
                    key.SetValue("FirstTime", false);

                    Properties.Settings.Default.HasCompletedTutorial = true;
                    Properties.Settings.Default.Save();

                    ShowGettingStarted();

                    DoDebug("Starting setup guide");
                }
                else
                {
                    if (!Properties.Settings.Default.HasCompletedTutorial)
                    {
                        ShowGettingStarted();
                        DoDebug("Didn't finish setup guide last time, opening again");
                    }
                }
                SetRegKey("ActionFolder", CheckPath());
                SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension);

                testActionWindow = new TestActionWindow();

                //If newly updated
                if (Properties.Settings.Default.LastKnownVersion != softwareVersion)
                {
                    //Up(or down)-grade, display version notes
                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                    if (gettingStarted != null)
                    {
                        DoDebug("'AboutVersion' window awaits, as 'Getting Started' is showing");
                        aboutVersionAwaiting = true;
                    }
                    else
                    {
                        Properties.Settings.Default.LastKnownVersion = softwareVersion;
                        new NewVersion().Show();
                    }
                    Properties.Settings.Default.Save();
                }

                /* 'Evalufied' user feedback implementation */
                if ((DateTime.Now - Properties.Settings.Default.LastUpdated).TotalDays >= 7 && Properties.Settings.Default.TimesOpened >= 7 &&
                    gettingStarted == null &&
                    !Properties.Settings.Default.HasPromptedFeedback)
                {
                    //User has had the software/update for at least 7 days, and has opened the software more than 7 times - time to ask for feedback
                    //(also the "getting started" window is not showing)
                    if (HasInternet())
                    {
                        try {
                            WebRequest      request  = WebRequest.Create("https://evalufied.dk/");
                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                            if (response == null || response.StatusCode != HttpStatusCode.OK)
                            {
                                DoDebug("'Evalufied' is down - won't show faulty feedback window");
                            }
                            else
                            {
                                DoDebug("Showing 'User Feedback' window");
                                Properties.Settings.Default.HasPromptedFeedback = true;
                                Properties.Settings.Default.Save();
                                new UserFeedback().Show();
                            }
                        } catch {
                            DoDebug("Failed to check for 'Evalufied'-availability");
                        }
                    }
                    else
                    {
                        DoDebug("No internet connection, not showing user feedback window");
                    }
                }

                //Action mods implementation
                ActionMods.CheckMods();
                TaskSchedulerSetup();

                SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //On wake up from sleep
                Application.Run();
            }

            if (sentryToken != "super_secret")
            {
                //Tracking issues with Sentry.IO - not forked from GitHub (official version)
                bool sentryOK = false;
                try {
                    if (Properties.Settings.Default.UID != "")
                    {
                        Properties.Settings.Default.UID = Guid.NewGuid().ToString();
                        Properties.Settings.Default.Save();
                    }

                    if (Properties.Settings.Default.UID != "")
                    {
                        SentrySdk.ConfigureScope(scope => {
                            scope.User = new Sentry.Protocol.User {
                                Id = Properties.Settings.Default.UID
                            };
                        });
                    }

                    using (SentrySdk.Init(sentryToken)) {
                        sentryOK = true;
                    }
                } catch {
                    //Sentry failed. Error sentry's side or invalid key - don't let this stop the app from running
                    DoDebug("Sentry initiation failed");
                    ActualMain();
                }

                if (sentryOK)
                {
                    try {
                        using (SentrySdk.Init(sentryToken)) {
                            DoDebug("Sentry initiated");
                            ActualMain();
                        }
                    } catch {
                        ActualMain();
                    }
                }
            }
            else
            {
                //Code is (most likely) forked - skip issue tracking
                ActualMain();
            }
        }
Example #26
0
        /// <summary>
        /// Main function
        /// Too many comments
        /// </summary>
        /// <param name="args">No args</param>
        static void Main(string[] args)
        {
            /*Create a folder for our account sentry files*/
            Console.Title = EndPoint.CONSOLE_TITLE;
            Directory.CreateDirectory(EndPoint.SENTRY_FOLDER_PATH);
            Directory.CreateDirectory(EndPoint.LOG_FOLDER_PATH);

            /*Set exit events so we'll log out all accounts if application is exited*/
            mEventHandler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(mEventHandler, true);

            /*Start the trayicon thread*/
            mThreadTray = new Thread(ToTray);
            mThreadTray.Start();

            /*We'll read and store the settings twice since we'll compare the two objects later on
            to see if something has changed by the user during runtime*/
            mSettings = Settings.GetSettings();
            if (mSettings == null)
                return;

            /*Read the application settings and start our session*/
            var settings = Settings.GetSettings();
            if (settings != null)
            {
                if (settings.Accounts.Count > 0)
                {
                    mSession = new Session(settings);
                    while (mSession.mBwg.IsBusy)
                        Thread.Sleep(250);

                    if (settings.HideToTrayAutomatically)
                    {
                        mTrayIcon.ShowBalloonTip(1000, "HourBoostr", "I'm down here!", ToolTipIcon.Info);
                        ShowConsole(false);
                    }
                }
                else
                {
                    Console.WriteLine("No accounts were loaded from settings.");
                }

                while (true)
                    Thread.Sleep(250);
            }
        }
Example #27
0
        public static void Main(string[] args)
        {
            #if !__MonoCS__
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);
            #else
            // http://stackoverflow.com/questions/6546509/detect-when-console-application-is-closing-killed
            var signums = new Signum []
            {
                Signum.SIGABRT,
                Signum.SIGINT,
                Signum.SIGKILL,
                Signum.SIGQUIT,
                Signum.SIGTERM,
                Signum.SIGSTOP,
                Signum.SIGTSTP
            };

            List<UnixSignal> signals = new List<UnixSignal>();
            foreach (var signum in signums)
            {
                try
                {
                    signals.Add(new UnixSignal(signum));
                }
                catch(Exception) {}
            }

            new Thread (delegate ()
            {
                // Wait for a signal to be delivered
                UnixSignal.WaitAny(signals.ToArray(), -1);
                app.Shutdown("UnixSignal");
            }).Start();
            #endif

            if (string.IsNullOrWhiteSpace(Settings.Default.TempPath))
            {
                Settings.Default.TempPath = Settings.Default.GetAppDataPath() + "tmp";
            }
            if (!Settings.Default.TempPath.EndsWith("" + Path.DirectorySeparatorChar))
            {
                Settings.Default.TempPath += Path.DirectorySeparatorChar;
            }
            new DirectoryInfo(Settings.Default.TempPath).Create();

            if (string.IsNullOrWhiteSpace(Settings.Default.ReadyPath))
            {
                Settings.Default.ReadyPath = Settings.Default.GetAppDataPath() + "dl";
            }
            if (!Settings.Default.ReadyPath.EndsWith("" + Path.DirectorySeparatorChar))
            {
                Settings.Default.ReadyPath += Path.DirectorySeparatorChar;
            }
            new DirectoryInfo(Settings.Default.ReadyPath).Create();

            Settings.Default.Save();

            if (File.Exists(Settings.Default.GetAppDataPath() + "log4net.xml"))
            {
                // load settings from file
                XmlConfigurator.Configure(new FileInfo(Settings.Default.GetAppDataPath() + "log4net.xml"));
            }
            else
            {
                // build our own, who logs only fatals to console
                Logger root = ((Hierarchy)LogManager.GetRepository()).Root;

                var lAppender = new ConsoleAppender
                {
                    Name = "Console",
                    Layout = new PatternLayout("%date{dd-MM-yyyy HH:mm:ss,fff} %5level [%2thread] %line:%logger.%message%n"),
            #if DEBUG
                    Threshold = Level.Info
            #else
                    Threshold = Level.Fatal
            #endif
                };
                lAppender.ActivateOptions();

                root.AddAppender(lAppender);
                root.Repository.Configured = true;
            }

            #if __MonoCS__
            PlatformID id = Environment.OSVersion.Platform;
            // Don't allow running as root on Linux or Mac
            try
            {
                if ((id == PlatformID.Unix || id == PlatformID.MacOSX) && new UnixUserInfo(UnixEnvironment.UserName).UserId == 0)
                {
                    LogManager.GetLogger(typeof(Programm)).Fatal("Sorry, you can't run XG with these permissions. Safety first!");
                    Environment.Exit(-1);
                }
            }
            catch (ArgumentException)
            {
                // arch linux fix
                // https://github.com/lformella/xdcc-grabscher/issues/36
            }
            #endif

            app = new App();

            app.AddPlugin(new Plugin.Irc.Plugin());
            if (Settings.Default.UseJabberClient)
            {
                app.AddPlugin(new Plugin.Jabber.Plugin());
            }
            if (Settings.Default.UseElasticSearch)
            {
                app.AddPlugin(new Plugin.ElasticSearch.Plugin());
            }
            if (Settings.Default.UseWebserver)
            {
                var webServer = new Plugin.Webserver.Plugin { RrdDB = app.RrdDb };
                webServer.OnShutdown += delegate { app.Shutdown(webServer); };
                app.AddPlugin(webServer);
            }

            app.OnShutdownComplete += delegate { Environment.Exit(0); };
            app.Start(typeof(App).ToString());
        }

        #endregion Methods
    }
Example #28
0
        static void Main(string[] args)
        {
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            CurrentServer = (string)Registry.GetValue(keyName, "ProxyServer", null);
            CurrentEnable = (int)Registry.GetValue(keyName, "ProxyEnable", 0);
            setProxy("127.0.0.1:80", 1);
            ProxyServer server = new ProxyServer();
            server.Start();
            setProxy(CurrentServer, 0);
        }
Example #29
0
        static void Main(string[] args)
        {
            ScpBus scpBus = new ScpBus();

            scpBus.UnplugAll();
            global_scpBus = scpBus;

            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            Thread.Sleep(400);

            Xiaomi_gamepad[] gamepads = new Xiaomi_gamepad[4];
            int index             = 1;
            var compatibleDevices = HidDevices.Enumerate(0x2717, 0x3144).ToList();

            foreach (var deviceInstance in compatibleDevices)
            {
                Console.WriteLine(deviceInstance);
                HidDevice Device = deviceInstance;
                try
                {
                    Device.OpenDevice(DeviceMode.Overlapped, DeviceMode.Overlapped, ShareMode.Exclusive);
                }
                catch
                {
                    Console.WriteLine("Could not open gamepad in exclusive mode. Try re-enable device.");
                    var instanceId = devicePathToInstanceId(deviceInstance.DevicePath);
                    if (TryReEnableDevice(instanceId))
                    {
                        try
                        {
                            Device.OpenDevice(DeviceMode.Overlapped, DeviceMode.Overlapped, ShareMode.Exclusive);
                            Console.WriteLine("Opened in exclusive mode.");
                        }
                        catch
                        {
                            Device.OpenDevice(DeviceMode.Overlapped, DeviceMode.Overlapped, ShareMode.ShareRead | ShareMode.ShareWrite);
                            Console.WriteLine("Opened in shared mode.");
                        }
                    }
                    else
                    {
                        Device.OpenDevice(DeviceMode.Overlapped, DeviceMode.Overlapped, ShareMode.ShareRead | ShareMode.ShareWrite);
                        Console.WriteLine("Opened in shared mode.");
                    }
                }

                byte[] Vibration = { 0x20, 0x00, 0x00 };
                if (Device.WriteFeatureData(Vibration) == false)
                {
                    Console.WriteLine("Could not write to gamepad (is it closed?), skipping");
                    Device.CloseDevice();
                    continue;
                }

                byte[] serialNumber;
                byte[] product;
                Device.ReadSerialNumber(out serialNumber);
                Device.ReadProduct(out product);


                gamepads[index - 1] = new Xiaomi_gamepad(Device, scpBus, index);
                ++index;

                if (index >= 5)
                {
                    break;
                }
            }

            Console.WriteLine("{0} controllers connected", index - 1);

            while (true)
            {
                Thread.Sleep(1000);
            }
        }
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            SetupDataFolder();
            if (File.Exists(logFilePath))
            {
                File.WriteAllText(logFilePath, string.Empty);
            }
            else
            {
                CreateLogFile();
            }

            //Check if software already runs, if so kill this instance
            var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull));

            if (otherACCs.Length > 1)
            {
                //DoDebug("ACC is already running, killing this proccess");
                //MessageBox.Show("ACC is already running.", "Already running | " + messageBoxTitle + "");
                //Process.GetCurrentProcess().Kill();

                Process.GetCurrentProcess();

                //Try kill the _other_ process instead
                foreach (Process p in otherACCs)
                {
                    if (p.Id != Process.GetCurrentProcess().Id)
                    {
                        p.Kill();
                        DoDebug("Other ACC instance was running. Killed it.");
                    }
                }
            }

            DoDebug("[ACC begun (v" + softwareVersion + ")]");
            AnalyticsSettings.SetupAnalyticsAsync();

            if (Properties.Settings.Default.CheckForUpdates)
            {
                if (HasInternet())
                {
                    new Thread(() => {
                        new ACC_Updater().Check();
                    }).Start();
                }
                else
                {
                    DoDebug("Couldn't check for new update as PC does not have access to the internet");
                }
            }

            //"updated.txt" not created. Use registry instead (for 1.1.0)

            /*if (File.Exists(Path.Combine(dataFolderLocation, "updated.txt"))) {
             *  File.Delete(Path.Combine(dataFolderLocation, "updated.txt"));
             *  new AboutVersion().Show();
             * }*/

            //On console close: hide NotifyIcon
            Application.ApplicationExit += new EventHandler(OnApplicationExit);
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            //Check if software starts with Windows
            if (!Properties.Settings.Default.StartWithWindows)
            {
                sysIcon.AddOpenOnStartupMenu();
            }

            //Create shortcut folder if doesn't exist
            if (!Directory.Exists(shortcutLocation))
            {
                Directory.CreateDirectory(shortcutLocation);
            }
            if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt")))
            {
                //Create example-file
                using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
                    sw.WriteLine("This is an example file.");
                    sw.WriteLine("If you haven't already, make your assistant open this file!");
                }
            }

            //Delete all old action files
            if (Directory.Exists(CheckPath()))
            {
                foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension))
                {
                    ClearFile(file);
                }
            }

            //SetupListener();
            watcher = new FileSystemWatcher()
            {
                Path         = CheckPath(),
                NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                               | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                Filter = "*." + Properties.Settings.Default.ActionFileExtension,
                EnableRaisingEvents = true
            };
            watcher.Changed += new FileSystemEventHandler(ActionChecker.FileFound);
            watcher.Created += new FileSystemEventHandler(ActionChecker.FileFound);

            DoDebug("\n[" + messageBoxTitle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions");

            Application.EnableVisualStyles();
            sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon;

            RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);

            if (Registry.GetValue(key.Name + "\\AssistantComputerControl", "FirstTime", null) == null)
            {
                key.CreateSubKey("AssistantComputerControl");
                key = key.OpenSubKey("AssistantComputerControl", true);
                key.SetValue("FirstTime", false);

                Properties.Settings.Default.HasCompletedTutorial = true;
                Properties.Settings.Default.Save();

                ShowGettingStarted();

                DoDebug("Starting setup guide");
            }
            else
            {
                if (!Properties.Settings.Default.HasCompletedTutorial)
                {
                    ShowGettingStarted();
                    DoDebug("Didn't finish setup guide last time, opening again");
                }
            }
            SetRegKey("ActionFolder", CheckPath());
            SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension);

            Application.Run();
        }
Example #31
0
 private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
Example #32
0
        static void Main(string[] args)
        {
            //Check if software already runs, if so kill this instance
            if (Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)).Length > 1)
            {
                DoDebug("ACC is already running, killing this proccess");
                MessageBox.Show("ACC is already running.", "Already running | " + messageBoxTitle + "");
                Process.GetCurrentProcess().Kill();
            }
            SetupDataFolder();
            if (File.Exists(logFilePath))
            {
                File.WriteAllText(logFilePath, string.Empty);
            }

            DoDebug("[ACC begun (v" + softwareVersion + ")]");
            ConfigSetup();

            if (checkForUpdates)
            {
                ACC_Updater updater = new ACC_Updater();
                updater.Check();
            }
            if (File.Exists(Path.Combine(dataFolderLocation, "updated.txt")))
            {
                string installerPath = File.ReadAllText(Path.Combine(dataFolderLocation, "updated.txt"));
                if (installerPath != String.Empty)
                {
                    if (File.Exists(installerPath))
                    {
                        File.Delete(installerPath);
                    }
                }
                File.Delete(Path.Combine(dataFolderLocation, "updated.txt"));
                MessageBox.Show("ACC has been updated to version v" + softwareVersion + "!", "Updated | " + messageBoxTitle, MessageBoxButtons.OK);
            }

            //On console close: hide NotifyIcon
            Application.ApplicationExit += new EventHandler(OnApplicationExit);
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            //If it's the first time:
            if (!File.Exists(Path.Combine(dataFolderLocation, "first_time.txt")))
            {
                if (!File.Exists(@startupFolder + @"\" + @startShortcutName))
                {
                    DialogResult dialogResult = MessageBox.Show("Thanks for using " + messageBoxTitle + "! Do you want this software to automatically open when Windows starts (recommended)? Click \"Yes\"", "Open on startup? | " + messageBoxTitle, MessageBoxButtons.YesNo);
                    if (dialogResult == DialogResult.Yes)
                    {
                        CreateStartupLink();
                        MessageBox.Show("Good choice! ACC is now fully operational, happy computer-controlling!", "Wuu! | " + messageBoxTitle + "");
                    }
                    else if (dialogResult == DialogResult.No)
                    {
                        MessageBox.Show("Alrighty. If you regret and want ACC to open automatically you always right-click on " + messageBoxTitle + " in the tray and click \"Open on startup\"!", "Aww | " + messageBoxTitle + "");
                    }
                }
                CreateFirstTimeFile();
            }

            //Create shortcut folder if doesn't exist
            if (!Directory.Exists(shortcutLocation))
            {
                Directory.CreateDirectory(shortcutLocation);

                //Create example-file
                using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
                    sw.WriteLine("This is an example file.");
                    sw.WriteLine("If you haven't already, make your assistant open this file!");
                }
            }

            //If a startup link is (still) not created, add trayMenu item for it
            if (!File.Exists(Path.Combine(startupFolder, startShortcutName)))
            {
                sysIcon.AddOpenOnStartupMenu();
            }

            foreach (string file in Directory.GetFiles(currentLocation, "*." + actionFileExtension))
            {
                ClearFile(file);
            }

            /* WATCHER */
            FileSystemWatcher watcher   = new FileSystemWatcher();
            string            checkPath = actionFilePath;

            watcher.Path         = (String.IsNullOrEmpty(checkPath) ? currentLocation : (Directory.Exists(checkPath) ? checkPath : currentLocation));
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                   | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.Filter              = "*.txt";
            watcher.Changed            += new FileSystemEventHandler(ActionChecker.FileFound);
            watcher.EnableRaisingEvents = true;
            /* END WATCHER */

            DoDebug("\n[" + messageBoxTitle + "] Initiated. \nCurrent location: " + currentLocation);
            DoDebug("Listening for actions to execute...");

            Application.EnableVisualStyles();
            Application.Run(sysIcon);
        }
Example #33
0
 private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate @delegate, bool add);
Example #34
0
        private static void Init()
        {
            ScpBus scpBus = new ScpBus();

            scpBus.UnplugAll();
            global_scpBus = scpBus;

            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            var compatibleDevices = HidDevices.Enumerate(0x79, 0x181c).ToList();

            Thread.Sleep(400);

            FuzeGamepad[] gamepads = new FuzeGamepad[4];
            int           index    = 1;

            //compatibleDevices.RemoveRange(1, compatibleDevices.Count - 1);
            foreach (var deviceInstance in compatibleDevices)
            {
                //Console.WriteLine(deviceInstance);
                HidDevice Device = deviceInstance;
                try
                {
                    Device.OpenDevice(DeviceMode.Overlapped, DeviceMode.Overlapped, ShareMode.Exclusive);
                }
                catch
                {
                    Log.WriteLine("Could not open gamepad in exclusive mode. Try re-enable device.", Log.LogType.warning);
                    var instanceId = devicePathToInstanceId(deviceInstance.DevicePath);
                    if (TryReEnableDevice(instanceId))
                    {
                        try
                        {
                            Device.OpenDevice(DeviceMode.Overlapped, DeviceMode.Overlapped, ShareMode.Exclusive);
                            Log.WriteLine("Opened in exclusive mode.");
                        }
                        catch
                        {
                            Device.OpenDevice(DeviceMode.Overlapped, DeviceMode.Overlapped, ShareMode.ShareRead | ShareMode.ShareWrite);
                            Log.WriteLine("Opened in shared mode.");
                        }
                    }
                    else
                    {
                        Device.OpenDevice(DeviceMode.Overlapped, DeviceMode.Overlapped, ShareMode.ShareRead | ShareMode.ShareWrite);
                        Log.WriteLine("Opened in shared mode.");
                    }
                }

                //byte[] Vibration = { 0x20, 0x00, 0x00 };
                //if (Device.WriteFeatureData(Vibration) == false)
                //{
                //    Console.WriteLine("Could not write to gamepad (is it closed?), skipping");
                //    Device.CloseDevice();
                //    continue;
                //}

                byte[] serialNumber;
                byte[] product;
                Device.ReadSerialNumber(out serialNumber);
                Device.ReadProduct(out product);


                gamepads[index - 1] = new FuzeGamepad(Device, scpBus, index);
                ++index;

                if (index >= 5)
                {
                    break;
                }
            }

            Log.WriteLine(string.Format("{0} controllers connected", index - 1));

            while (true)
            {
                Thread.Sleep(1000);
            }
        }
Example #35
0
        static int Main(string[] args)
        {
            _color = Console.ForegroundColor;
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);

            string[] filteredArgs = ParseArguments(args);
            if (filteredArgs == null)
            {
                return 2;
            }

            if (filteredArgs.Length < 1)
            {
                WriteUsage();
                return 2;
            }

            string[] excluderegexs = filteredArgs.Skip(1).ToArray();

            string path;
            string pattern;
            ParsePath(filteredArgs[0], out path, out pattern);

            return SearchForMisformattedFiles(path, pattern, excluderegexs);
        }
Example #36
0
        public static void Main(string[] args)
        {
#if !__MonoCS__
            handler = new ConsoleEventDelegate(ConsoleEventCallback);
            SetConsoleCtrlHandler(handler, true);
#else
            // http://stackoverflow.com/questions/6546509/detect-when-console-application-is-closing-killed
            var signums = new[]
            {
                Signum.SIGABRT,
                Signum.SIGINT,
                Signum.SIGKILL,
                Signum.SIGQUIT,
                Signum.SIGTERM,
                Signum.SIGSTOP,
                Signum.SIGTSTP
            };

            var signals = new List <UnixSignal>();
            foreach (var signum in signums)
            {
                try
                {
                    signals.Add(new UnixSignal(signum));
                }
                catch (Exception)
                {
                    // ...
                }
            }
#if !DEBUG
            new Thread(delegate()
            {
                // Wait for a signal to be delivered
                UnixSignal.WaitAny(signals.ToArray(), -1);
                app.Shutdown("UnixSignal");
            }).Start();
#endif
#endif

            if (string.IsNullOrWhiteSpace(Settings.Default.TempPath))
            {
                Settings.Default.TempPath = Settings.Default.GetAppDataPath() + "tmp";
            }
            if (!Settings.Default.TempPath.EndsWith("" + Path.DirectorySeparatorChar, StringComparison.CurrentCulture))
            {
                Settings.Default.TempPath += Path.DirectorySeparatorChar;
            }
            new DirectoryInfo(Settings.Default.TempPath).Create();

            if (string.IsNullOrWhiteSpace(Settings.Default.ReadyPath))
            {
                Settings.Default.ReadyPath = Settings.Default.GetAppDataPath() + "dl";
            }
            if (!Settings.Default.ReadyPath.EndsWith("" + Path.DirectorySeparatorChar, StringComparison.CurrentCulture))
            {
                Settings.Default.ReadyPath += Path.DirectorySeparatorChar;
            }
            new DirectoryInfo(Settings.Default.ReadyPath).Create();

            Settings.Default.Save();

            if (File.Exists(Settings.Default.GetAppDataPath() + "log4net.xml"))
            {
                // load settings from file
                XmlConfigurator.Configure(new FileInfo(Settings.Default.GetAppDataPath() + "log4net.xml"));
            }
            else
            {
                // build our own, who logs only fatals to console
                Logger root = ((Hierarchy)LogManager.GetRepository()).Root;

                var lAppender = new ConsoleAppender
                {
                    Name   = "Console",
                    Layout = new PatternLayout("%date{dd-MM-yyyy HH:mm:ss,fff} %5level [%2thread] %line:%logger.%message%n"),
#if DEBUG
                    Threshold = Level.Info
#else
                    Threshold = Level.Fatal
#endif
                };
                lAppender.ActivateOptions();

                root.AddAppender(lAppender);
                root.Repository.Configured = true;
            }

#if __MonoCS__
            PlatformID id = Environment.OSVersion.Platform;
            // Don't allow running as root on Linux or Mac
            try
            {
                if ((id == PlatformID.Unix || id == PlatformID.MacOSX) && new UnixUserInfo(UnixEnvironment.UserName).UserId == 0)
                {
                    LogManager.GetLogger(typeof(Programm)).Fatal("Sorry, you can't run XG with these permissions. Safety first!");
                    Environment.Exit(-1);
                }
            }
            catch (ArgumentException)
            {
                // arch linux fix
                // https://github.com/lformella/xdcc-grabscher/issues/36
            }
#endif

            app = new App();

            app.AddPlugin(new Plugin.Irc.Plugin());
            if (Settings.Default.UseJabberClient)
            {
                app.AddPlugin(new Plugin.Jabber.Plugin());
            }
            if (Settings.Default.UseElasticSearch)
            {
                app.AddPlugin(new Plugin.ElasticSearch.Plugin());
            }
            if (Settings.Default.UseWebserver)
            {
                var webServer = new Plugin.Webserver.Plugin {
                    RrdDB = app.RrdDb
                };
                webServer.OnShutdown += delegate { app.Shutdown(webServer); };
                app.AddPlugin(webServer);
            }

            app.OnShutdownComplete += delegate { Environment.Exit(0); };
            app.Start(typeof(App).ToString());
        }
    }
 public static void SetConsoleEventHandler(ConsoleEventDelegate handler)
 {
     _handler = handler;
     SetConsoleCtrlHandler(_handler, true);
 }
Example #38
0
 public void Setup()
 {
     // Console event (Used for detecting user closing it)
     handler = new ConsoleEventDelegate(ConsoleEventCallback);
     SetConsoleCtrlHandler(handler, true);
 }
Example #39
0
 public static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate handler, bool add);
Example #40
0
 static ConsoleMonitor()
 {
     handler = new ConsoleEventDelegate(ConsoleEventCallback);
     SetConsoleCtrlHandler(handler, true);
 }
Example #41
0
 public static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
Example #42
0
 static void Main(string[] args)
 {
     exitHandler = new ConsoleEventDelegate(ConsoleEventCallback);
     SetConsoleCtrlHandler(exitHandler, true);
     new Program().Start().GetAwaiter().GetResult();
 }