Beispiel #1
0
 public int Insert(AirPortModel.Models.DetailValue obj)
 {
     try
     {
         ////
         int id = _db.detailValues.OrderByDescending(x => x.DateCreate).Count() + 1;
         obj.Id = id;
         ////
         obj.DateCreate = DateTime.Now;
         obj.LastUpdate = DateTime.Now;
         obj.IsDelete   = false;
         _db.detailValues.Add(obj);
         /////
         _db.Database.OpenConnection();
         _db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Tbl_DetailValue ON");
         _db.SaveChanges();
         _db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Tbl_DetailValue OFF");
         ////
         return(obj.Id);
     }
     catch (Exception ex)
     {
         string mes = ex.Message;
         return(0);
     }
     finally
     {
         _db.Database.CloseConnection();
     }
 }
 public Genre Post([FromBody] Genre genre)
 {
     Console.WriteLine(genre.Name); ////////
     _context.Genres.Add(genre);
     _context.SaveChanges();
     return(_context.Genres.LastOrDefault());
 }
Beispiel #3
0
        public int Insert(AirPortModel.Models.Customer obj)
        {
            try
            {
                //*****************chek shavad hatma************************************
                AirPortModel.Models.Address Oaddress = new AirPortModel.Models.Address();
                Address address = new Address(_db);
                obj.address = _db.Adresses.FirstOrDefault(x => x.Id == 4);
                //*****************End chek shavad hatma************************************
                //obj.address = null;
                obj.Mobile       = null;
                obj.ProfileImage = null;
                obj.Sex          = true;
                obj.Isactive     = false;
                obj.IsDelete     = false;

                obj.DateCreate = DateTime.Now;
                obj.LastUpdate = DateTime.Now;
                _db.customers.Add(obj);
                _db.SaveChanges();
                return(obj.Id);
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                return(0);
            }
        }
Beispiel #4
0
        public IQueryable <Book> Post([FromBody] Book book)
        {
            _context.Books.Add(book);
            _context.SaveChanges();
            var bookId = _context.Books.LastOrDefault();

            return(_context.Books.Where(b => b.Id == bookId.Id).Include(b => b.Genre));
        }
        public void Post([FromBody] string value)
        {
            User user = new User();

            user.Name = value;
            user.Age  = 26;

            _db.Add(user);
            _db.SaveChanges();
        }
Beispiel #6
0
        public void Post([FromBody] string value)
        {
            User user = new User();

            user.Name = value;
            user.Age  = 20;

            _ctx.Users.Add(user); //Insert
            _ctx.SaveChanges();   //commint
        }
Beispiel #7
0
        public void CreateRecord(Record record)
        {
            if (_ctx.Records.Any(r => r.StartTime == record.StartTime && r.EndTime == record.EndTime && r.CameraId == record.CameraId))
            {
                throw new ArgumentException($"Attempted to create duplicate record");
            }

            record.Id     = 0;
            record.Status = RecordStatus.Awaits;

            _ctx.Records.Add(record);
            _ctx.SaveChanges();
        }
Beispiel #8
0
        public void Post([FromBody] Person person)
        {
            try
            {
                _ctx.Persons.Add(person);

                _ctx.SaveChanges();
            }
            catch (Exception e)
            {
                throw new HttpListenerException(500, Constants.Response.Error500);
            }
        }
Beispiel #9
0
        public void CreateCamera(Camera camera)
        {
            var existing = _ctx.Cameras.FirstOrDefault(c => c.IpAddress == camera.IpAddress);

            if (existing != null)
            {
                throw new ArgumentException($"Camera with IP: {existing.IpAddress} already exists");
            }

            camera.Id     = 0;
            camera.Status = CameraStatus.Offline;

            _ctx.Add(camera);
            _ctx.SaveChanges();
        }
Beispiel #10
0
        //сохранить новую либо обновить существующую запись в БД
        public int SaveNote(Note entity)
        {
            if (entity.Id == default)
            {
                entity.Date = DateTime.Now;
                context.Notes.Add(entity);
                //  context.Entry(entity).State = EntityState.Added;
            }
            else
            {
                context.Entry(entity).State = EntityState.Modified;
            }
            context.SaveChanges();

            return(entity.Id);
        }
Beispiel #11
0
        public int Save()
        {
            try
            {
                return(_context.SaveChanges());

                // TODO figure out a way to commit cosmos db changes in a transactional fashion
            }
            catch (DbEntityValidationException e)
            {
                // TODO: Handle exceptions and Log errors to db. Probably try to create a new instance of db context. If that fails, log to a file somewhere.
                var outputLines = new List <string>();
                foreach (var eve in e.EntityValidationErrors)
                {
                    outputLines.Add(string.Format("{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:", DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
                    foreach (var ve in eve.ValidationErrors)
                    {
                        outputLines.Add(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
                    }
                }
                File.AppendAllLines(@"C:\errors.txt", outputLines);

                throw;
            }
        }
Beispiel #12
0
        public void Post(/*Person person, List<Skill> skills*/)
        {
            /*_context.Persons.Add(person);
             * _context.SaveChanges();
             * for (var i = 0; i < skills.Count; i++)
             * {
             *  skills[i].PersonId = person.Id;
             *  _context.Skills.Add(skills[i]);
             * }
             *
             * _context.SaveChanges();*/
            Person person = new Person("Тест", "ASD");

            _context.Persons.Add(person);
            _context.SaveChanges();
        }
Beispiel #13
0
 public int Insert(AirPortModel.Models.Raiting obj)
 {
     try
     {
         obj.DateCreate = DateTime.Now;
         obj.LastUpdate = DateTime.Now;
         obj.IsDelete   = false;
         _db.raitings.Add(obj);
         _db.SaveChanges();
         return(obj.Id);
     }
     catch (Exception)
     {
         return(0);
     }
 }
Beispiel #14
0
        public ArticlesTest()
        {
            options = new DbContextOptionsBuilder <AppDatabaseContext>().
                      UseInMemoryDatabase(databaseName: "AppDatabaseArticles").Options;

            db = new AppDatabaseContext(options);

            var article1 = new Article
            {
                Id    = firstArticleId,
                Title = "Article 1"
            };

            var article2 = new Article
            {
                Id    = secondArticleId,
                Title = "Article 2"
            };

            try
            {
                db.Articles.Add(article1);
                db.Articles.Add(article2);

                db.SaveChanges();
            }
            catch (ArgumentException)
            {
                db.Articles.RemoveRange(db.Articles);
            }
        }
Beispiel #15
0
 public int Insert(AirPortModel.Models.Detail obj)
 {
     try
     {
         obj.DateCreate = DateTime.Now;
         obj.LastUpdate = DateTime.Now;
         obj.IsDelete   = false;
         _db.details.Add(obj);
         _db.SaveChanges();
         return(obj.Id);
     }
     catch (Exception ex)
     {
         _ = ex.Message;
         return(0);
     }
 }
Beispiel #16
0
 public int Insert(AirPortModel.Models.Gallery obj)
 {
     try
     {
         obj.DateCreate = DateTime.Now;
         obj.LastUpdate = DateTime.Now;
         obj.IsDelete   = false;
         _db.galleries.Add(obj);
         _db.SaveChanges();
         return(obj.Id);
     }
     catch (Exception ex)
     {
         string mes = ex.Message;
         return(0);
     }
 }
Beispiel #17
0
        public void Move(int posX)
        {
            int y = 0;

            if (AgainstAi)
            {
                Random r = new Random();
                var    x = r.Next(0, BoardWidth - 1);

                var h = 0;
                for (int i = 0; i < BoardHeight; i++)
                {
                    if (Board[i, x].Equals(CellState.Empty))
                    {
                        h = i;
                    }
                }

                if (Board[h, x] == CellState.Empty)
                {
                    Board[h, x]  = MoveCounter % 2 != 0 ? CellState.X : CellState.O;
                    MoveCounter += 1;
                }
                else
                {
                    return;
                }
            }

            for (int i = 0; i < BoardHeight; i++)
            {
                if (Board[i, posX].Equals(CellState.Empty))
                {
                    y = i;
                }
            }

            if (Board[y, posX] == CellState.Empty)
            {
                Board[y, posX] = MoveCounter % 2 != 0 ? CellState.X : CellState.O;
                MoveCounter   += 1;
                //There should be a pop up message with js
            }
            else
            {
                return;
            }

            //_context.Entry(_gameSettings).State = EntityState.Detached;
            _gameSettings.MovesCounter = MoveCounter;
            _gameSettings.CellStates   = Board;
            _context.Settings.Update(_gameSettings);
            _context.SaveChanges();
            if (Validator(Board, BoardHeight, BoardWidth))
            {
            }
        }
Beispiel #18
0
        public bool Subscribe(int feedId, string userId)
        {
            bool success = true;

            try
            {
                _appDbContext.FeedUserSubscriptions.Add(new FeedUserSubscription
                {
                    FeedId           = feedId,
                    UserSubscriberId = userId
                });

                _appDbContext.SaveChanges();
            }
            catch (Exception ex)
            {
                _logger.LogError($"An attempt to subscribe User: '******' to Feed: {feedId} threw an error: {ex}");
                success = false;
            }
            return(success);
        }
Beispiel #19
0
        private void AddTestCountries()
        {
            var countries = DummyDataGenerator.GetCountries(10);

            using (var appDbcontext = new AppDatabaseContext())
            {
                foreach (var country in countries)
                {
                    appDbcontext.Countries.Add(country);
                }
                appDbcontext.SaveChanges();
            }
        }
Beispiel #20
0
 public int Insert(AirPortModel.Models.CustomerFlight obj)
 {
     try
     {
         if (_db.CustomerFlight.FirstOrDefault(x => x.FlightId.Equals(obj.FlightId) && x.CustomerId.Equals(obj.CustomerId)) == null)
         {
             obj.DateCreate = DateTime.Now;
             obj.LastUpdate = DateTime.Now;
             obj.IsDelete   = false;
             _db.CustomerFlight.Add(obj);
             _db.SaveChanges();
             return(obj.Id);
         }
         else
         {
             return(0);
         }
     }
     catch (Exception)
     {
         return(0);
     }
 }
Beispiel #21
0
        //По идее post - создает ресурс, а put - обновляет или редактирует,
        //но раз в ТЗ написано что put - должен создавать,
        //а post  - редактировать, так тому и быть )
        public async Task <IActionResult> Put(long id, [FromBody] Person requestPerson)
        {
            if (!PersonExists(id))
            {
                return(NotFound());
            }
            var person      = _context.Persons.Include(p => p.skills).Where(p => p.id == id).FirstOrDefault();
            var skillRemove = _context.Skills.Where(s => s.PersonId == person.id).ToList();

            foreach (var i in skillRemove)
            {
                _context.Skills.Remove(i);
                _context.SaveChanges();
            }

            foreach (var i in requestPerson.skills)
            {
                Skill skill = new Skill();
                skill.level    = i.level;
                skill.name     = i.name;
                skill.PersonId = person.id;
                _context.Skills.Add(skill);
                person.skills.Add(skill);
                _context.SaveChanges();
            }

            person.name        = requestPerson.name;
            person.displayName = requestPerson.displayName;
            try {
                _context.Update(person);
                await _context.SaveChangesAsync();

                return(Ok(person));
            } catch {
                return(BadRequest());
            }
        }
Beispiel #22
0
        private void AddTestCities()
        {
            var cities = DummyDataGenerator.GetCities(10);

            using (var appDbcontext = new AppDatabaseContext())
            {
                var state = appDbcontext.States.First();
                foreach (var city in cities)
                {
                    city.StateId = state.Id;
                    appDbcontext.Cities.Add(city);
                }
                appDbcontext.SaveChanges();
            }
        }
Beispiel #23
0
        private void AddTestStates()
        {
            var states = DummyDataGenerator.GetStates(10);

            using (var appDbcontext = new AppDatabaseContext())
            {
                var country = appDbcontext.Countries.First();
                foreach (var state in states)
                {
                    state.CountryId = country.Id;
                    appDbcontext.States.Add(state);
                }
                appDbcontext.SaveChanges();
            }
        }
Beispiel #24
0
        private void AddTestAddresses()
        {
            var addresses = DummyDataGenerator.GetAddresses(10);

            using (var appDbcontext = new AppDatabaseContext())
            {
                var countries = appDbcontext.Countries.ToList();
                var states    = appDbcontext.States.ToList();
                var cities    = appDbcontext.Cities.ToList();
                foreach (var address in addresses)
                {
                    var random  = new Random();
                    var country = countries[random.Next(0, countries.Count - 1)];
                    var state   = states[random.Next(0, states.Count - 1)];
                    var city    = cities[random.Next(0, cities.Count - 1)];
                    address.CityId = city.Id;
                    appDbcontext.Addresses.Add(address);
                }
                appDbcontext.SaveChanges();
            }
        }
Beispiel #25
0
        public static string GameEngine()
        {
            _settings = new GameSettings {
                MovesCounter = 0, Time = DateTime.Now
            };
            if (Menu.AgainstAi)
            {
                _settings.AgainstAi = true;
            }

            int  userBoardHeightInt;
            int  userBoardWidthInt;
            bool success;
            bool nameSet;

            do
            {
                Console.WriteLine("Enter your Name");
                Console.Write(">");
                _settings.PlayerName = Console.ReadLine();
                nameSet = _settings.PlayerName != null && _settings.PlayerName.Length >= 1;

                if (!nameSet)
                {
                    Console.WriteLine("Please enter your name!");
                    //_settings.Time = DateTime.Now;
                }
            } while (!nameSet);

            do
            {
                Console.WriteLine("Enter board height");
                Console.Write(">");
                var userBoardHeight = Console.ReadLine();
                success = int.TryParse(userBoardHeight, out userBoardHeightInt);
                if (!success || userBoardHeightInt < 6)
                {
                    Console.WriteLine($"{userBoardHeight} is not a number or too small(6)!");
                    success = false;
                }
            } while (!success);

            do
            {
                Console.WriteLine("Enter board width");
                Console.Write(">");
                var userBoardWidth = Console.ReadLine();
                success = int.TryParse(userBoardWidth, out userBoardWidthInt);
                if (!success || userBoardWidthInt < 7)
                {
                    Console.WriteLine($"{userBoardWidth} is not a number or is too small(7)!");
                    success = false;
                }
            } while (!success);

            _settings.BoardHeight = userBoardHeightInt;
            _settings.BoardWidth  = userBoardWidthInt;
            var  game = new Game(_settings);
            bool done;

            do
            {
                UserInterface.BoardPrint(game);
                int userYInt;
                do
                {
                    if (_settings.MovesCounter % 2 == 0 && _settings.AgainstAi)
                    {
                        Console.WriteLine("Mastermind AI move");
                        var r = new Random();
                        userYInt = r.Next(0, _settings.BoardWidth - 1);
                        success  = true;
                    }
                    else
                    {
                        Console.WriteLine("Enter EXIT to Go to Main Menu");
                        Console.WriteLine($"Enter column number(0-{userBoardHeightInt - 1})");
                        Console.WriteLine("Your move");
                        Console.Write(">");

                        var userY = Console.ReadLine();
                        if (userY == "EXIT")
                        {
                            Menu.AgainstAi = false;
                            return("");
                        }

                        success = int.TryParse(userY, out userYInt);
                        if (!success || userYInt > _settings.BoardWidth)
                        {
                            Console.WriteLine($"{userY} is not a number or is out of board!");
                            success = false;
                        }
                    }
                } while (!success);

                _settings.MovesCounter += game.Move(userYInt);
                _settings.CellStates    = game.GetBoard();
                using (var ctx = new AppDatabaseContext())
                {
                    if (ctx.Settings.Any(n => n.PlayerName == _settings.PlayerName))
                    {
                        ctx.Settings.Update(_settings);
                    }
                    else
                    {
                        ctx.Settings.Add(_settings);
                    }

                    ctx.SaveChanges();
                }


                done = Validator(_settings.CellStates, userBoardHeightInt, userBoardWidthInt);
            } while (!done);

            UserInterface.BoardPrint(game);
            using (var ctx = new AppDatabaseContext())
            {
                ctx.Attach(_settings);
                ctx.Remove(_settings);
                ctx.SaveChanges();
            }

            Console.WriteLine("Game Over!");
            return("");
        }
Beispiel #26
0
        public List <Item> GetItemsWithPrice(List <Item> items, AppDatabaseContext context, List <HttpClient> clients)
        {
            List <Item>         responseItems = new List <Item>();
            List <Task <Item> > taskPool      = new List <Task <Item> >();

            #region FastWay
            //int index = 0;
            //while (items.Count > 0)
            //{
            //    while (taskPool.Count <= 10)
            //    {
            //        Item curItem = items[0];
            //        HttpClient tempClient = clients[index];
            //        taskPool.Add(Task.Run(() => Steam.GetItemPrice(tempClient, curItem))); //Почему нельзя передават сразу параметры, а только через переменные-посредники?
            //        items.Remove(curItem);
            //        index++;
            //        if (index >= Proxies.Count())
            //        {
            //            index = 0;
            //        }
            //    }
            //    int taskIndex = Task.WaitAny(taskPool.ToArray());
            //    Item item = taskPool[taskIndex].Result;
            //    taskPool.Remove(taskPool[taskIndex]);
            //    responseItems.Add(item);
            //}
            #endregion

            //Поиск по базе данных, и если Айтем нашелся и он был обновлен меньше чем 30 минут назад, то добавляем его в список возвращяемых Айтемов
            List <Item> itemsToRemove = new List <Item>();
            foreach (Item item in items)
            {
                Item dbItem = context.Items.Where(c => c.Name == item.Name && c.IdSecond == item.IdSecond).FirstOrDefault();
                if (dbItem != null)
                {
                    if ((DateTime.Now - dbItem.UpTime).TotalMinutes < 30)
                    {
                        dbItem.Price = item.Price;
                        responseItems.Add(dbItem);
                        itemsToRemove.Add(item);
                        context.Attach(dbItem);
                    }
                }
            }

            foreach (Item rmItem in itemsToRemove)
            {
                items.Remove(rmItem);
            }

            //Медленный способ запросов на стим площадку, обновление базы данных.
            int temp = items.Count / clients.Count();
            for (int i = 0; i < temp + 1; i++)
            {
                for (int j = i * clients.Count(); j < (i + 1) * clients.Count(); j++)
                {
                    if (j >= items.Count())
                    {
                        break;
                    }
                    Item       curItem   = items[j];
                    HttpClient curClient = clients[j - i * clients.Count()];
                    taskPool.Add(Task.Run(() => Steam.GetItemPrice(curClient, curItem)));
                }
                Task.WaitAll(taskPool.ToArray());
                for (int y = 0; y < taskPool.Count(); y++)
                {
                    Item res = taskPool[y].Result;
                    Console.WriteLine("Not Loaded: " + res.Name);
                    if (res.SteamPrice != -100)
                    {
                        Item dbItem = context.Items.Where(c => c.Name == res.Name && c.IdSecond == res.IdSecond).FirstOrDefault();
                        if (dbItem != null)
                        {
                            dbItem.SteamPrice = res.SteamPrice;
                            dbItem.UpTime     = res.UpTime;
                            responseItems.Add(dbItem);
                            context.Attach(dbItem);
                        }
                        else
                        {
                            responseItems.Add(res);
                            context.Items.Update(res);
                        }
                    }
                }
                taskPool.Clear();
            }
            context.SaveChanges();
            Console.WriteLine("Items delivered: " + responseItems.Count().ToString());
            return(responseItems);
        }
 public int SaveChanges() => _dbContext.SaveChanges();
Beispiel #28
0
 public virtual void Commit()
 {
     _context.SaveChanges();
 }
Beispiel #29
0
        public static string LoadSavedGame()
        {
            var    filenames  = new List <string>();
            var    fileNames2 = new Dictionary <int, string>();
            int    savedFileInt;
            string savedFile;

            using var ctx = new AppDatabaseContext();
            do
            {
                Console.WriteLine("Saved Games :");
                foreach (var fileName in ctx.Settings)
                {
                    Console.WriteLine(fileName.GameSettingsId + " " + fileName.PlayerName + " " + fileName.Time.ToString("yyyy-MM-dd HH:mm"));
                    fileNames2.Add(fileName.GameSettingsId, fileName.PlayerName);
                    filenames.Add(fileName.PlayerName);
                }


                Console.WriteLine();
                Console.WriteLine("Enter saved game number");
                Console.WriteLine("Enter EXIT to leave");
                Console.Write(">");
                savedFile = Console.ReadLine();
                if (savedFile == "EXIT")
                {
                    return("");
                }

                var loadSuccess = false;
                loadSuccess = int.TryParse(savedFile, out savedFileInt);
                if (!loadSuccess)
                {
                    Console.WriteLine($"{savedFile} is not a number");
                }

                if (!ctx.Settings.Any(n => n.GameSettingsId == savedFileInt))
                {
                    Console.WriteLine("No Such Saved game!");
                }
            } while (!fileNames2.ContainsKey(savedFileInt));


            GameSettings savedGame = ctx.Settings.First(n => n.GameSettingsId == savedFileInt);

            if (savedGame != null)
            {
                ctx.Entry(savedGame).State = EntityState.Detached;
            }

            var game = new Game(savedGame);

            game.SetBoard(savedGame?.CellStates);
            bool done;

            do
            {
                UserInterface.BoardPrint(game);
                int  userYInt;
                bool success;

                do
                {
                    if (savedGame?.MovesCounter % 2 == 0 && savedGame.AgainstAi)
                    {
                        Console.WriteLine("Mastermind AI move");
                        Random r = new Random();
                        userYInt = r.Next(0, savedGame.BoardWidth - 1);
                        success  = true;
                    }
                    else
                    {
                        Console.WriteLine("Enter EXIT to Go to Main Menu");
                        Console.WriteLine($"Enter column number(0-{savedGame?.BoardHeight - 1})");
                        Console.WriteLine("Your move");
                        Console.Write(">");

                        var userY = Console.ReadLine();
                        if (userY == "EXIT")
                        {
                            Menu.AgainstAi = false;
                            return("");
                        }

                        success = int.TryParse(userY, out userYInt);
                        if (!success || userYInt > savedGame?.BoardWidth)
                        {
                            Console.WriteLine($"{userY} is not a number or is out of board!");
                            success = false;
                        }
                    }
                } while (!success);


                savedGame.MovesCounter += game.Move(userYInt);
                savedGame.CellStates    = game.GetBoard();

                ctx.Entry(savedGame).State = EntityState.Modified;
                //ctx.Settings.Update(savedGame);
                ctx.SaveChanges();

                done = Validator(savedGame.CellStates, savedGame.BoardHeight, savedGame.BoardWidth);
            } while (!done);
            UserInterface.BoardPrint(game);
            ctx.Attach(savedGame);
            ctx.Remove(savedGame);
            ctx.SaveChanges();
            Console.WriteLine("Game Over!");
            return("");
        }