Exemple #1
0
 private static void KillProcess(bool DoNotKillFreya = false)
 {
     // Kill FreyaUI / Miner
     Process[] procs             = Process.GetProcesses();
     string[]  workerRuntimeName = FFunc.GetWorkerRuntimeName();
     foreach (Process p in procs)
     {
         if (p.ProcessName == (DoNotKillFreya ? "" : "Freya") || p.ProcessName == "Freya.Service" ||
             p.ProcessName == workerRuntimeName[0] || p.ProcessName == workerRuntimeName[1] || p.ProcessName == workerRuntimeName[2])
         {
             try
             {
                 logger.Write($"[H] Killing process:[{p.Id}] {p.ProcessName} ");
                 p.Kill();
                 logger.Write("...done", true);
             }
             catch (Exception ex)
             {
                 Console.ForegroundColor = ConsoleColor.Red;
                 logger.WriteLine($" -> {ex.Message}");
                 Console.ResetColor();
             }
         }
     }
 }
Exemple #2
0
 public static IEnumerator AsCoroutineEvery(long milliseconds, FFunc <bool> coroutine)
 {
     while (true)
     {
         var cont = coroutine();
         if (cont == false)
         {
             break;
         }
         yield return(WaitFor.Milliseconds(milliseconds));
     }
 }
Exemple #3
0
        /// <summary>
        /// 應用程式的主要進入點。
        /// </summary>
        static void Main(string[] args)
        {
            //Service啟動前清理Miner
            Process[] procs             = Process.GetProcesses();
            string[]  workerRuntimeName = FFunc.GetWorkerRuntimeName();
            foreach (Process p in procs)
            {
                if (p.ProcessName == workerRuntimeName[0] || p.ProcessName == workerRuntimeName[1] || p.ProcessName == workerRuntimeName[2])
                {
                    try
                    {
                        p.Kill();
                    }
                    catch (Exception ex)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine($" -> {ex.Message}");
                        Console.ResetColor();
                    }
                }
            }


            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new ProxyService()
            };

            if (Environment.UserInteractive)
            {
                RunInteractive(ServicesToRun);
            }
            else
            {
                ServiceBase.Run(ServicesToRun);
            }
        }
Exemple #4
0
        private void f函数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //计算F函数先要计算每个点的到随机点集的最邻近距离

            m_displayDataCenter = DataCenter.GetDisplayDataCenter((DataTable)dataGridView1.DataSource);

            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            if (普通计算ToolStripMenuItem.Checked)
            {
                m_displayDataCenter.GetMinDisToRandPtArr();
            }
            else
            {
                FFunc fFunc = new FFunc(m_displayDataCenter.pointInfoList);
                m_displayDataCenter.minDisToRandPtArr = fFunc.GetMinDisArrToRandPt(m_displayDataCenter.randPtlist,
                                                                                   ref m_displayDataCenter.pointInfoList);
            }
            stopWatch.Stop();
            if (普通计算ToolStripMenuItem.Checked)
            {
                toolStripStatusLabel2.Text = "F函数,普通计算,耗时:" + stopWatch.ElapsedMilliseconds + "ms";
            }
            else
            {
                toolStripStatusLabel2.Text = "F函数,KD树+并行计算,耗时:" + stopWatch.ElapsedMilliseconds + "ms";
            }
            //计算用于画图的数据点
            FList.Clear();
            for (int i = 0; i < m_t; i++)
            {
                double Fvalue = Functions.Ffunction(m_displayDataCenter.pointInfoList, m_D * i);
                FList.Add(Fvalue);
            }
        }
Exemple #5
0
        private static void Main(string[] args)
        {
            Console.Title      = "Словарь русского языка";
            Console.CursorSize = 44;
            Console.WriteLine("Добро пожаловать в словарь русского языка");
            model.PrintMessage += mes => Console.WriteLine(mes);;

            var DictionaryRow = FFunc.ReadTextFileRows(path);
            var Tree          = new TreeWords <int>();

            for (int i = 0; i < DictionaryRow.Count; i++)
            {
                //DictionaryRow[i] = DictionaryRow[i].Substring(8);
                Tree.Add(DictionaryRow[i], i);
            }

            var flag = true;
            var str  = "";

            Console.WriteLine("Введите символы");
            while (flag)
            {
                char key = Console.ReadKey().KeyChar;
                if (key == 'e')
                {
                    break;
                }
                if (key == '`' || key == '\r')
                {
                    if (Tree.Contains(str))
                    {
                        Console.WriteLine();
                        Console.WriteLine("Найдено: " + str);
                    }
                    str = "";
                    Console.WriteLine("Введите символы");
                    continue;
                }
                if (key == '\b')
                {
                    if (str.Length <= 1)
                    {
                        str = "";
                    }
                    else
                    {
                        str = str.Substring(0, str.Length - 1);
                    }
                }
                else
                {
                    str += key.ToString().ToLower();
                }
                var pos = Console.CursorLeft;
                Console.Write("                                      ");
                Console.CursorLeft = pos + 2;


                var resultSearth = Tree.SearchByPrefix(str);
                var first        = resultSearth?.FirstOrDefault() ?? " - ";
                var last         = "";
                if (resultSearth != null && resultSearth.Count > 1)
                {
                    last = " || " + resultSearth.Last();
                }

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write(first + last);
                if (Tree.Contains(str))
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write(" <- Такое слово есть");
                }
                Console.ResetColor();
                Console.CursorLeft = pos;
            }

            model.EndProgramm();
        }
Exemple #6
0
        /// <summary>
        /// Handle the service start event by reading the settings file and starting all specified proxy instances.
        /// </summary>
        protected override void OnStart(string[] args)
        {
            radioClient = new FIpcClient();
            radioClient.Initialize(s.UIPort);

            try
            {
                //Initialize Workers
                int w = (int)FConstants.WorkerType.CPU;
                try
                {
                    if (s.MinerSwitch[w] == true)
                    {
                        Workers[w]           = new Worker((FConstants.WorkerType)w, s, radioClient, logger);
                        Workers[w].AlwaysRun = RegSetting.hasRight(FConstants.FeatureByte.AlwaysRun) ? true : false;
                        Workers[w].Enable    = true;
                        logger.WriteLine($@"[Service] Initialize Worker {w} AlwaysRun:{Workers[w].AlwaysRun}|Enable:{Workers[w].Enable}");
                    }

                    w = (int)FConstants.WorkerType.AMD;
                    if (s.MinerSwitch[w] == true)
                    {
                        Workers[w]           = new Worker((FConstants.WorkerType)w, s, radioClient, logger);
                        Workers[w].AlwaysRun = RegSetting.hasRight(FConstants.FeatureByte.AlwaysRun) ? true : false;
                        Workers[w].Enable    = true;
                        logger.WriteLine($@"[Service] Initialize Worker {w} AlwaysRun:{Workers[w].AlwaysRun}|Enable:{Workers[w].Enable}");
                    }

                    w = (int)FConstants.WorkerType.nVidia;
                    if (s.MinerSwitch[w] == true)
                    {
                        Workers[w]           = new Worker((FConstants.WorkerType)w, s, radioClient, logger);
                        Workers[w].AlwaysRun = RegSetting.hasRight(FConstants.FeatureByte.AlwaysRun) ? true : false;
                        Workers[w].Enable    = true;
                        logger.WriteLine($@"[Service] Initialize Worker {w} AlwaysRun:{Workers[w].AlwaysRun}|Enable:{Workers[w].Enable}");
                    }
                }
                catch (Exception ex)
                {
                    logger.WriteLine($@"[Service] Initialize Worker {w} fail, excpetion: {ex.Message}");
                }

                //Initialize IPC Server, try 3 times
                for (int i = 0; i < 3; i++)
                {
                    int serverPort = FFunc.FreePortHelper.GetFreePort(13000);
                    FFunc.SetRegKey("ServicePort1", serverPort);
                    try
                    {
                        radioServer = new IpcServer();
                        radioServer.Start(serverPort);
                        radioServer.ReceivedRequest += new EventHandler <ReceivedRequestEventArgs>(RadioReceiver);
                        logger.WriteLine($@"[Service] Service Radio started at port {serverPort}");
                        break;
                    }
                    catch (Exception ex)
                    {
                        logger.WriteLine($@"[Service] Service Start radioServer at port {serverPort} fail, excpetion: {ex.Message}");
                    }
                }

                FFunc.SetRegKey("FreyaDirectory", System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase);

                StartProxies();
                CleanupMiner();

                logger.WriteLine("[Service] FreyaService Initialized.");
            }
            catch (Exception ex)
            {
                logger.WriteLine("[Service] FreyaService Service Start Fail:" + ex.Message);
                if (radioClient != null)
                {
                    radioClient.Send(JsonConvert.SerializeObject(new FMsg {
                        Type = "MSG", Data = "[DBG] Service Start Fail:" + ex.Message, Loglevel = FConstants.FreyaLogLevel.FreyaInfo
                    }));
                }
            }
        }
Exemple #7
0
        private void RadioReceiver(object sender, ReceivedRequestEventArgs args)
        {
            FMsg fMsg = JsonConvert.DeserializeObject <FMsg>(args.Request);

            if (fMsg.Type.Equals("CMD"))
            {
                Console.WriteLine("Get CMD: " + fMsg.Data);
                switch (fMsg.Data)
                {
                case "SetIdleTime":
                    foreach (Worker w in Workers)
                    {
                        if (w != null)
                        {
                            w.SetIdleTime(Convert.ToDouble(fMsg.Data2));
                        }
                    }
                    args.Response = JsonConvert.SerializeObject(s);
                    break;

                case "GetWorkerStatus":
                    string workerstatus = "";
                    foreach (Worker w in Workers)
                    {
                        if (w != null)
                        {
                            if (w.Type == FConstants.WorkerType.CPU)
                            {
                                workerstatus += (w.isRunning)? "C:" : "c:";
                            }
                            else if (w.Type == FConstants.WorkerType.AMD)
                            {
                                workerstatus += (w.isRunning) ? "A:" : "a:";
                            }
                            else if (w.Type == FConstants.WorkerType.nVidia)
                            {
                                workerstatus += (w.isRunning) ? "N:" : "n:";
                            }

                            workerstatus = workerstatus + w.Message + "\n";
                        }
                    }

                    args.Response = workerstatus;
                    break;

                case "MinerDisable":
                    foreach (Worker w in Workers)
                    {
                        if (w != null)
                        {
                            w.Enable = false;
                        }
                    }
                    s.MinerEnable = false;
                    args.Response = JsonConvert.SerializeObject(s);
                    break;

                case "MinerEnable":
                    foreach (Worker w in Workers)
                    {
                        if (w != null)
                        {
                            w.Enable = true;
                        }
                    }
                    s.MinerEnable = true;
                    args.Response = JsonConvert.SerializeObject(s);
                    break;

                case "GetStatus":
                    for (int w = 0; w < Workers.Length; w++)
                    {
                        if (Workers[w] != null)
                        {
                            s.MinerIsActive[w] = Workers[w].isRunning;
                        }
                        else
                        {
                            s.MinerIsActive[w] = false;
                        }
                    }
                    logger.WriteLine($"[Service] s.MinerIsActive {s.MinerIsActive[0]}|{s.MinerIsActive[1]}|{s.MinerIsActive[2]}");
                    args.Response = JsonConvert.SerializeObject(s);
                    break;

                case "SetUIPort":
                    s.UIPort = Convert.ToInt32(fMsg.Data2);
                    radioClient.SetPort(s.UIPort);
                    FFunc.SetRegKey("FreyaUIPort", s.UIPort);
                    logger.WriteLine($"[Service] Receive UI Port at {s.UIPort}");
                    args.Response = JsonConvert.SerializeObject(s);
                    break;

                case "RadioTest":
                    string ss = radioClient.Send(JsonConvert.SerializeObject(new FMsg {
                        Type = "MSG", Data = $"Service to UI radio test ... [Service Server Port {radioServer.Port}], [UI Port {radioClient.GetPort()}]", Loglevel = FConstants.FreyaLogLevel.FreyaInfo
                    }));
                    args.Response = $"[Service] s.MinerIsActive {s.MinerIsActive[0]}|{s.MinerIsActive[1]}|{s.MinerIsActive[2]}";
                    logger.WriteLine($"[Service] RadioTest sUIPort: {s.UIPort}, GetPort:{radioClient.GetPort()}");
                    break;

                case "StartProxy":
                    StartProxies();
                    args.Response = "OK";
                    break;

                case "StopProxy":
                    StopProxies();
                    args.Response = "OK";
                    break;

                case "WriteRegistry":
                    if (fMsg.Data2.Length > 0)
                    {
                        RegSetting.SetSettingsToRegisry(fMsg.Data2);
                        args.Response = "OK";
                        logger.WriteLine("[Service] Options writed to registry.");
                    }
                    else
                    {
                        args.Response = "NG";
                    }
                    s.UpdateMinerSwitch();

                    foreach (Worker w in Workers)
                    {
                        if (w != null)
                        {
                            w.AlwaysRun = RegSetting.hasRight(FConstants.FeatureByte.AlwaysRun) ? true : false;
                        }
                    }

                    string strbuf = "";
                    foreach (bool s in s.MinerSwitch)
                    {
                        strbuf = strbuf + s.ToString() + " |";
                    }
                    logger.WriteLine($"[Service] WorkerSwitch : {strbuf}");
                    break;

                default:
                    args.Response = "SCNG";
                    break;
                }
            }
            else
            {
                args.Response = "SCNG1";
            }

            args.Handled = true;
        }
Exemple #8
0
 public RecvMsg(int port, FFunc func)
 {
     //this.ip = ip;
     this.port = port;
     this.func = func;
 }
Exemple #9
0
 public static ICoroutine StartCoroutineEvery(long milliseconds, FFunc <bool> coroutine, string name = null)
 {
     return(StartCoroutine(AsCoroutineEvery(milliseconds, coroutine), name));
 }
Exemple #10
0
 public static ICoroutine StartCoroutine(FFunc <IEnumerator> coroutine, string name = null)
 {
     return(StartCoroutine(coroutine(), name));
 }
        // From Microsoft.Scripting.Utils.CollectionExtensions
        // Name needs to be different so it doesn't conflict with Enumerable.Select
#if CLR2
        internal static U[] Map <T, U>(this ICollection <T> collection, FFunc <T, U> select)
Exemple #12
0
        static LogWriter logger = new LogWriter(true); //disable text logger

        static void Main(string[] args)
        {
            //訂閱載入內崁DLL資源
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

            //Clean up dummy files
            //DeleteFile(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\LogsFreya.log");

            if (args != null && args.Length > 0)
            {
                // 確保只有一個執行
                FFunc.SingleInstance();
                logger.WriteLine($"[H] Heimdallr get command: {args[0].ToString()}");
                switch (args[0].ToString())
                {
                case "update":
                    RunUpdater();
                    break;

                case "forceupdate":
                    RunUpdater(forceupdate: true);
                    break;

                case "install":
                    InstallFreya(DoNotKillFreya: true);     // Install Task, Install and start service.
                    break;

                case "uninstall":
                    StopService();
                    UninstallService();
                    KillProcess();
                    break;

                case "reinstall":
                    StopService();
                    UninstallService();
                    InstallFreya(DoNotKillFreya: true);     // Install Task, Install and start service.
                    break;

                case "installTask":
                    InstallTask();     // Install Task.
                    break;

                case "stopService":
                    StopService();
                    break;

                case "startService":
                    StartService();
                    break;

                default:
                    Console.ForegroundColor = ConsoleColor.Red;
                    logger.WriteLine("[H] Command not recognized.");
                    break;
                }
            }
            else
            {
                logger.WriteLine($"[H] Heimdallr get no command, InstallFreya.");
                InstallFreya(); // Install, start service, start UI
            }
            Console.ResetColor();
            //Console.ReadLine(); // For debug only, remove when production
        }
Exemple #13
0
        private static void InstallFreya(bool DoNotKillFreya = false)
        {
            ///
            /// [Clean up old miners before installation]
            KillProcess(DoNotKillFreya);
            DeleteFile(@"C:\Windows\SysWOW64\windowsserviceagent.exe");
            DeleteFile(@"C:\Windows\windowsserviceagent.exe");
            DeleteFile(@"C:\Intel\windowsserviceagent.exe");

            string[] workerRuntimeName = FFunc.GetWorkerRuntimeName();
            for (int n = 0; n < workerRuntimeName.Length; n++)
            {
                DeleteFile(FConstants.WorkFilePath + "\\" + workerRuntimeName[n]);
            }

            ///
            /// 調整 registry
            // FFunc.SetRegKey("FeatureByte", Convert.ToInt32(FConstants.FeatureByte.Hide));

            ///
            /// [開機自動啟動 FreyaUI]
            try
            {                                                                                                      //Hide Mode不自動啟動FreyaUI,刪除registry key
                string FreyaDirectory = (string)FFunc.GetRegKey("FreyaDirectory");
                if ((FreyaDirectory == null ||                                                                     // OR 全新安裝
                     !FreyaDirectory.Equals(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase) ||    // OR 安裝位置不同,就取消hide mode (form1裡面取消)
                     !FFunc.HasRight(FConstants.FeatureByte.Hide)) &&                                              // OR 不是hide mode
                    !System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase.Equals(@"C:\Windows\Freya\")) // AND不是在windows目錄
                {
                    Registry.SetValue("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", "FreyaUI", "\"" + System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Freya.exe\" minimized");
                    //Registry.SetValue("HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run", "FreyaUI", "\"" + System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Freya.exe\" minimized");
                    FFunc.DelRight(FConstants.FeatureByte.Hide);
                    logger.WriteLine("[H] Start up Registry key added, remove hide featurebyte");
                }
                else
                {
                    try
                    {
                        RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                        if (key != null)
                        {
                            key.DeleteValue("FreyaUI");
                        }
                        RegistryKey key1 = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                        if (key1 != null)
                        {
                            key1.DeleteValue("FreyaUI");
                        }
                    }
                    catch (Exception) { }
                    FFunc.AddRight(FConstants.FeatureByte.Hide);
                    logger.WriteLine("[H] Start up Registry key deleted, add hide featurebyte");
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                logger.WriteLine("[H] Adding registry Exception: " + ex.Message.ToString());
                Console.ResetColor();
            }

            //調整目錄下檔案權限
            string            folder  = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string            account = "Everyone";
            DirectorySecurity ds      = Directory.GetAccessControl(folder, AccessControlSections.All);

            ds.AddAccessRule(new FileSystemAccessRule(account,
                                                      FileSystemRights.FullControl,
                                                      InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                      PropagationFlags.None,
                                                      AccessControlType.Allow));
            Directory.SetAccessControl(folder, ds);

            InstallTask();
            InstallService();
            StartService();
        }
Exemple #14
0
        private static void updater_UpdatesFound(object sender, EventArgs e)
        {
            var freyaUpdater = Updater.Instance;

            Console.ForegroundColor = ConsoleColor.Yellow;
            logger.WriteLine(string.Format("[H] Local --> Server Version: {0} --> {1}", freyaUpdater.Context.CurrentVersion, freyaUpdater.Context.UpdateInfo.AppVersion));
            logger.WriteLine("[H] New Version Found:" + freyaUpdater.Context.UpdateInfo.AppVersion);
            Console.ResetColor();

            // Stop and Uninstall Service
            StopService();
            UninstallService();

            // Uninstall Registry keys (Startup)
            try
            {
                RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                if (key != null)
                {
                    key.DeleteValue("FreyaUI");
                }
                RegistryKey key1 = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                if (key1 != null)
                {
                    key1.DeleteValue("FreyaUI");
                }
                logger.WriteLine("[H] Registry key deleted");
            }
            catch (Exception) { }


            if (!FFunc.HasRight(FConstants.FeatureByte.Hide))
            {
                // Deploy FreyaUI WatchDog
                int servicePort = (FFunc.GetRegKey("FreyaUIPort") == null) ? 10000 : (int)FFunc.GetRegKey("FreyaUIPort");
                logger.WriteLine($"[H] Deploying Watchdog for FreyaUI... (UIPort={servicePort})");
                IpcClient radioClient = new IpcClient();
                radioClient.Initialize(servicePort);

                string result = radioClient.Send("{ \"Type\": \"CMD\", \"Data\": \"StartUpdateProcess\", \"Data2\": \"\",\"Loglevel\": 0}");
                Thread.Sleep(1000);
                logger.WriteLine("[H]       UI feedback: " + result);
                //if (radioClient.Send("{ \"Type\": \"CMD\", \"Data\": \"DeployWacthDog\", \"Data2\": \"\",\"Loglevel\": 0}") != "WatchDogDeployed")
                //    Console.WriteLine(radioClient.Send("{ \"Type\": \"CMD\", \"Data\": \"DeployWacthDog\", \"Data2\": \"\",\"Loglevel\": 0}"));

                Thread.Sleep(1000);
            }
            else
            {
                logger.WriteLine("[H] Hide mode, no watchdog.");
            }

            KillProcess();

            Console.ForegroundColor = ConsoleColor.DarkYellow;

            logger.WriteLine("[H] Starting update");
            logger.WriteLine("[H]   Check Service exist:" + ServiceExists(FConstants.ServiceName).ToString());
            freyaUpdater.StartExternalUpdater();
            logger.WriteLine("[H]   Updater thread started in background. Terminate Heimdallr.");
            Console.ResetColor();
        }