public override void Execute(Level level)
        {
            if (level.Avatar.AccountPrivileges >= GetRequiredAccountPrivileges())
            {
                if (m_vArgs.Length >= 1)
                {
                    ClientAvatar avatar = level.Avatar;
                    var          mail   = new AllianceMailStreamEntry();
                    mail.ID = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                    mail.SetSender(avatar);
                    mail.IsNew             = 2;
                    mail.AllianceId        = 0;
                    mail.AllianceBadgeData = 1526735450;
                    mail.AllianceName      = "UCS Server Information";
                    mail.Message           = @"Online Players: " + ResourcesManager.m_vOnlinePlayers.Count +
                                             "\nIn Memory Players: " + ResourcesManager.m_vInMemoryLevels.Count +
                                             "\nConnected Players: " + ResourcesManager.GetConnectedClients().Count +
                                             "\nServer Ram: " + Performances.GetUsedMemory() + "% / " + Performances.GetTotalMemory() + "MB";

                    var p = new AvatarStreamEntryMessage(level.Client);
                    p.SetAvatarStreamEntry(mail);
                    Processor.Send(p);
                }
            }
            else
            {
                SendCommandFailedMessage(level.Client);
            }
        }
Example #2
0
        void ExecuteLoadItemsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            try
            {
                Performances.Clear();
                var items = Event.Performances;
                foreach (var item in items)
                {
                    Performances.Add(item);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
Example #3
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Name,ShowId,Date")] Performances performances)
        {
            if (id != performances.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(performances);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PerformancesExists(performances.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(performances));
        }
Example #4
0
        public Dictionary <DayOfWeek, ActivityState> PerformanceStatus(DateTime relativeTo)
        {
            Dictionary <DayOfWeek, ActivityState> ret = new Dictionary <DayOfWeek, ActivityState>();

            foreach (DayOfWeek day in Enum.GetValues(typeof(DayOfWeek)))
            {
                ActivityState state = ActivityState.NotScheduled;

                var performancesThisWeek = Performances.Where(d => d.IsBetweenDates(Util.StartOfWeek(relativeTo), Util.EndOfWeek(relativeTo)));

                if (DaysPerformedList.Contains(day))
                {
                    state = day < relativeTo.DayOfWeek ? ActivityState.PastDue : ActivityState.Upcoming;
                }

                if (performancesThisWeek.Any(d => d.WhenPerformed.DayOfWeek == day))
                {
                    state = ActivityState.Completed;
                }

                ret.Add(day, state);
            }

            return(ret);
        }
Example #5
0
        public override void Execute(Level level)
        {
            if (level.GetAccountPrivileges() >= GetRequiredAccountPrivileges())
            {
                if (m_vArgs.Length >= 1)
                {
                    var avatar = level.GetPlayerAvatar();
                    var mail   = new AllianceMailStreamEntry();
                    mail.SetId((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
                    mail.SetSenderId(avatar.GetId());
                    mail.SetSenderAvatarId(avatar.GetId());
                    mail.SetSenderName(avatar.GetAvatarName());
                    mail.SetIsNew(2);
                    mail.SetAllianceId(0);
                    mail.SetAllianceBadgeData(1526735450);
                    mail.SetAllianceName("UCS Server Information");
                    mail.SetMessage(@"Online Players: " + ResourcesManager.GetOnlinePlayers().Count +
                                    "\nIn Memory Players: " + ResourcesManager.GetInMemoryLevels().Count +
                                    "\nConnected Players: " + ResourcesManager.GetConnectedClients().Count +
                                    "\nServer Ram: " + Performances.GetUsedMemory() + "% / " + Performances.GetTotalMemory() + "MB"
                                    );

                    mail.SetSenderLevel(avatar.GetAvatarLevel());
                    mail.SetSenderLeagueId(avatar.GetLeagueId());

                    var p = new AvatarStreamEntryMessage(level.GetClient());
                    p.SetAvatarStreamEntry(mail);
                    PacketProcessor.Send(p);
                }
            }
            else
            {
                SendCommandFailedMessage(level.GetClient());
            }
        }
Example #6
0
 public DynamicJsonValue ToJson()
 {
     return(new DynamicJsonValue
     {
         [nameof(Environments)] = new DynamicJsonArray(Environments.Select(x => x.ToJson())),
         [nameof(Performances)] = new DynamicJsonArray(Performances.Select(x => x.ToJson()))
     });
 }
Example #7
0
 private static void InsertTestData()
 {
     Performances.Record(MethodBase.GetCurrentMethod().Name);
     Functions.SqlServer.TestData.Insert();
     Consoles.Write(
         DisplayAccessor.Displays.Get("CodeDefinerInsertTestDataCompleted"),
         Consoles.Types.Success);
     Performances.Record(MethodBase.GetCurrentMethod().Name);
 }
Example #8
0
 private static void CreateCssCode()
 {
     Performances.Record(MethodBase.GetCurrentMethod().Name);
     Functions.Web.Styles.CssCreator.Create();
     Consoles.Write(
         DisplayAccessor.Displays.Get("CodeDefinerCssCompleted"),
         Consoles.Types.Success);
     Performances.Record(MethodBase.GetCurrentMethod().Name);
 }
Example #9
0
 private static void CreateSolutionBackup()
 {
     Performances.Record(MethodBase.GetCurrentMethod().Name);
     Functions.CodeDefiner.BackupCreater.BackupSolutionFiles();
     Consoles.Write(
         DisplayAccessor.Displays.Get("CodeDefinerBackupCompleted"),
         Consoles.Types.Success);
     Performances.Record(MethodBase.GetCurrentMethod().Name);
 }
Example #10
0
 private static void CreateMvcCode(string target)
 {
     Performances.Record(MethodBase.GetCurrentMethod().Name);
     Functions.AspNetMvc.CSharp.MvcCreator.Create(target);
     Consoles.Write(
         DisplayAccessor.Displays.Get("CodeDefinerMvcCompleted"),
         Consoles.Types.Success);
     Performances.Record(MethodBase.GetCurrentMethod().Name);
 }
Example #11
0
 private static void ConfigureDatabase()
 {
     TryOpenConnections();
     Performances.Record(MethodBase.GetCurrentMethod().Name);
     Functions.SqlServer.Configurator.Configure();
     Consoles.Write(
         DisplayAccessor.Displays.Get("CodeDefinerRdsCompleted"),
         Consoles.Types.Success);
     Performances.Record(MethodBase.GetCurrentMethod().Name);
 }
Example #12
0
        protected void LoadDraft(int id)
        {
            PerformanceJson performanceJson = Performances.Where(p => p.Id == id).FirstOrDefault();

            // Use the Deserializer method of the JsonSerializer class (in the System.Text.Json namespace) to create
            // a Performance object
            Performance performance = JsonSerializer.Deserialize <Performance>(performanceJson.PerformanceContent);

            // Populate Performance service fields
            Performance.Id                  = performance.Id;
            Performance.Nickname            = performance.Nickname;
            Performance.Style               = performance.Style;
            Performance.StyleOther          = performance.StyleOther;
            Performance.AssociationDropDown = performance.AssociationDropDown;
            Performance.AssociationFreeForm = performance.AssociationFreeForm;
            Performance.Date                = performance.Date;
            Performance.Distributed         = performance.Distributed;
            Performance.Location            = performance.Location;
            Performance.County              = performance.County;
            Performance.Address             = performance.Address;
            Performance.Tenor               = performance.Tenor;
            Performance.Platform            = performance.Platform;
            Performance.Time                = performance.Time;
            Performance.ImportFromCompLib   = performance.ImportFromCompLib;
            Performance.CompLibId           = performance.CompLibId;
            Performance.Length              = performance.Length;
            Performance.Title               = performance.Title;
            Performance.Composer            = performance.Composer;
            Performance.Detail              = performance.Detail;

            Performance.NumRingers           = performance.NumRingers;
            Performance.BellsPerRinger       = performance.BellsPerRinger;
            Performance.AdditionalRingerInfo = performance.AdditionalRingerInfo;

            Performance.Ringers.Clear();

            foreach (RingerData ringerData in performance.Ringers)
            {
                Performance.Ringers.Add(ringerData);
            }

            Performance.NewMethodsNamed = performance.NewMethodsNamed;

            Performance.NewMethods.Clear();

            foreach (NewMethodData newMethodData in performance.NewMethods)
            {
                Performance.NewMethods.Add(newMethodData);
            }

            Performance.Footnotes      = performance.Footnotes;
            Performance.NormDepartures = performance.NormDepartures;

            NavManager.NavigateTo("/preview");
        }
Example #13
0
        /// <summary>
        /// Called at the end of the database Initialiser and used to repair and/or upgrade the database
        /// Note this method must contain re-runnable code as it executes at every app startup
        /// </summary>
        public void UpgradeContent()
        {
            foreach (var track in Tracks.Where(t => t.AlphamericTitle == null))
            {
                log.Warning($"track {track.Title} [T-{track.Id}] has no alphameric text");
                track.AlphamericTitle = track.Title.ToAlphaNumerics().ToLower();
            }
            foreach (var work in Works.Where(w => w.AlphamericName == null))
            {
                log.Warning($"work {work.Name} [W-{work.Id}] has no alphameric text");
                work.AlphamericName = work.Name.ToAlphaNumerics().ToLower();
            }
            foreach (var performance in Performances.Where(w => w.AlphamericPerformers == null))
            {
                log.Warning($"performance {performance.Performers} [P-{performance.Id}] has no alphameric text");
                performance.AlphamericPerformers = performance.Performers.ToAlphaNumerics().ToLower();
            }
            foreach (var composition in Compositions.Where(w => w.AlphamericName == null))
            {
                log.Warning($"composition {composition.Name} [C-{composition.Id}] has no alphameric text");
                composition.AlphamericName = composition.Name.ToAlphaNumerics().ToLower();
            }


            var toBeRemoved = TaskItems.Where(x => x.Type != TaskType.ResampleWork).ToList();

            toBeRemoved.AddRange(TaskItems.Where(x => x.Status == Core.TaskStatus.Finished || x.Status == Core.TaskStatus.Failed));
            TaskItems.RemoveRange(toBeRemoved);
            log.Information($"{toBeRemoved.Count()} task items removed");
            TaskItems.ToList().ForEach(x => x.Status = Core.TaskStatus.Pending);
            SaveChanges();
//#if DEBUG
//            var allItems = TaskItems.ToArray();
//            TaskItems.RemoveRange(allItems);
//            log.Warning($"{allItems.Count()} task items removed");
//#else
//            var staleTaskItemDate = DateTimeOffset.Now - TimeSpan.FromDays(5);
//            foreach (var item in TaskItems.Where(t => t.CreatedAt < staleTaskItemDate).ToArray())
//            {
//                switch(item.Status)
//                {
//                    case Core.TaskStatus.Finished:
//                        break;
//                    case Core.TaskStatus.Failed:
//                        log.Warning($"Task {item.Type} created on {item.CreatedAt.ToDefaultWithTime()} for {item.TaskString} failed - removed");
//                        break;
//                    default:
//                        log.Warning($"Task {item.Type} created on {item.CreatedAt.ToDefaultWithTime()} for {item.TaskString}, status {item.Status} - removed");
//                        break;
//                }
//                TaskItems.Remove(item);
//            }
//#endif
//            SaveChanges();
        }
Example #14
0
 private void Handler(string type)
 {
     try
     {
         if (type == "inmemclans")
         {
             jsonapp = Convert.ToString(ObjectManager.GetInMemoryAlliances().Count);
         }
         else if (type == "inmemplayers")
         {
             jsonapp = Convert.ToString(ResourcesManager.GetInMemoryLevels().Count);
         }
         else if (type == "onlineplayers")
         {
             jsonapp = Convert.ToString(ResourcesManager.GetOnlinePlayers().Count);
         }
         else if (type == "totalclients")
         {
             jsonapp = Convert.ToString(ResourcesManager.GetConnectedClients().Count);
         }
         else if (type == "all")
         {
             var json = new JsonApi
             {
                 UCS = new Dictionary <string, string>
                 {
                     { "PatchingServer", ConfigurationManager.AppSettings["patchingServer"] },
                     { "Maintenance", ConfigurationManager.AppSettings["maintenanceMode"] },
                     { "MaintenanceTimeLeft", ConfigurationManager.AppSettings["maintenanceTimeLeft"] },
                     { "ClientVersion", ConfigurationManager.AppSettings["clientVersion"] },
                     { "ServerVersion", Assembly.GetExecutingAssembly().GetName().Version.ToString() },
                     { "OnlinePlayers", Convert.ToString(ResourcesManager.GetOnlinePlayers().Count) },
                     { "InMemoryPlayers", Convert.ToString(ResourcesManager.GetInMemoryLevels().Count) },
                     { "InMemoryClans", Convert.ToString(ObjectManager.GetInMemoryAlliances().Count) },
                     { "TotalConnectedClients", Convert.ToString(ResourcesManager.GetConnectedClients().Count) }
                 }
             };
             jsonapp = JsonConvert.SerializeObject(json);
             mime    = "application/json";
         }
         else if (type == "ram")
         {
             jsonapp = Performances.GetUsedMemory();
         }
         else
         {
             jsonapp = "OK";
         }
     }
     catch (Exception ex)
     {
         jsonapp = "An exception occured in UCS : \n" + ex;
     }
 }
Example #15
0
        public async Task <IActionResult> Create([Bind("Id,Name,ShowId,Date")] Performances performances)
        {
            if (ModelState.IsValid)
            {
                _context.Add(performances);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(performances));
        }
Example #16
0
 private static void TestPerformance(int loopCount, params Action[] actionCollection)
 {
     actionCollection
     .Select((o, i) => new { Count = i + 1, Action = o })
     .ForEach(data =>
     {
         Performances.Record("Action:" + data.Count);
         for (int count = 1; count <= loopCount; count++)
         {
             data.Action();
         }
         Performances.Record("Action:" + data.Count);
     });
 }
Example #17
0
        public override void Execute(Level level)
        {
            if (level.Avatar.AccountPrivileges >= GetRequiredAccountPrivileges())
            {
                if (m_vArgs.Length >= 1)
                {
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor");
                    var cpuTimes = searcher.Get()
                                   .Cast <ManagementObject>()
                                   .Select(mo => new
                    {
                        Name  = mo["Name"],
                        Usage = mo["PercentProcessorTime"]
                    }
                                           )
                                   .ToList();
                    var query         = cpuTimes.Where(x => x.Name.ToString() == "_Total").Select(x => x.Usage);
                    var CPUParcentage = query.SingleOrDefault();
                    RAMUsage       = PerformanceInfo.GetTotalMemoryInMiB() - PerformanceInfo.GetPhysicalAvailableMemoryInMiB();
                    DriveLetter    = Path.GetPathRoot(Directory.GetCurrentDirectory());
                    DiskSpace      = new DriveInfo(DriveLetter.Substring(0, DriveLetter.Length - 2));
                    TotalFreeSpace = DiskSpace.TotalFreeSpace / 1073741824;
                    TotalDiskSize  = DiskSpace.TotalSize / 1073741824;
                    DiskspaceUsed  = TotalDiskSize - TotalFreeSpace;
                    ClientAvatar avatar = level.Avatar;
                    var          mail   = new AllianceMailStreamEntry();
                    mail.ID = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                    mail.SetSender(avatar);
                    mail.IsNew             = 2;
                    mail.AllianceId        = 0;
                    mail.AllianceBadgeData = 1526735450;
                    mail.AllianceName      = "UCS Server Information";
                    mail.Message           = @"Online Players: " + ResourcesManager.m_vOnlinePlayers.Count +
                                             "\nIn Memory Players: " + ResourcesManager.m_vInMemoryLevels.Count +
                                             "\nConnected Players: " + ResourcesManager.GetConnectedClients().Count +
                                             "\nTotal System CPU Usage: " + CPUParcentage + "%" +
                                             "\nServer RAM: " + Performances.GetUsedMemory() + "% / " + Performances.GetTotalMemory() + "MB" +
                                             "\nTotal Server Ram Usage: " + RAMUsage + "MB / " + Performances.GetTotalMemory() + "MB" +
                                             "\nServer Disk Space Used: " + Math.Round(DiskspaceUsed, 2) + "GB / " + Math.Round(TotalDiskSize, 2) + "GB";

                    var p = new AvatarStreamEntryMessage(level.Client);
                    p.SetAvatarStreamEntry(mail);
                    Processor.Send(p);
                }
            }
            else
            {
                SendCommandFailedMessage(level.Client);
            }
        }
        protected override void ExecuteInsertPerformanceCommand(string[] commandWords)
        {
            switch (commandWords[2])
            {
            case "theatre":
                var venue   = GetVenue(commandWords[5]);
                var theatre = new Theatre(commandWords[3], decimal.Parse(commandWords[4]), venue, DateTime.Parse(commandWords[6] + " " + commandWords[7]));
                Performances.Add(theatre);
                break;

            case "concert":
                var venue2  = GetVenue(commandWords[5]);
                var concert = new Concert(commandWords[3], decimal.Parse(commandWords[4]), venue2, DateTime.Parse(commandWords[6] + " " + commandWords[7]));
                Performances.Add(concert);
                break;

            default:
                base.ExecuteInsertPerformanceCommand(commandWords);
                break;
            }
        }
        public static void Main(string[] args)
        {
            Directory.CreateDirectory(".\\logs");
            var logName = $".\\logs\\Implem.CodeDefiner_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.log";

            Trace.Listeners.Add(new TextWriterTraceListener(logName));
            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
            AppDomain.CurrentDomain.UnhandledException += (_, e) =>
            {
                if (e.ExceptionObject is SqlException sqlException)
                {
                    Consoles.Write($"UnhandledException: [{sqlException.Number}] {sqlException.Message}", Consoles.Types.Error, true);
                }
                else
                {
                    Consoles.Write("UnhandledException: " + e.ExceptionObject, Consoles.Types.Error, true);
                }
            };
            var argList = args.Select(o => o.Trim());

            ValidateArgs(argList);
            var argHash = new TextData(argList.Skip(1).Join(string.Empty), '/', 1);
            var action  = args[0];
            var path    = argHash.Get("p")?.Replace('\\', System.IO.Path.DirectorySeparatorChar);
            var target  = argHash.Get("t");

            Initializer.Initialize(
                path,
                assemblyVersion: Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                codeDefiner: true,
                setSaPassword: argHash.ContainsKey("s"),
                setRandomPassword: argHash.ContainsKey("r"));
            Performances.Record(MethodBase.GetCurrentMethod().Name);
            DeleteTemporaryFiles();
            switch (action)
            {
            case "_rds":
                ConfigureDatabase();
                break;

            case "rds":
                ConfigureDatabase();
                CreateDefinitionAccessorCode();
                CreateMvcCode(target);
                break;

            case "_def":
                CreateDefinitionAccessorCode();
                break;

            case "def":
                CreateDefinitionAccessorCode();
                CreateMvcCode(target);
                break;

            case "mvc":
                CreateMvcCode(target);
                break;

            case "css":
                CreateCssCode();
                break;

            case "backup":
                CreateSolutionBackup();
                break;

            default:
                WriteErrorToConsole(args);
                break;
            }
            Performances.Record(MethodBase.GetCurrentMethod().Name);
            Performances.PerformanceCollection.Save(Directories.Logs());
            if (Consoles.ErrorCount > 0)
            {
                Consoles.Write(
                    string.Format(DisplayAccessor.Displays.Get("CodeDefinerErrorCount"),
                                  Consoles.ErrorCount,
                                  Path.GetFullPath(logName)),
                    Consoles.Types.Error);
            }
            else
            {
                Consoles.Write(
                    DisplayAccessor.Displays.Get("CodeDefinerCompleted"),
                    Consoles.Types.Success);
            }
            WaitConsole(args);
        }
Example #20
0
        static ParserThread()
        {
            T = new Thread((ThreadStart)(() =>
            {
                while (true)
                {
                    string entry = Console.ReadLine().ToLower();
                    switch (entry)
                    {
                    case "/help":
                        Print("------------------------------------------------------------------------------>");
                        Say("/status            - Shows the actual UCS status.");
                        Say("/clear             - Clears the console screen.");
                        Say("/gui               - Shows the UCS Graphical User Interface.");
                        Say("/restart           - Restarts UCS instantly.");
                        Say("/shutdown          - Shuts UCS down instantly.");
                        Say("/banned            - Writes all Banned IP's into the Console.");
                        Say("/addip             - Add an IP to the Blacklist");
                        Say("/maintenance       - Begin Server Maintenance.");
                        Say("/saveall           - Saves everything in memory to the Database");
                        Say("/dl csv            - Downloads latest CSV Files (if Fingerprint is up to Date).");
                        Say("/info              - Shows the UCS Informations.");
                        Say("/info 'command'    - More Info On a Command. Ex: /info gui");
                        Print("------------------------------------------------------------------------------>");
                        break;

                    case "/info":
                        Console.WriteLine("------------------------------------->");
                        Say($"UCS Version:         {Constants.Version}");
                        Say($"Build:               {Constants.Build}");
                        Say($"LicenseID:           {Constants.LicensePlanID}");
                        Say($"CoC Version from SC: {VersionChecker.LatestCoCVersion()}");
                        Say($"Ultrapower  - {DateTime.Now.Year}");
                        Console.WriteLine("------------------------------------->");
                        break;

                    case "/dl csv":
                        CSVManager.DownloadLatestCSVFiles();
                        break;

                    case "/info dl csv":
                        Print("------------------------------------------------------------------------------>");
                        Say(@"/dl csv > Downloads COC Assets such as CSVs and if enabled:");
                        Say(@"     - Logic,");
                        Say(@"     - Sound Files ");
                        Say(@"     - SCs");
                        Print("------------------------------------------------------------------------------>");
                        break;

                    case "/banned":
                        Console.WriteLine("------------------------------------->");
                        Say("Banned IP Addresses:");
                        ConnectionBlocker.GetBannedIPs();
                        Console.WriteLine("------------------------------------->");
                        break;

                    case "/addip":
                        Console.WriteLine("------------------------------------->");
                        Console.Write("IP: ");
                        string s = Console.ReadLine();
                        ConnectionBlocker.AddNewIpToBlackList(s);
                        Console.WriteLine("------------------------------------->");
                        break;

                    case "/saveall":
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("----------------------------------------------------->");
                        Say($"Starting saving of all Players... ({ResourcesManager.m_vInMemoryLevels.Count})");
                        Resources.DatabaseManager.Save(ResourcesManager.m_vInMemoryLevels.Values.ToList()).Wait();
                        Say("Finished saving of all Players!");
                        Say($"Starting saving of all Alliances... ({ResourcesManager.GetInMemoryAlliances().Count})");
                        Resources.DatabaseManager.Save(ResourcesManager.GetInMemoryAlliances()).Wait();
                        Say("Finished saving of all Alliances!");
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("----------------------------------------------------->");
                        Console.ResetColor();
                        break;



                    case "/maintenance":
                        StartMaintenance();
                        break;

                    case "/info maintenance":
                        Print("------------------------------------------------------------------------------>");
                        Say(@"/maintenance > Enables Maintenance which will do the following:");
                        Say(@"     - All Online Users will be notified (Attacks will be disabled),");
                        Say(@"     - All new connections get a Maintenace Message at the Login. ");
                        Say(@"     - After 5min all Players will be kicked.");
                        Say(@"     - After the Maintenance Players will be able to connect again.");
                        Print("------------------------------------------------------------------------------>");
                        break;

                    case "/status":
                        Say($"Please wait retrieving Ultrapower Server status");
                        ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor");
                        var cpuTimes = searcher.Get()
                                       .Cast <ManagementObject>()
                                       .Select(mo => new
                        {
                            Name = mo["Name"],
                            Usage = mo["PercentProcessorTime"]
                        }
                                               )
                                       .ToList();
                        var query = cpuTimes.Where(x => x.Name.ToString() == "_Total").Select(x => x.Usage);
                        var CPUParcentage = query.SingleOrDefault();
                        Print("------------------------------------------------------->");
                        Say($"CPU Usage:                {CPUParcentage}%");
                        Say($"RAM Usage:                {Performances.GetUsedMemory()}%");
                        Say($"Time:                     {DateTime.Now}");
                        Say($"IP Address:               {Dns.GetHostByName(Dns.GetHostName()).AddressList[0]}");
                        Say($"Online Players:           {ResourcesManager.m_vOnlinePlayers.Count}");
                        Say($"Connected Players:        {ResourcesManager.GetConnectedClients().Count}");
                        Say($"In Memory Players:        {ResourcesManager.m_vInMemoryLevels.Values.ToList().Count}");
                        Say($"In Memory Alliances:      {ResourcesManager.GetInMemoryAlliances().Count}");
                        Say($"Client Version:           {ConfigurationManager.AppSettings["ClientVersion"]}");
                        Print("------------------------------------------------------->");
                        break;

                    case "/info status":
                        Print("----------------------------------------------------------------->");
                        Say(@"/status > Shows current state of server including:");
                        Say(@"     - Online Status");
                        Say(@"     - Server IP Address");
                        Say(@"     - Amount of Online Players");
                        Say(@"     - Amount of Connected Players");
                        Say(@"     - Amount of Players in Memory");
                        Say(@"     - Amount of Alliances in Memory");
                        Say(@"     - Clash of Clans Version.");
                        Print("----------------------------------------------------------------->");
                        break;

                    case "/clear":
                        Clear();
                        break;

                    case "/info shutdown":
                        Print("---------------------------------------------------------------------------->");
                        Say(@"/shutdown > Shuts Down UCS instantly after doing the following:");
                        Say(@"     - Throws all Players an 'Client Out of Sync Message'");
                        Say(@"     - Disconnects All Players From the Server");
                        Say(@"     - Saves all Players in Database");
                        Say(@"     - Shutsdown UCS.");
                        Print("---------------------------------------------------------------------------->");
                        break;

                    case "/gui":
                        Application.Run(new UCSUI());
                        break;

                    case "/info gui":
                        Print("------------------------------------------------------------------------------->");
                        Say(@"/gui > Starts the UCS Gui which includes many features listed here:");
                        Say(@"     - Status Controler/Manager");
                        Say(@"     - Player Editor");
                        Say(@"     - Config.UCS editor.");
                        Print("------------------------------------------------------------------------------->");
                        break;

                    case "/restart":
                        UCSControl.UCSRestart();
                        break;

                    case "/shutdown":
                        UCSControl.UCSClose();
                        break;

                    case "/info restart":
                        Print("---------------------------------------------------------------------------->");
                        Say(@"/restart > Restarts UCS instantly after doing the following:");
                        Say(@"     - Throws all Players an 'Client Out of Sync Message'");
                        Say(@"     - Disconnects All Players From the Server");
                        Say(@"     - Saves all Players in Database");
                        Say(@"     - Restarts UCS.");
                        Print("---------------------------------------------------------------------------->");
                        break;

                    default:
                        Say("Unknown command, type \"/help\" for a list containing all available commands.");
                        break;
                    }
                }
            }));
            T.Start();
        }
Example #21
0
        static void Main(string[] args)
        {
            // エンコードプロバイダーの登録が必要
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            var argList = args.Select(o => o.Trim());

            ValidateArgs(argList);
            var argHash = new TextData(argList.Skip(1).Join(string.Empty), '/', 1);
            var action  = args[0];
            var path    = argHash.Get("p");
            var target  = argHash.Get("t");

            Initializer.Initialize(
                path,
                assemblyVersion: Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                codeDefiner: true,
                setSaPassword: argHash.ContainsKey("s"),
                setRandomPassword: argHash.ContainsKey("r"));
            Performances.Record(MethodBase.GetCurrentMethod().Name);
            DeleteTemporaryFiles();
            switch (action)
            {
            case "_rds":
                ConfigureDatabase();
                break;

            case "rds":
                ConfigureDatabase();
                CreateDefinitionAccessorCode();
                CreateMvcCode(target);
                break;

            case "_def":
                CreateDefinitionAccessorCode();
                break;

            case "def":
                CreateDefinitionAccessorCode();
                CreateMvcCode(target);
                break;

            case "mvc":
                CreateMvcCode(target);
                break;

            case "css":
                CreateCssCode();
                break;

            case "backup":
                CreateSolutionBackup();
                break;

            default:
                WriteErrorToConsole(args);
                break;
            }
            Performances.Record(MethodBase.GetCurrentMethod().Name);
            Performances.PerformanceCollection.Save(Directories.Logs());
            Consoles.Write(
                DisplayAccessor.Displays.Get("CodeDefinerCompleted"),
                Consoles.Types.Success);
            WaitConsole(args);
        }
        //Load Items Asynchronious
        public void LoadItems()
        {
            IList <PerformanceVM> calculateModels = new List <PerformanceVM>();

            Performances.Clear();
            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += new DoWorkEventHandler((sender, args) =>
            {
                IList <Venue> venues = administrationService.GetVenues();
                foreach (Venue venue in venues)
                {
                    IList <Performance> performances = administrationService.GetPerformancesByVenueAndDay(venue, CurrentDate);
                    if (performances.Count > 4)
                    {
                        return;
                    }
                    DateTime d       = CurrentDate.Date;
                    Performance col1 = new Performance();
                    col1.StagingTime = d.AddHours(14);
                    Performance col2 = new Performance();
                    col2.StagingTime = d.AddHours(15);
                    Performance col3 = new Performance();
                    col3.StagingTime = d.AddHours(16);
                    Performance col4 = new Performance();
                    col4.StagingTime = d.AddHours(17);
                    Performance col5 = new Performance();
                    col5.StagingTime = d.AddHours(18);

                    foreach (Performance p in performances)
                    {
                        if (p.StagingTime.Hour >= 18)
                        {
                            col5 = p;
                        }
                        else if (p.StagingTime.Hour >= 17)
                        {
                            col4 = p;
                        }
                        else if (p.StagingTime.Hour >= 16)
                        {
                            col3 = p;
                        }
                        else if (p.StagingTime.Hour >= 15)
                        {
                            col2 = p;
                        }
                        else if (p.StagingTime.Hour >= 14)
                        {
                            col1 = p;
                        }
                    }

                    calculateModels.Add(new PerformanceVM(venue, col1, col2, col3, col4, col5, administrationService, this));
                }
            });
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, args) => {
                Performances.Clear();
                foreach (PerformanceVM vm in calculateModels)
                {
                    vm.GroupCheckBox();
                    Performances.Add(vm);
                }
                RaisePropertyChangedEvent(nameof(Performances));
            });
            worker.RunWorkerAsync(System.Reflection.Assembly.GetExecutingAssembly().Location);
        }
Example #23
0
        public virtual void CreateNextGeneration()
        {
            //rank population
            List <KeyValuePair <EvolutionalEntity <A>, float> > orderedPerformances = Performances.OrderBy(p => p.Value).Reverse().ToList();

            List <EvolutionalEntity <A> > populationAfterDeath = new List <EvolutionalEntity <A> >();

            //kill the weakest links and repopulate
            for (int i = 0; i < orderedPerformances.Count / 2; i++)
            {
                EvolutionalEntity <A> survivor = orderedPerformances[i].Key;

                for (int j = 0; j < 2; j++)
                {
                    EvolutionalEntity <A> child = survivor.CreateOffspring();
                    populationAfterDeath.Add(child);
                }
            }

            Population = populationAfterDeath;

            Generation++;
            Performances = new Dictionary <EvolutionalEntity <A>, float>();
            States       = new Dictionary <EvolutionalEntity <A>, S>();

            foreach (EvolutionalEntity <A> entity in Population)
            {
                States.Add(entity, DefaultState);
            }

            Ticks = 0;
        }
Example #24
0
        public override void Execute(Level level)
        {
            if (level.GetAccountPrivileges() >= GetRequiredAccountPrivileges())
            {
                if (m_vArgs.Length >= 1)
                {
                    _cpuCounter.NextValue(); //Always 0
                    var avatar = level.GetPlayerAvatar();
                    var mail   = new AllianceMailStreamEntry();
                    mail.SetId((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
                    mail.SetSenderId(avatar.GetId());
                    mail.SetSenderAvatarId(avatar.GetId());
                    mail.SetSenderName(avatar.GetAvatarName());
                    mail.SetIsNew(2);
                    mail.SetAllianceId(0);
                    mail.SetAllianceBadgeData(1526735450);
                    mail.SetAllianceName("UCS Server Information");
                    mail.SetMessage(@"Online Players: " + ResourcesManager.GetOnlinePlayers().Count +
                                    "\nIn Memory Players: " + ResourcesManager.GetInMemoryLevels().Count +
                                    "\nConnected Players: " + ResourcesManager.GetConnectedClients().Count +
                                                                                    //"\nUCS Ram: " + (Process.GetCurrentProcess().WorkingSet64 / 1048576) + "MB/" + //Unknown yet how to get properly
                                    "\nServer Ram: " + PerformanceInfo.GetPhysicalAvailableMemoryInMiB() + "MB/" + Performances.GetTotalMemory() + "MB" +
                                    "\nServer CPU " + _cpuCounter.NextValue() + "%" //Match Taskmanager
                                    );

                    mail.SetSenderLevel(avatar.GetAvatarLevel());
                    mail.SetSenderLeagueId(avatar.GetLeagueId());

                    var p = new AvatarStreamEntryMessage(level.GetClient());
                    p.SetAvatarStreamEntry(mail);
                    p.Send();
                }
            }
            else
            {
                SendCommandFailedMessage(level.GetClient());
            }
        }