Exemplo n.º 1
0
        // 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();
                }
            }
        }
Exemplo n.º 2
0
        public override string Log(Error error)
        {
            if (error == null)
            {
                throw new ArgumentNullException(nameof(error));
            }

            var errorXml = ErrorXml.EncodeString(error);

            using (var scope = DataAccessScope.CreateReadCommitted())
            {
                var dbElmahError = dataModel.ElmahErrors.Create();

                dbElmahError.Application = ApplicationName;
                dbElmahError.Host        = error.HostName;
                dbElmahError.Type        = error.Type;
                dbElmahError.Source      = error.Source;
                dbElmahError.Message     = error.Message;
                dbElmahError.User        = error.User;
                dbElmahError.StatusCode  = error.StatusCode;
                dbElmahError.TimeUtc     = error.Time;
                dbElmahError.AllXml      = errorXml;

                scope.Complete();

                return(dbElmahError.Id.ToString());
            }
        }
Exemplo n.º 3
0
        private async Task Test_Nested_Scope_Update_Async(ManualResetEvent e)
        {
            Guid id;
            var  methodName = MethodBase.GetCurrentMethod().Name;

            using (var scope = new DataAccessScope())
            {
                var child = this.model.Children.Create();

                await scope.FlushAsync().ContinueOnAnyContext();

                id = child.Id;

                using (var inner = new DataAccessScope())
                {
                    child.Nickname = methodName;

                    await inner.CompleteAsync().ContinueOnAnyContext();
                }

                await scope.FlushAsync();

                Assert.AreEqual(child.Id, this.model.Children.Single(c => c.Nickname == methodName).Id);

                await scope.CompleteAsync().ContinueOnAnyContext();
            }

            Assert.AreEqual(id, this.model.Children.Single(c => c.Nickname == methodName).Id);

            e.Set();
        }
Exemplo n.º 4
0
        public async Task <bool> SendAsync(string receiver, string title, string message)
        {
            // ToDo consume pen
            // ToDo check for ignore

            var accDto = await AuthDatabase.Instance.Accounts
                         .FirstOrDefaultAsync(acc => acc.Nickname == receiver)
                         .ConfigureAwait(false);

            if (accDto == null)
            {
                return(false);
            }

            using (var scope = new DataAccessScope())
            {
                var mailDto = GameDatabase.Instance.Players
                              .GetReference(accDto.Id)
                              .Inbox.Create();
                mailDto.SenderPlayer  = GameDatabase.Instance.Players.GetReference((int)Player.Account.Id);
                mailDto.SentDate      = DateTimeOffset.Now.ToUnixTimeSeconds();
                mailDto.Title         = title;
                mailDto.Message       = message;
                mailDto.IsMailNew     = true;
                mailDto.IsMailDeleted = false;

                await scope.CompleteAsync()
                .ConfigureAwait(false);

                var plr = GameServer.Instance.PlayerManager.Get(receiver);
                plr?.Mailbox.Add(new Mail(mailDto));
                return(true);
            }
        }
Exemplo n.º 5
0
        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();
            }
        }
Exemplo n.º 6
0
        private void ObtainAverage()
        {
            Console.WriteLine("Choose Prod Id to obtain Average");
            int prodId;

            while (!int.TryParse(Console.ReadLine(), out prodId))
            {
                Console.WriteLine("Invalid number, please try again!");
            }

            using (var das = new DataAccessScope(true))
            {
                IMapperProdVendidoPorFranqueado map = new MapperProdVendidoPorFranqueado();
                List <AvgSale> avgSales             = map.AvgSalesInPresentYear(prodId);
                if (avgSales.Count == 0)
                {
                    Console.WriteLine("Product with id = {0} did not sell any units this year", prodId);
                }
                foreach (AvgSale avg in avgSales)
                {
                    Console.WriteLine("Product {0} sold on average {1} units during this year", avg.ProdId, avg.Avg);
                }
                Console.WriteLine("Press any key to continue");
                Console.ReadKey();
            }
        }
Exemplo n.º 7
0
        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();
                }
            });
        }
        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);
        }
Exemplo n.º 9
0
        public async Task UpdateAsync(Consent consent)
        {
            using (var scope = DataAccessScope.CreateReadCommitted())
            {
                var item = dataModel.Consents.SingleOrDefault(x => x.Subject == consent.Subject && x.ClientId == consent.ClientId);

                if (consent.Scopes == null || !consent.Scopes.Any())
                {
                    item?.Delete();
                }
                else
                {
                    if (item == null)
                    {
                        item          = dataModel.Consents.Create();
                        item.Id       = Guid.NewGuid();
                        item.Subject  = consent.Subject;
                        item.ClientId = consent.ClientId;
                    }

                    item.Scopes = StringifyScopes(consent.Scopes);
                }

                await scope.CompleteAsync();
            }
        }
Exemplo n.º 10
0
        internal async void UpdateCharacter(int charId, string objeto, string value = null)
        {
            using (var scope = new DataAccessScope())
            {
                var character = Model.Characters.GetReference(charId);

                // Define Online/Offline
                if (objeto == "online" && character.is_online)
                {
                    character.is_online = false;
                }
                else
                {
                    character.is_online = true;
                }

                // Define primeiro Login
                if (objeto == "firstlogin")
                {
                    character.is_movie_played = true;
                }

                // Define primeiro Login
                if (objeto == "watchFaction" && value != null)
                {
                    character.watched_faction = int.Parse(value);
                }

                await scope.CompleteAsync();
            }
        }
Exemplo n.º 11
0
        public void Execute()
        {
            Console.WriteLine("What percentage relative to maxStock should be considered as running out of stock? (0-100)");
            double percentagemRutura = Double.Parse(Console.ReadLine());

            Console.WriteLine("Which franchisee is making the order?");
            int fid = int.Parse(Console.ReadLine());

            List <Entrega> produtosEmRutura;


            using (var das = new DataAccessScope(true))
            {
                IMapperProdVendidoPorFranqueado map   = new MapperProdVendidoPorFranqueado();
                List <ProdVendidoPorFranqueado> lpvpf = map.GetOutOfStock(percentagemRutura, fid);
                produtosEmRutura = lpvpf.Select(pvpf => ToEntrega(pvpf)).ToList();
                das.Commit();
            }

            using (var das = new DataAccessScope(true))
            {
                IMapperEntrega map = new MapperEntrega();
                map.OrderOutOfStock(produtosEmRutura);
                das.Commit();
            }
        }
Exemplo n.º 12
0
        public void Update(Franqueado entity)
        {
            using (var das = new DataAccessScope(true))
            {
                using (var ctx = new SI2_Bom_e_BaratoEntities())
                {
                    var franq_found = ctx.Franqueado.Find(entity.id);
                    if (franq_found != null)
                    {
                        var f = (from a in ctx.Franqueado where a.id == entity.id select a).SingleOrDefault();

                        f.id     = entity.id;
                        f.nif    = entity.nif;
                        f.morada = entity.morada;
                        f.nome   = entity.nome;

                        try
                        {
                            ctx.SaveChanges();
                            Console.WriteLine("Franchisee {0} updated.", entity.id);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.GetBaseException());
                        }
                    }
                    else
                    {
                        Console.WriteLine("Error updating Franchisee {0}", entity.id);
                    }
                }
                das.Commit();
            }
        }
Exemplo n.º 13
0
        public void Delete(int ProdId)
        {
            using (var das = new DataAccessScope(true))
            {
                using (var ctx = new SI2_Bom_e_BaratoEntities())
                {
                    var prd_found = ctx.Produto.Find(ProdId);

                    if (prd_found != null)
                    {
                        ctx.ProdVendidoPorFranqueado.RemoveRange(ctx.ProdVendidoPorFranqueado.Where(x => x.prod_id == prd_found.id));
                        ctx.HistoricoVendas.RemoveRange(ctx.HistoricoVendas.Where(x => x.prod_id == prd_found.id));
                        ctx.Entrega.RemoveRange(ctx.Entrega.Where(x => x.prod_id == prd_found.id));
                        ctx.Produto.Remove(prd_found);
                        ctx.SaveChanges();
                        Console.WriteLine("Product with ID {0} removed.", ProdId);
                    }
                    else
                    {
                        Console.WriteLine("Error removing Product {0}", ProdId);
                    }
                }
                das.Commit();
            }
        }
Exemplo n.º 14
0
        public async Task LoseDurabilityAsync(int loss)
        {
            if (loss < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(loss));
            }

            if (Inventory.Player.Room == null)
            {
                throw new InvalidOperationException("Player is not inside a room");
            }

            if (Durability == -1)
            {
                return;
            }

            Durability -= loss;
            if (Durability < 0)
            {
                Durability = 0;
            }

            using (var scope = new DataAccessScope())
            {
                var dto = GameDatabase.Instance.PlayerItems.GetReference((int)Id);
                dto.Durability = Durability;

                await scope.CompleteAsync()
                .ConfigureAwait(false);
            }

            await Inventory.Player.Session.SendAsync(new SItemDurabilityInfoAckMessage(new[] { this.Map <PlayerItem, ItemDurabilityInfoDto>() }))
            .ConfigureAwait(false);
        }
Exemplo n.º 15
0
        public void Test_DeleteAsync()
        {
            Func <Task> func = async delegate
            {
                using (var scope = new DataAccessScope())
                {
                    var school = this.model.Schools.Create();

                    await scope.FlushAsync();

                    var id = school.Id;

                    var item = await this.model.Schools.FirstOrDefaultAsync(c => c.Id == id);

                    Assert.IsNotNull(item);

                    await this.model.Schools.Where(c => c.Id == id).DeleteAsync();

                    item = await this.model.Schools.FirstOrDefaultAsync(c => c.Id == id);

                    Assert.IsNull(item);

                    await scope.CompleteAsync();
                }
            };

            var task = Task.Run(func);

            task.GetAwaiter().GetResult();
        }
        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);
        }
Exemplo n.º 17
0
        // 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();
                }
            }
        }
Exemplo n.º 18
0
        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();
            }
        }
Exemplo n.º 19
0
		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();
			}
		}
Exemplo n.º 20
0
        public async Task CreateNickHandler(GameServer server, GameSession session, CCreateNickReqMessage message)
        {
            if (session.Player == null || !string.IsNullOrWhiteSpace(session.Player.Account.Nickname))
            {
                session.Dispose();
                return;
            }

            Logger.Info()
            .Account(session)
            .Message("Creating nickname {0}", message.Nickname)
            .Write();

            if (!await IsNickAvailableAsync(message.Nickname).ConfigureAwait(false))
            {
                Logger.Error()
                .Account(session)
                .Message("Nickname not available: {0}", message.Nickname)
                .Write();

                await session.SendAsync(new SCheckNickAckMessage(false))
                .ConfigureAwait(false);

                return;
            }

            session.Player.Account.Nickname = message.Nickname;
            using (var scope = new DataAccessScope())
            {
                var accountDto = AuthDatabase.Instance.Accounts.GetReference((int)session.Player.Account.Id);
                //if (accountDto == null)
                //{
                //    Logger.Error()
                //        .Account(session)
                //        .Message("Account {0} not found", session.Player.Account.Id)
                //        .Write();

                //    await session.SendAsync(new SCheckNickAckMessage(false))
                //        .ConfigureAwait(false);
                //    return;
                //}
                accountDto.Nickname = message.Nickname;

                await scope.CompleteAsync()
                .ConfigureAwait(false);
            }
            //session.Send(new SCreateNickAckMessage { Nickname = msg.Nickname });
            await session.SendAsync(new SServerResultInfoAckMessage(ServerResult.CreateNicknameSuccess))
            .ConfigureAwait(false);

            Logger.Info()
            .Account(session)
            .Message("Created nickname {0}", message.Nickname)
            .Write();

            await LoginAsync(server, session)
            .ConfigureAwait(false);
        }
Exemplo n.º 21
0
 private void UpdateStock(List <ProdutoViewInStore> sale)
 {
     using (var das = new DataAccessScope(true))
     {
         IMapperProdVendidoPorFranqueado map = new MapperProdVendidoPorFranqueado();
         map.UpdateInBulk(franqId, sale);
         das.Commit();
     }
 }
Exemplo n.º 22
0
 private void RemoveFromProduto(int prodId)
 {
     using (var das = new DataAccessScope(true))
     {
         IMapperProduto map = new MapperProduto();
         map.Delete(prodId);
         das.Commit();
     }
 }
Exemplo n.º 23
0
 public async void FactionInative(int characterId, int faction, byte enabled)
 {
     using (var scope = new DataAccessScope())
     {
         var factions = Model.CharactersFactions.GetReference(new { Id = faction, CharacterId = characterId });
         factions.flags = enabled;
         await scope.CompleteAsync();
     }
 }
Exemplo n.º 24
0
 private void RemoveFranchiseeFromEntrega(int franqId)
 {
     using (var das = new DataAccessScope(true))
     {
         IMapperEntrega map = new MapperEntrega();
         map.DeleteAllWithFranqId(franqId);
         das.Commit();
     }
 }
Exemplo n.º 25
0
 private void RemoveFranchiseeFromFranqueado(int franqId)
 {
     using (var das = new DataAccessScope(true))
     {
         IMapperFranqueado map = new MapperFranqueado();
         map.Delete(franqId);
         das.Commit();
     }
 }
Exemplo n.º 26
0
 private void RemoveProductFromFornecedorProduto(int prodId)
 {
     using (var das = new DataAccessScope(true))
     {
         IMapperFornecedorProduto map = new MapperFornecedorProduto();
         map.DeleteAllWithProdId(prodId);
         das.Commit();
     }
 }
Exemplo n.º 27
0
 private void RemoveFranchiseeFromHistoricoVendas(int franqId)
 {
     using (var das = new DataAccessScope(true))
     {
         IMapperHistoricoVendas map = new MapperHistoricoVendas();
         map.DeleteAllWithFranqId(franqId);
         das.Commit();
     }
 }
Exemplo n.º 28
0
        public async Task RemoveAsync(string key)
        {
            using (var scope = DataAccessScope.CreateReadCommitted())
            {
                await DataModel.Tokens.DeleteAsync(x => x.Key == key && x.TokenType == TokenType);

                await scope.CompleteAsync();
            }
        }
Exemplo n.º 29
0
 private void RemoveFranchiseeFromProdVendidoPorFranqueado(int franqId)
 {
     using (var das = new DataAccessScope(true))
     {
         IMapperProdVendidoPorFranqueado map = new MapperProdVendidoPorFranqueado();
         map.DeleteAllWithFranqId(franqId);
         das.Commit();
     }
 }
Exemplo n.º 30
0
        public async Task RevokeAsync(string subject, string client)
        {
            using (var scope = DataAccessScope.CreateReadCommitted())
            {
                await dataModel.Consents.DeleteAsync(x => x.Subject == subject && x.ClientId == client);

                await scope.CompleteAsync();
            }
        }
Exemplo n.º 31
0
        // 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++;
                }
            }
        }
Exemplo n.º 32
0
		public TransactionScopeAdapter(DataAccessScope dataAccessScope)
		{
			this.dataAccessScope = dataAccessScope;
		}
Exemplo n.º 33
0
		/// <summary>Fetches existing entity that with PK set.</summary>
		public virtual bool Fetch(IActor actor, DataAccessScope detailLevel)
		{
			 IEntityDAO dao = DALHelper.GetDao(this, _ConnectionProvider);
			 bool exists = dao.SelectOne(detailLevel.IncludesParents);
			 if (exists && detailLevel.IncludesChildren)
				  DbFetchChildren();

			 return exists;
		}
Exemplo n.º 34
0
		/// <summary>Saves biz object if actor has required permission and if biz object is valid.</summary>
		public virtual BusinessRuleCollection FetchIfValid(IActor actor, DataAccessScope detailLevel, bool enforceSecurityChecks)
		{
				BusinessRuleCollection rules = new BusinessRuleCollection();

				// Check permissions.
				if (enforceSecurityChecks)
				    rules.Add(GrantFetch(actor));

				if (rules.HasBrokenRules)
				    return rules.GetBrokenRules();

				rules.Add(new BusinessRule("Entity_Exists", this.Fetch(actor, detailLevel), "Entity does not exist.", 1));
				return rules.GetBrokenRules();
		}