protected virtual void CreateDatabaseSchema(Expression dataDefinitionExpressions, DatabaseCreationOptions options) { using (var scope = new DataAccessScope()) { using (var dataTransactionContext = this.SqlDatabaseContext.CreateSqlTransactionalCommandsContext(null)) { using (this.SqlDatabaseContext.AcquireDisabledForeignKeyCheckContext(dataTransactionContext)) { var result = this.SqlDatabaseContext.SqlQueryFormatterManager.Format(dataDefinitionExpressions); using (var command = dataTransactionContext.CreateCommand(SqlCreateCommandOptions.Default | SqlCreateCommandOptions.UnpreparedExecute)) { command.CommandText = result.CommandText; Logger.Info(command.CommandText); command.ExecuteNonQuery(); } } dataTransactionContext.Commit(); } scope.Complete(); } }
public void Test_Nested_Scope_Abort2() { Assert.Throws(Is.InstanceOf <TransactionAbortedException>().Or.InstanceOf <DataAccessTransactionAbortedException>(), () => { var methodName = MethodBase.GetCurrentMethod().Name; using (var scope = new DataAccessScope()) { var child = this.model.Children.Create(); scope.Flush(); using (var inner = new DataAccessScope()) { child.Nickname = methodName; } scope.Flush(); Assert.AreEqual(child.Id, this.model.Children.Single(c => c.Nickname == methodName).Id); scope.Complete(); } }); }
// DONE: Generate ActionBar for Creation Char internal void GenerateActionBar(Characters character) { var initRaceClass = XmlReader.GetRaceClass(character.race, character.classe); /* * foreach (var actionBase in initRace.actions) * { * using (var scope = new DataAccessScope()) * { * var ActionBar = Model.CharactersActionBars.Create(); * ActionBar.character = character; * ActionBar.button = actionBase.button; * ActionBar.action = actionBase.action; * ActionBar.type = actionBase.type; * ActionBar.created_at = DateTime.Now; * * scope.Complete(); * } * } */ foreach (var actionBase in initRaceClass.actions) { using (var scope = new DataAccessScope()) { var actionBar = Model.CharactersActionBars.Create(); actionBar.character = character; actionBar.button = actionBase.button; actionBar.action = actionBase.action; actionBar.type = actionBase.type; actionBar.created_at = DateTime.Now; scope.Complete(); } } }
// DONE: Generate Spells for Creation Char Player internal void GenerateSpells(Characters character) { var initRace = XmlReader.GetRace(character.race); var initRaceClass = XmlReader.GetRaceClass(character.race, character.classe); foreach (var spellBase in initRace.spells) { using (var scope = new DataAccessScope()) { var spell = Model.CharactersSpells.Create(); spell.character = character; spell.spell = spellBase.id; spell.active = 1; spell.created_at = DateTime.Now; scope.Complete(); } } foreach (var spellBase in initRaceClass.spells) { using (var scope = new DataAccessScope()) { var spell = Model.CharactersSpells.Create(); spell.character = character; spell.spell = spellBase.id; spell.active = 1; spell.created_at = DateTime.Now; scope.Complete(); } } }
public void AddOrUpdate(string name, string value) { using (var scope = new DataAccessScope()) { if (_settings.ContainsKey(name)) { var dto = GameDatabase.Instance.Players .First(plr => plr.Id == (int)Player.Account.Id) .Settings .First(s => s.Setting == name); dto.Value = value; _settings[name] = value; } else { var dto = GameDatabase.Instance.Players .First(plr => plr.Id == (int)Player.Account.Id); var settingsDto = dto.Settings.Create(); settingsDto.Setting = name; settingsDto.Value = value; _settings[name] = value; } scope.Complete(); } }
public void Test_Nested_DataAccessScope_Inner_Complete_Calls_DataModelHook(bool flush, bool complete) { using (var outerScope = new DataAccessScope()) { var cat1 = this.model.Cats.Create(); using (var innerScope = new DataAccessScope()) { var cat2 = this.model.Cats.Create(); innerScope.Complete(); } var cat3 = this.model.Cats.Create(); if (flush) { outerScope.Flush(); } if (complete) { outerScope.Complete(); } } Assert.AreEqual(complete ? 1 : 0, this.testDataModelHook.CommitCount); Assert.AreEqual(complete || !flush ? 0 : 1, this.testDataModelHook.RollbackCount); }
public void Test_Distributed_Transaction_DataAccessScope_CreateFlushComplete_Calls_DataModelHook(bool flush, bool complete) { var config2 = this.CreateSqliteClassicInMemoryConfiguration(null); var model2 = DataAccessModel.BuildDataAccessModel <ComplexPrimaryKeyDataAccessModel>(config2); var hook2 = new TestDataModelHook(); model2.AddHook(hook2); model2.Create(DatabaseCreationOptions.IfDatabaseNotExist); using (var scope = new DataAccessScope()) { var cat = this.model.Cats.Create(); var coord = model2.Coordinates.Create(1); Console.WriteLine("==="); if (flush) { scope.Flush(); } if (complete) { scope.Complete(); } } Assert.AreEqual(complete ? 1 : 0, this.testDataModelHook.CommitCount); Assert.AreEqual(complete || !flush ? 0 : 1, this.testDataModelHook.RollbackCount); Assert.AreEqual(complete ? 1 : 0, hook2.CommitCount); Assert.AreEqual(complete || !flush ? 0 : 1, hook2.RollbackCount); }
// Generate Player Taxi Zones // Generate Inventory for Creation Char internal void GenerateInventory(Characters character) { var stack = 1; uint countBag = 0; CharStartOutfit startItems = MainForm.CharacterOutfitReader.Get(character.classe, character.race, character.gender); if (startItems == null) { return; } for (int j = 0; j < startItems.Items.Length; ++j) { if (startItems.Items[j] <= 0) { continue; } var item = XmlReader.GetItem(startItems.Items[j]); if (item == null) { continue; } if (item.@class == 0) { stack = 5; } if (item.id == 6948) { stack = 1; } using (var scope = new DataAccessScope()) { var inventory = Model.CharactersInventorys.Create(); inventory.item = (ulong)item.id; inventory.bag = character.Id; inventory.slot = PrefInvSlot(item) == 23 ? 23 + countBag : PrefInvSlot(item); inventory.stack = (uint)stack; //inventory.durability = item. inventory.flags = 1; inventory.character = character; inventory.created_at = DateTime.Now; scope.Complete(); } if (PrefInvSlot(item) == 23) { countBag++; } } }
public void InsertOne() { using (var scope = new DataAccessScope()) { var person = model.Books.Create(); var p = model.GetDataAccessObjects <Person>().Create(); person.PublisherName = "Penguin"; scope.Complete(); } }
public string CreateUrn(long longId) { if (!this.dataAccessModel.GetCurrentSqlDatabaseContext().GetType().Name.StartsWith("Sqlite")) { using (var scope = new DataAccessScope(DataAccessIsolationLevel.ReadUncommitted, DataAccessScopeOptions.RequiresNew, TimeSpan.Zero)) { ((ComplexPrimaryKeyDataAccessModel)this.dataAccessModel).Shops.ToList(); scope.Complete(); } } return($"urn:mall:{longId}"); }
public void Update() { using (var scope = new DataAccessScope()) { // Gets a reference to an object with a composite primary key without hitting the database var book = model.Books.GetReference(new { PublisherName = "Penguin" }); //var s=model.GetDataAccessObjects<Book>().GetReference(new {Id = 100, PublisherName = "Penguin"}); book.Title = "Expert Shaolinq"; // Will throw if the book (above) does not exist on commit in a single trip to the database scope.Complete(); } }
internal static void Create(CMSG_CHAR_CREATE handler, Users users) { using (var scope = new DataAccessScope()) { // DONE: Save Char var Char = Model.Characters.Create(); Char.user = users; // DONE: Make name capitalized as on official Char.name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(handler.Name); Char.race = (Races)handler.Race; Char.classe = (Classes)handler.Classe; Char.gender = (Genders)handler.Gender; Char.level = 1; Char.money = 0; /// Char.MapId = 0; Char.MapZone = 12; Char.MapX = -8949.95f; Char.MapY = -132.493f; Char.MapZ = 83.5312f; Char.MapO = 1.0f; Char.char_skin = handler.Skin; Char.char_face = handler.Face; Char.char_hairStyle = handler.HairStyle; Char.char_hairColor = handler.HairColor; Char.char_facialHair = handler.FacialHair; Char.created_at = DateTime.Now; Char.watched_faction = 255; // Set Another status // Set Taxi Zones // tutorial Flags // Map Explored // Set Honor // Query Access Level and Account ID // Char.level scope.Complete(); } }
public DatabaseManager() { //if (File.Exists("database.sqlite")) //return; // Recria a base inteira Model.Create(DatabaseCreationOptions.DeleteExistingDatabase); using (var scope = new DataAccessScope()) { // Inserindo Usuarios var user = Model.Users.Create(); user.name = "John Doe"; user.username = "******"; user.email = "*****@*****.**"; user.password = "******"; user.created_at = DateTime.Now; var user2 = Model.Users.Create(); user2.name = "Dabal Doe"; user2.username = "******"; user2.email = "*****@*****.**"; user2.password = "******"; user2.created_at = DateTime.Now; var user3 = Model.Users.Create(); user3.name = "John Doe"; user3.username = "******"; user3.email = "*****@*****.**"; user3.password = "******"; user3.created_at = DateTime.Now; user3.bannet_at = DateTime.Now; // Inserindo Realm var realmPvp = Model.Realms.Create(); realmPvp.flag = RealmFlag.NewPlayers; realmPvp.timezone = RealmTimezone.AnyLocale; realmPvp.type = RealmType.PVP; realmPvp.name = "Firetree"; realmPvp.address = "127.0.0.1:1001"; realmPvp.created_at = DateTime.Now; scope.Complete(); } }
public void Test_DataAccessScope_InvalidTransaction_ShouldCallRollbackHook() { var ex = Assert.Throws <DataAccessTransactionAbortedException>( () => { using (var scope = new DataAccessScope()) { var obj = this.model.DefaultsTestObjects.Create(); // Value required fields not populated scope.Complete(); } }); Console.WriteLine(ex); Assert.AreEqual(1, this.testDataModelHook.RollbackCount); }
// DONE: Generate Factions(Reputation) for Creation Char internal void GenerateFactions(Characters character) { var initiFactions = MainForm.FactionReader.GenerateFactions(character.race); foreach (var valFaction in initiFactions) { string[] faction = valFaction.Split(','); using (var scope = new DataAccessScope()) { var charFactions = Model.CharactersFactions.Create(); charFactions.character = character; charFactions.faction = int.Parse(faction[0]); charFactions.flags = int.Parse(faction[1]); charFactions.standing = int.Parse(faction[2]); charFactions.created_at = DateTime.Now; scope.Complete(); } } }
public void AddOrUpdate <T>(string name, T value) { var converter = GetConverter(name); if (converter == null && typeof(T) != typeof(string)) { throw new Exception($"No PlayerSettingConverter for {name} found"); } var str = converter != null?converter.GetString(value) : (string)(object)value; using (var scope = new DataAccessScope()) { if (_settings.ContainsKey(name)) { var dto = GameDatabase.Instance.Players .First(plr => plr.Id == (int)Player.Account.Id) .Settings .First(s => s.Setting == name); dto.Value = str; _settings[name] = value; } else { var dto = GameDatabase.Instance.Players .First(plr => plr.Id == (int)Player.Account.Id); var settingsDto = dto.Settings.Create(); settingsDto.Setting = name; settingsDto.Value = str; _settings[name] = value; } scope.Complete(); } }
public void Test_Updated_DeflatedPredicated_That_Does_Not_Exist() { Assert.Throws <MissingDataAccessObjectException>(() => { try { using (var scope = new DataAccessScope()) { var student = this.model.Students.GetReference(c => c.Firstname == Guid.NewGuid().ToString()); student.Nickname = "Test"; student.TimeSinceLastSlept = TimeSpan.FromHours(72); Assert.IsTrue(student.IsDeflatedReference()); scope.Complete(); } } catch (DataAccessTransactionAbortedException e) { throw e.InnerException; } }); }
public void Test_Nested_DataAccessScope_TransactionScope(bool completeOuter, bool completeInner) { using (var dataAccessScope = new DataAccessScope()) { var cat1 = this.model.Cats.Create(); using (var transactionScope = new TransactionScope()) { var cat2 = this.model.Cats.Create(); if (completeInner) { transactionScope.Complete(); } } if (completeOuter) { dataAccessScope.Complete(); } } Assert.AreEqual(completeOuter && completeInner ? 1 : 0, this.testDataModelHook.CommitCount); }
internal void CreateChar(CmsgCharCreate handler, Users users) { Helper = new CharacterHelper(); using (var scope = new DataAccessScope()) { var initRace = XmlReader.GetRace((Races)handler.Race); // Check Name in Use // Can't create character named as the bot // Check for disabled class/race, only for non GM/Admin // Check for both horde and alliance (Only if it's a pvp realm) // Check for max characters in total on all realms // DONE: Save Char var Char = Model.Characters.Create(); Char.user = users; // DONE: Make name capitalized as on official Char.name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(handler.Name); Char.race = (Races)handler.Race; Char.classe = (Classes)handler.Classe; Char.gender = (Genders)handler.Gender; Char.level = 1; Char.money = 0; Char.MapId = initRace.init.MapId; Char.MapZone = initRace.init.ZoneId; Char.MapX = initRace.init.MapX; Char.MapY = initRace.init.MapY; Char.MapZ = initRace.init.MapZ; Char.MapO = initRace.init.MapR; Char.char_skin = handler.Skin; Char.char_face = handler.Face; Char.char_hairStyle = handler.HairStyle; Char.char_hairColor = handler.HairColor; Char.char_facialHair = handler.FacialHair; Char.created_at = DateTime.Now; Char.watched_faction = 255; // Set Another status // Set Taxi Zones // tutorial Flags // Map Explored // Set Honor // Query Access Level and Account ID // Char.level scope.Complete(); } var character = MainForm.Database.GetCharacaterByName(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(handler.Name)); Helper.GenerateActionBar(character); // DONE: Generate Action Bar Helper.GenerateFactions(character); // DONE: Generate Reputation Factions Helper.GenerateSkills(character); // DONE: Generate Skills Helper.GenerateSpells(character); // DONE: Generate Spells Helper.GenerateInventory(character); // DONE: Generate Inventory }
public void StressTest() { var config = PostgresConfiguration.Create("StressTest", "localhost", "postgres", "postgres"); (config.SqlDatabaseContextInfos[0] as PostgresSqlDatabaseContextInfo).MaxPoolSize = 2; (config.SqlDatabaseContextInfos[0] as PostgresSqlDatabaseContextInfo).KeepAlive = 0; var dataModel = DataAccessModel.BuildDataAccessModel <TestDataAccessModel>(config); dataModel.Create(DatabaseCreationOptions.DeleteExistingDatabase); Console.WriteLine(dataModel.GetCurrentSqlDatabaseContext().ConnectionString); using (var scope = new DataAccessScope()) { var school = dataModel.Schools.Create(); var student = dataModel.Students.Create(); student.School = school; student.Firstname = "Tum"; student.Lastname = "Nguyen"; for (var i = 0; i < 10000; i++) { var s2 = dataModel.Students.Create(); s2.School = school; s2.Firstname = "Student " + i; } scope.Complete(); } const int numThreads = 10; var cancellationTokenSource = new CancellationTokenSource(); var resetEvents = new List <WaitHandle>(); for (var i = 0; i < numThreads; i++) { var resetEvent = new ManualResetEvent(false); resetEvents.Add(resetEvent); var dispatchThread = new Thread(_ => { while (!cancellationTokenSource.Token.IsCancellationRequested) { try { dataModel.Students.ToList(); } catch (Exception ex) { Console.WriteLine("Test error: {0}", ex); } } resetEvent.Set(); }) { Name = $"Thread: {i + 1}" }; dispatchThread.Start(); } Thread.Sleep(10000); cancellationTokenSource.Cancel(); WaitHandle.WaitAll(resetEvents.ToArray()); }
private static void FillShop() { var db = GameDatabase.Instance; if (!db.ShopVersion.Any()) { using (var scope = new DataAccessScope()) { var version = db.ShopVersion.Create(1); version.Version = DateTimeOffset.UtcNow.ToString("yyyyMMddHHmmss"); scope.Complete(); } } if (!Config.Instance.NoobMode || db.ShopEffectGroups.Any() || db.ShopEffects.Any() || db.ShopPriceGroups.Any() || db.ShopPrices.Any() || db.ShopItemInfos.Any() || db.ShopItems.Any()) { return; } Logger.Info() .Message("NoobMode: Filling the shop with items") .Write(); using (var scope = new DataAccessScope()) { #region Effects var noneEffectGroup = db.ShopEffectGroups.Create(); noneEffectGroup.Name = "None"; var hp30EffectGroup = db.ShopEffectGroups.Create(); hp30EffectGroup.Name = "HP+30"; hp30EffectGroup.ShopEffects.Create().Effect = 1030; var hp15EffectGroup = db.ShopEffectGroups.Create(); hp15EffectGroup.Name = "HP+15"; hp15EffectGroup.ShopEffects.Create().Effect = 1015; var sp40EffectGroup = db.ShopEffectGroups.Create(); sp40EffectGroup.Name = "SP+40"; sp40EffectGroup.ShopEffects.Create().Effect = 2040; var dualMasteryEffectGroup = db.ShopEffectGroups.Create(); dualMasteryEffectGroup.Name = "HP+20 & SP+20"; dualMasteryEffectGroup.ShopEffects.Create().Effect = 4001; var sp3EffectGroup = db.ShopEffectGroups.Create(); sp3EffectGroup.Name = "SP+3"; sp3EffectGroup.ShopEffects.Create().Effect = 2003; var defense7EffectGroup = db.ShopEffectGroups.Create(); defense7EffectGroup.Name = "Defense+7"; defense7EffectGroup.ShopEffects.Create().Effect = 19907; var hp3EffectGroup = db.ShopEffectGroups.Create(); hp3EffectGroup.Name = "HP+3"; hp3EffectGroup.ShopEffects.Create().Effect = 1003; #endregion #region Price var priceGroup = db.ShopPriceGroups.Create(); priceGroup.Name = "PEN"; priceGroup.PriceType = (byte)ItemPriceType.PEN; var price = priceGroup.ShopPrices.Create(); price.PeriodType = (byte)ItemPeriodType.None; price.IsRefundable = false; price.Durability = 1000000; price.IsEnabled = true; price.Price = 1; #endregion #region Items var items = GameServer.Instance.ResourceCache.GetItems().Values.ToArray(); for (var i = 0; i < items.Length; ++i) { var item = items[i]; var effectToUse = noneEffectGroup; switch (item.ItemNumber.Category) { case ItemCategory.Weapon: break; case ItemCategory.Skill: if (item.ItemNumber.SubCategory == 0 && item.ItemNumber.Number == 0) // half hp mastery { effectToUse = hp15EffectGroup; } if (item.ItemNumber.SubCategory == 0 && item.ItemNumber.Number == 1) // hp mastery { effectToUse = hp30EffectGroup; } if (item.ItemNumber.SubCategory == 0 && item.ItemNumber.Number == 2) // sp mastery { effectToUse = sp40EffectGroup; } if (item.ItemNumber.SubCategory == 0 && item.ItemNumber.Number == 3) // dual mastery { effectToUse = dualMasteryEffectGroup; } break; case ItemCategory.Costume: if (item.ItemNumber.SubCategory == (int)CostumeSlot.Hair) { effectToUse = defense7EffectGroup; } if (item.ItemNumber.SubCategory == (int)CostumeSlot.Face) { effectToUse = sp3EffectGroup; } if (item.ItemNumber.SubCategory == (int)CostumeSlot.Pants) { effectToUse = defense7EffectGroup; } if (item.ItemNumber.SubCategory == (int)CostumeSlot.Gloves) { effectToUse = hp3EffectGroup; } if (item.ItemNumber.SubCategory == (int)CostumeSlot.Shoes) { effectToUse = hp3EffectGroup; } if (item.ItemNumber.SubCategory == (int)CostumeSlot.Accessory) { effectToUse = sp3EffectGroup; } break; default: continue; } var shopItem = db.ShopItems.Create((uint)item.ItemNumber); shopItem.RequiredGender = (byte)item.Gender; shopItem.RequiredLicense = (byte)item.License; shopItem.IsDestroyable = true; var shopItemInfo = shopItem.ItemInfos.Create(); shopItemInfo.PriceGroup = priceGroup; shopItemInfo.EffectGroup = effectToUse; shopItemInfo.IsEnabled = true; Logger.Info() .Message("[{0}/{1}] {2}: {3}", i, items.Length, item.ItemNumber, item.Name) .Write(); } #endregion scope.Complete(); } }