Exemple #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            CustomerInformation objCustomerInformation = new CustomerInformation();
            objCustomerInformation.Action = InvokeOperation.Type.SE;
            objCustomerInformation.CustomerID = Session["UserName"].ToString();

            IList<CustomerInformation> listofCustomerInformation;
            listofCustomerInformation = new ProcessManager(objCustomerInformation).GetList<CustomerInformation>();

            lblFullName.Text = listofCustomerInformation[0].CustomerName.ToString();
            lblSponsorName.Text = listofCustomerInformation[0].SponsorID.ToString();//SponserName
            lblMySponsorID.Text = listofCustomerInformation[0].SponsorID.ToString();
            lblEmailAddress.Text = listofCustomerInformation[0].Email.ToString();
            lblTotalSponsor.Text = listofCustomerInformation[0].SponsorID.ToString();//totalSponser
            lblAgentCode.Text = listofCustomerInformation[0].AgentID.ToString();
            lblBankAccountNo.Text = listofCustomerInformation[0].AgentID.ToString();//Bank Account
            lblCurrentBalance.Text = listofCustomerInformation[0].CurrentBalance.ToString();
            lblTotalWithDraw.Text = listofCustomerInformation[0].CurrentBalance.ToString();//totalwidrow
            lblTotalIncome.Text = listofCustomerInformation[0].CurrentBalance.ToString();//TotalIncome
            lblUnpaidWithdraw.Text = listofCustomerInformation[0].CurrentBalance.ToString();// unpaidwithdraw

            //userNameTextBox.Text = listofSecret[0].CustomerID.ToString();
            //if (listofSecret[0].CustomerID == userNameTextBox.Text.Trim() && listofSecret[0].Password == passwordTextBox.Text.Trim())
            //{

            //}
            //else
            //{
            //    Response.Redirect("~/Home.aspx");

            //}
        }
Exemple #2
0
        /// <summary>
        /// 保存xml文件
        /// </summary>
        /// <param name="package"></param>
        public void SaveProcessFile(package package)
        {
            var xmlDoc = Serialize(package);

            var processGUID = package.process.id;
            var pm = new ProcessManager();
            var entity = pm.GetByGUID(processGUID);

            if (entity != null)
            {
                var serverPath = ConfigHelper.GetAppSettingString("WorkflowFileServer");
                var physicalFileName = string.Format("{0}\\{1}", serverPath, entity.XmlFilePath);

                //判断目录是否存在,否则创建
                var pathName = Path.GetDirectoryName(physicalFileName);
                if (!Directory.Exists(pathName))
                    Directory.CreateDirectory(pathName);

                xmlDoc.Save(physicalFileName);
            }
            else
            {
                throw new ApplicationException(string.Format("无法获取流程定义记录! ProcessGUID: {0}", processGUID));
            }
        }
Exemple #3
0
 static void RunVcRedist() {
     using (var pm = new ProcessManager()) {
         // TODO: This needs to get improved somehow, because we will be killed if we take too long to process etc..
         InstallVcRedist(pm, "vcredist_x86-2012.exe");
         InstallVcRedist(pm, "vcredist_x86.exe");
     }
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            M2MTransferCore m2mTransfer = new M2MTransferCore();

            m2mTransfer.Action = InvokeOperation.Type.SE;
            m2mTransfer.WhereCondition = new System.Text.StringBuilder("1245878");//nee to implement customerid
            IList<M2MTransferCore> payeeList = new ProcessManager(m2mTransfer).GetList<M2MTransferCore>();
        }
Exemple #5
0
        static void PrintProcesses()
        {
            var procsManager = new ProcessManager();

            procsManager.Display();

            Console.WriteLine("Total threads: {0}",procsManager.TotalThreads);
        }
Exemple #6
0
 public static void Main(string[] args)
 {
     Console.Clear();
     Console.WriteLine ("Welcome to LittleTalk v0.1a");
     var pm = new ProcessManager();
     pm.Processes.Add(new Process(pm));
     pm.Start();
 }
Exemple #7
0
        private static void TestKillNotepad()
        {
            Console.Write("Press enter to kill Notepad");
            Console.ReadLine();

            var newProcs = new ProcessManager();
            newProcs.KillProcess(p => p.ProcessName.Equals("notepad"));
        }
 public static ProcessManager getInstance()
 {
     if (_instance == null)
     {
         _instance = new ProcessManager();
     }
     return _instance;
 }
Exemple #9
0
 public void AddBlocked()
 {
     var manager = new ProcessManager();
     //manager.TryAddBlocked("notepad++.exe");
     manager.BlockedApps.Add("notepad++.exe");
     List<string> expected = new List<string>();
     expected.Add("notepad++.exe");
     return;
 }
        public void CanGetTestCmdRunOutput()
        {
            ProcessManager pm = new ProcessManager("Resources\\test")
            {
                Arguments = "these are not the droids you are looking for",
            }.Run();

            Assert.Equal(String.Empty, pm.StandardError);
            Assert.Equal("test arguments: these are not the droids you are looking for\r\n", pm.StandardOutput);
        }
        /// <summary>
        /// Creates a new instance of the ProcessManager
        /// </summary>
        public ProcessManager()
        {

            InitializeComponent();
            // When someone creates a process manager it automatically assumes that it should be the default.
            // If this is not the case, then DefaultProcessManager should be set at a different time.
            DefaultProcessManager = this;

            // By default, this gets set to the default log manager
            _logManager = LogManager.DefaultLogManager;
        }
 protected void btnSend_Click(object sender, EventArgs e)
 {
     M2MTransferCore m2mTransfer = new M2MTransferCore();
     m2mTransfer.Action = InvokeOperation.Type.IN;
     m2mTransfer.ToCustomerID = txtRecivingID.Text;
     m2mTransfer.FromCustomerID = Session[""].ToString();
     m2mTransfer.TransferAmount =Convert.ToDecimal(txtTransferAmount.Text);
     m2mTransfer.TransferID =4343434;
     m2mTransfer.TransferDate = DateTime.Today;
     m2mTransfer.Descriptions = "";
     ProcessManager pM = new ProcessManager(m2mTransfer);
 }
        public void CanGetTestCmdStartOutput()
        {
            ProcessManager pm = new ProcessManager("Resources\\test")
            {
                Arguments = "may the force be with you",
            }.Start();

            Assert.Equal("cmd.exe", pm.Executable);
            Assert.True(pm.Process.WaitForExit(10 * 1000));
            Assert.Equal(String.Empty, pm.StandardError);
            Assert.Equal("test arguments: may the force be with you\r\n", pm.StandardOutput);
        }
        public MainWindow()
        {
            InitializeComponent();
            Manager = new ProcessManager();
            Manager.RefreshProcessList();

            TimePickerBox.Value = DateTime.Now;
            ScheduledBox.ItemsSource = Manager.ScheduledList;
            ProcessBox.ItemsSource = Manager.ProcessList;

            CollectionView processView = (CollectionView)CollectionViewSource.GetDefaultView(ProcessBox.ItemsSource);
            CollectionView scheduledView = (CollectionView)CollectionViewSource.GetDefaultView(ScheduledBox.ItemsSource);
            processView.Filter = ProcessFilter;

            Manager.ScheduledView = scheduledView;
            Manager.ProcessView = processView;
        }
Exemple #15
0
 //[TestMethod]
 public void RemoveBlocked()
 {
     var manager = new ProcessManager();
     List<string> blocked = new List<string>()
         {
             "notepad++.exe", "minecraft.exe", "leagueoflegends.exe"
         };
     foreach (var app in blocked)
     {
         manager.BlockedApps.Add(app);
     }
     List<string> expected = new List<string>()
         {
            "notepad++.exe", "minecraft.exe"
         };
     manager.RemoveBlocked("leagueoflegends.exe");
     Assert.AreSame(expected, manager.BlockedApps);
 }
        public void CanDetectRepositoryChanged()
        {
            var repo = CreateProxiedTestGitManager();
            repo.Update();

            using (var file = File.CreateText(Path.Combine(GitRepositoryFixture.LocalTestProxyRepository, "added.txt")))
            {
                file.WriteLine("This is added.txt");
            }

            var addCmd = new ProcessManager("git", "add added.txt", GitRepositoryFixture.LocalTestProxyRepository).Run();
            Assert.Equal(0, addCmd.ExitCode);
            var commitCmd = new ProcessManager("git", "commit -m added.txt", GitRepositoryFixture.LocalTestProxyRepository).Run();
            Assert.Equal(0, commitCmd.ExitCode);

            Assert.Equal(RepositoryStatus.OutOfDate, repo.Check());
            Assert.Equal(RepositoryStatus.OutOfDate, repo.Check()); // ensure the check doesn't make the repo up to date.
        }
Exemple #17
0
        static void TestZipLong()
        {
            var procsManager = new ProcessManager();
            var interfaceManger = new InterfaceManager("mscorlib");

            var zipLongRresult = procsManager.ZipLong(interfaceManger, (p, i) =>
            {
                if (p.IsDefault())
                    return string.Format("Interface: {0}", i.Name);

                return i.IsDefault() 
                    ? string.Format("Process: {0}", p.ProcessName) 
                    : string.Format("Interface: {0}. Process: {1}",i.Name, p.ProcessName);
            });

            foreach (var zip in zipLongRresult)
            {
                Console.WriteLine(zip);
            }
        }
Exemple #18
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            CustomerSecret secret = new CustomerSecret();
            secret.Action = InvokeOperation.Type.SE;
            secret.CustomerID = userNameTextBox.Text.Trim();
            secret.Password = passwordTextBox.Text.Trim();
            IList<CustomerSecret> listofSecret;
            listofSecret = new ProcessManager(secret).GetList<CustomerSecret>();
            if (listofSecret[0].CustomerID == userNameTextBox.Text.Trim() && listofSecret[0].Password == passwordTextBox.Text.Trim())
            {
                Session["UserName"] = userNameTextBox.Text.Trim();
                Session["Password"] = passwordTextBox.Text.Trim();
                Response.Redirect("~/Default.aspx");
            }
            else
            {
                Response.Redirect("~/Home.aspx");

            }
        }
Exemple #19
0
        static void Main(string[] args)
        {
            Console.WriteLine("Нажмите любую клавишу для выхода\n\n");

            //ProcessManager<ListPriorityQueue<Process>, Process> pm =
            //    new ProcessManager<ListPriorityQueue<Process>, Process>();

            ProcessManager<HeapPriorityQueue<Process>, Process> pm =
                new ProcessManager<HeapPriorityQueue<Process>, Process>();

            pm.Add(new Process(1));
            pm.Add(new Process(2));
            pm.Add(new Process(3));
            pm.Add(new Process(4));

            pm.Run();

            Console.ReadKey();
            Console.WriteLine(Environment.NewLine);
        }
Exemple #20
0
        static void SetupWebServer() {
            // TODO: Try multiple ports?
            const int maxTries = 10;
            const int timeOut = 1500;
            var tries = 0;

            var sslPort = Consts.SrvPort;
            var httpPort = Consts.SrvHttpPort;

            using (var pm = new ProcessManager()) {
                var si = new ServerInfo(pm);
                if (!si.SslRegistered())
                    sslPort = 0;
                if (!si.isHttpRegistered)
                    httpPort = 0;
            }

            retry:
            try {
                _webServer = Startup.Start(Consts.SrvAddress, sslPort, httpPort);
            } catch (TargetInvocationException ex) {
                var unwrapped = ex.UnwrapExceptionIfNeeded();
                if (!(unwrapped is HttpListenerException))
                    throw;

                if (tries++ >= maxTries)
                    throw GetCustomException(unwrapped, Consts.SrvPort);
                MainLog.Logger.Write(unwrapped.Format(), LogLevel.Warn);
                Thread.Sleep(timeOut);
                goto retry;
            } catch (HttpListenerException ex) {
                if (tries++ >= maxTries)
                    throw GetCustomException(ex, Consts.SrvPort);
                MainLog.Logger.Write(ex.Format(), LogLevel.Warn);
                Thread.Sleep(timeOut);
                goto retry;
            }
        }
 public ProcessServices()
 {
     _processManager = new ProcessManager();
 }
Exemple #22
0
 private static void FastTravelScreen_ctor(On.Menu.FastTravelScreen.orig_ctor orig, Menu.FastTravelScreen self, ProcessManager manager, ProcessManager.ProcessID ID)
 {
     if (PlayerManager.GetCustomPlayer(self.PlayerCharacter) != null)
     {
         checkFastTravelForCustom = true;
     }
     try
     {
         orig(self, manager, ID);
     }
     finally
     {
         checkFastTravelForCustom = false;
     }
 }
 public ChangeToChasingEnemyDirector(Engine engine, ContentManager content, ProcessManager processManager) : base(engine, content, processManager)
 {
 }
Exemple #24
0
        public VellumHost(string[] args)
        {
            Thread _ioThread;
            bool   _readInput = true;

            bool   printHelp       = false;
            bool   noStart         = false;
            string restorePath     = null;
            bool   backupOnStartup = true;

            OptionSet options = new OptionSet()
            {
                { "h|help", "Displays a help screen.", v => { printHelp = v != null; } },
                { "c=|configuration=", "The configuration file to load settings from.", v => { if (!String.IsNullOrWhiteSpace(v))
                                                                                               {
                                                                                                   _configPath = v.Trim();
                                                                                               }
                  } },
                { "p=|plugin-directory=", "The directory to scan for plugins.", v => { if (!String.IsNullOrWhiteSpace(v))
                                                                                       {
                                                                                           _pluginDirectory = v;
                                                                                       }
                  } },
                { "r=|restore=", "Path to an archive to restore a backup from.", v => { if (!String.IsNullOrWhiteSpace(v))
                                                                                        {
                                                                                            restorePath = Path.GetFullPath(v);
                                                                                        }
                  } },
                { "no-start", "In conjunction with the --restore flag, this tells the application to not start the server after successfully restoring a backup.", v => { noStart = v != null; } },
                { "no-backup-on-startup", "Disables the initial temporary backup on startup.", v => { backupOnStartup = v == null; } }
            };

            System.Collections.Generic.List <string> extraOptions = options.Parse(args);

            if (printHelp)
            {
                System.Console.WriteLine("Overview of available parameters:");
                options.WriteOptionDescriptions(Console.Out);
                System.Environment.Exit(0);
            }

            Version bdsVersion = new Version();

            if (File.Exists(_configPath))
            {
                // Load configuration
                RunConfig = LoadConfiguration(_configPath);

                string bdsDirPath = Path.GetDirectoryName(RunConfig.BdsBinPath);
                string worldName  = "Bedrock level";

                Console.Write($"Reading \"{_serverPropertiesPath}\"... ");

                using (StreamReader reader = new StreamReader(File.OpenRead(Path.Join(bdsDirPath, _serverPropertiesPath))))
                    worldName = Regex.Match(reader.ReadToEnd(), @"^level\-name\=(.+)", RegexOptions.Multiline).Groups[1].Value.Trim();

                string worldPath     = Path.Join(bdsDirPath, "worlds", worldName);
                string tempWorldPath = Path.Join(Directory.GetCurrentDirectory(), TempPath, worldName);

                Console.WriteLine("Done!");

                if (!String.IsNullOrWhiteSpace(restorePath))
                {
                    Console.WriteLine("\n\"--restore\" flag provided, attempting to restore backup from specified archive...");
                    BackupManager.Restore(restorePath, worldPath);
                    Console.WriteLine();

                    if (noStart)
                    {
                        Console.WriteLine("\"--no-start\" flag provided, exiting...");
                        System.Environment.Exit(0);
                    }
                }


                #region CONDITIONAL UPDATE CHECK
                if (RunConfig.CheckForUpdates)
                {
                    Console.WriteLine("Checking for updates...");

                    if (_updateChecker.GetLatestVersion())
                    {
                        if (_updateChecker.RemoteVersion > _localVersion)
                        {
                            Console.WriteLine("\nA new update is available!\nLocal version:\t{0}\nRemote version:\t{1}\nVisit {2} to update.\n", UpdateChecker.ParseVersion(_localVersion, VersionFormatting.MAJOR_MINOR_REVISION), UpdateChecker.ParseVersion(_updateChecker.RemoteVersion, VersionFormatting.MAJOR_MINOR_REVISION), @"https://git.io/vellum-latest");
                        }
                    }
                    else
                    {
                        System.Console.WriteLine("Could not check for updates.");
                    }
                }
                #endregion

                if (RunConfig.Renders.EnableRenders && String.IsNullOrWhiteSpace(RunConfig.Renders.PapyrusBinPath))
                {
                    Console.WriteLine("Disabling renders because no valid path to a Papyrus executable has been specified");
                    RunConfig.Renders.EnableRenders = false;
                }


                #region BDS process and input thread
                ProcessStartInfo serverStartInfo = new ProcessStartInfo()
                {
                    FileName         = RunConfig.BdsBinPath,
                    WorkingDirectory = bdsDirPath
                };

                // Set environment variable for linux-based systems
                if (System.Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    serverStartInfo.EnvironmentVariables.Add("LD_LIBRARY_PATH", bdsDirPath);
                }

                ProcessManager bds = new ProcessManager(serverStartInfo, new string[] {
                    "^(" + worldName.Trim() + @"(?>\/db)?\/)",
                    "^(Saving...)",
                    "^(A previous save has not been completed.)",
                    "^(Data saved. Files are now ready to be copied.)",
                    "^(Changes to the level are resumed.)",
                    "Running AutoCompaction..."
                });

                if (RunConfig.BdsWatchdog)
                {
                    _bdsWatchdog = new Watchdog(bds);

                    _bdsWatchdog.RegisterHook((byte)Watchdog.Hook.LIMIT_REACHED, (object sender, EventArgs e) =>
                    {
                        SaveConfiguration(RunConfig, _configPath);
                        System.Environment.Exit(1);
                    });
                }

                // Stop BDS gracefully on unhandled exceptions
                if (RunConfig.StopBdsOnException)
                {
                    System.AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) =>
                    {
                        Console.WriteLine($"Stopping BDS due to an unhandled exception from vellum...\n{e.ExceptionObject.ToString()}");

                        if (bds.IsRunning)
                        {
                            bds.SendInput("stop");
                            bds.Process.WaitForExit();
                            bds.Close();
                        }
                    };
                }

                // Input thread
                _ioThread = new Thread(() =>
                {
                    while (_readInput)
                    {
                        inStream?.Invoke(Console.ReadLine());
                    }
                });
                _ioThread.Start();

                // Store current BDS version
                bds.RegisterMatchHandler(CommonRegex.Version, (object sender, MatchedEventArgs e) =>
                {
                    bdsVersion = UpdateChecker.ParseVersion(e.Matches[0].Groups[1].Value, VersionFormatting.MAJOR_MINOR_REVISION_BUILD);
                });

                playerCount = 0;

                bool nextBackup = true;
                if (RunConfig.Backups.OnActivityOnly)
                {
                    nextBackup = false;

                    // Player connect/ disconnect messages
                    bds.RegisterMatchHandler(CommonRegex.PlayerConnected, (object sender, MatchedEventArgs e) =>
                    {
                        playerCount++;
                        nextBackup = true;
                    });

                    bds.RegisterMatchHandler(CommonRegex.PlayerDisconnected, (object sender, MatchedEventArgs e) =>
                    {
                        playerCount--;
                    });
                }
                #endregion

                _renderManager = new RenderManager(bds, RunConfig);
                _backupManager = new BackupManager(bds, RunConfig);

                #region PLUGIN LOADING
                if (Directory.Exists(_pluginDirectory))
                {
                    SetPluginDirectory(_pluginDirectory);

                    #region INTERNAL PLUGINS
                    AddPlugin(bds);
                    AddPlugin(_backupManager);
                    AddPlugin(_renderManager);

                    if (RunConfig.BdsWatchdog)
                    {
                        AddPlugin(_bdsWatchdog);
                    }
                    #endregion

                    if (LoadPlugins() > 0)
                    {
                        foreach (IPlugin plugin in GetPlugins())
                        {
                            if (plugin.PluginType == PluginType.EXTERNAL)
                            {
                                Console.WriteLine($"Loaded plugin: {plugin.GetType().Name} v{UpdateChecker.ParseVersion(System.Reflection.Assembly.GetAssembly(plugin.GetType()).GetName().Version, VersionFormatting.MAJOR_MINOR_REVISION)}");
                            }
                        }

                        Console.WriteLine();
                    }
                }
                else
                {
                    Directory.CreateDirectory(_pluginDirectory);
                }
                #endregion

                // Scheduled/ interval backups
                if (RunConfig.Backups.EnableBackups)
                {
                    double interval = RunConfig.Backups.BackupInterval * 60000;

                    if (RunConfig.Backups.EnableSchedule)
                    {
                        if (RunConfig.Backups.Schedule.Length == 0)
                        {
                            Console.WriteLine("Scheduled backups are enabled but there are no entries in the schedule, switching to interval backups!");
                        }
                        else
                        {
                            interval = 1;
                        }
                    }

                    System.Timers.Timer backupIntervalTimer = new System.Timers.Timer(interval);
                    backupIntervalTimer.AutoReset = true;
                    backupIntervalTimer.Elapsed  += (object sender, ElapsedEventArgs e) =>
                    {
                        if (backupIntervalTimer.Interval != 1) // This prevents performing a backup if scheduled backups are enabled and the next real time-span hasn't been determined yet
                        {
                            if (nextBackup)
                            {
                                if (RunConfig.Backups.OnActivityOnly && playerCount == 0)
                                {
                                    nextBackup = false;
                                }

                                InvokeBackup(worldPath, tempWorldPath);
                            }
                            else
                            {
                                Console.WriteLine("Skipping this backup because no players were online since the last one was taken...");
                            }
                        }
                    };

                    if (RunConfig.Backups.EnableSchedule && RunConfig.Backups.Schedule.Length > 0)
                    {
                        backupIntervalTimer.Elapsed += (object sender, ElapsedEventArgs e) =>
                        {
                            // Check which entry is up next
                            TimeSpan nextSpan = TimeSpan.MaxValue;

                            foreach (string clockTime in RunConfig.Backups.Schedule)
                            {
                                // Parse & validate entry
                                // Match match = Regex.Match(clockTime, @"^\s*(\d{1,2})\s*:\s*(\d{1,2})\s*([aApP][mM])");   // 12h format
                                Match match = Regex.Match(clockTime, @"^\s*(\d{1,2})\s*:\s*(\d{1,2})\s*$");                 // 24h format

                                bool valid = false;
                                int  hour, minute;

                                if (match.Groups.Count == 3)
                                {
                                    hour   = Convert.ToInt32(match.Groups[1].Value);
                                    minute = Convert.ToInt32(match.Groups[2].Value);

                                    if ((hour >= 0 && hour <= 23) && (minute >= 0 && minute <= 59))
                                    {
                                        valid = true;

                                        TimeSpan span = new TimeSpan((hour == 0 ? 24 : hour) - DateTime.Now.Hour, minute - DateTime.Now.Minute, 0 - DateTime.Now.Second);

                                        if (span.TotalSeconds > 0 && span < nextSpan)
                                        {
                                            nextSpan = span;
                                        }
                                    }
                                }

                                if (!valid)
                                {
                                    Console.WriteLine($"Invalid schedule entry \"{clockTime}\" in \"{_configPath}\"!");
                                }
                            }

                            // Set the new interval
                            Console.WriteLine($"Next scheduled backup is at {(DateTime.Now + nextSpan).ToShortTimeString()} (in {nextSpan.Days} days, {nextSpan.Hours} hours, {nextSpan.Minutes} minutes and {nextSpan.Seconds} seconds)");
                            backupIntervalTimer.Interval = nextSpan.TotalMilliseconds;
                            CallHook((byte)Hook.BACKUP_SCHEDULED, new HookEventArgs()
                            {
                                Attachment = nextSpan
                            });
                        };
                    }

                    backupIntervalTimer.Start();

                    bds.RegisterMatchHandler("Starting Server", (object sender, MatchedEventArgs e) =>
                    {
                        // bds.RegisterMatchHandler(CommonRegex.ServerStarted, (object sender, MatchedEventArgs e) => {
                        if (RunConfig.Backups.StopBeforeBackup)
                        {
                            System.Timers.Timer backupNotificationTimer = new System.Timers.Timer((RunConfig.Backups.BackupInterval * 60000) - Math.Clamp(RunConfig.Backups.NotifyBeforeStop * 1000, 0, RunConfig.Backups.BackupInterval * 60000));
                            backupNotificationTimer.AutoReset           = false;
                            backupNotificationTimer.Elapsed            += (object sender, ElapsedEventArgs e) =>
                            {
                                bds.SendTellraw(String.Format("Shutting down server in {0} seconds to take a backup.", RunConfig.Backups.NotifyBeforeStop));
                            };
                            backupNotificationTimer.Start();
                        }
                    });
                }

                // Render interval
                if (RunConfig.Renders.EnableRenders)
                {
                    System.Timers.Timer renderIntervalTimer = new System.Timers.Timer(RunConfig.Renders.RenderInterval * 60000);
                    renderIntervalTimer.AutoReset = true;
                    renderIntervalTimer.Elapsed  += (object sender, ElapsedEventArgs e) =>
                    {
                        InvokeRender(worldPath, tempWorldPath);
                    };
                    renderIntervalTimer.Start();
                }

                if (backupOnStartup)
                {
                    // Create initial world backup
                    Console.WriteLine("Creating initial temporary copy of world directory...");
                    _backupManager.CreateWorldBackup(worldPath, tempWorldPath, true, false); // If "StopBeforeBackup" is set to "true" this will also automatically start the server when it's done
                }

                // Start server in case the BackupManager hasn't started it yet
                if (!bds.IsRunning)
                {
                    bds.Start();
                    bds.WaitForMatch(CommonRegex.ServerStarted); // Wait until BDS successfully started
                }

                // Input thread
                inStream = (string text) =>
                {
                    if (RunConfig.BusyCommands || (!_backupManager.Processing && !_renderManager.Processing))
                    {
                        #region CUSTOM COMMANDS
                        MatchCollection cmd = Regex.Matches(text.ToLower().Trim(), @"(\S+)");

                        if (cmd.Count > 0)
                        {
                            bool result = false;
                            switch (cmd[0].Captures[0].Value)
                            {
                            case "force":
                                if (cmd.Count >= 3)
                                {
                                    switch (cmd[1].Captures[0].Value)
                                    {
                                    case "start":
                                        switch (cmd[2].Captures[0].Value)
                                        {
                                        case "backup":
                                            InvokeBackup(worldPath, tempWorldPath);
                                            result = true;
                                            CallHook((byte)Hook.FORCE_BACKUP);
                                            break;

                                        case "render":
                                            InvokeRender(worldPath, tempWorldPath);
                                            result = true;
                                            CallHook((byte)Hook.FORCE_RENDER);
                                            break;
                                        }
                                        break;
                                    }
                                }
                                break;

                            case "stop":
                                System.Timers.Timer shutdownTimer = new System.Timers.Timer();
                                shutdownTimer.AutoReset = false;
                                shutdownTimer.Elapsed  += (object sender, ElapsedEventArgs e) =>
                                {
                                    // _renderManager.Abort();
                                    _bdsWatchdog.Disable();
                                    bds.SendInput("stop");
                                    bds.Process.WaitForExit();
                                    bds.Close();
                                    _readInput = false;
                                    shutdownTimer.Close();

                                    SaveConfiguration(RunConfig, _configPath);

                                    CallHook((byte)Hook.EXIT_USER);

                                    Console.WriteLine("vellum quit correctly");
                                    System.Environment.Exit(0);
                                };

                                if (cmd.Count == 2 && !String.IsNullOrWhiteSpace(cmd[1].Captures[0].Value))
                                {
                                    try
                                    {
                                        double interval = Convert.ToDouble(cmd[1].Captures[0].Value);
                                        shutdownTimer.Interval = (interval > 0 ? interval * 1000 : 1);
                                        bds.SendTellraw(String.Format("Scheduled shutdown in {0} seconds...", interval));
                                        result = true;
                                        CallHook((byte)Hook.EXIT_SCHEDULED, new HookEventArgs()
                                        {
                                            Attachment = interval
                                        });
                                    }
                                    catch
                                    {
                                        Console.WriteLine("Could not schedule shutdown because \"{0}\" is not a valid number.", cmd[1].Captures[0].Value);
                                        result = false;
                                    }
                                }
                                else
                                {
                                    shutdownTimer.Interval = 1;
                                    result = true;
                                }

                                if (result)
                                {
                                    shutdownTimer.Start();
                                }
                                break;

                            case "reload":
                                bool isVellumConfig = false;

                                if (cmd.Count == 2 && cmd[1].Captures[0].Value == "vellum")
                                {
                                    RunConfig      = LoadConfiguration(_configPath);
                                    isVellumConfig = true;
                                }
                                else
                                {
                                    bds.SendInput(text);
                                }
                                result = true;
                                CallHook((byte)Hook.RELOAD_CONFIG, new HookEventArgs()
                                {
                                    Attachment = isVellumConfig
                                });
                                break;

                            case "updatecheck":
                                Console.WriteLine("Checking for updates...");

                                // BDS
                                UpdateChecker bdsUpdateChecker = new UpdateChecker(ReleaseProvider.HTML, "https://minecraft.net/en-us/download/server/bedrock/", @"https:\/\/minecraft\.azureedge\.net\/bin-" + (System.Environment.OSVersion.Platform == PlatformID.Win32NT ? "win" : "linux") + @"\/bedrock-server-(\d+\.\d+\.\d+(?>\.\d+)?)\.zip");
                                if (bdsUpdateChecker.GetLatestVersion())
                                {
                                    Console.WriteLine(String.Format("Bedrock Server:\t{0} -> {1}\t({2})", UpdateChecker.ParseVersion(bdsVersion, VersionFormatting.MAJOR_MINOR_REVISION_BUILD), UpdateChecker.ParseVersion(bdsUpdateChecker.RemoteVersion, VersionFormatting.MAJOR_MINOR_REVISION_BUILD), UpdateChecker.CompareVersions(bdsVersion, bdsUpdateChecker.RemoteVersion, VersionFormatting.MAJOR_MINOR_REVISION_BUILD) < 0 ? "outdated" : "up to date"));
                                }
                                else
                                {
                                    Console.WriteLine("Could not check for Bedrock server updates...");
                                }

                                // vellum
                                if (_updateChecker.GetLatestVersion())
                                {
                                    Console.WriteLine(String.Format("vellum:\t\t{0} -> {1}\t({2})", UpdateChecker.ParseVersion(_localVersion, VersionFormatting.MAJOR_MINOR_REVISION), UpdateChecker.ParseVersion(_updateChecker.RemoteVersion, VersionFormatting.MAJOR_MINOR_REVISION), UpdateChecker.CompareVersions(_localVersion, _updateChecker.RemoteVersion, VersionFormatting.MAJOR_MINOR_REVISION) < 0 ? "outdated" : "up to date"));
                                }
                                else
                                {
                                    Console.WriteLine("Could not check for vellum updates...");
                                }

                                result = true;
                                break;

                            default:
                                result = true;
                                bds.SendInput(text);
                                break;
                            }

                            if (!result)
                            {
                                Console.WriteLine("Could not execute vellum command \"{0}\".", text);
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        Console.WriteLine("Could not execute vellum command \"{0}\". Please wait until all tasks have finished or enable \"BusyCommands\" in your \"{1}\".", text, _configPath);
                    }
                };
            }
            else
            {
                Console.WriteLine("No previous configuration file found. Creating one...");

                using (StreamWriter writer = new StreamWriter(_configPath))
                {
                    writer.Write(JsonConvert.SerializeObject(new RunConfiguration()
                    {
                        BdsBinPath = System.Environment.OSVersion.Platform != PlatformID.Win32NT ? "bedrock_server" : "bedrock_server.exe",
                        Backups    = new BackupConfig()
                        {
                            EnableBackups  = true,
                            EnableSchedule = true,
                            Schedule       = new string[] {
                                "00:00",
                                "06:00",
                                "12:00",
                                "18:00"
                            },
                            BackupInterval   = 60,
                            ArchivePath      = "./backups/",
                            StopBeforeBackup = false,
                            NotifyBeforeStop = 60,
                            BackupsToKeep    = 10,
                            OnActivityOnly   = false,
                            PreExec          = "",
                            PostExec         = "",
                        },
                        Renders = new RenderConfig()
                        {
                            EnableRenders     = true,
                            RenderInterval    = 180,
                            PapyrusBinPath    = "",
                            PapyrusGlobalArgs = "-w $WORLD_PATH -o $OUTPUT_PATH --htmlfile index.html -f png -q 100 --deleteexistingupdatefolder",
                            PapyrusTasks      = new string[] {
                                "--dim 0",
                                "--dim 1",
                                "--dim 2"
                            },
                            PapyrusOutputPath = "",
                            LowPriority       = false
                        },
                        QuietMode          = false,
                        HideStdout         = true,
                        BusyCommands       = true,
                        CheckForUpdates    = true,
                        StopBdsOnException = true,
                        BdsWatchdog        = true,
                        Plugins            = new Dictionary <string, PluginConfig>()
                    },
                                                             Formatting.Indented));
                }

                Console.WriteLine(String.Format("Done! Please edit the \"{0}\" file and restart this application.", _configPath));
            }
        }
Exemple #25
0
 public void OpenExternalApplication(string path, string parameters)
 {
     ProcessManager.OpenProcess(path, parameters);
 }
Exemple #26
0
        /// <summary>
        /// CURSED
        /// </summary>
        private static void MultiplayerMenu_ctor(On.Menu.MultiplayerMenu.orig_ctor orig, Menu.MultiplayerMenu self, ProcessManager manager)
        {
            orig(self, manager);

            foreach (KeyValuePair <string, string> keyValues in CustomWorldMod.activatedPacks)
            {
                /*
                 * string path = Custom.RootFolderDirectory() + CustomWorldMod.resourcePath + keyValues.Value + Path.DirectorySeparatorChar + "Levels";
                 */
                string path = CRExtras.BuildPath(keyValues.Value, CRExtras.CustomFolder.Levels);

                if (Directory.Exists(path))
                {
                    CustomWorldMod.Log($"Custom Regions: Loading arena(s) from [{keyValues.Value}]");

                    string[] files = Directory.GetFiles(path);

                    for (int i = 0; i < files.Length; i++)
                    {
                        if (files[i].Substring(files[i].Length - 4, 4) == ".txt" && files[i].Substring(files[i].Length - 13, 13) != "_Settings.txt" &&
                            files[i].Substring(files[i].Length - 10, 10) != "_Arena.txt" && !files[i].Contains(CustomWorldMod.customUnlocksFileName))
                        {
                            string[] array = files[i].Substring(0, files[i].Length - 4).Split(new char[]
                            {
                                Path.DirectorySeparatorChar
                            });
                            self.allLevels.Add(array[array.Length - 1]);
                        }
                        for (int j = self.allLevels.Count - 1; j >= 0; j--)
                        {
                            if (!self.multiplayerUnlocks.IsLevelUnlocked(self.allLevels[j]))
                            {
                                self.allLevels.RemoveAt(j);
                            }
                        }
                        self.allLevels.Sort((string A, string B) =>
                                            self.multiplayerUnlocks.LevelListSortString(A).CompareTo(self.multiplayerUnlocks.LevelListSortString(B)));

                        foreach (string level in self.allLevels)
                        {
                            if (!self.thumbsToBeLoaded.Contains(level))
                            {
                                self.thumbsToBeLoaded.Add(level);
                            }
                        }

                        /*for (int k = 0; k < self.allLevels.Count; k++)
                         * {
                         *  self.thumbsToBeLoaded.Add(self.allLevels[k]);
                         * }*/
                    }
                }
                string debug  = $"Custom Regions: Loaded arenas [";
                string debug2 = $"Custom Regions: Pending thumbnails [";

                foreach (string level in self.allLevels)
                {
                    debug += level + ", ";
                }
                foreach (string thumb in self.thumbsToBeLoaded)
                {
                    debug2 += thumb + ", ";
                }

                CustomWorldMod.Log(debug + "]");
                //CustomWorldMod.CustomWorldLog(debug2 + "]");
                self.ClearGameTypeSpecificButtons();
                self.InitiateGameTypeSpecificButtons();
            }
        }
Exemple #27
0
 private void Start()
 {
     myProcessManager = FindObjectOfType <ProcessManager>();
 }
Exemple #28
0
        public ActionResult Processes()
        {
            var mng = new ProcessManager();

            return(View());
        }
Exemple #29
0
        private void Form1_Load(object sender, EventArgs e)
        {
            _avalonFloatWindow.MainForm = this;

            ThreadPool.QueueUserWorkItem(new WaitCallback(GetAdProc), this);
            ThreadPool.QueueUserWorkItem(new WaitCallback(UpdateAdPictureProc), this);

            string temp = _currentDir.TrimEnd("\\/".ToCharArray());
            string parentDir = Path.GetDirectoryName(temp);
            _bfgMinerDir = Path.Combine(parentDir, Constants.BfgMinerDirName);
            _bfgMinerPath = Path.Combine(_bfgMinerDir, Constants.BfgMinerFileName);
            _configPath = Path.Combine(_currentDir, ConfigFileName);

            LOG.Info("config path: " + _configPath);
            _appConfig = new AvalonConfig(_configPath);
            _appConfig.LoadConfig();

            _processManager = new ProcessManager();
            _summaryQueue = new Queue<SummaryResult>();

            //DebugMinerData();

            string windowsRoot = Environment.GetEnvironmentVariable("SystemRoot");
            string systemDir = Environment.SystemDirectory;

            string pathValue = string.Format("{0};{1};{2};", _bfgMinerDir, systemDir, windowsRoot);
            Environment.SetEnvironmentVariable("PATH", pathValue);
            
            int screenWidth = Screen.PrimaryScreen.Bounds.Width;
            int screenHeight = Screen.PrimaryScreen.Bounds.Height;
            //_avalonFloatWindow.Location = new Point(screenWidth - 186 - 50, 50);
            _avalonFloatWindow.Location = new Point(screenWidth - 261 - 50, 50);
            _avalonFloatWindow.USBCount = DeviceCounter.GetNanoCount();

            LOG.Info("Form_load, usb count: " + _avalonFloatWindow.USBCount);

            if (_avalonFloatWindow.USBCount > 0)
            {
                RunMinerAndMonitorData();
                _avalonFloatWindow.Show();
                notifyIcon1.Visible = true;
                _avalonFloatWindowVisible = true;
            }
            else
            {
                //_avalonFloatWindow.Show();
                notifyIcon1.Visible = false;
                _avalonFloatWindowVisible = false;
                this.Visible = this.ShowInTaskbar = false;
            }

            _namedpipeServer.ClientConnected += OnClientConnected;
            _namedpipeServer.ClientDisconnected += OnClientDisconnected;
            _namedpipeServer.ClientMessage += OnClientMessage;
            _namedpipeServer.Start();
        }
Exemple #30
0
        // Add custom slugcat select screens
        private static void SlugcatSelectMenu_ctor(On.Menu.SlugcatSelectMenu.orig_ctor orig, Menu.SlugcatSelectMenu self, ProcessManager manager)
        {
            int selectedSlugcat = manager.rainWorld.progression.miscProgressionData.currentlySelectedSinglePlayerSlugcat;

            orig(self, manager);

            List <SlugBaseCharacter> plys = PlayerManager.customPlayers;
            int origLength = self.slugcatColorOrder.Length;

            // Add all SlugBase characters to the select screen
            // All other player mods should change this array, so we have a nice lower bound for indices we can take

            // Find the next available slugcat index, skipping Nightcat
            int firstCustomIndex = 4;

            // Take color order into account
            for (int i = 0; i < self.slugcatColorOrder.Length; i++)
            {
                firstCustomIndex = Math.Max(self.slugcatColorOrder[i] + 1, firstCustomIndex);
            }

            // Take slugcat names into account
            foreach (SlugcatStats.Name name in Enum.GetValues(typeof(SlugcatStats.Name)))
            {
                firstCustomIndex = Math.Max((int)name + 1, firstCustomIndex);
            }

            int nextCustomIndex = firstCustomIndex;

            // Add SlugBase characters to the page order and assign empty slots a default value
            Array.Resize(ref self.slugcatColorOrder, origLength + plys.Count);
            for (int i = origLength; i < self.slugcatColorOrder.Length; i++)
            {
                self.slugcatColorOrder[i] = -1;
            }

            for (int i = 0; i < plys.Count; i++)
            {
                // Assign each player a unique index, then save it to the page order
                // This will cause weird behavior if the user skips over the title screen using EDT, so... don't do that
                self.slugcatColorOrder[origLength + i] = nextCustomIndex;
                plys[i].slugcatIndex = nextCustomIndex++;
            }

            // Retrieve save data
            Array.Resize(ref self.saveGameData, origLength + plys.Count);

            for (int i = 0; i < plys.Count; i++)
            {
                self.saveGameData[origLength + i] = SlugcatSelectMenu.MineForSaveData(self.manager, plys[i].slugcatIndex);
            }

            // Add a new page to the menu
            Array.Resize(ref self.slugcatPages, origLength + plys.Count);

            for (int i = 0; i < plys.Count; i++)
            {
                int o = origLength + i;
                if (self.saveGameData[o] != null)
                {
                    self.slugcatPages[o] = new SlugcatSelectMenu.SlugcatPageContinue(self, null, o + 1, self.slugcatColorOrder[o]);
                }
                else
                {
                    self.slugcatPages[o] = new SlugcatSelectMenu.SlugcatPageNewGame(self, null, o + 1, self.slugcatColorOrder[o]);
                }

                // Select the correct page
                if (selectedSlugcat == self.slugcatColorOrder[o])
                {
                    self.slugcatPageIndex = o;
                }

                self.pages.Add(self.slugcatPages[o]);

                // Make sure the start button reflects the changed slugcat index
                self.UpdateStartButtonText();
                self.UpdateSelectedSlugcatInMiscProg();
            }
        }
Exemple #31
0
        // The select menu relies on a manifest of save information
        // In vanilla, this is either pulled from the current game or mined from the progression file
        // If the indicated slugcat is added by slugbase, instead mine from the custom save file
        private static SlugcatSelectMenu.SaveGameData SlugcatSelectMenu_MineForSaveData(On.Menu.SlugcatSelectMenu.orig_MineForSaveData orig, ProcessManager manager, int slugcat)
        {
            SlugBaseCharacter ply = PlayerManager.GetCustomPlayer(slugcat);

            if (ply != null)
            {
                SaveState save = manager.rainWorld.progression.currentSaveState;
                if (save != null && save.saveStateNumber == slugcat)
                {
                    return(new SlugcatSelectMenu.SaveGameData
                    {
                        karmaCap = save.deathPersistentSaveData.karmaCap,
                        karma = save.deathPersistentSaveData.karma,
                        karmaReinforced = save.deathPersistentSaveData.reinforcedKarma,
                        shelterName = save.denPosition,
                        cycle = save.cycleNumber,
                        hasGlow = save.theGlow,
                        hasMark = save.deathPersistentSaveData.theMark,
                        redsExtraCycles = save.redExtraCycles,
                        food = save.food,
                        redsDeath = save.deathPersistentSaveData.redsDeath,
                        ascended = save.deathPersistentSaveData.ascended
                    });
                }
                int slot = manager.rainWorld.options.saveSlot;
                return(SaveManager.GetCustomSaveData(manager.rainWorld, ply.Name, slot));
            }
            return(orig(manager, slugcat));
        }
Exemple #32
0
        public static Entity Create(Engine engine, ProcessManager processManager, Vector2 position, float angle)
        {
            Entity entity = CreateSpriteOnly(engine, position, angle);

            return(AddBehavior(engine, entity, processManager));
        }
 private static void SlugMenuCtorPatch(On.Menu.SlugcatSelectMenu.orig_ctor orig, SlugcatSelectMenu self, ProcessManager manager)
 {
     orig.Invoke(self, manager);
     foreach (OptionInterface oi in OptionScript.loadedInterfaces)
     {
         oi.GenerateDataArray(self.slugcatColorOrder.Length);
     }
     LoadAndSaveOI(0, true);
 }
        public SteamMultiplayerMenu(ProcessManager manager, bool shouldCreateLobby = false) : base(manager, ProcessManager.ProcessID.MainMenu)
        {
            if (shouldCreateLobby)
            {
                MonklandSteamManager.instance.CreateLobby();
            }

            this.blackFade     = 1f;
            this.lastBlackFade = 1f;
            this.pages.Add(new Page(this, null, "main", 0));
            //this.scene = new InteractiveMenuScene( this, this.pages[0], MenuScene.SceneID.Landscape_SU );
            //this.pages[0].subObjects.Add( this.scene );
            this.darkSprite         = new FSprite("pixel", true);
            this.darkSprite.color   = new Color(0f, 0f, 0f);
            this.darkSprite.anchorX = 0f;
            this.darkSprite.anchorY = 0f;
            this.darkSprite.scaleX  = 1368f;
            this.darkSprite.scaleY  = 770f;
            this.darkSprite.x       = -1f;
            this.darkSprite.y       = -1f;
            this.darkSprite.alpha   = 0.85f;
            this.pages[0].Container.AddChild(this.darkSprite);
            this.blackFadeSprite        = new FSprite("Futile_White", true);
            this.blackFadeSprite.scaleX = 87.5f;
            this.gameStarting           = false;
            this.blackFadeSprite.scaleY = 50f;
            this.blackFadeSprite.x      = manager.rainWorld.screenSize.x / 2f;
            this.blackFadeSprite.y      = manager.rainWorld.screenSize.y / 2f;
            this.blackFadeSprite.color  = new Color(0f, 0f, 0f);
            Futile.stage.AddChild(this.blackFadeSprite);

            //Multiplayer Settings Box
            colorBox = new RoundedRect(this, this.pages[0], new Vector2(940, 125), new Vector2(400, 600), false);
            this.pages[0].subObjects.Add(colorBox);

            //Settings Label
            settingsLabel = new FLabel("font", "Multiplayer Settings");
            settingsLabel.SetPosition(new Vector2(1140, manager.rainWorld.screenSize.y - 60));
            Futile.stage.AddChild(this.settingsLabel);

            //Body Color Label
            bodyLabel = new FLabel("font", "Body Color");
            bodyLabel.SetPosition(new Vector2(1140, manager.rainWorld.screenSize.y - 90));
            Futile.stage.AddChild(this.bodyLabel);

            //Red Slider
            bodyRed                       = new HorizontalSlider(this, this.pages[0], "Red", new Vector2(960, manager.rainWorld.screenSize.y - 130), new Vector2(255, 30), (Slider.SliderID)patch_Slider.SliderID.BodyRed, false);
            bodyRed.floatValue            = 1f;
            bodyRed.buttonBehav.greyedOut = false;
            this.pages[0].subObjects.Add(this.bodyRed);
            //Green Slider
            bodyGreen                       = new HorizontalSlider(this, this.pages[0], "Green", new Vector2(960, manager.rainWorld.screenSize.y - 170), new Vector2(255, 30), (Slider.SliderID)patch_Slider.SliderID.BodyGreen, false);
            bodyGreen.floatValue            = 1f;
            bodyGreen.buttonBehav.greyedOut = false;
            this.pages[0].subObjects.Add(this.bodyGreen);
            //Blue Slider
            bodyBlue                       = new HorizontalSlider(this, this.pages[0], "Blue", new Vector2(960, manager.rainWorld.screenSize.y - 210), new Vector2(255, 30), (Slider.SliderID)patch_Slider.SliderID.BodyBlue, false);
            bodyBlue.floatValue            = 1f;
            bodyBlue.buttonBehav.greyedOut = false;
            this.pages[0].subObjects.Add(this.bodyBlue);

            //Eye Color Label
            eyesLabel = new FLabel("font", "Eye Color");
            eyesLabel.SetPosition(new Vector2(1140, manager.rainWorld.screenSize.y - 235));
            Futile.stage.AddChild(this.eyesLabel);

            //Red Slider
            eyesRed            = new HorizontalSlider(this, this.pages[0], "Red ", new Vector2(960, manager.rainWorld.screenSize.y - 280), new Vector2(255, 30), (Slider.SliderID)patch_Slider.SliderID.EyesRed, false);
            eyesRed.floatValue = 0f;
            this.pages[0].subObjects.Add(this.eyesRed);
            //Green Slider
            eyesGreen            = new HorizontalSlider(this, this.pages[0], "Green ", new Vector2(960, manager.rainWorld.screenSize.y - 320), new Vector2(255, 30), (Slider.SliderID)patch_Slider.SliderID.EyesGreen, false);
            eyesGreen.floatValue = 0f;
            this.pages[0].subObjects.Add(this.eyesGreen);
            //Blue Slider
            eyesBlue            = new HorizontalSlider(this, this.pages[0], "Blue ", new Vector2(960, manager.rainWorld.screenSize.y - 360), new Vector2(255, 30), (Slider.SliderID)patch_Slider.SliderID.EyesBlue, false);
            eyesBlue.floatValue = 0f;
            this.pages[0].subObjects.Add(this.eyesBlue);


            //Slugcat Eyes Sprite
            eyes           = new FSprite("FoodCircleB", true);
            eyes.scaleX    = 1f;
            eyes.scaleY    = 1f;
            eyes.color     = new Color(0, 0, 0);
            eyes.x         = 964;
            eyes.y         = manager.rainWorld.screenSize.y - 236;
            eyes.isVisible = true;
            this.pages[0].Container.AddChild(this.eyes);

            //Slugcat Sprite
            slugcat           = new FSprite("slugcatSleeping", true);
            slugcat.scaleX    = 1f;
            slugcat.scaleY    = 1f;
            slugcat.color     = new Color(1f, 1f, 1f);
            slugcat.x         = 970;
            slugcat.y         = manager.rainWorld.screenSize.y - 235;
            slugcat.isVisible = true;
            this.pages[0].Container.AddChild(this.slugcat);

            //Back button
            this.backButton = new SimpleButton(this, this.pages[0], base.Translate("BACK"), "EXIT", new Vector2(100f, 50f), new Vector2(110f, 30f));
            this.pages[0].subObjects.Add(this.backButton);

            //Back button
            this.backButton = new SimpleButton(this, this.pages[0], base.Translate("BACK"), "EXIT", new Vector2(100f, 50f), new Vector2(110f, 30f));
            this.pages[0].subObjects.Add(this.backButton);

            //Start Game button
            this.startGameButton = new SimpleButton(this, this.pages[0], "Start Game", "STARTGAME", new Vector2(1060, 50f), new Vector2(110f, 30f));
            this.pages[0].subObjects.Add(this.startGameButton);

            //Ready Up button
            this.readyUpButton = new SimpleButton(this, this.pages[0], "Ready UP", "READYUP", new Vector2(940, 50f), new Vector2(110f, 30f));
            this.pages[0].subObjects.Add(this.readyUpButton);

            //Multiplayer Chat
            this.gameChat = new MultiplayerChat(this, this.pages[0], new Vector2(320, 125), new Vector2(600, 600));
            this.pages[0].subObjects.Add(this.gameChat);

            //Invite menu
            playerList = new MultiplayerPlayerList(this, this.pages[0], new Vector2(100, 125), new Vector2(200, 600), new Vector2(180, 180));
            this.pages[0].subObjects.Add(this.playerList);

            //Controller Combatability
            this.bodyRed.nextSelectable[1]         = this.readyUpButton;
            this.bodyRed.nextSelectable[3]         = this.bodyGreen;
            this.bodyGreen.nextSelectable[1]       = this.bodyRed;
            this.bodyGreen.nextSelectable[3]       = this.bodyBlue;
            this.bodyBlue.nextSelectable[1]        = this.bodyGreen;
            this.bodyBlue.nextSelectable[3]        = this.eyesRed;
            this.eyesRed.nextSelectable[1]         = this.bodyBlue;
            this.eyesRed.nextSelectable[3]         = this.eyesGreen;
            this.eyesGreen.nextSelectable[1]       = this.eyesRed;
            this.eyesGreen.nextSelectable[3]       = this.eyesBlue;
            this.eyesBlue.nextSelectable[1]        = this.eyesGreen;
            this.eyesBlue.nextSelectable[3]        = this.readyUpButton;
            this.readyUpButton.nextSelectable[0]   = this.backButton;
            this.readyUpButton.nextSelectable[1]   = this.eyesBlue;
            this.readyUpButton.nextSelectable[2]   = this.startGameButton;
            this.readyUpButton.nextSelectable[3]   = this.bodyRed;
            this.startGameButton.nextSelectable[0] = this.readyUpButton;
            this.startGameButton.nextSelectable[1] = this.eyesBlue;
            this.startGameButton.nextSelectable[2] = this.backButton;
            this.startGameButton.nextSelectable[3] = this.bodyRed;
            this.backButton.nextSelectable[0]      = this.startGameButton;
            this.backButton.nextSelectable[2]      = this.readyUpButton;
            this.backButton.nextSelectable[1]      = this.bodyRed;
            this.backButton.nextSelectable[3]      = this.eyesBlue;

            //Some Nice Music :)
            if (manager.musicPlayer != null)
            {
                manager.musicPlayer.MenuRequestsSong("NA_05 - Sparkles", 1.2f, 10f);
            }
        }
Exemple #35
0
        public static void Start()
        {
            Screen.Color = 0x0;
            Screen.Clear();
            Screen.GotoTop();
            Screen.Color = 0x0E;
            Screen.Write('M');
            Screen.Write('O');
            Screen.Write('S');
            Screen.Write('A');
            Screen.Write(' ');
            Screen.Write('O');
            Screen.Write('S');
            Screen.Write("!");
            Screen.Write(" ");

            DebugClient.Setup(Serial.COM1);
            Screen.Write('0');
            IDT.SetInterruptHandler(null);
            Screen.Write('1');
            Multiboot.Setup();
            Screen.Write('2');
            PIC.Setup();
            Screen.Write('3');
            GDT.Setup();
            Screen.Write('4');
            IDT.Setup();
            Screen.Write('5');
            PageFrameAllocator.Setup();
            Screen.Write('6');
            PageTable.Setup();
            Screen.Write('7');
            VirtualPageAllocator.Setup();
            Screen.Write('8');
            ProcessManager.Setup();
            Screen.Write('9');
            GC.Setup();
            Screen.Write('0');
            //Runtime.Setup();
            Screen.Write('A');
            TaskManager.Setup();
            Screen.Write('B');
            IDT.SetInterruptHandler(ProcessInterrupt);
            Screen.Write('C');
            ConsoleManager.Setup();
            Screen.Write('D');
            Console = ConsoleManager.Controller.Boot;
            Screen.Write('E');
            Screen.Write('F');

            Console.Color           = 0x0E;
            Console.BackgroundColor = 1;
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("!MOSA is alive!");

            Console.WriteLine();

            KernelTest.RunTests();

            Console.WriteLine();

            DumpStackTrace();

            //System.Threading.SpinLock splk = new System.Threading.SpinLock();

            //bool lockTaken = false;
            //splk.Enter(ref lockTaken);
            //if (splk.IsHeld)
            //	Console.Write("Entered...");

            //lockTaken = false;
            //splk.Enter(ref lockTaken);

            //Console.Write("Should have looped!!!");

            Console.Goto(22, 0);

            Process();
        }
Exemple #36
0
 public patch_SleepAndDeathScreen(ProcessManager manager, ProcessManager.ProcessID ID) : base(manager, ID)
 {
 }
 public HazardCollisionOnEnemyDirector(Engine engine, ContentManager content, ProcessManager processManager) : base(engine, content, processManager)
 {
 }
Exemple #38
0
        private static void Start()
        {
            var processManager = new ProcessManager();

            processManager.ConnectServer(_ipAddress, _portNum, 0);
            EventCapsule capsule;
            byte         fileSavepid;
            string       logFileName = @"Log/testLog.txt ";// + DateTime.Now.ToString(new CultureInfo("en-US")) + ".txt";
            FileStream   file        = File.Open(logFileName, FileMode.OpenOrCreate);

            for (int i = 0; i < 2; i++)
            {
                capsule = processManager.DequeueEventQueue();
                string timelog = " || " + DateTime.Now.ToString(new CultureInfo("en-US"));
                WriteToFile(
                    "NetworkEvent: " + capsule.NetworkEvent + "ErrorType: " + capsule.ErrorType + "ProcessId" +
                    capsule.ProcessId + "\n", file);
                WriteToFile(timelog, file); // Timelog
                Console.WriteLine(capsule.NetworkEvent + timelog);

                if (capsule.NetworkEvent == NetworkEvent.Connected)
                {
                    Console.WriteLine("Connected");
                }
                if (capsule.NetworkEvent == NetworkEvent.IdRequestDone)
                {
                    Console.WriteLine("Id:" + capsule.UserId);
                    processManager.RequestFile(@"scg/target1.jpg", FileType.Dlc);
                    processManager.RequestFile(@"scg/target2.png", FileType.Dlc);
                    processManager.RequestFile(@"scg/target3.png", FileType.Dlc);
                    processManager.RequestFile(@"scg/target1.jpg", FileType.Dlc);
                    processManager.RequestFile(@"scg/target2.png", FileType.Dlc);
                    processManager.RequestFile(@"scg/target3.png", FileType.Dlc);
                    processManager.RequestFile(@"scg/target1.jpg", FileType.Dlc);
                    processManager.RequestFile(@"scg/target2.png", FileType.Dlc);
                    processManager.RequestFile(@"scg/target3.png", FileType.Dlc);
                    byte[] fileData = File.ReadAllBytes(@"umaru_source.jpg");
                    fileSavepid = processManager.SaveUserFile("Umaru.jpg", fileData);
                    break;
                }
                else
                {
                    Console.WriteLine(capsule.NetworkEvent);
                    Console.WriteLine(capsule.ErrorType);
                }
            }

            while (testActivated)
            {
                while (processManager.CountProcessList() > 0 || processManager.CountEventQueue() > 0)
                {
                    capsule = processManager.DequeueEventQueue();

                    string timelog = DateTime.Now.ToString(new CultureInfo("en-US"));
                    WriteToFile(
                        "NetworkEvent: " + capsule.NetworkEvent + "ErrorType: " + capsule.ErrorType + "ProcessId" +
                        capsule.ProcessId + "\n", file);
                    WriteToFile(timelog, file); // Timelog
                    Console.WriteLine(capsule.NetworkEvent + timelog);

                    if (capsule.NetworkEvent == NetworkEvent.FileSaveDone)
                    {
                        processManager.RequestFile("Umaru.jpg", FileType.User);
                    }
                    if (capsule.NetworkEvent == NetworkEvent.FileRequestDone)
                    {
                        File.WriteAllBytes(((FileCapsule)capsule).FileName,
                                           ((FileCapsule)capsule).Data);
                    }
                }

                processManager.RequestFile(@"scg/target1.jpg", FileType.Dlc);
                processManager.RequestFile(@"scg/target2.png", FileType.Dlc);
                processManager.RequestFile(@"scg/target3.png", FileType.Dlc);
                processManager.RequestFile(@"scg/target1.jpg", FileType.Dlc);
                processManager.RequestFile(@"scg/target2.png", FileType.Dlc);
                processManager.RequestFile(@"scg/target3.png", FileType.Dlc);
                processManager.RequestFile(@"scg/target1.jpg", FileType.Dlc);
                processManager.RequestFile(@"scg/target2.png", FileType.Dlc);
                processManager.RequestFile(@"scg/target3.png", FileType.Dlc);
                byte[] fileData = File.ReadAllBytes(@"umaru_source.jpg");
                fileSavepid = processManager.SaveUserFile("Umaru.jpg", fileData);
            }

            WriteToFile("Shutting down", file);
            file.Close();

            processManager.SaveUserFile("log.txt", File.ReadAllBytes(logFileName)); //send the log file to server
            processManager.DequeueEventQueue();                                     //Dequeue saveDone capsule

            processManager.Shutdown();
            Console.WriteLine("shutting down");
        }
Exemple #39
0
        /**
         * Creates a new Link or gets an existing one from the the given NodeID.
         *
         * @param nodeID
         *            NodeID of the Node to connect to.
         * @return A Link connected to the remote Node of given NodeID
         * @//throws JCSPNetworkException
         *             Thrown if there is a problem connecting to the Node
         * @//throws ArgumentException
         *             Thrown if an attempt is made to connect to the local Node
         */
        public static Link getLink(NodeID nodeID)
        ////throws JCSPNetworkException, ArgumentException
        {
            if (nodeID.equals(Node.getInstance().getNodeID()))
            {
                throw new ArgumentException("Attempted to connect to the local Node");
            }

            // Log start of Link creation
            Node.log.log(typeof(LinkFactory), "Trying to get link to " + nodeID.toString());

            // First check if Link to NodeID exists. Request the Link from the Link Manager
            Link toReturn = LinkManager.getInstance().requestLink(nodeID);

            if (toReturn != null)
            {
                // A Link already exists to given NodeID. Log and return existing Link
                Node.log.log(typeof(LinkFactory), "Link to " + nodeID.toString()
                             + " already exists.  Returning existing Link");
                return(toReturn);
            }

            // An existing Link does not exist within the Link Manager. Log, and then create Link via the address
            Node.log.log(typeof(LinkFactory), "Link does not exist to " + nodeID.toString() + ".  Creating new Link");
            toReturn = nodeID.getNodeAddress().createLink();

            // Now attempt to connect the Link. If connect fails, then the opposite node already has a connection to us.
            // This may occur during connection if the opposite end registered its Link prior to us doing so. In such
            // a circumstance, the Link should eventually appear in the LinkManager.
            if (!toReturn.connect())
            {
                // Connect failed. Get NodeID of remote Node (this will have been set during the connect operation)
                NodeID remoteID = toReturn.getRemoteNodeID();

                // Log failed connect
                Node.log.log(typeof(LinkFactory), "Failed to connect to " + remoteID.toString());

                // Set the Link to return to null
                toReturn = null;

                // Loop until the Link is connected. This is a possible weakness. Although it is believed that the
                // opposite end will eventually connect, we may have a problem if this continually loops. For information,
                // log every attempt.
                while (toReturn == null)
                {
                    try
                    {
                        // Go to sleep for a bit, and give the Link a chance to register
                        Thread.Sleep(100);

                        // Log start of attempt
                        Node.log.log(typeof(LinkFactory), "Attempting to retrieve Link to " + remoteID.toString());

                        // Retrieve Link from LinkManager
                        toReturn = LinkManager.getInstance().requestLink(remoteID);
                    }
                    catch (ThreadInterruptedException ie)
                    {
                        // Ignore. Should never really happen
                    }
                }
                // Return the Link retrieved from the LinkManager
                return(toReturn);
            }

            // Connection succeeded. Register Link with the LinkManager
            toReturn.registerLink();

            // Now start the Link
            ProcessManager proc = new ProcessManager(toReturn);

            proc.setPriority(toReturn.priority);
            proc.start();

            // Return the Link
            return(toReturn);
        }
 public override void SetConsoleCtrlHandler(ProcessManager.CtrlHandlerDelegate Handler)
 {
     ProcessManager.SetConsoleCtrlHandler(Handler, true);
 }
        public SteamMultiplayerMenu(ProcessManager manager, bool shouldCreateLobby = false) : base(manager, ProcessManager.ProcessID.MainMenu)
        {
            if (shouldCreateLobby)
            {
                MonklandSteamManager.instance.CreateLobby();
            }

            #region UI ELEMENTS SIZE DEFINITION

            float resOffset = (1366 - manager.rainWorld.screenSize.x) / 2; // shift everything to the right depending on the resolution. 1/2 of the diff with the max resolution.

            float screenWidth  = manager.rainWorld.screenSize.x;
            float screenHeight = manager.rainWorld.screenSize.y;
            // initialize some dynamic sizes and positions for UI elements.
            // player list and multiplayer settings have the same size no matter what the resolution.
            // the room chat adjusts to fill all the middle space
            float panelGutter = 15;                                                                             // gap width between the panels

            float playerListWidth                = 200;                                                         // constant
            float multiplayerSettingsWidth       = 300;                                                         // constant
            float multiplayerSettingsSliderWidth = multiplayerSettingsWidth - 115;                              // constant
            float roomChatWidth = screenWidth - (playerListWidth + multiplayerSettingsWidth + panelGutter * 4); // depends on resolution

            float playerListPositionX                = panelGutter;                                             // position depending on size
            float multiplayerSettingsPositionX       = screenWidth - (multiplayerSettingsWidth + panelGutter);  // position depending on screen width
            float multiplayerSettingsSliderPositionX = multiplayerSettingsPositionX + 10;                       // constant
            float roomChatPositionX = playerListWidth + panelGutter * 2;                                        // position depending on player list width

            float controlButtonSpaceHeight = 100;                                                               // constant
            float panelHeight    = screenHeight - (controlButtonSpaceHeight + panelGutter * 2);                 // leaving a space for control buttons
            float panelPositionY = controlButtonSpaceHeight;                                                    // constant

            #endregion UI ELEMENTS SIZE DEFINITION

            this.blackFade     = 1f;
            this.lastBlackFade = 1f;
            this.pages.Add(new Page(this, null, "main", 0));
            //this.scene = new InteractiveMenuScene( this, this.pages[0], MenuScene.SceneID.Landscape_SU );
            //this.pages[0].subObjects.Add( this.scene );
            this.darkSprite = new FSprite("pixel", true)
            {
                color   = new Color(0f, 0f, 0f),
                anchorX = 0f,
                anchorY = 0f,
                scaleX  = screenWidth,
                scaleY  = screenHeight,
                x       = screenWidth / 2f,
                y       = screenHeight / 2f,
                alpha   = 0.85f
            };
            this.pages[0].Container.AddChild(this.darkSprite);
            this.blackFadeSprite = new FSprite("Futile_White", true)
            {
                scaleX = 87.5f,
                scaleY = 50f,
                x      = screenWidth / 2f,
                y      = screenHeight / 2f,
                color  = new Color(0f, 0f, 0f)
            };
            Futile.stage.AddChild(this.blackFadeSprite);

            //Multiplayer Settings Box
            colorBox = new RoundedRect(this, this.pages[0], new Vector2(resOffset + multiplayerSettingsPositionX, panelPositionY), new Vector2(multiplayerSettingsWidth, panelHeight), false);
            this.pages[0].subObjects.Add(colorBox);

            //Settings Label
            settingsLabel = new FLabel("font", "Multiplayer Settings");
            settingsLabel.SetPosition(new Vector2(multiplayerSettingsPositionX + 70.01f, screenHeight - 60.01f));
            Futile.stage.AddChild(this.settingsLabel);

            //Body Color Label
            bodyLabel = new FLabel("font", "Body Color");
            bodyLabel.SetPosition(new Vector2(multiplayerSettingsPositionX + 70.01f, screenHeight - 90.01f));
            Futile.stage.AddChild(this.bodyLabel);

            //Red Slider
            bodyRed                       = new HorizontalSlider(this, this.pages[0], "Red", new Vector2(resOffset + multiplayerSettingsSliderPositionX, screenHeight - 130), new Vector2(multiplayerSettingsSliderWidth, 30), (Slider.SliderID)(-1), false);
            bodyRed.floatValue            = MonklandSteamManager.bodyColor.r;
            bodyRed.buttonBehav.greyedOut = false;
            this.pages[0].subObjects.Add(this.bodyRed);
            //Green Slider
            bodyGreen                       = new HorizontalSlider(this, this.pages[0], "Green", new Vector2(resOffset + multiplayerSettingsSliderPositionX, screenHeight - 170), new Vector2(multiplayerSettingsSliderWidth, 30), (Slider.SliderID)(-1), false);
            bodyGreen.floatValue            = MonklandSteamManager.bodyColor.g;
            bodyGreen.buttonBehav.greyedOut = false;
            this.pages[0].subObjects.Add(this.bodyGreen);
            //Blue Slider
            bodyBlue                       = new HorizontalSlider(this, this.pages[0], "Blue", new Vector2(resOffset + multiplayerSettingsSliderPositionX, screenHeight - 210), new Vector2(multiplayerSettingsSliderWidth, 30), (Slider.SliderID)(-1), false);
            bodyBlue.floatValue            = MonklandSteamManager.bodyColor.b;
            bodyBlue.buttonBehav.greyedOut = false;
            this.pages[0].subObjects.Add(this.bodyBlue);

            //Eye Color Label
            eyesLabel = new FLabel("font", "Eye Color");
            eyesLabel.SetPosition(new Vector2(multiplayerSettingsPositionX + 70.01f, screenHeight - 240.01f));
            Futile.stage.AddChild(this.eyesLabel);

            //Red Slider
            eyesRed            = new HorizontalSlider(this, this.pages[0], "Red ", new Vector2(resOffset + multiplayerSettingsSliderPositionX, screenHeight - 280), new Vector2(multiplayerSettingsSliderWidth, 30), (Slider.SliderID)(-1), false);
            eyesRed.floatValue = MonklandSteamManager.eyeColor.r;
            this.pages[0].subObjects.Add(this.eyesRed);
            //Green Slider
            eyesGreen            = new HorizontalSlider(this, this.pages[0], "Green ", new Vector2(resOffset + multiplayerSettingsSliderPositionX, screenHeight - 320), new Vector2(multiplayerSettingsSliderWidth, 30), (Slider.SliderID)(-1), false);
            eyesGreen.floatValue = MonklandSteamManager.eyeColor.g;
            this.pages[0].subObjects.Add(this.eyesGreen);
            //Blue Slider
            eyesBlue            = new HorizontalSlider(this, this.pages[0], "Blue ", new Vector2(resOffset + multiplayerSettingsSliderPositionX, screenHeight - 360), new Vector2(multiplayerSettingsSliderWidth, 30), (Slider.SliderID)(-1), false);
            eyesBlue.floatValue = MonklandSteamManager.eyeColor.b;
            this.pages[0].subObjects.Add(this.eyesBlue);

            //Slugcat Eyes Sprite
            eyes           = new FSprite("FoodCircleB", true);
            eyes.scaleX    = 1f;
            eyes.scaleY    = 1.1f;
            eyes.color     = new Color(0, 0, 0);
            eyes.x         = multiplayerSettingsPositionX + 130;
            eyes.y         = manager.rainWorld.screenSize.y - 236;
            eyes.isVisible = true;
            this.pages[0].Container.AddChild(this.eyes);

            //Slugcat Sprite
            slugcat           = new FSprite("slugcatSleeping", true);
            slugcat.scaleX    = 1f;
            slugcat.scaleY    = 1f;
            slugcat.color     = new Color(1f, 1f, 1f);
            slugcat.x         = multiplayerSettingsPositionX + 136;
            slugcat.y         = manager.rainWorld.screenSize.y - 235;
            slugcat.isVisible = true;
            this.pages[0].Container.AddChild(this.slugcat);

            //Debug Mode checkbox
            this.debugCheckBox = new CheckBox(this, this.pages[0], this, new Vector2(resOffset + multiplayerSettingsSliderPositionX + 120f, screenHeight - 400f), 120f, "Debug Mode", "DEBUG");
            this.pages[0].subObjects.Add(this.debugCheckBox);

            //Slugcat Buttons
            this.slugcatButtons    = new SelectOneButton[3];
            this.slugcatButtons[0] = new SelectOneButton(this, this.pages[0], base.Translate("SURVIOR"), "Slugcat", new Vector2(resOffset + multiplayerSettingsSliderPositionX, screenHeight - 445f), new Vector2(110f, 30f), this.slugcatButtons, 0);
            this.pages[0].subObjects.Add(this.slugcatButtons[0]);
            this.slugcatButtons[1] = new SelectOneButton(this, this.pages[0], base.Translate("MONK"), "Slugcat", new Vector2(resOffset + multiplayerSettingsSliderPositionX, screenHeight - 490f), new Vector2(110f, 30f), this.slugcatButtons, 1);
            this.pages[0].subObjects.Add(this.slugcatButtons[1]);
            this.slugcatButtons[2] = new SelectOneButton(this, this.pages[0], base.Translate("HUNTER"), "Slugcat", new Vector2(resOffset + multiplayerSettingsSliderPositionX, screenHeight - 535f), new Vector2(110f, 30f), this.slugcatButtons, 2);
            this.pages[0].subObjects.Add(this.slugcatButtons[2]);

            //Back button
            this.backButton = new SimpleButton(this, this.pages[0], base.Translate("BACK"), "EXIT", new Vector2(resOffset + 15f, 50f), new Vector2(110f, 30f));
            this.pages[0].subObjects.Add(this.backButton);

            //Start Game button
            this.startGameButton = new SimpleButton(this, this.pages[0], "Start Game", "STARTGAME", new Vector2(resOffset + screenWidth - 125, 50f), new Vector2(110f, 30f));
            this.pages[0].subObjects.Add(this.startGameButton);

            //Ready Up button
            this.readyUpButton = new SimpleButton(this, this.pages[0], "Ready UP", "READYUP", new Vector2(resOffset + screenWidth - 250, 50f), new Vector2(110f, 30f));
            this.pages[0].subObjects.Add(this.readyUpButton);

            //Multiplayer Chat
            this.gameChat = new MultiplayerChat(this, this.pages[0], new Vector2(resOffset + roomChatPositionX, panelPositionY), new Vector2(roomChatWidth, panelHeight));
            this.pages[0].subObjects.Add(this.gameChat);

            //Invite menu
            playerList = new MultiplayerPlayerList(this, this.pages[0], new Vector2(resOffset + playerListPositionX, panelPositionY), new Vector2(playerListWidth, panelHeight), new Vector2(playerListWidth - 20, playerListWidth - 20));
            this.pages[0].subObjects.Add(this.playerList);

            //Controller Combatability
            this.bodyRed.nextSelectable[1]         = this.readyUpButton;
            this.bodyRed.nextSelectable[3]         = this.bodyGreen;
            this.bodyGreen.nextSelectable[1]       = this.bodyRed;
            this.bodyGreen.nextSelectable[3]       = this.bodyBlue;
            this.bodyBlue.nextSelectable[1]        = this.bodyGreen;
            this.bodyBlue.nextSelectable[3]        = this.eyesRed;
            this.eyesRed.nextSelectable[1]         = this.bodyBlue;
            this.eyesRed.nextSelectable[3]         = this.eyesGreen;
            this.eyesGreen.nextSelectable[1]       = this.eyesRed;
            this.eyesGreen.nextSelectable[3]       = this.eyesBlue;
            this.eyesBlue.nextSelectable[1]        = this.eyesGreen;
            this.eyesBlue.nextSelectable[3]        = this.debugCheckBox;
            this.debugCheckBox.nextSelectable[1]   = this.eyesBlue;
            this.debugCheckBox.nextSelectable[3]   = this.readyUpButton;
            this.readyUpButton.nextSelectable[0]   = this.backButton;
            this.readyUpButton.nextSelectable[1]   = this.debugCheckBox;
            this.readyUpButton.nextSelectable[2]   = this.startGameButton;
            this.readyUpButton.nextSelectable[3]   = this.bodyRed;
            this.startGameButton.nextSelectable[0] = this.readyUpButton;
            this.startGameButton.nextSelectable[1] = this.eyesBlue;
            this.startGameButton.nextSelectable[2] = this.backButton;
            this.startGameButton.nextSelectable[3] = this.bodyRed;
            this.backButton.nextSelectable[0]      = this.startGameButton;
            this.backButton.nextSelectable[2]      = this.readyUpButton;
            this.backButton.nextSelectable[1]      = this.bodyRed;
            this.backButton.nextSelectable[3]      = this.eyesBlue;

            //Some Nice Music :)
            if (manager.musicPlayer != null)
            {
                manager.musicPlayer.MenuRequestsSong("NA_05 - Sparkles", 1.2f, 10f);
            }

            //Fix Label pixelperfect
            foreach (MenuObject o in this.pages[0].subObjects)
            {
                if (o is MenuLabel l)
                {
                    l.pos += new Vector2(0.01f, 0.01f);
                }
            }
        }
        public void RemoveTemporaryProcess(ProcessManager pm)
        {
            if (TemporaryProcess == null) return;//throw new SystemException("Temporary process was null");
            TemporaryProcess.active = false;
            foreach(KeyAction ka in TemporaryProcess.processKeyActions.Keys)
            {
                KeyBundle kb = TemporaryProcess.processKeyActions[ka];
                if (Keybinds.ContainsKey(kb) && ka == Keybinds[kb])
                {
                    Keybinds.Remove(TemporaryProcess.processKeyActions[ka]);
                }
            }
            if (ReplacedBundles.ContainsKey(TemporaryProcess))
            {
                List<Tuple<KeyBundle, KeyAction>> list = ReplacedBundles[TemporaryProcess];
                foreach(Tuple<KeyBundle, KeyAction> tup in list)
                {
                    if (Keybinds.ContainsKey(tup.Item1)) continue; //maybe shouldn't do this; doesn't replace if something took the slot
                    Keybinds.Add(tup.Item1, tup.Item2);
                }
            }
            pm.activeProcesses.Remove(TemporaryProcess);

            ReplacedBundles.Remove(TemporaryProcess);
            TemporaryProcess = null; //maybe disable temporary process? or should we let caller do that
        }
Exemple #43
0
		public static IDisposable Start()
		{
			ProcessManager result = new ProcessManager();
			result.StartProcess();
			return result;
		}
        async Task CheckForUpdates()
        {
            try
            {
                if (Config.Default.settings.update.isDisabled)
                {
                    Trace.TraceInformation("The software update check is disabled by the user; skipping check");
                    return;
                }

                // Remove any old ClickOnce installs
                try
                {
                    var uninstallInfo = UninstallInfo.Find("IPFilter Updater");
                    if (uninstallInfo != null)
                    {
                        Trace.TraceWarning("Old ClickOnce app installed! Trying to remove...");
                        var uninstaller = new Uninstaller();
                        uninstaller.Uninstall(uninstallInfo);
                        Trace.TraceInformation("Successfully removed ClickOnce app");
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to remove old ClickOnce app: " + ex);
                }

                Trace.TraceInformation("Checking for software updates...");
                progress.Report(new ProgressModel(UpdateState.Downloading, "Checking for software updates...", -1));

                var updater = new Updater();

                var result = await updater.CheckForUpdateAsync(Config.Default.settings.update.isPreReleaseEnabled);

                if (result == null)
                {
                    return;
                }

                // The ProductVersion contains the informational, semantic version e.g. "3.0.0-beta"
                var versionInfo    = Process.GetCurrentProcess().MainModule.FileVersionInfo;
                var currentVersion = new SemanticVersion(versionInfo.ProductVersion);

                var latestVersion = new SemanticVersion(result.Version);

                Update.IsUpdateAvailable = latestVersion > currentVersion;

                if (Update.IsUpdateAvailable)
                {
                    Update.AvailableVersion       = latestVersion;
                    Update.IsUpdateRequired       = true;
                    Update.MinimumRequiredVersion = latestVersion;
                    Update.UpdateSizeBytes        = 2000000;
                }

                Trace.TraceInformation("Current version: {0}", Update.CurrentVersion);
                Trace.TraceInformation("Available version: {0}", Update.AvailableVersion?.ToString() ?? "<no updates>");

                if (!Update.IsUpdateAvailable)
                {
                    return;
                }

                if (MessageBoxHelper.Show(dispatcher, "Update Available", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes,
                                          "An update to version {0} is available. Would you like to update now?", Update.AvailableVersion) != MessageBoxResult.Yes)
                {
                    return;
                }

                Trace.TraceInformation("Starting application update...");

                // If we're not "installed", then don't check for updates. This is so the
                // executable can be stand-alone. Stand-alone self-update to come later.
                using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\IPFilter"))
                {
                    var installPath = (string)key?.GetValue("InstallPath");
                    if (installPath == null)
                    {
                        using (var process = new Process())
                        {
                            process.StartInfo = new ProcessStartInfo("https://davidmoore.github.io/ipfilter/")
                            {
                                UseShellExecute = true
                            };

                            process.Start();
                            return;
                        }
                    }
                }

                var msiPath = Path.Combine(Path.GetTempPath(), "IPFilter.msi");

                // Download the installer
                using (var handler = new WebRequestHandler())
                {
                    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                    var uri = new Uri($"{result.Uri}?{DateTime.Now.ToString("yyyyMMddHHmmss")}");

                    using (var httpClient = new HttpClient(handler))
                        using (var response = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken.Token))
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                Update.IsUpdating = false;
                                return;
                            }

                            var    length          = response.Content.Headers.ContentLength;
                            double lengthInMb      = !length.HasValue ? -1 : (double)length.Value / 1024 / 1024;
                            double bytesDownloaded = 0;

                            using (var stream = await response.Content.ReadAsStreamAsync())
                                using (var msi = File.Open(msiPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                                {
                                    var buffer = new byte[65535 * 4];

                                    int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);

                                    while (bytesRead != 0)
                                    {
                                        await msi.WriteAsync(buffer, 0, bytesRead, cancellationToken.Token);

                                        bytesDownloaded += bytesRead;

                                        if (length.HasValue)
                                        {
                                            double downloadedMegs = bytesDownloaded / 1024 / 1024;
                                            var    percent        = (int)Math.Floor((bytesDownloaded / length.Value) * 100);

                                            var status = string.Format(CultureInfo.CurrentUICulture, "Downloaded {0:F2} MB of {1:F2} MB", downloadedMegs, lengthInMb);

                                            Update.IsUpdating         = true;
                                            Update.DownloadPercentage = percent;
                                            progress.Report(new ProgressModel(UpdateState.Downloading, status, percent));
                                        }

                                        if (cancellationToken.IsCancellationRequested)
                                        {
                                            progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                            Update.IsUpdating = false;
                                            return;
                                        }

                                        bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);
                                    }
                                }
                        }
                }

                progress.Report(new ProgressModel(UpdateState.Ready, "Launching update...", 100));
                Update.IsUpdating = false;

                // Now run the installer
                var sb = new StringBuilder("msiexec.exe ");

                // Enable logging for the installer
                sb.AppendFormat(" /l*v \"{0}\"", Path.Combine(Path.GetTempPath(), "IPFilter.log"));

                sb.AppendFormat(" /i \"{0}\"", msiPath);

                //sb.Append(" /passive");

                ProcessInformation processInformation = new ProcessInformation();
                StartupInfo        startupInfo        = new StartupInfo();
                SecurityAttributes processSecurity    = new SecurityAttributes();
                SecurityAttributes threadSecurity     = new SecurityAttributes();
                processSecurity.nLength = Marshal.SizeOf(processSecurity);
                threadSecurity.nLength  = Marshal.SizeOf(threadSecurity);

                const int NormalPriorityClass = 0x0020;

                if (!ProcessManager.CreateProcess(null, sb, processSecurity,
                                                  threadSecurity, false, NormalPriorityClass,
                                                  IntPtr.Zero, null, startupInfo, processInformation))
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                try
                {
                    //dispatcher.Invoke(DispatcherPriority.Normal, new Action(Application.Current.Shutdown));
                    Application.Current.Shutdown();
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Exception when shutting down app for update: " + ex);
                    Update.ErrorMessage = "Couldn't shutdown the app to apply update.";
                }
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Application update check failed: " + ex);
            }
            finally
            {
                progress.Report(new ProgressModel(UpdateState.Ready, "Ready", 0));
            }
        }
 //メインメソッド
 static void Main()
 {
     ProcessManager pm = new ProcessManager();
     pm.pmMain();
 }
 public extern void OriginalConstructor(ProcessManager manager);
 /// <summary>
 /// After Mainwindow finished loaded, event called and Init variables
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 void MainWindow_Loaded(object sender, RoutedEventArgs e)
 {
     var desktopWorkingArea = SystemParameters.WorkArea;
     Top = desktopWorkingArea.Bottom - Height+40;
     WindowStyle = WindowStyle.None;
     this.Width =SystemParameters.PrimaryScreenWidth;
     ResizeMode = ResizeMode.NoResize;
     m_FileUploadThread = new Thread(UploadManager.Instance.Main);
     m_FileUploadThread.Start();
     m_ProcessManager = ProcessManager.Instance;
     m_ImageCaptureManager = ImageCaptureManager.Instance;
     m_PowerPointManager = new PowerPointManager();
     m_bIsTempCanvasOpen = false;
     m_ImageCaptureManager.LoadPreviousStorke += new EventHandler(LoadPreviousStorkes);
 }
Exemple #48
0
        public override async Task RunTestAsync()
        {
            var projectDir = System.IO.Path.GetDirectoryName(ProjectFile);
            var name       = System.IO.Path.GetFileName(projectDir);

            if (string.Equals("mac", name, StringComparison.OrdinalIgnoreCase))
            {
                name = System.IO.Path.GetFileName(System.IO.Path.GetDirectoryName(projectDir));
            }
            var suffix = string.Empty;

            switch (Platform)
            {
            case TestPlatform.Mac_Modern:
                suffix = "-modern";
                break;

            case TestPlatform.Mac_Full:
                suffix = "-full";
                break;

            case TestPlatform.Mac_System:
                suffix = "-system";
                break;
            }
            if (ProjectFile.EndsWith(".sln", StringComparison.Ordinal))
            {
                Path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(ProjectFile), "bin", BuildTask.ProjectPlatform, BuildTask.ProjectConfiguration + suffix, name + ".app", "Contents", "MacOS", name);
            }
            else
            {
                var project = new XmlDocument();
                project.LoadWithoutNetworkAccess(ProjectFile);
                var outputPath   = project.GetOutputPath(BuildTask.ProjectPlatform, BuildTask.ProjectConfiguration).Replace('\\', '/');
                var assemblyName = project.GetAssemblyName();
                Path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(ProjectFile), outputPath, assemblyName + ".app", "Contents", "MacOS", assemblyName);
            }

            using (var resource = await NotifyAndAcquireDesktopResourceAsync()) {
                using (var proc = new Process()) {
                    proc.StartInfo.FileName = Path;
                    var            arguments    = new List <string> ();
                    IFileBackedLog xmlLog       = null;
                    var            useXmlOutput = Harness.InCI || true;
                    if (IsUnitTest)
                    {
                        var extension = useXmlOutput ? "xml" : "log";
                        var type      = useXmlOutput ? LogType.XmlLog : LogType.NUnitResult;
                        xmlLog = Logs.Create($"test-{Platform}-{Timestamp}.{extension}", type.ToString());
                        arguments.Add($"-transport:FILE");
                        proc.StartInfo.EnvironmentVariables ["NUNIT_TRANSPORT"] = "FILE";
                        arguments.Add($"--logfile:{xmlLog.FullPath}");
                        proc.StartInfo.EnvironmentVariables ["NUNIT_LOG_FILE"] = xmlLog.FullPath;
                        if (useXmlOutput)
                        {
                            arguments.Add("--enablexml");
                            proc.StartInfo.EnvironmentVariables ["NUNIT_ENABLE_XML_OUTPUT"] = "true";
                            arguments.Add("--xmlmode=wrapped");
                            proc.StartInfo.EnvironmentVariables ["NUNIT_ENABLE_XML_MODE"] = "wrapped";
                            arguments.Add("--xmlversion=nunitv3");
                            proc.StartInfo.EnvironmentVariables ["NUNIT_XML_VERSION"] = "nunitv3";
                        }
                        arguments.Add("--autostart");
                        proc.StartInfo.EnvironmentVariables ["NUNIT_AUTOSTART"] = "true";
                        arguments.Add("--autoexit");
                        proc.StartInfo.EnvironmentVariables ["NUNIT_AUTOEXIT"] = "true";
                    }
                    if (!Harness.GetIncludeSystemPermissionTests(Platform, false))
                    {
                        proc.StartInfo.EnvironmentVariables ["DISABLE_SYSTEM_PERMISSION_TESTS"] = "1";
                    }
                    proc.StartInfo.EnvironmentVariables ["MONO_DEBUG"] = "no-gdb-backtrace";
                    proc.StartInfo.EnvironmentVariables.Remove("DYLD_FALLBACK_LIBRARY_PATH");                      // VSMac might set this, and the test may end up crashing
                    proc.StartInfo.Arguments = StringUtils.FormatArguments(arguments);
                    Jenkins.MainLog.WriteLine("Executing {0} ({1})", TestName, Mode);
                    var log = Logs.Create($"execute-{Platform}-{Timestamp}.txt", LogType.ExecutionLog.ToString());
                    ICrashSnapshotReporter snapshot = null;
                    if (!Jenkins.Harness.DryRun)
                    {
                        ExecutionResult = TestExecutingResult.Running;

                        snapshot = CrashReportSnapshotFactory.Create(log, Logs, isDevice: false, deviceName: null);
                        await snapshot.StartCaptureAsync();

                        ProcessExecutionResult result = null;
                        try {
                            var timeout = TimeSpan.FromMinutes(20);

                            result = await ProcessManager.RunAsync(proc, log, timeout);

                            if (result.TimedOut)
                            {
                                FailureMessage = $"Execution timed out after {timeout.TotalSeconds} seconds.";
                                log.WriteLine(FailureMessage);
                                ExecutionResult = TestExecutingResult.TimedOut;
                            }
                            else if (result.Succeeded)
                            {
                                ExecutionResult = TestExecutingResult.Succeeded;
                            }
                            else
                            {
                                ExecutionResult = TestExecutingResult.Failed;
                                FailureMessage  = result.ExitCode != 1 ? $"Test run crashed (exit code: {result.ExitCode})." : "Test run failed.";
                                log.WriteLine(FailureMessage);
                            }
                        } finally {
                            await snapshot.EndCaptureAsync(TimeSpan.FromSeconds(Succeeded ? 0 : result?.ExitCode > 1 ? 120 : 5));
                        }
                    }
                    Jenkins.MainLog.WriteLine("Executed {0} ({1})", TestName, Mode);

                    if (IsUnitTest)
                    {
                        var reporterFactory = new TestReporterFactory(ProcessManager);
                        var listener        = new Microsoft.DotNet.XHarness.iOS.Shared.Listeners.SimpleFileListener(xmlLog.FullPath, log, xmlLog, useXmlOutput);
                        var reporter        = reporterFactory.Create(Harness.HarnessLog, log, Logs, snapshot, listener, Harness.ResultParser, new AppBundleInformation("N/A", "N/A", "N/A", "N/A", true, null), RunMode.MacOS, Harness.XmlJargon, "no device here", TimeSpan.Zero);
                        var rv = await reporter.ParseResult();

                        ExecutionResult = rv.ExecutingResult;
                        FailureMessage  = rv.ExecutingResult == TestExecutingResult.Succeeded ? null : rv.ResultMessage;
                    }
                }
            }
        }
 /// <summary>
 /// Sets the console control handler for the current platform.
 /// </summary>
 /// <param name="Handler"></param>
 public abstract void SetConsoleCtrlHandler(ProcessManager.CtrlHandlerDelegate Handler);
Exemple #50
0
 public void Setup(ProcessManager processManager, GameObject owner)
 {
     _processManager = processManager;
     _owner          = owner;
 }
        public void AddProcess(ProcessManager pm, Process p, bool Temporary = true)
        {
            if (p == null) throw new SystemException("Process parameter was null"); //well ya see kids...
            if (p.processKeyActions == null) throw new SystemException("Process parameter had no keyactions");
            p.active = true;
            if (Temporary)
            {
                if (TemporaryProcess != p)
                {
                    //remove current temporary process and reinstate the keybinds it had replaced when it was added
                    RemoveTemporaryProcess(pm);

                    ReplacedBundles[p] = new List<Tuple<KeyBundle, KeyAction>>();
                    foreach (KeyAction a in p.processKeyActions.Keys)
                    {

                        //store previous keyaction in replacedbundles
                        if (Keybinds.ContainsKey(p.processKeyActions[a]))
                        {
                            ReplacedBundles[p].Add(new Tuple<KeyBundle, KeyAction>(p.processKeyActions[a], Keybinds[p.processKeyActions[a]]));
                        }
                        //insert new keybind
                        Keybinds[p.processKeyActions[a]] = a;
                    }
                    TemporaryProcess = p;
                    if (!pm.activeProcesses.Contains(p))
                        pm.activeProcesses.Add(p);
                }
            }
            else //permanent process
            {
                if (!PermanentProcesses.Contains(p))
                {
                    PermanentProcesses.Add(p);
                    foreach (KeyAction a in p.processKeyActions.Keys)
                    {
                        //insert new keybind
                        Keybinds[p.processKeyActions[a]] = a;
                    }
                }
            }
            if (ui.sidebar != null) ui.sidebar.UpdateProcessView();
        }
Exemple #52
0
 private void txtWaistSize_Click(object sender, EventArgs e)
 {
     ProcessManager.KillProcessByName("TabTip");
     CustomNumKeyboard.GetInstance(sender).ShowDialog();
 }
        public void ctor_RainWorldGame(ProcessManager manager)
        {
            OriginalConstructor(manager);
            MonklandSteamManager.monklandUI = new UI.MonklandUI(Futile.stage);

            AbstractRoom thisRoom = this.world.GetAbstractRoom(this.overWorld.FIRSTROOM);


            if (thisRoom != null)
            {
                int num = thisRoom.index;

                foreach (AbstractCreature ac in session.Players)
                {
                    ac.Destroy();
                    this.world.GetAbstractRoom(ac.Room.index).RemoveEntity(ac);
                }

                foreach (AbstractPhysicalObject absPhys in thisRoom.entities)
                {
                    patch_AbstractPhysicalObject patch = absPhys as patch_AbstractPhysicalObject;

                    if (!MonklandSteamManager.ObjectManager.IsNetObject(patch))
                    {
                        patch.ownerID = NetworkGameManager.playerID;
                        MonklandSteamManager.ObjectManager.SendObjectCreation(patch);
                    }
                }

                session.Players.Clear();

                if (mainGame == null)
                {
                    mainGame = this;
                }

                ulong playerID = MonklandSteamManager.instance.allChannels[0].SendForcewaitPacket(0, (CSteamID)NetworkGameManager.managerID);

                Debug.Log("Player Count is " + session.Players.Count);

                if (this.IsStorySession)
                {
                    patch_AbstractCreature playerCreature = new AbstractCreature(this.world, StaticWorld.GetCreatureTemplate("Slugcat"), null, new WorldCoordinate(num, 15, 25, -1), new EntityID(-1, (int)playerID)) as patch_AbstractCreature;
                    playerCreature.state = new PlayerState(playerCreature, 0, this.GetStorySession.saveState.saveStateNumber, false);
                    this.world.GetAbstractRoom(playerCreature.pos.room).AddEntity(playerCreature);
                    if (this.session.Players.Count > 0)
                    {
                        this.session.Players.Insert(0, playerCreature);
                    }
                    else
                    {
                        this.session.Players.Add(playerCreature);
                    }

                    playerCreature.ownerIDNew = NetworkGameManager.playerID;
                    MonklandSteamManager.ObjectManager.SendObjectCreation(playerCreature);

                    MonklandUI.trackedPlayer = playerCreature;

                    this.cameras[0].followAbstractCreature = playerCreature;
                    this.roomRealizer.followCreature       = playerCreature;
                }
            }
        }
Exemple #54
0
        private void ButtonClick(object sender, EventArgs e)
        {
            if (sender == btnWebsite)
            {
                ProcessManager.OpenLink(Program.Website);
                return;
            }
            if (sender == btnRebuildReport)
            {
                StartWorker();
                return;
            }
            if (sender == btnOpenReport)
            {
                if (!ApplicationArguments.Instance.IsListenServer)
                {
                    Program.HtmlTemplate.OpenInDefaultBrowser();
                    return;
                }


                var ip = string.Format("http://{0}:{1}", Equals(ApplicationArguments.Instance.ListenServerIPEndPoint.Address, IPAddress.Any)
                    ? "127.0.0.1"
                    : ApplicationArguments.Instance.ListenServerIPEndPoint.Address.ToString(), ApplicationArguments.Instance.ListenServerIPEndPoint.Port);

                ProcessManager.OpenLink(ip);

                return;
            }
            if (sender == btnOpenFolder)
            {
                Program.HtmlTemplate.ShowInExplorer();

                return;
            }

            if (sender == btnListenServer)
            {
                if (ReferenceEquals(FrmServerOptions, null))
                {
                    FrmServerOptions = new FrmServerOptions();
                }

                if (FrmServerOptions.ShowDialog() == DialogResult.OK)
                {
                    ApplicationArguments.Instance.ListenServerIPEndPoint     = FrmServerOptions.IPEndPoint;
                    ApplicationArguments.Instance.ListenServerUpdateInterval = FrmServerOptions.UpdateInterval;
                    EnableListenServer();
                }

                return;
            }

            if (sender == btnExit || sender == cmTrayExit)
            {
                Application.Exit();
                return;
            }

            if (sender == cmTrayShow)
            {
                ShowForm();
                return;
            }
        }
Exemple #55
0
        public ActionResult ProcessItem_getItems()
        {
            var parameters = AjaxModel.GetParameters(HttpContext);
            var mng        = new ProcessManager();
            var items      = mng.GetProcessItems()
                             .AsQueryable()
                             .Skip(parameters.pageSize * (parameters.page - 1))
                             .Take(parameters.pageSize);
            //
            //var items = mng.GetSQLClients("GetCRMClients").AsQueryable();

            var sortName      = parameters.sort.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            var sortDirection = parameters.direction.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            if (sortName.Length > 0 & sortDirection.Length > 0)
            {
                for (int i = 0; i < sortName.Length; i++)
                {
                    if (i > 0)
                    {
                        items = items.ThenByField(sortName[i], (sortDirection[0] == "up"));
                    }
                    else
                    {
                        items = items.OrderByField(sortName[i], (sortDirection[0] == "up"));
                    }
                }
            }

            if (parameters.filter != null && parameters.filter.Count > 0)
            {
                if (parameters.filter.ContainsKey("name"))
                {
                    if (!string.IsNullOrWhiteSpace(parameters.filter["name"].ToString()))
                    {
                        items = items.Where(x => x.name.Contains(parameters.filter["name"].ToString()));
                    }
                }
                if (parameters.filter.ContainsKey("isFinish"))
                {
                    if (parameters.filter["isFinish"].ToString() != "-1")
                    {
                        items = items.Where(x => x.isFinish == Convert.ToBoolean(RDL.Convert.StrToInt(parameters.filter["isFinish"].ToString(), 0)));
                    }
                }
                if (parameters.filter.ContainsKey("roles"))
                {
                    string[] statusIDs;
                    statusIDs = (parameters.filter["roles"] as ArrayList).ToArray().Select(x => x.ToString()).ToArray();
                    if (statusIDs.Length != 0)
                    {
                        items = items.Where(x => SearchArrayPattern(statusIDs, x.roles.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)));
                    }
                }
                if (parameters.filter.ContainsKey("users"))
                {
                    string[] statusIDs;
                    statusIDs = (parameters.filter["users"] as ArrayList).ToArray().Select(x => x.ToString()).ToArray();
                    if (statusIDs.Length != 0)
                    {
                        items = items.Where(x => SearchArrayPattern(statusIDs, x.users.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)));
                    }
                }
                if (parameters.filter.ContainsKey("processID"))
                {
                    if (parameters.filter["processID"].ToString() != "0")
                    {
                        items = items.Where(x => x.proc_processes.id == RDL.Convert.StrToInt(parameters.filter["processID"].ToString(), 0));
                    }
                }
            }

            /* ==================================================
             * if (parameters.filter != null && parameters.filter.Count > 0)
             * {
             *  var text = parameters.filter.ContainsKey("text") ? parameters.filter["text"].ToString() : "";
             *
             *  var sourceID = parameters.filter.ContainsKey("sourceName") ? RDL.Convert.StrToInt(parameters.filter["sourceName"].ToString(), 0) : 0;
             *  items = items.Where(x => (sourceID == 0 || x.sourceID == sourceID));
             *
             *  List<int?> statusIDs = new List<int?>();
             *  if (parameters.filter.ContainsKey("statusName"))
             *  {
             *      statusIDs = (parameters.filter["statusName"] as ArrayList).ToArray().Select(x => (int?)RDL.Convert.StrToInt(x.ToString(), 0)).ToList();
             *  }
             *  items = items.Where(x =>
             *      (statusIDs.Count == 0 || statusIDs.Contains(x.statusID))
             *  );
             *
             *
             *  var needActive = parameters.filter.ContainsKey("needActive") ? RDL.Convert.StrToInt(parameters.filter["needActive"].ToString(), -1) : -1;
             *  items = items.Where(x =>
             *      //фильтр в этом месте не срабатывает для needActive=NULL
             *      (needActive == -1 || x.needActive == (needActive == 1 ? true : false))
             *  );
             *
             *  DateTime nextContactMin = DateTime.MinValue, nextContactMax = DateTime.MaxValue;
             *  if (parameters.filter.ContainsKey("nextContact") && parameters.filter["nextContact"] != null)
             *  {
             *      var dates = parameters.filter["nextContact"].ToString().Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
             *      if (dates.Length > 0)
             *      {
             *          nextContactMin = RDL.Convert.StrToDateTime(dates[0].Trim(), DateTime.MinValue);
             *      }
             *      if (dates.Length > 1)
             *      {
             *          nextContactMax = RDL.Convert.StrToDateTime(dates[1].Trim(), DateTime.MaxValue).AddDays(1);
             *      }
             *      items = items.Where(x =>
             *          (nextContactMin <= x.nextContact && x.nextContact <= nextContactMax));
             *  }
             *
             *  if (text != "")
             *  {
             *      items = items.ToList().Where(x =>
             *          x.fio != null && x.fio.IndexOf(text, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
             *          x.city != null && x.city.IndexOf(text, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
             *          x.note != null && x.note.IndexOf(text, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
             *          x.username != null && x.username.IndexOf(text, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
             *          x.addedBy != null && x.addedBy.IndexOf(text, StringComparison.CurrentCultureIgnoreCase) >= 0
             *          ).AsQueryable();
             *  }
             * }
             *
             * var sorts = parameters.sort.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
             * var directions = parameters.direction.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
             * var sort1 = sorts.Length > 0 ? sorts[0] : "";
             * var direction1 = directions.Length > 0 ? directions[0] : "";
             *
             * var sort2 = sorts.Length > 1 ? sorts[1] : "";
             * var direction2 = directions.Length > 1 ? directions[1] : "";
             *
             * IOrderedQueryable<crm_clients> orderedItems = items.OrderByDescending(p => p.created);
             *
             * switch (sort1)
             * {
             *  case "fio":
             *      if (direction1 == "up") orderedItems = items.OrderBy(x => x.fio);
             *      else orderedItems = items.OrderByDescending(x => x.fio);
             *      break;
             *  case "city":
             *      if (direction1 == "up") orderedItems = items.OrderBy(x => x.city);
             *      else orderedItems = items.OrderByDescending(x => x.city);
             *      break;
             *  case "note":
             *      if (direction1 == "up") orderedItems = items.OrderBy(x => x.note);
             *      else orderedItems = items.OrderByDescending(x => x.note);
             *      break;
             *  case "addedBy":
             *      if (direction1 == "up") orderedItems = items.OrderBy(x => x.addedBy);
             *      else orderedItems = items.OrderByDescending(x => x.addedBy);
             *      break;
             *  case "statusName":
             *      if (direction1 == "up") orderedItems = items.OrderBy(x => x.crm_clientStatuses.name);
             *      else orderedItems = items.OrderByDescending(x => x.crm_clientStatuses.name);
             *      break;
             *  case "sourceName":
             *      if (direction1 == "up") orderedItems = items.OrderBy(x => x.crm_sources.name);
             *      else orderedItems = items.OrderByDescending(x => x.crm_sources.name);
             *      break;
             *  case "subchannel":
             *      if (direction1 == "up") orderedItems = items.OrderBy(x => x.subchannel);
             *      else orderedItems = items.OrderByDescending(x => x.subchannel);
             *      break;
             *  case "username":
             *      if (direction1 == "up") orderedItems = items.OrderBy(x => x.username);
             *      else orderedItems = items.OrderByDescending(x => x.username);
             *      break;
             *  case "needActive":
             *      if (direction1 == "up") orderedItems = items.OrderBy(x => x.needActive);
             *      else orderedItems = items.OrderByDescending(x => x.needActive);
             *      break;
             *  case "nextContact":
             *      if (direction1 == "up") orderedItems = items.OrderBy(x => x.nextContact);
             *      else orderedItems = items.OrderByDescending(x => x.nextContact);
             *      break;
             *
             *  default:
             *      if (direction1 == "up") orderedItems = items.OrderBy(x => x.created);
             *      else orderedItems = items.OrderByDescending(x => x.created);
             *      break;
             * }
             *
             * if (sort2 != "")
             * {
             *  switch (sort2)
             *  {
             *      case "fio":
             *          if (direction2 == "up") orderedItems = orderedItems.ThenBy(x => x.fio);
             *          else orderedItems = orderedItems.ThenByDescending(x => x.fio);
             *          break;
             *      case "city":
             *          if (direction2 == "up") orderedItems = orderedItems.ThenBy(x => x.city);
             *          else orderedItems = orderedItems.ThenByDescending(x => x.city);
             *          break;
             *      case "note":
             *          if (direction2 == "up") orderedItems = orderedItems.ThenBy(x => x.note);
             *          else orderedItems = orderedItems.ThenByDescending(x => x.note);
             *          break;
             *      case "addedBy":
             *          if (direction2 == "up") orderedItems = orderedItems.ThenBy(x => x.addedBy);
             *          else orderedItems = orderedItems.ThenByDescending(x => x.addedBy);
             *          break;
             *      case "statusName":
             *          if (direction2 == "up") orderedItems = orderedItems.ThenBy(x => x.crm_clientStatuses.name);
             *          else orderedItems = orderedItems.ThenByDescending(x => x.crm_clientStatuses.name);
             *          break;
             *      case "sourceName":
             *          if (direction2 == "up") orderedItems = orderedItems.ThenBy(x => x.crm_sources.name);
             *          else orderedItems = orderedItems.ThenByDescending(x => x.crm_sources.name);
             *          break;
             *      case "subchannel":
             *          if (direction2 == "up") orderedItems = orderedItems.ThenBy(x => x.subchannel);
             *          else orderedItems = orderedItems.ThenByDescending(x => x.subchannel);
             *          break;
             *      case "username":
             *          if (direction2 == "up") orderedItems = orderedItems.ThenBy(x => x.username);
             *          else orderedItems = orderedItems.ThenByDescending(x => x.username);
             *          break;
             *      case "needActive":
             *          if (direction2 == "up") orderedItems = orderedItems.ThenBy(x => x.needActive);
             *          else orderedItems = orderedItems.ThenByDescending(x => x.needActive);
             *          break;
             *      case "nextContact":
             *          if (direction2 == "up") orderedItems = orderedItems.ThenBy(x => x.nextContact);
             *          else orderedItems = orderedItems.ThenByDescending(x => x.nextContact);
             *          break;
             *
             *      default:
             *          if (direction2 == "up") orderedItems = orderedItems.ThenBy(x => x.created);
             *          else orderedItems = orderedItems.ThenByDescending(x => x.created);
             *          break;
             *  }
             * }
             *
             * var total = orderedItems.Count();
             * var res2 = orderedItems.Skip(parameters.pageSize * (parameters.page - 1)).Take(parameters.pageSize).ToList();
             */

            return(Json(new
            {
                items = items.Select(x => new
                {
                    x.id,
                    name = x.name ?? "",
                    isFinish = x.isFinish ? "Завершен" : "Активен",
                    roles = x.roles ?? "",
                    users = x.users ?? "",
                    processID = x.proc_processes != null ? x.proc_processes.name : ""
                }),
                total = items.Count <proc_processItems>()
            }, JsonRequestBehavior.AllowGet));
        }
    public void Start()
    {
        Awake();
        buildType = BuildType.Development;
        try
        {
            worldVersion = int.Parse(File.ReadAllText(string.Concat(new object[]
            {
                Custom.RootFolderDirectory(),
                Path.DirectorySeparatorChar,
                "World",
                Path.DirectorySeparatorChar,
                "worldVersion.txt"
            })));
        }
        catch
        {
        }
        gameVersion = 1;
        setup       = LoadSetupValues(buildType == BuildType.Distribution);
        options     = new Options();
        progression = new PlayerProgression(this, setup.loadProg);
        if (setup.singlePlayerChar != -1)
        {
            progression.miscProgressionData.currentlySelectedSinglePlayerSlugcat = setup.singlePlayerChar;
        }
        flatIllustrations = File.Exists(Custom.RootFolderDirectory() + "flatmode.txt");
        if (Screen.fullScreen != options.fullScreen || Screen.width != (int)options.ScreenSize.x || Screen.height != (int)options.ScreenSize.y)
        {
            Screen.SetResolution((int)options.ScreenSize.x, (int)options.ScreenSize.y, false);
            Screen.fullScreen = options.fullScreen;
        }
        if (buildType != BuildType.Development)
        {
            Screen.showCursor = !options.fullScreen;
        }
        else
        {
            Screen.showCursor = true;
        }
        if (!WorldChecksumController.ControlCheckSum(buildType))
        {
            Debug.Log("World Checksum INCORRECT!");
            progression.gameTinkeredWith = false;
        }
        FutileParams futileParams = new FutileParams(true, true, true, true);

        futileParams.AddResolutionLevel(options.ScreenSize.x, 1f, 1f, string.Empty);
        futileParams.origin = new Vector2(0f, 0f);
        Futile.instance.Init(futileParams);
        Futile.displayScale = 1f;
        persistentData      = new PersistentData(this);
        Shaders             = new Dictionary <string, FShader>();
        Shaders.Add("Basic", FShader.CreateShader("Basic", Shader.Find("Futile/Basic")));
        Shaders.Add("LevelColor", FShader.CreateShader("LevelColor", Shader.Find("Futile/LevelColor")));
        Shaders.Add("Background", FShader.CreateShader("Background", Shader.Find("Futile/Background")));
        Shaders.Add("WaterSurface", FShader.CreateShader("WaterSurface", Shader.Find("Futile/WaterSurface")));
        Shaders.Add("DeepWater", FShader.CreateShader("DeepWater", Shader.Find("Futile/DeepWater")));
        Shaders.Add("Shortcuts", FShader.CreateShader("ShortCut0", Shader.Find("Futile/ShortCut0")));
        Shaders.Add("DeathRain", FShader.CreateShader("DeathRain", Shader.Find("Futile/DeathRain")));
        Shaders.Add("LizardLaser", FShader.CreateShader("LizardLaser", Shader.Find("Futile/LizardLaser")));
        Shaders.Add("WaterLight", FShader.CreateShader("WaterLight", Shader.Find("Futile/WaterLight")));
        Shaders.Add("WaterFall", FShader.CreateShader("WaterFall", Shader.Find("Futile/WaterFall")));
        Shaders.Add("ShockWave", FShader.CreateShader("ShockWave", Shader.Find("Futile/ShockWave")));
        Shaders.Add("Smoke", FShader.CreateShader("Smoke", Shader.Find("Futile/Smoke")));
        Shaders.Add("Spores", FShader.CreateShader("Spores", Shader.Find("Futile/Spores")));
        Shaders.Add("Steam", FShader.CreateShader("Steam", Shader.Find("Futile/Steam")));
        Shaders.Add("ColoredSprite", FShader.CreateShader("ColoredSprite", Shader.Find("Futile/ColoredSprite")));
        Shaders.Add("ColoredSprite2", FShader.CreateShader("ColoredSprite2", Shader.Find("Futile/ColoredSprite2")));
        Shaders.Add("LightSource", FShader.CreateShader("LightSource", Shader.Find("Futile/LightSource")));
        Shaders.Add("LightBloom", FShader.CreateShader("LightBloom", Shader.Find("Futile/LightBloom")));
        Shaders.Add("SkyBloom", FShader.CreateShader("SkyBloom", Shader.Find("Futile/SkyBloom")));
        Shaders.Add("Adrenaline", FShader.CreateShader("Adrenaline", Shader.Find("Futile/Adrenaline")));
        Shaders.Add("CicadaWing", FShader.CreateShader("CicadaWing", Shader.Find("Futile/CicadaWing")));
        Shaders.Add("BulletRain", FShader.CreateShader("BulletRain", Shader.Find("Futile/BulletRain")));
        Shaders.Add("CustomDepth", FShader.CreateShader("CustomDepth", Shader.Find("Futile/CustomDepth")));
        Shaders.Add("UnderWaterLight", FShader.CreateShader("UnderWaterLight", Shader.Find("Futile/UnderWaterLight")));
        Shaders.Add("FlatLight", FShader.CreateShader("FlatLight", Shader.Find("Futile/FlatLight")));
        Shaders.Add("FlatLightBehindTerrain", FShader.CreateShader("FlatLightBehindTerrain", Shader.Find("Futile/FlatLightBehindTerrain")));
        Shaders.Add("VectorCircle", FShader.CreateShader("VectorCircle", Shader.Find("Futile/VectorCircle")));
        Shaders.Add("VectorCircleFadable", FShader.CreateShader("VectorCircleFadable", Shader.Find("Futile/VectorCircleFadable")));
        Shaders.Add("FlareBomb", FShader.CreateShader("FlareBomb", Shader.Find("Futile/FlareBomb")));
        Shaders.Add("Fog", FShader.CreateShader("Fog", Shader.Find("Futile/Fog")));
        Shaders.Add("WaterSplash", FShader.CreateShader("WaterSplash", Shader.Find("Futile/WaterSplash")));
        Shaders.Add("EelFin", FShader.CreateShader("EelFin", Shader.Find("Futile/EelFin")));
        Shaders.Add("EelBody", FShader.CreateShader("EelBody", Shader.Find("Futile/EelBody")));
        Shaders.Add("JaggedCircle", FShader.CreateShader("JaggedCircle", Shader.Find("Futile/JaggedCircle")));
        Shaders.Add("JaggedSquare", FShader.CreateShader("JaggedSquare", Shader.Find("Futile/JaggedSquare")));
        Shaders.Add("TubeWorm", FShader.CreateShader("TubeWorm", Shader.Find("Futile/TubeWorm")));
        Shaders.Add("LizardAntenna", FShader.CreateShader("LizardAntenna", Shader.Find("Futile/LizardAntenna")));
        Shaders.Add("TentaclePlant", FShader.CreateShader("TentaclePlant", Shader.Find("Futile/TentaclePlant")));
        Shaders.Add("LevelMelt", FShader.CreateShader("LevelMelt", Shader.Find("Futile/LevelMelt")));
        Shaders.Add("LevelMelt2", FShader.CreateShader("LevelMelt2", Shader.Find("Futile/LevelMelt2")));
        Shaders.Add("CoralCircuit", FShader.CreateShader("CoralCircuit", Shader.Find("Futile/CoralCircuit")));
        Shaders.Add("DeadCoralCircuit", FShader.CreateShader("DeadCoralCircuit", Shader.Find("Futile/DeadCoralCircuit")));
        Shaders.Add("CoralNeuron", FShader.CreateShader("CoralNeuron", Shader.Find("Futile/CoralNeuron")));
        Shaders.Add("Bloom", FShader.CreateShader("Bloom", Shader.Find("Futile/Bloom")));
        Shaders.Add("GravityDisruptor", FShader.CreateShader("GravityDisruptor", Shader.Find("Futile/GravityDisruptor")));
        Shaders.Add("GlyphProjection", FShader.CreateShader("GlyphProjection", Shader.Find("Futile/GlyphProjection")));
        Shaders.Add("BlackGoo", FShader.CreateShader("BlackGoo", Shader.Find("Futile/BlackGoo")));
        Shaders.Add("Map", FShader.CreateShader("Map", Shader.Find("Futile/Map")));
        Shaders.Add("MapAerial", FShader.CreateShader("MapMapAerial", Shader.Find("Futile/MapAerial")));
        Shaders.Add("MapShortcut", FShader.CreateShader("MapShortcut", Shader.Find("Futile/MapShortcut")));
        Shaders.Add("LightAndSkyBloom", FShader.CreateShader("LightAndSkyBloom", Shader.Find("Futile/LightAndSkyBloom")));
        Shaders.Add("SceneBlur", FShader.CreateShader("SceneBlur", Shader.Find("Futile/SceneBlur")));
        Shaders.Add("EdgeFade", FShader.CreateShader("EdgeFade", Shader.Find("Futile/EdgeFade")));
        Shaders.Add("HeatDistortion", FShader.CreateShader("HeatDistortion", Shader.Find("Futile/HeatDistortion")));
        Shaders.Add("Projection", FShader.CreateShader("Projection", Shader.Find("Futile/Projection")));
        Shaders.Add("SingleGlyph", FShader.CreateShader("SingleGlyph", Shader.Find("Futile/SingleGlyph")));
        Shaders.Add("DeepProcessing", FShader.CreateShader("DeepProcessing", Shader.Find("Futile/DeepProcessing")));
        Shaders.Add("Cloud", FShader.CreateShader("Cloud", Shader.Find("Futile/Cloud")));
        Shaders.Add("CloudDistant", FShader.CreateShader("CloudDistant", Shader.Find("Futile/CloudDistant")));
        Shaders.Add("DistantBkgObject", FShader.CreateShader("DistantBkgObject", Shader.Find("Futile/DistantBkgObject")));
        Shaders.Add("BkgFloor", FShader.CreateShader("BkgFloor", Shader.Find("Futile/BkgFloor")));
        Shaders.Add("House", FShader.CreateShader("House", Shader.Find("Futile/House")));
        Shaders.Add("DistantBkgObjectRepeatHorizontal", FShader.CreateShader("DistantBkgObjectRepeatHorizontal", Shader.Find("Futile/DistantBkgObjectRepeatHorizontal")));
        Shaders.Add("Dust", FShader.CreateShader("Dust", Shader.Find("Futile/Dust")));
        Shaders.Add("RoomTransition", FShader.CreateShader("RoomTransition", Shader.Find("Futile/RoomTransition")));
        Shaders.Add("VoidCeiling", FShader.CreateShader("VoidCeiling", Shader.Find("Futile/VoidCeiling")));
        Shaders.Add("FlatLightNoisy", FShader.CreateShader("FlatLightNoisy", Shader.Find("Futile/FlatLightNoisy")));
        Shaders.Add("VoidWormBody", FShader.CreateShader("VoidWormBody", Shader.Find("Futile/VoidWormBody")));
        Shaders.Add("VoidWormFin", FShader.CreateShader("VoidWormFin", Shader.Find("Futile/VoidWormFin")));
        Shaders.Add("VoidWormPincher", FShader.CreateShader("VoidWormPincher", Shader.Find("Futile/VoidWormPincher")));
        Shaders.Add("FlatWaterLight", FShader.CreateShader("FlatWaterLight", Shader.Find("Futile/FlatWaterLight")));
        Shaders.Add("WormLayerFade", FShader.CreateShader("WormLayerFade", Shader.Find("Futile/WormLayerFade")));
        Shaders.Add("OverseerZip", FShader.CreateShader("OverseerZip", Shader.Find("Futile/OverseerZip")));
        Shaders.Add("GhostSkin", FShader.CreateShader("GhostSkin", Shader.Find("Futile/GhostSkin")));
        Shaders.Add("GhostDistortion", FShader.CreateShader("GhostDistortion", Shader.Find("Futile/GhostDistortion")));
        Shaders.Add("GateHologram", FShader.CreateShader("GateHologram", Shader.Find("Futile/GateHologram")));
        Shaders.Add("OutPostAntler", FShader.CreateShader("OutPostAntler", Shader.Find("Futile/OutPostAntler")));
        Shaders.Add("WaterNut", FShader.CreateShader("WaterNut", Shader.Find("Futile/WaterNut")));
        Shaders.Add("Hologram", FShader.CreateShader("Hologram", Shader.Find("Futile/Hologram")));
        Shaders.Add("FireSmoke", FShader.CreateShader("FireSmoke", Shader.Find("Futile/FireSmoke")));
        Shaders.Add("HoldButtonCircle", FShader.CreateShader("HoldButtonCircle", Shader.Find("Futile/HoldButtonCircle")));
        Shaders.Add("GoldenGlow", FShader.CreateShader("GoldenGlow", Shader.Find("Futile/GoldenGlow")));
        Shaders.Add("ElectricDeath", FShader.CreateShader("ElectricDeath", Shader.Find("Futile/ElectricDeath")));
        Shaders.Add("VoidSpawnBody", FShader.CreateShader("VoidSpawnBody", Shader.Find("Futile/VoidSpawnBody")));
        Shaders.Add("SceneLighten", FShader.CreateShader("SceneLighten", Shader.Find("Futile/SceneLighten")));
        Shaders.Add("SceneBlurLightEdges", FShader.CreateShader("SceneBlurLightEdges", Shader.Find("Futile/SceneBlurLightEdges")));
        Shaders.Add("SceneRain", FShader.CreateShader("SceneRain", Shader.Find("Futile/SceneRain")));
        Shaders.Add("SceneOverlay", FShader.CreateShader("SceneOverlay", Shader.Find("Futile/SceneOverlay")));
        Shaders.Add("SceneSoftLight", FShader.CreateShader("SceneSoftLight", Shader.Find("Futile/SceneSoftLight")));
        Shaders.Add("HologramImage", FShader.CreateShader("HologramImage", Shader.Find("Futile/HologramImage")));
        Shaders.Add("HologramBehindTerrain", FShader.CreateShader("HologramBehindTerrain", Shader.Find("Futile/HologramBehindTerrain")));
        Shaders.Add("Decal", FShader.CreateShader("Decal", Shader.Find("Futile/Decal")));
        Shaders.Add("SpecificDepth", FShader.CreateShader("SpecificDepth", Shader.Find("Futile/SpecificDepth")));
        Shaders.Add("LocalBloom", FShader.CreateShader("LocalBloom", Shader.Find("Futile/LocalBloom")));
        Shaders.Add("MenuText", FShader.CreateShader("MenuText", Shader.Find("Futile/MenuText")));
        Shaders.Add("DeathFall", FShader.CreateShader("DeathFall", Shader.Find("Futile/DeathFall")));
        Shaders.Add("KingTusk", FShader.CreateShader("KingTusk", Shader.Find("Futile/KingTusk")));
        Shaders.Add("HoloGrid", FShader.CreateShader("HoloGrid", Shader.Find("Futile/HoloGrid")));
        Shaders.Add("SootMark", FShader.CreateShader("SootMark", Shader.Find("Futile/SootMark")));
        Shaders.Add("NewVultureSmoke", FShader.CreateShader("NewVultureSmoke", Shader.Find("Futile/NewVultureSmoke")));
        Shaders.Add("SmokeTrail", FShader.CreateShader("SmokeTrail", Shader.Find("Futile/SmokeTrail")));
        Shaders.Add("RedsIllness", FShader.CreateShader("RedsIllness", Shader.Find("Futile/RedsIllness")));
        Shaders.Add("HazerHaze", FShader.CreateShader("HazerHaze", Shader.Find("Futile/HazerHaze")));
        Shaders.Add("Rainbow", FShader.CreateShader("Rainbow", Shader.Find("Futile/Rainbow")));
        Shaders.Add("LightBeam", FShader.CreateShader("LightBeam", Shader.Find("Futile/LightBeam")));
        LoadResources();
        Shader.SetGlobalVector("_screenSize", screenSize);
        Shader.SetGlobalColor("_MapCol", MapColor);
        inGameTranslator = new InGameTranslator(this);
        processManager   = new ProcessManager(this);
    }
 private void ResetInstance()
 {
     this.Instance.Stop();
     _Instance = CreateInstance();
     this.Start();
 }
Exemple #58
0
        public static async Task Add(string videoPath)
        {
            var ff = new ProcessManager();
            var rc = new Recording();
            var sm = new SettingsManager();
            var rs = new RecordingSettings();

            using var sw = new StreamWriter(sm.GetFilePath("PastRecordings.json"), true);

            sm.GetSettings(rs);

            // Video Path
            rc.VideoPath = videoPath;

            // Thumbnail Path
            rc.ThumbPath = await VideoThumbnailer.Create(videoPath);

            // File Size
            rc.FileSize = new FileInfo(videoPath).Length;

            #region Get Infro from ffprobe (fps, duration)
            // Query ffprobe to get video duration and fps
            // https://trac.ffmpeg.org/wiki/FFprobeTips
            var info = await ff.StartProcess(
                $"-v error -select_streams v:0 -show_entries format=duration:stream=avg_frame_rate -of default=noprint_wrappers=1 \"{videoPath}\"",
                "ffprobe",
                true,
                true
                );

            // Loop over each line in response from ffprobe
            foreach (var line in info.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
            {
                // Get framerate
                if (line.ToLower().Contains("avg_frame_rate"))
                {
                    var fps = line.ToLower().Replace("avg_frame_rate=", "").Split("/");

                    // Check that fps contains more than 1 item, 2 are needed
                    if (fps.Count() > 1)
                    {
                        // Make sure fps[0 & 1] are able to be parsed
                        if (int.TryParse(fps[0], out int res0) && int.TryParse(fps[1], out int res1))
                        {
                            rc.FPS = (res0 / res1).ToString();
                        }
                    }
                }

                // Get duration
                if (line.ToLower().Contains("duration"))
                {
                    // Try parsing duration of video into float, if can't don't set any duration
                    if (float.TryParse(line.ToLower().Replace("duration=", ""), out var res))
                    {
                        // Convert duration in seconds to TimeSpan
                        var t = TimeSpan.FromSeconds(res);

                        #region Set Readable Duration
                        // If t.Days > 0, then set Duration to it and append Day(s) ...
                        // ... and skip rest of foreach iteration

                        if (t.Days > 0)
                        {
                            rc.Duration = (t.Days > 1) ? $"{t.Days} Days" : $"{t.Days} Day";
                            continue;
                        }

                        if (t.Hours > 0)
                        {
                            rc.Duration = (t.Hours > 1) ? $"{t.Hours} Hours" : $"{t.Hours} Hour";
                            continue;
                        }

                        if (t.Minutes > 0)
                        {
                            rc.Duration = (t.Minutes > 1) ? $"{t.Minutes} Minutes" : $"{t.Minutes} Minute";
                            continue;
                        }

                        if (t.Seconds > 0)
                        {
                            rc.Duration = (t.Seconds > 1) ? $"{t.Seconds} Seconds" : $"{t.Seconds} Second";
                            continue;
                        }

                        if (t.Milliseconds > 0)
                        {
                            rc.Duration = (t.Milliseconds > 1) ? $"{t.Milliseconds} Milliseconds" : $"{t.Milliseconds} Milliseconds";
                            continue;
                        }
                        #endregion
                    }
                }
            }
            #endregion

            // Serialize json from Recording object
            var json = (JObject)JToken.FromObject(rc);

            // If file is empty then append json normally, if it isn't then append json starting with a ','
            sw.Write((new FileInfo(sm.GetFilePath("PastRecordings.json")).Length == 0) ? json.ToString() : $",{json}");
            sw.Close();
        }
 public override void SetConsoleCtrlHandler(ProcessManager.CtrlHandlerDelegate Handler)
 {
     // @todo: add mono support
 }
        private static void SlugcatSelectMenu_ctor(On.Menu.SlugcatSelectMenu.orig_ctor orig, SlugcatSelectMenu self, ProcessManager manager)
        {
            orig(self, manager);

            int saveSlot = self.manager.rainWorld.options.saveSlot;

            if (CustomWorldMod.saveProblems[saveSlot].AnyProblems)
            {
                bool   allNewGame = true;
                string errorText  = CustomWorldMod.Translate("Problems found in your save, please check the tab SaveAnalyzer in the config screen for more information.");
                for (int m = 0; m < self.slugcatPages.Length; m++)
                {
                    if (self.saveGameData[m] != null)
                    {
                        allNewGame = false;
                        break;
                    }
                }
                if (allNewGame)
                {
                    errorText = CustomWorldMod.Translate("Problems found in your save, please use the Reset Progress button in the RW options menu");
                }

                MenuLabel menuLabel = new MenuLabel(self, self.pages[0],
                                                    errorText,
                                                    new Vector2(self.manager.rainWorld.options.ScreenSize.x * 0.5f, self.manager.rainWorld.options.ScreenSize.y * 0.85f),
                                                    new Vector2(0, 0), false);

                menuLabel.label.color     = new Color((108f / 255f), 0.001f, 0.001f);
                menuLabel.label.alignment = FLabelAlignment.Center;

                self.pages[0].subObjects.Add(menuLabel);
            }
        }