public Racer(int id, string name, int age, int salary) { this.id = id; try { NameValidator validator = new NameValidator(name); validator.validation(); this.name = name; } catch (NameNotValidNameIsEmptyException e) { Debug.WriteLine(e.Message); throw new RacerException(e.Message + "\n" + name); } catch (NameNotValidFirstLetterProblemException e) { Debug.WriteLine(e.Message); throw new RacerException(e.Message + "\n" + name); } try { AgeValidator ageValidator = new AgeValidator(age); ageValidator.validation(); this.age = age; } catch (AgeIsZeroException e) { Debug.WriteLine(e.Message); throw new RacerException(e.Message + "\n" + age); } catch (AgeUnderMinimumAgeException e) { Debug.WriteLine(e.Message); throw new RacerException(e.Message + "\n" + age); } catch (AgeAboveMaximumAgeException e) { Debug.WriteLine(e.Message); throw new RacerException(e.Message + "\n" + age); } try { SalaryValidator salaryValidator = new SalaryValidator(salary); salaryValidator.validation(); this.salary = salary; } catch (SalaryZeroException e) { Debug.WriteLine(e.Message); throw new RacerException(e.Message + "\n" + salary); } catch (NegativeSalaryException e) { Debug.WriteLine(e.Message); throw new RacerException(e.Message + "\n" + salary); } catch (HighSalaryException e) { Debug.WriteLine(e.Message); throw new RacerException(e.Message + "\n" + salary); } }
internal static void ValidateTableName(string tableName) { NameValidator.ValidateTableName(tableName); }
internal static void ValidateBlobName(string blobName) { NameValidator.ValidateBlobName(blobName); }
public override string ToString() { var argsName = _args.Select(x => string.Format("{0} {1}", NameValidator.GetGenericTypeName(x.ArgType), x.ArgName)).ToArray(); return(string.Format("{0}({1})", _name, string.Join(" , ", argsName))); }
public void RejectInvalidSpacesInEmployeeName(string name) { var empNameVal = new NameValidator(); Assert.False(empNameVal.IsValid(name)); }
protected override void Initialize() { Logger.Log("Initializing GameClass."); string windowTitle = ClientConfiguration.Instance.WindowTitle; Window.Title = string.IsNullOrEmpty(windowTitle) ? string.Format("{0} Client", MainClientConstants.GAME_NAME_SHORT) : windowTitle; base.Initialize(); string primaryNativeCursorPath = ProgramConstants.GetResourcePath() + "cursor.cur"; string alternativeNativeCursorPath = ProgramConstants.GetBaseResourcePath() + "cursor.cur"; AssetLoader.Initialize(GraphicsDevice, content); AssetLoader.AssetSearchPaths.Add(ProgramConstants.GetResourcePath()); AssetLoader.AssetSearchPaths.Add(ProgramConstants.GetBaseResourcePath()); AssetLoader.AssetSearchPaths.Add(ProgramConstants.GamePath); #if !XNA && !WINDOWSGL // Try to create and load a texture to check for MonoGame 3.7.1 compatibility try { Texture2D texture = new Texture2D(GraphicsDevice, 100, 100, false, SurfaceFormat.Color); Color[] colorArray = new Color[100 * 100]; texture.SetData(colorArray); UISettings.ActiveSettings.CheckBoxClearTexture = AssetLoader.LoadTextureUncached("checkBoxClear.png"); } catch (Exception ex) { if (ex.Message.Contains("DeviceRemoved")) { Logger.Log("Creating texture on startup failed! Creating .dxfail file and re-launching client launcher."); if (!Directory.Exists(ProgramConstants.GamePath + "Client")) { Directory.CreateDirectory(ProgramConstants.GamePath + "Client"); } // Create .dxfail file that the launcher can check for this error // and handle it by redirecting the user to the XNA version instead File.WriteAllBytes(ProgramConstants.GamePath + "Client" + Path.DirectorySeparatorChar + ".dxfail", new byte[] { 1 }); string launcherExe = ClientConfiguration.Instance.LauncherExe; if (string.IsNullOrEmpty(launcherExe)) { // LauncherExe is unspecified, just throw the exception forward // because we can't handle it Logger.Log("No LauncherExe= specified in ClientDefinitions.ini! " + "Forwarding exception to regular exception handler."); throw ex; } else { Logger.Log("Starting " + launcherExe + " and exiting."); Process.Start(ProgramConstants.GamePath + launcherExe); Environment.Exit(0); } } } #endif InitializeUISettings(); WindowManager wm = new WindowManager(this, graphics); wm.Initialize(content, ProgramConstants.GetBaseResourcePath()); SetGraphicsMode(wm); wm.SetIcon(ProgramConstants.GetBaseResourcePath() + "clienticon.ico"); wm.SetControlBox(true); wm.Cursor.Textures = new Texture2D[] { AssetLoader.LoadTexture("cursor.png"), AssetLoader.LoadTexture("waitCursor.png") }; if (File.Exists(primaryNativeCursorPath)) { wm.Cursor.LoadNativeCursor(primaryNativeCursorPath); } else if (File.Exists(alternativeNativeCursorPath)) { wm.Cursor.LoadNativeCursor(alternativeNativeCursorPath); } Components.Add(wm); string playerName = UserINISettings.Instance.PlayerName.Value.Trim(); if (UserINISettings.Instance.AutoRemoveUnderscoresFromName) { while (playerName.EndsWith("_")) { playerName = playerName.Substring(0, playerName.Length - 1); } } if (string.IsNullOrEmpty(playerName)) { playerName = WindowsIdentity.GetCurrent().Name; playerName = playerName.Substring(playerName.IndexOf("\\") + 1); } playerName = Renderer.GetSafeString(NameValidator.GetValidOfflineName(playerName), 0); ProgramConstants.PLAYERNAME = playerName; UserINISettings.Instance.PlayerName.Value = playerName; LoadingScreen ls = new LoadingScreen(wm); wm.AddAndInitializeControl(ls); ls.ClientRectangle = new Rectangle((wm.RenderResolutionX - ls.Width) / 2, (wm.RenderResolutionY - ls.Height) / 2, ls.Width, ls.Height); }
private void Create_Click(object sender, RoutedEventArgs e) { var firstName = FirstNameBox.Text; var lastName = LastNameBox.Text; var pesel = PeselBox.Text; var email = EmailBox.Text; var doB = DoB.Text; var street = StreetBox.Text; var city = CityBox.Text; var country = CountryBox.Text; var zipCode = ZipCodeBox.Text; var phone = PhoneBox.Text; var nameValidator = new NameValidator(); var mailValidator = new MailValidator(); var peselValidator = new PeselValidator(); var dobValidator = new DateOfBirthValidator(); var phoneValidator = new PhoneValidator(); if (!nameValidator.ValidateName(firstName)) { MessageBox.Show("Podałeś nieprawidłowę imię."); } else if (!nameValidator.ValidateName(lastName)) { MessageBox.Show("Podałeś nieprawidłowe nazwisko"); } else if (!peselValidator.ValidatePesel(pesel)) { MessageBox.Show("Podałeś nieprawidłowy numer PESEL"); } else if (!mailValidator.ValidateMail(email)) { MessageBox.Show("Podałeś nieprawidłowy adres Email"); } else if (!phoneValidator.ValidatePhoneNumber(phone)) { MessageBox.Show("Nieprawidłowy numer telefonu"); } else if (!dobValidator.ValidateDoB(doB)) { MessageBox.Show("Nieprawidłowa data urodzenia"); } else if (string.IsNullOrEmpty(street) || string.IsNullOrEmpty(zipCode) || string.IsNullOrEmpty(country) || string.IsNullOrEmpty(city)) { MessageBox.Show("Pole adresowe nie może być puste"); } else { var gender = (Gender)Enum.Parse(typeof(Gender), GenderComboBox.Text); var account = new BankAccount(); var personalAccount = new PersonalAccount(firstName, lastName, doB, gender, pesel, email, street, zipCode, country, phone, city, account) { BankAccount = { Balance = 0.0 } }; var filePath = Environment.CurrentDirectory + @"\" + "Personal_Accounts.xml"; var listToXml = new ListToXml(); listToXml.PersonalAccounts(personalAccount, filePath); Close(); } }
public override async Task <object> GetObjectAsync(Authentication authentication, string path) { var dataBasePath = new DataBasePath(path); if (dataBasePath.DataBaseName == string.Empty) { return(null); } var dataBase = this.DataBaseContext[dataBasePath.DataBaseName]; if (dataBase == null) { throw new DataBaseNotFoundException(dataBasePath.DataBaseName); } if (dataBasePath.Context == string.Empty) { return(dataBase); } if (dataBasePath.ItemPath == string.Empty) { return(null); } if (dataBase.IsLoaded == false) { await dataBase.LoadAsync(authentication); } var tableContext = dataBase.GetService(typeof(ITableContext)) as ITableContext; var typeContext = dataBase.GetService(typeof(ITypeContext)) as ITypeContext; if (dataBasePath.Context == CremaSchema.TableDirectory) { if (NameValidator.VerifyCategoryPath(dataBasePath.ItemPath) == true) { return(tableContext[dataBasePath.ItemPath]); } var item = tableContext[dataBasePath.ItemPath + PathUtility.Separator]; if (item != null) { return(item); } return(tableContext[dataBasePath.ItemPath]); } else if (dataBasePath.Context == CremaSchema.TypeDirectory) { if (NameValidator.VerifyCategoryPath(dataBasePath.ItemPath) == true) { return(typeContext[dataBasePath.ItemPath]); } var item = typeContext[dataBasePath.ItemPath + PathUtility.Separator]; if (item != null) { return(item); } return(typeContext[dataBasePath.ItemPath]); } else { return(null); } }
public ItemTreeViewItemViewModel(string path) { NameValidator.ValidateItemPath(path); this.itemName = new ItemName(path); this.Target = path; }
public bool IsNameValid(string naame) { return(NameValidator.isNameValid(naame)); }
public UnitTest1() { age = new AgeValidator(); bornNumber = new BornNumberValidator(); nameValidator = new NameValidator(); }
public string GenerateTypePath(string categoryPath, string typeName) { NameValidator.ValidateCategoryPath(categoryPath); return(PathUtility.ConvertFromUri(this.basePath + categoryPath + typeName + CremaSchema.SchemaExtension)); }
internal PseudoFile(string name) : base(name) { NameValidator.ValidateFileName(name); }
public async Task CreateAsync() { var authentication = this.CommandContext.GetAuthentication(this); var tableNames = this.GetTableNamesAsync(); var template = await CreateTemplateAsync(); var dataTypes = template.Dispatcher.Invoke(() => template.SelectableTypes); var tableName = template.Dispatcher.Invoke(() => template.TableName); var tableInfo = JsonTableInfo.Default; if (tableInfo.TableName == string.Empty) { tableInfo.TableName = tableName; } var schema = JsonSchemaUtility.GetSchema(typeof(JsonTableInfo)); var itemsSchema = schema.Properties[nameof(JsonTableInfo.Columns)]; var itemSchema = itemsSchema.Items.First(); itemSchema.SetEnums(nameof(JsonTableInfo.JsonTableColumnInfo.DataType), dataTypes); itemSchema.SetEnums(nameof(JsonTableInfo.JsonTableColumnInfo.Tags), TagInfoUtility.Names); try { if (JsonEditorHost.TryEdit(ref tableInfo, schema) == false) { return; } if (this.CommandContext.ReadYesOrNo($"do you want to create table '{tableInfo.TableName}'?") == false) { return; } await SetDataAsync(); template = null; } finally { if (template != null) { await template.CancelEditAsync(authentication); } } async Task <ITableTemplate> CreateTemplateAsync() { if (this.ParentPath == string.Empty) { var category = await this.GetCategoryAsync(this.GetCurrentDirectory()); return(await category.AddNewTableAsync(authentication)); } else if (NameValidator.VerifyCategoryPath(this.ParentPath) == true) { var category = await this.GetCategoryAsync(this.ParentPath); return(await category.AddNewTableAsync(authentication)); } else if (await this.GetTableAsync(this.ParentPath) is ITable table) { return(await table.NewTableAsync(authentication)); } else { throw new NotImplementedException(); } } async Task SetDataAsync() { await template.SetTableNameAsync(authentication, tableInfo.TableName); await template.SetTagsAsync(authentication, (TagInfo)tableInfo.Tags); await template.SetCommentAsync(authentication, tableInfo.Comment); foreach (var item in tableInfo.Columns) { var column = await template.AddNewAsync(authentication); await column.SetNameAsync(authentication, item.Name); await column.SetIsKeyAsync(authentication, item.IsKey); await column.SetCommentAsync(authentication, item.Comment); await column.SetDataTypeAsync(authentication, item.DataType); await column.SetIsUniqueAsync(authentication, item.IsUnique); await column.SetAutoIncrementAsync(authentication, item.AutoIncrement); await column.SetDefaultValueAsync(authentication, item.DefaultValue); await column.SetTagsAsync(authentication, (TagInfo)item.Tags); await column.SetIsReadOnlyAsync(authentication, item.IsReadOnly); await template.EndNewAsync(authentication, column); } await template.EndEditAsync(authentication); } }
public static void Main(string[] args) { { // Quickest way to use Syllabore's name generator // without specifying any configuration. This instance // will default to using StandaloneSyllableProvider for // name generator and will not use any NameValidator to // improve output. var g = new NameGenerator(); for (int i = 0; i < 10; i++) { Console.WriteLine(g.Next()); } } { // Normally the constructor takes a SyllableProvider // and NameValidator. There are "Standalone" classes // available for quick and dirty use. It is recommended // you create your own by using ISyllableProvider/INameValidator // or inheriting from ConfigurableSyllableProvider/ConfigurableNameValidator. var provider = new DefaultSyllableProvider(); var validator = new NameValidator() .DoNotAllowPattern(@"[j|p|q|w]$") // Invalidate these awkward endings .DoNotAllowPattern(@"(\w)\1\1") // Invalidate any sequence of 3 or more identical letters .DoNotAllowPattern(@"([^aeiouAEIOU])\1\1\1"); // Invalidate any sequence of 4 or more consonants var g = new NameGenerator(provider, validator); for (int i = 0; i < 10; i++) { Console.WriteLine(g.Next()); } } { // You can choose to build name generators programmatically. var g = new NameGenerator() .UsingProvider(x => x .WithLeadingConsonants("str") .WithVowels("ae")) .LimitSyllableCount(3); for (int i = 0; i < 10; i++) { Console.WriteLine(g.Next()); } Console.WriteLine(); } { // Creating variations of a single name var g = new NameGenerator().UsingMutator(new VowelMutator()); for (int i = 0; i < 3; i++) { var name = g.NextName(); Console.WriteLine(name); for (int j = 0; j < 4; j++) { var variation = g.Mutate(name); Console.WriteLine(variation); } } } { Console.WriteLine(); var g = new NameGenerator() .UsingProvider(p => p .WithVowels("aeoy") .WithLeadingConsonants("vstlr") .WithTrailingConsonants("zrt") .WithVowelSequences("ey", "ay", "oy")) .UsingMutator(m => m .WithMutation(x => x.ReplaceSyllable(0, "Gran")) .WithMutation(x => x.ReplaceSyllable(0, "Bri")) .WithMutation(x => x.InsertSyllable(0, "Deu").AppendSyllable("gard").WithWeight(2)) .WithMutation(x => x.When(-2, "[aeoyAEOY]$").ReplaceSyllable(-1, "opolis")) .WithMutation(x => x.When(-2, "[^aeoyAEOY]$").ReplaceSyllable(-1, "polis")) .WithMutationCount(1)) .UsingValidator(v => v .DoNotAllowPattern( @".{12,}", @"(\w)\1\1", // Prevents any letter from occuring three times in a row @".*([y|Y]).*([y|Y]).*", // Prevents double y @".*([z|Z]).*([z|Z]).*", // Prevents double z @"(zs)", // Prevents "zs" @"(y[v|t])")) // Prevents "yv" and "yt" .LimitMutationChance(0.99) .LimitSyllableCount(2, 4); ConfigurationFile.Save(g, "city-name-generator.txt"); var g2 = ConfigurationFile.Load("city-name-generator.txt"); for (int i = 0; i < 50; i++) { var name = g.NextName(); Console.WriteLine(name); } Console.WriteLine(); } { var provider = new SyllableProvider(); provider.WithVowels("a", "e", "o", "y"); provider.WithLeadingConsonants("v", "s", "t", "l", "r"); provider.WithTrailingConsonants("z", "r", "t"); provider.WithVowelSequences("ey", "ay", "oy"); provider.DisallowLeadingConsonantSequences(); provider.DisallowTrailingConsonantSequences(); var shifter = new VowelMutator("a", "e", "o", "y"); var validator = new NameValidator(); validator.DoNotAllowPattern(@"(\w)\1\1"); validator.DoNotAllowPattern(@"([^aeoyAEOY])\1"); validator.DoNotAllowPattern(@".*([y|Y]).*([y|Y]).*"); validator.DoNotAllowPattern(@".*([z|Z]).*([z|Z]).*"); validator.DoNotAllowPattern(@"(zs)"); validator.DoNotAllowPattern(@"(y[v|t])"); var g = new NameGenerator(provider, shifter, validator); g.LimitSyllableCount(2, 3); } { var name = new Name("syl", "la", "bore"); var mutator = new NameMutator() .Join(new DefaultNameMutator()) .Join(new VowelMutator()); for (int i = 0; i < 20; i++) { Console.WriteLine(mutator.Mutate(name)); } } }
public ItemTreeViewItemViewModel(IItem item) { NameValidator.ValidateItemPath(item.Path); this.Target = item; this.itemName = new ItemName(item.Path); }
private void Finish() { if (!ClientConfiguration.Instance.ModMode) { ProgramConstants.GAME_VERSION = CUpdater.GameVersion; } var gameCollection = new GameCollection(); gameCollection.Initialize(GraphicsDevice); var lanLobby = new LANLobby(WindowManager, gameCollection, mapLoader.GameModes, mapLoader); var cncnetUserData = new CnCNetUserData(WindowManager); var cncnetManager = new CnCNetManager(WindowManager, gameCollection); var tunnelHandler = new TunnelHandler(WindowManager, cncnetManager); var topBar = new TopBar(WindowManager, cncnetManager); var optionsWindow = new OptionsWindow(WindowManager, gameCollection, topBar); var pmWindow = new PrivateMessagingWindow(WindowManager, cncnetManager, gameCollection, cncnetUserData); privateMessagingPanel = new PrivateMessagingPanel(WindowManager); var cncnetGameLobby = new CnCNetGameLobby(WindowManager, "MultiplayerGameLobby", topBar, mapLoader.GameModes, cncnetManager, tunnelHandler, gameCollection, cncnetUserData, mapLoader); var cncnetGameLoadingLobby = new CnCNetGameLoadingLobby(WindowManager, topBar, cncnetManager, tunnelHandler, mapLoader.GameModes, gameCollection); var cncnetLobby = new CnCNetLobby(WindowManager, cncnetManager, cncnetGameLobby, cncnetGameLoadingLobby, topBar, pmWindow, tunnelHandler, gameCollection, cncnetUserData); var gipw = new GameInProgressWindow(WindowManager); var skirmishLobby = new SkirmishLobby(WindowManager, topBar, mapLoader.GameModes); topBar.SetSecondarySwitch(cncnetLobby); var mainMenu = new MainMenu(WindowManager, skirmishLobby, lanLobby, topBar, optionsWindow, cncnetLobby, cncnetManager); WindowManager.AddAndInitializeControl(mainMenu); DarkeningPanel.AddAndInitializeWithControl(WindowManager, skirmishLobby); DarkeningPanel.AddAndInitializeWithControl(WindowManager, cncnetGameLoadingLobby); DarkeningPanel.AddAndInitializeWithControl(WindowManager, cncnetGameLobby); DarkeningPanel.AddAndInitializeWithControl(WindowManager, cncnetLobby); DarkeningPanel.AddAndInitializeWithControl(WindowManager, lanLobby); DarkeningPanel.AddAndInitializeWithControl(WindowManager, optionsWindow); WindowManager.AddAndInitializeControl(privateMessagingPanel); privateMessagingPanel.AddChild(pmWindow); topBar.SetTertiarySwitch(pmWindow); WindowManager.AddAndInitializeControl(gipw); skirmishLobby.Disable(); cncnetLobby.Disable(); cncnetGameLobby.Disable(); cncnetGameLoadingLobby.Disable(); lanLobby.Disable(); pmWindow.Disable(); optionsWindow.Disable(); WindowManager.AddAndInitializeControl(topBar); topBar.AddPrimarySwitchable(mainMenu); mainMenu.PostInit(); if (UserINISettings.Instance.AutomaticCnCNetLogin && NameValidator.IsNameValid(ProgramConstants.PLAYERNAME) == null) { cncnetManager.Connect(); } WindowManager.RemoveControl(this); Cursor.Visible = visibleSpriteCursor; }
public void Inject() { Log.Information("ChatManager initializing"); this.config = DI.Get <Configuration>(); this.nameValidator = DI.Get <NameValidator>(); this.userRoomService = DI.Get <UserRoomService>(); this.giftService = DI.Get <GiftsService>(); this.dispatcher = DI.Get <EventDispatcher>(); this.services = new IDIService[] { this.userRoomService, this.giftService, DI.Get <ChatActionsAuthenticator>(), DI.Get <ServerPromptService>(), DI.Get <GroupService>(), DI.Get <LobbyService>(), DI.Get <LoginService>(), DI.Get <CharacterService>(), }; this.nameValidator.ServerName = this.Monogram; this.World = new World(); Log.Information("Loading permanent rooms ({count} total)", this.config.PermanentRooms.Count); this.userRoomService.LoadPermanentRooms(); CIOReactor.Spawn("playerTimeoutWatchdog", () => { while (true) { Thread.Sleep(TimeSpan.FromSeconds(this.config.PlayerInactivityTimeout)); lock (this) { Log.Verbose("Checking players timeouts"); try { var players = this.World.Players.ToArray(); foreach (var handle in players) { this.CheckPlayerTimedOut(handle); } } catch (Exception e) { Log.Error("Caught exception in playerTimeoutWatchdog: {ex}", e); } } } }); CIOReactor.Spawn("excelRecordsWatchdog", () => { Log.Debug("Cleaning up expel records"); while (true) { #if !DEBUG var duration = TimeSpan.FromMinutes(10); #else var duration = TimeSpan.FromSeconds(30); #endif Thread.Sleep(duration); try { this.userRoomService.CleanupExpelRecords(); } catch (Exception e) { Log.Error("Caught exception in excelRecordsWatchdog: {ex}", e); } } }); CIOReactor.Spawn("danglingRoomWatchdog", () => { while (true) { #if !DEBUG var duration = TimeSpan.FromMinutes(3); #else var duration = TimeSpan.FromSeconds(30); #endif Thread.Sleep(duration); if (!this.config.DanglingRoom.Enabled) { continue; } Log.Debug("Cleaning up dangling rooms"); try { this.userRoomService.CleanupDanglingRooms(); } catch (Exception e) { Log.Error("Caught exception in danglingRoomWatchdog: {ex}", e); } } }); }
private void Finish() { ProgramConstants.GAME_VERSION = ClientConfiguration.Instance.ModMode ? "N/A" : CUpdater.GameVersion; DiscordHandler discordHandler = null; if (!string.IsNullOrEmpty(ClientConfiguration.Instance.DiscordAppId)) { discordHandler = new DiscordHandler(WindowManager); } ClientGUICreator.Instance.AddControl(typeof(GameLobbyCheckBox)); ClientGUICreator.Instance.AddControl(typeof(GameLobbyDropDown)); ClientGUICreator.Instance.AddControl(typeof(MapPreviewBox)); ClientGUICreator.Instance.AddControl(typeof(GameLaunchButton)); ClientGUICreator.Instance.AddControl(typeof(ChatListBox)); ClientGUICreator.Instance.AddControl(typeof(XNAChatTextBox)); var gameCollection = new GameCollection(); gameCollection.Initialize(GraphicsDevice); var lanLobby = new LANLobby(WindowManager, gameCollection, mapLoader.GameModes, mapLoader, discordHandler); var cncnetUserData = new CnCNetUserData(WindowManager); var cncnetManager = new CnCNetManager(WindowManager, gameCollection); var tunnelHandler = new TunnelHandler(WindowManager, cncnetManager); var topBar = new TopBar(WindowManager, cncnetManager); var optionsWindow = new OptionsWindow(WindowManager, gameCollection, topBar); var pmWindow = new PrivateMessagingWindow(WindowManager, cncnetManager, gameCollection, cncnetUserData); privateMessagingPanel = new PrivateMessagingPanel(WindowManager); var cncnetGameLobby = new CnCNetGameLobby(WindowManager, "MultiplayerGameLobby", topBar, mapLoader.GameModes, cncnetManager, tunnelHandler, gameCollection, cncnetUserData, mapLoader, discordHandler); var cncnetGameLoadingLobby = new CnCNetGameLoadingLobby(WindowManager, topBar, cncnetManager, tunnelHandler, mapLoader.GameModes, gameCollection, discordHandler); var cncnetLobby = new CnCNetLobby(WindowManager, cncnetManager, cncnetGameLobby, cncnetGameLoadingLobby, topBar, pmWindow, tunnelHandler, gameCollection, cncnetUserData); var gipw = new GameInProgressWindow(WindowManager); var skirmishLobby = new SkirmishLobby(WindowManager, topBar, mapLoader.GameModes, discordHandler); topBar.SetSecondarySwitch(cncnetLobby); var mainMenu = new MainMenu(WindowManager, skirmishLobby, lanLobby, topBar, optionsWindow, cncnetLobby, cncnetManager, discordHandler); WindowManager.AddAndInitializeControl(mainMenu); DarkeningPanel.AddAndInitializeWithControl(WindowManager, skirmishLobby); DarkeningPanel.AddAndInitializeWithControl(WindowManager, cncnetGameLoadingLobby); DarkeningPanel.AddAndInitializeWithControl(WindowManager, cncnetGameLobby); DarkeningPanel.AddAndInitializeWithControl(WindowManager, cncnetLobby); DarkeningPanel.AddAndInitializeWithControl(WindowManager, lanLobby); DarkeningPanel.AddAndInitializeWithControl(WindowManager, optionsWindow); WindowManager.AddAndInitializeControl(privateMessagingPanel); privateMessagingPanel.AddChild(pmWindow); topBar.SetTertiarySwitch(pmWindow); topBar.SetOptionsWindow(optionsWindow); WindowManager.AddAndInitializeControl(gipw); skirmishLobby.Disable(); cncnetLobby.Disable(); cncnetGameLobby.Disable(); cncnetGameLoadingLobby.Disable(); lanLobby.Disable(); pmWindow.Disable(); optionsWindow.Disable(); WindowManager.AddAndInitializeControl(topBar); topBar.AddPrimarySwitchable(mainMenu); mainMenu.PostInit(); if (UserINISettings.Instance.AutomaticCnCNetLogin && NameValidator.IsNameValid(ProgramConstants.PLAYERNAME) == null) { cncnetManager.Connect(); } if (!UserINISettings.Instance.PrivacyPolicyAccepted) { WindowManager.AddAndInitializeControl(new PrivacyNotification(WindowManager)); } WindowManager.RemoveControl(this); Cursor.Visible = visibleSpriteCursor; PreprocessorBackgroundTask.Instance.CheckException(); }
public EnumValue(NameNode name) { NameValidator.ValidateDefault(name.Name, NamedElement.EnumValue); NameNode = name; }
private void HandleField(IComplexGraphType?parentType, FieldType field, TypeCollectionContext context, bool applyNameConverter) { // applyNameConverter will be false while processing the three root introspection query fields: __schema, __type, and __typename // // During processing of those three root fields, the NameConverter will be set to the schema's selected NameConverter, // and the field names must not be processed by the NameConverter // // For other introspection types and fields, the NameConverter will be set to CamelCaseNameConverter at the time this // code executes, and applyNameConverter will be true // // For any other fields, the NameConverter will be set to the schema's selected NameConverter at the time this code // executes, and applyNameConverter will be true if (applyNameConverter) { field.Name = _nameConverter.NameForField(field.Name, parentType !); NameValidator.ValidateNameOnSchemaInitialize(field.Name, NamedElement.Field); } if (field.ResolvedType == null) { if (field.Type == null) { throw new InvalidOperationException($"Both ResolvedType and Type properties on field '{parentType?.Name}.{field.Name}' are null."); } object typeOrError = RebuildType(field.Type, parentType is IInputObjectGraphType, context.TypeMappings); if (typeOrError is string error) { throw new InvalidOperationException($"The GraphQL type for field '{parentType?.Name}.{field.Name}' could not be derived implicitly. " + error); } field.Type = (Type)typeOrError; AddTypeIfNotRegistered(field.Type, context); field.ResolvedType = BuildNamedType(field.Type, context.ResolveType); } else { AddTypeIfNotRegistered(field.ResolvedType, context); } if (field.Arguments?.Count > 0) { foreach (var arg in field.Arguments.List !) { if (applyNameConverter) { arg.Name = _nameConverter.NameForArgument(arg.Name, parentType !, field); NameValidator.ValidateNameOnSchemaInitialize(arg.Name, NamedElement.Argument); } if (arg.ResolvedType == null) { if (arg.Type == null) { throw new InvalidOperationException($"Both ResolvedType and Type properties on argument '{parentType?.Name}.{field.Name}.{arg.Name}' are null."); } object typeOrError = RebuildType(arg.Type, true, context.TypeMappings); if (typeOrError is string error) { throw new InvalidOperationException($"The GraphQL type for argument '{parentType?.Name}.{field.Name}.{arg.Name}' could not be derived implicitly. " + error); } arg.Type = (Type)typeOrError; AddTypeIfNotRegistered(arg.Type, context); arg.ResolvedType = BuildNamedType(arg.Type, context.ResolveType); } else { AddTypeIfNotRegistered(arg.ResolvedType, context); } } } }
void Implement_body(StreamWriter sw, EventMethodsGroupsCollection groups) { WrapIn(sw, "namespace Events.Groups", () => { foreach (var group in groups) { WrapIn(sw, "namespace " + group.GroupName, () => { StringBuilder interfacesNames = new StringBuilder(); StringBuilder interfaceDeclereration = new StringBuilder(); StringBuilder invokerListDecloration = new StringBuilder(); StringBuilder invokerMethodsDecloration = new StringBuilder(); foreach (var method in group) { //---------------------------------------------------------------------------------- var args = method.Args.Select( x => string.Format("{0} {1}", NameValidator.GetGenericTypeFullName(x.ArgType), x.ArgName)).ToArray(); var argsAsMethodArgs = args.Length == 0 ? "" : string.Join(",", args); var argsWithoutNames = method.Args.Select(x => NameValidator.GetGenericTypeName(x.ArgType)).ToArray(); var argTypes_AsName = argsWithoutNames.Length == 0 ? "" : string.Join("_", argsWithoutNames); argTypes_AsName = Regex.Replace(argTypes_AsName, "[^A-Za-z0-9 _]", ""); //---------------------------------------------------------------------------------- var interfaceName = (argsWithoutNames.Length > 0) ? string.Format("I{0}_{1}", @method.Name, argTypes_AsName) : string.Format("I{0}", @method.Name); interfaceDeclereration.AppendLine(string.Format("public interface {0} : Tools.IEventMethodBase{{ {1} }}", interfaceName, method.MethodFullSigneture)); invokerListDecloration.AppendLine(string.Format("static List<Methods.{0}> _users_{0} = new List<Methods.{0}>();", interfaceName)); invokerMethodsDecloration.AppendLine(string.Format("internal static void RegisterUser(Methods.{0} user){{", interfaceName)); invokerMethodsDecloration.AppendLine("if(user == null) return;"); invokerMethodsDecloration.AppendLine(string.Format("if(!_users_{0}.Contains(user)) _users_{0}.Add(user);\n}}", interfaceName)); invokerMethodsDecloration.AppendLine(string.Format("internal static void UnRegisterUser(Methods.{0} user){{", interfaceName)); invokerMethodsDecloration.AppendLine("if(user == null) return;"); invokerMethodsDecloration.AppendLine(string.Format("if(_users_{0}.Contains(user)) _users_{0}.Remove(user);\n}}", interfaceName)); invokerMethodsDecloration.AppendLine(string.Format("public static void {0}({1}){{", method.Name, argsAsMethodArgs)); invokerMethodsDecloration.AppendLine(string.Format("_users_{0}.ForEach(x=> x.{1}({2})); \n}}", interfaceName, method.Name, string.Join(",", method.Args.Select(x => x.ArgName).ToArray()))); // is used for the IAll_Group_Events interface interfacesNames.Append(string.Format("Methods.{0},", interfaceName)); //---------------------------------------------------------------------------------- } WrapIn(sw, "namespace Methods", () => { WriteToStream(sw, interfaceDeclereration.ToString()); }); //static WrapIn(sw, "public static class Invoke", () => { WriteToStream(sw, invokerListDecloration.ToString()); WriteToStream(sw, invokerMethodsDecloration.ToString()); }); //interface IAll_Group_Events sw.Write("public interface IAll_Group_Events"); if (!string.IsNullOrEmpty(interfacesNames.ToString())) { interfacesNames = interfacesNames.Remove(interfacesNames.Length - 1, 1); //remove the "," at the end of the string builder WriteToStream(sw, ":", interfacesNames.ToString()); } sw.Write("{ }\n"); }); //end namespace {GroupName} warp } }); //end namespace "Events.Groups" warp }
public void AcceptValidEmployeeName(string name) { var empNameVal = new NameValidator(); Assert.True(empNameVal.IsValid(name)); }
void Implement_body(StreamWriter sw, EventMethodsGroupsCollection groups) { WrapIn(sw, "namespace Events.Groups", () => { foreach (var group in groups) { WrapIn(sw, "namespace " + group.GroupName, () => { StringBuilder interfacesNames = new StringBuilder(); WrapIn(sw, "namespace Methods", () => { foreach (var method in group) { //---------------------------------------------------------------------------------- var args = method.Args.Select( x => string.Format("{0} {1}", NameValidator.GetGenericTypeFullName(x.ArgType), x.ArgName)).ToArray(); var argsAsMethodArgs = args.Length == 0 ? "" : string.Join(",", args); var argsWithoutNames = method.Args.Select(x => NameValidator.GetGenericTypeName(x.ArgType)).ToArray(); var argTypes_AsName = argsWithoutNames.Length == 0 ? "" : string.Join("_", argsWithoutNames); argTypes_AsName = Regex.Replace(argTypes_AsName, "[^A-Za-z0-9 _]", ""); //---------------------------------------------------------------------------------- var interfaceName = (argsWithoutNames.Length > 0) ? string.Format("I{0}_{1}", @method.Name, argTypes_AsName) : string.Format("I{0}", @method.Name); WrapIn(sw, string.Format("public static class {0}{1}", @method.Name, (argsWithoutNames.Length > 0 ? string.Format("_{0}", argTypes_AsName) : "")), // methods arg types () => { WriteToStream(sw, "static List<", interfaceName, "> _users = new List<", interfaceName, ">();"); //write inteface WrapIn(sw, string.Format("public interface {0} : Tools.IEventMethodBase", interfaceName), () => { WriteToStream(sw, method.MethodFullSigneture); }); interfacesNames.Append(string.Format("Methods.{0}.{1},", interfaceName.Substring(1), interfaceName)); //register user method WrapIn(sw, string.Format("internal static void RegisterListener({0} user)", interfaceName), () => { WriteToStream(sw, "if(user == null) return;"); WriteToStream(sw, "if(!_users.Contains(user)) _users.Add(user);"); }); //Unregister user method WrapIn(sw, string.Format("internal static void UnRegisterListener({0} user)", interfaceName), () => { WriteToStream(sw, "if(user == null) return;"); WriteToStream(sw, "if(_users.Contains(user)) _users.Remove(user);"); }); //invoke WrapIn(sw, string.Format("public static void Invoke({0})", argsAsMethodArgs), () => { WriteToStream(sw, "_users.ForEach(x=> x.", method.Name, "(", string.Join(",", method.Args.Select(x => x.ArgName).ToArray()), "));"); }); }); //---------------------------------------------------------------------------------- } }); //interface IAll_Group_Events sw.Write("public interface IAll_Group_Events"); if (!string.IsNullOrEmpty(interfacesNames.ToString())) { interfacesNames = interfacesNames.Remove(interfacesNames.Length - 1, 1); //remove the "," at the end of the string builder WriteToStream(sw, ":", interfacesNames.ToString()); } sw.Write("{ }\n"); }); //end namespace {GroupName} warp } }); //end namespace "Events.Groups" warp }
public void ThrowExceptionWhenNullName() { var empNameVal = new NameValidator(); Assert.Throws <ArgumentNullException>(() => empNameVal.IsValid(null)); }
void Implement_body(StreamWriter sw, EventMethodsGroupsCollection groups) { WrapIn(sw, "namespace Events.Groups", () => { foreach (var group in groups) { WrapIn(sw, "namespace " + group.GroupName, () => { StringBuilder interfacesNames = new StringBuilder(); foreach (var method in group) { //---------------------------------------------------------------------------------- var args = method.Args.Select(x => string.Format("{0} {1}", NameValidator.GetGenericTypeFullName(x.ArgType), x.ArgName)).ToArray(); var argsAsMethodArgs = args.Length == 0 ? "" : string.Join(",", args); var argsWithoutNames = method.Args.Select(x => NameValidator.GetGenericTypeName(x.ArgType)).ToArray(); var argTypes_AsName = argsWithoutNames.Length == 0 ? "" : string.Join("_", argsWithoutNames); argTypes_AsName = Regex.Replace(argTypes_AsName, "[^A-Za-z0-9 _]", ""); //---------------------------------------------------------------------------------- WrapIn(sw, "namespace Methods", () => { WrapIn(sw, string.Format("public static class {0}{1}", @method.Name, (argsWithoutNames.Length > 0 ? string.Format("_{0}", argTypes_AsName) : "")), // methods arg types () => { string delegateType = string.Format("delegate_{0}_{1}", @group.GroupName, @method.Name); WriteDelegate(sw, delegateName: delegateType, argNamesAndTypes: args); //write inteface if (argsWithoutNames.Length > 0) { WrapIn(sw, string.Format("public interface I{0}_{1} : Tools.IEventMethodBase", @method.Name, argTypes_AsName), () => { WriteToStream(sw, method.MethodFullSigneture); }); interfacesNames.Append(string.Format("Methods.{0}_{1}.I{0}_{1},", @method.Name, argTypes_AsName)); } else { WrapIn(sw, string.Format("public interface I{0} : Tools.IEventMethodBase", @method.Name), () => { WriteToStream(sw, method.MethodFullSigneture); }); interfacesNames.Append(string.Format("Methods.{0}.I{0},", @method.Name)); } //delegate instance WriteToStream(sw, "private static ", delegateType, " _listener;\n"); //register user method WrapIn(sw, string.Format("public static void RegisterListener({0} user)", delegateType), () => { WriteToStream(sw, "if(user == null) return;"); WriteToStream(sw, "if(_listener == null) _listener = user;"); WriteToStream(sw, "else if(!_listener.GetInvocationList().Contains(user)) _listener += user;"); }); //Unregister user method WrapIn(sw, string.Format("public static void UnRegisterListener({0} user)", delegateType), () => { WriteToStream(sw, "if(user == null) return;"); WriteToStream(sw, "if(_listener == null) return;"); WriteToStream(sw, "if(_listener.GetInvocationList().Contains(user)) _listener -= user;"); }); //invoke WrapIn(sw, string.Format("public static void Invoke({0})", argsAsMethodArgs), () => { WriteToStream(sw, "if(_listener != null) _listener(", string.Join(",", method.Args.Select(x => x.ArgName).ToArray()), ");"); }); }); }); //---------------------------------------------------------------------------------- } //interface IAll_Group_Events sw.Write("public interface IAll_Group_Events"); if (!string.IsNullOrEmpty(interfacesNames.ToString())) { interfacesNames = interfacesNames.Remove(interfacesNames.Length - 1, 1); //remove the "," at the end of the string builder WriteToStream(sw, ":", interfacesNames.ToString()); } sw.Write("{ }\n"); }); //end namespace {GroupName} warp } }); //end namespace "Events.Groups" warp }
internal static void ValidateContainerName(string containerName) { NameValidator.ValidateContainerName(containerName); }
public GivenNameValidator() { _validator = new NameValidator(ErrorCodes.NameCannotBeEmpty); _propertyRule = new PropertyRule(null, null, null, null, null, null); }
/// <summary> /// Versenyző adatainak módosítása /// Kösse be a Validatorokkat a metódusba! /// </summary> /// <param name="teamName">A csapat neve</param> /// <param name="oldRacerName">A versenyző régi neve</param> /// <param name="racerName">A versenyző új neve</param> /// <param name="racerAge">A versenyző új neve</param> /// <param name="racerSalary">A versenyző költsége</param> public void updateRacerInTeam(string teamName, string oldRacerName, string racerName, string racerAge, string racerSalary) { int racerAgeNumber = 0; if (!int.TryParse(racerAge, out racerAgeNumber)) { throw new ControllerException("A megadott életkor nem megfelelő alakú szám!"); } int racerSalaryNumber = 0; if (!int.TryParse(racerSalary, out racerSalaryNumber)) { throw new ControllerException("A megadott fizetés nem megfelelő alakú szám!"); } if (teamService.existRacer(racerName, racerAgeNumber)) { throw new ControllerException("Már létezik " + racerName + " nevű versenyző, aki " + racerAge + " éves."); } try { NameValidator nv = new NameValidator(racerName); nv.validation(); } catch (NameNotValidNameIsEmptyException e) { throw new ControllerException(e.Message); } catch (NameNotValidFirstLetterProblemException e) { throw new ControllerException(e.Message); } try { AgeValidator av = new AgeValidator(racerAgeNumber); av.validation(); } catch (AgeIsZeroException e) { throw new ControllerException(e.Message); } catch (AgeUnderMinimumAgeException e) { throw new ControllerException(e.Message); } catch (AgeAboveMaximumAgeException e) { throw new ControllerException(e.Message); } try { SalaryValidator sv = new SalaryValidator(racerSalaryNumber); sv.validation(); } catch (SalaryZeroException e) { throw new ControllerException(e.Message); } catch (NegativeSalaryException e) { throw new ControllerException(e.Message); } catch (HighSalaryException e) { throw new ControllerException(e.Message); } try { int racerId = teamService.getRacerId(teamName, oldRacerName); if (racerId > 0) { Racer newRacer = new Racer(racerId, racerName, racerAgeNumber, racerSalaryNumber); teamService.updateReacerInTeam(teamName, oldRacerName, newRacer); } else { throw new ControllerException("A megadott versenyőjnek nem találom az azonosítáját"); } } catch (TeamServiceExeption tse) { throw new ControllerException(tse.Message); } catch (RacerException re) { throw new ControllerException(re.Message); } }
public CategoryTreeViewItemViewModel(string path) { NameValidator.ValidateCategoryPath(path); this.categoryName = new CategoryName(path); this.Target = path; }