// GET: Auctions
        public ActionResult Index()
        {
            AuctionContext db       = new AuctionContext();
            List <Auction> auctions = db.Auctions.ToList();

            return(View(auctions));
        }
Example #2
0
        public async Task <IEnumerable <LotModel> > GetLotByNameAndDate(string name, DateTime start, DateTime end)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            using (var db = new AuctionContext())
            {
                var lots = db.Lots
                           .Where(L =>
                                  L.AuctionDate >= start &&
                                  L.AuctionDate <= end &&
                                  L.Name == name)
                           .Select(L => new LotModel
                {
                    Id            = L.Id,
                    Name          = L.Name,
                    Description   = L.Description,
                    Quantity      = L.Quantity,
                    Unit          = L.Unit,
                    StartingPrice = L.StartingPrice,
                    CurrentPrice  = L.CurrentPrice,
                    MinimalBid    = L.MinimalBid,
                    BidCount      = L.BidCount,
                    AuctionDate   = L.AuctionDate
                })
                           .ToList();

                return(lots);
            }
        }
Example #3
0
        public async Task <IEnumerable <LotModel> > GetLots()
        {
            using (var db = new AuctionContext())
            {
                try
                {
                    var lots = db.Lots.Select(L => new LotModel
                    {
                        Id            = L.Id,
                        Name          = L.Name,
                        Description   = L.Description,
                        Quantity      = L.Quantity,
                        Unit          = L.Unit,
                        StartingPrice = L.StartingPrice,
                        CurrentPrice  = L.CurrentPrice,
                        MinimalBid    = L.MinimalBid,
                        BidCount      = L.BidCount,
                        AuctionDate   = L.AuctionDate
                    }).ToList();

                    return(lots);
                }
                catch (Exception)
                {
                    return(new List <LotModel>());
                }
            }
        }
Example #4
0
        public void UpdateItems()
        {
            HtmlWeb          web         = new HtmlWeb();
            List <string>    NewItemList = new List <string>();
            List <ItemClass> NewItems    = new List <ItemClass>();

            string[]     a = new[] { "head", "body", "weapon", "hands", "feet", "amulet", "consumable" };
            HtmlDocument doc;
            HtmlEntity   util;

            foreach (var i in a)
            {
                doc = web.Load($"https://www.roshpit.ca/items?slot={i}");
                HtmlNodeCollection items = doc.DocumentNode.SelectNodes($"//div[@id={Strings.Chr(34)}item-table-container{Strings.Chr(34)}]//a");
                foreach (var it in items)
                {
                    NewItemList.Add(it.GetAttributeValue("href", "none"));
                }
            }
            foreach (var it in NewItemList)
            {
                NewItems.Add(LoadItem($"https://www.roshpit.ca/{it}"));
                System.Threading.Thread.Sleep(500);
            }
            using (AuctionContext myx = new AuctionContext())
            {
                myx.Items.AddRange(NewItems);
                myx.SaveChanges();
            }
        }
Example #5
0
        public ActionResult Auction(long id)
        {
            AuctionContext context = new AuctionContext();
            var            auction = db.Auctions.Find(id);

            return(View(auction));
        }
        public async Task <RaffleEntry> AddRaffleEntry(string raffleId, long amount, string description)
        {
            var raffle = GetRaffle(raffleId);

            if (raffle == null)
            {
                return(null);
            }
            if (raffle.FinishedAt != -1)
            {
                return(null);
            }
            var raffleEntry = new RaffleEntry
            {
                Amount   = amount,
                Memo     = description,
                Raffle   = raffle,
                RaffleId = raffle.Id,
            };

            raffle.RaffleEntries.Add(raffleEntry);
            using (var context = new AuctionContext())
            {
                context.Raffles.Update(raffle);
                raffleEntry = context.RaffleEntries.Add(raffleEntry).Entity;
                await context.SaveChangesAsync();
            }
            return(raffleEntry);
        }
        public bool SetWinnersForProducts()
        {
            var expiredProducts = ProductController.Instance().GetExpiredProductsIds();

            using (var db = new AuctionContext())
            {
                var bids = db.Bids
                           .Where(b => expiredProducts.Contains(b.ProductId))
                           .ToList();

                if (bids.Count == 0)
                {
                    return(false);
                }

                foreach (var productId in expiredProducts)
                {
                    var currentBids = bids
                                      .Where(b => b.ProductId == productId)
                                      .ToList();   // remove this and include the where in first or default below

                    var lastBidder = currentBids
                                     .OrderByDescending(r => r.DateOfCreated)        // or coins doesn't matter
                                     .Take(1)
                                     .FirstOrDefault();

                    lastBidder.IsWon = true;
                }

                db.SaveChanges();
            }

            return(true);
        }
        public async Task <IEnumerable <TraderModel> > GetTradersByNameAndDate(string name, DateTime start, DateTime end)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            using (var db = new AuctionContext())
            {
                var traders = db.Traders
                              .Where(t =>
                                     t.AuctionDate >= start &&
                                     t.AuctionDate <= end &&
                                     t.Name == name)
                              .Select(t => new TraderModel
                {
                    Id                = t.Id,
                    Name              = t.Name,
                    LegacyForm        = t.LegacyForm,
                    IdentityNumber    = t.IdentityNumber,
                    ApplicantName     = t.ApplicantName,
                    ParticipantName   = t.ParticipantName,
                    ParticipantStatus = t.ParticipantStatus,
                    PhoneNumber       = t.PhoneNumber,
                    Email             = t.Email,
                    BankName          = t.BankName,
                    BankAccountNumber = t.BankAccountNumber,
                    Swift             = t.Swift,
                    AuctionDate       = t.AuctionDate
                }).ToList();

                return(traders);
            }
        }
        public async Task <TraderModel> EditTrader(TraderModel trader)
        {
            if (trader == null)
            {
                throw new ArgumentNullException(nameof(trader));
            }

            using (var db = new AuctionContext())
            {
                var traderEntity = db.Traders.FirstOrDefault(t => t.Id == trader.Id);
                if (traderEntity == null)
                {
                    return(null);
                }

                traderEntity.LegacyForm        = trader.LegacyForm;
                traderEntity.IdentityNumber    = trader.IdentityNumber;
                traderEntity.ApplicantName     = trader.ApplicantName;
                traderEntity.ParticipantName   = trader.ParticipantName;
                traderEntity.ParticipantStatus = trader.ParticipantStatus;
                traderEntity.PhoneNumber       = trader.PhoneNumber;
                traderEntity.Email             = trader.Email;
                traderEntity.BankName          = trader.BankName;
                traderEntity.BankAccountNumber = trader.BankAccountNumber;
                traderEntity.Swift             = trader.Swift;
                traderEntity.AuctionDate       = trader.AuctionDate;

                await db.SaveChangesAsync();

                return(trader);
            }
        }
Example #10
0
        public List <Bid> GetAllBids(short lotId, string order, string filterPrice, string filterDate, int pageSize = 5, int pageNumber = 1)
        {
            // Filtering
            // Price formating
            List <int> filterPriceRange = new List <int>();
            int        minPrice = 0, maxPrice = int.MaxValue;

            if (string.IsNullOrEmpty(filterPrice))
            {
                filterPrice = "";
            }
            else if (!filterPrice.Contains(","))
            {
                filterPrice      = "0," + filterPrice;
                filterPriceRange = filterPrice.Split(',').Select(item => int.Parse(item)).ToList();
                minPrice         = filterPriceRange[0]; maxPrice = filterPriceRange[1];
            }
            else
            {
                filterPriceRange = filterPrice.Split(',').Select(item => int.Parse(item)).ToList();
                minPrice         = filterPriceRange[0]; maxPrice = filterPriceRange[1];
            }

            // Date formating
            List <DateTime> filterDateRange = new List <DateTime>();
            DateTime        minDate = new DateTime(2000, 1, 1); DateTime maxDate = new DateTime(2100, 1, 1);

            if (string.IsNullOrEmpty(filterDate))
            {
                filterDate = "";
            }
            else if (!filterDate.Contains(","))
            {
                filterDate      = DateTime.MinValue.ToString() + "," + filterDate;
                filterDateRange = filterDate.Split(',').Select(item => DateTime.Parse(item)).ToList();
                minDate         = new DateTime(2000, 1, 1); maxDate = filterDateRange[1];
            }
            else
            {
                filterDateRange = filterDate.Split(',').Select(item => DateTime.Parse(item)).ToList();
                minDate         = filterDateRange[0]; maxDate = filterDateRange[1];
            }


            AuctionContext      db         = new AuctionContext();
            List <SqlParameter> parameters = new List <SqlParameter>()
            {
                new SqlParameter("@LotId", lotId),
                new SqlParameter("@PriceMin", minPrice),
                new SqlParameter("@PriceMax", maxPrice),
                new SqlParameter("@DateMin", minDate),
                new SqlParameter("@DateMax", maxDate),
                new SqlParameter("@StartRowIndex", pageSize * (pageNumber - 1)),
                new SqlParameter("@PageSize", pageSize)
            };
            var result = db.Database.SqlQuery <Bid>("dbo.GetBids @LotId , @PriceMin , @PriceMax ,@DateMin , @DateMax , @StartRowIndex , @PageSize ", parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6]).ToList();

            result = string.IsNullOrEmpty(order) ? result : result.AsQueryable().ApplySort(order).ToList();
            return(result);
        }
        public async Task <TraderModel> AddTrader(TraderModel trader)
        {
            if (trader == null)
            {
                throw new ArgumentNullException(nameof(trader));
            }

            using (var db = new AuctionContext())
            {
                var traderEntity = new Trader()
                {
                    Name              = trader.Name,
                    LegacyForm        = trader.LegacyForm,
                    IdentityNumber    = trader.IdentityNumber,
                    ApplicantName     = trader.ApplicantName,
                    ParticipantName   = trader.ParticipantName,
                    ParticipantStatus = trader.ParticipantStatus,
                    PhoneNumber       = trader.PhoneNumber,
                    Email             = trader.Email,
                    BankName          = trader.BankName,
                    BankAccountNumber = trader.BankAccountNumber,
                    Swift             = trader.Swift,
                    AuctionDate       = trader.AuctionDate
                };

                db.Traders.Add(traderEntity);
                await db.SaveChangesAsync();

                trader.Id = traderEntity.Id;
                return(trader);
            }
        }
        public ActionResult Bid(Bid bid)
        {
            AuctionContext db = new AuctionContext();

            var auction = db.Auctions.Find(bid.AuctionId);

            if (auction == null)
            {
                ModelState.AddModelError("AuctionId", "Auction Not Found");
            }
            else if (auction.CurrentPrice >= bid.Amount)
            {
                ModelState.AddModelError("Amount", "Bid Amount Less then the current Amount");
            }
            else
            {
                bid.UserName = User.Identity.Name;
                db.Bids.Add(bid);
                auction.CurrentPrice = bid.Amount;
                db.SaveChanges();
            }
            if (!Request.IsAjaxRequest())
            {
                return(RedirectToAction("FindingBy", new { id = bid.AuctionId }));
            }

            return(Json(new
            {
                CurrentPrice = bid.Amount.ToString("C"),
                BidCount = auction.Bidcount
            }));
        }
        public ActionResult Auction([Bind(Exclude = "CurrentPrice")] Auction auction)
        {
            //if (string.IsNullOrWhiteSpace(auction.Title))
            //{
            //    ModelState.AddModelError("Title", "Title Must  be Required");
            //}
            //else if (auction.Title.Length < 5 || auction.Title.Length > 200)
            //{
            //    ModelState.AddModelError("Title", "Your Title Must be Greater Then 5 and Less then 200 char");
            //}

            if (ModelState.IsValid)
            {
                AuctionContext db = new AuctionContext();
                using (db)
                {
                    db.Auctions.Add(auction);
                    db.SaveChanges();
                }

                return(RedirectToAction("Index"));
            }

            return(View());
        }
        public ActionResult FindingBy(long id)
        {
            AuctionContext db      = new AuctionContext();
            var            auction = db.Auctions.Find(id);

            return(View(auction));
        }
Example #15
0
        static void Main(string[] args)
        {
            AuctionContext context = new AuctionContext();
            UnitOfWork     uow     = new UnitOfWork(context, new ContextRepository <Lot>(context), new ContextRepository <Role>(context), new ContextRepository <User>(context));

            uow.Roles.Create(new Role()
            {
                Role_name = "Admin"
            });
            uow.Roles.Create(new Role()
            {
                Role_name = "Manager"
            });
            uow.Roles.Create(new Role()
            {
                Role_name = "User"
            });
            uow.Roles.Create(new Role()
            {
                Role_name = "Guest"
            });
            uow.Save();
            uow.Users.Create(new User()
            {
                Login = "******", Pass = "******", Name = "Admin1", Role_FK = 1
            });
            uow.Save();
            Console.WriteLine("Done");
            Console.ReadLine();
        }
        public Task Handle(ProductSelectionChanged message)
        {
            _bidItemsViewModels.Clear();

            return(Task.Run(() =>
            {
                if (message.Product == null)
                {
                    return;
                }

                using (var db = new AuctionContext())
                {
                    var bids = db.Bids.Where(bid => bid.ProductId == message.Product.Id).OrderByDescending(bid => bid.BidDate).ToList();

                    foreach (var bid in bids)
                    {
                        _bidItemsViewModels.Add(new BidItemViewModel
                        {
                            BidAmount = bid.BidAmount,
                            BidDate = bid.BidDate,
                            BidderName = db.Accounts.First(account => account.Id == bid.AccountId).UserName,
                        });
                    }
                }
            }));
        }
Example #17
0
        public void SubmitBid(Product product)
        {
            var vm = new PlaceBidViewModel
            {
                BidAmount = product.LastBidAmount,
                Title     = product.Title
            };

            _windowManager.ShowDialog(vm);

            if (vm.IsCancelled)
            {
                return;
            }

            using (var db = new AuctionContext())
            {
                product.LastBidAmount   = vm.BidAmount;
                db.Entry(product).State = EntityState.Modified;
                db.Bids.Add(new Bid
                {
                    AccountId = _loginViewModel.Account.Id,
                    BidAmount = vm.BidAmount,
                    ProductId = product.Id
                });
                db.SaveChanges();
            }
        }
Example #18
0
        public async Task <AuctioneerModel> RegisterAuctioneer(AuctioneerModel auctioneerModel)
        {
            if (auctioneerModel == null)
            {
                throw new ArgumentNullException(nameof(auctioneerModel));
            }

            using (var db = new AuctionContext())
            {
                var found = db.Auctioneers.Any(a =>
                                               a.UserName.Equals(auctioneerModel.UserName, StringComparison.CurrentCultureIgnoreCase));
                if (found)
                {
                    return(null);
                }

                Auctioneer auctioneer = new Auctioneer
                {
                    FirstName = auctioneerModel.FirstName,
                    LastName  = auctioneerModel.LastName,
                    UserName  = auctioneerModel.UserName,
                    Password  = auctioneerModel.Password,
                    IsAdmin   = auctioneerModel.IsAdmin,
                };

                db.Auctioneers.Add(auctioneer);
                await db.SaveChangesAsync();

                auctioneerModel.Id = auctioneer.Id;
                return(auctioneerModel);
            }
        }
Example #19
0
        public IList <Bid> GetAllBidsByProductName(string productName)
        {
            CoreValidator.ThrowIfNullOrEmpty(productName, nameof(productName));

            using (var db = new AuctionContext())
            {
                var isExisting = ProductController.Instance().IsProductExisting(productName);

                if (!isExisting)
                {
                    throw new ArgumentException("The product doesn't exist in the system.");
                }

                var resultBids = db.Bids
                                 .Include("Product")
                                 .Include("User")
                                 .Where(b => b.Product.Name == productName)
                                 .OrderByDescending(b => b.DateOfCreated)
                                 .ThenByDescending(b => b.Coins)
                                 .ToList();

                CoreValidator.ThrowIfNull(resultBids, nameof(resultBids));

                return(resultBids);
            }
        }
Example #20
0
        private async void LndService_OnHoldInvoiceActivated(object sender, Invoice invoice, byte[] preImage)
        {
            Console.WriteLine("In Hodle Activated {0}", invoice);
            try
            {
                var auctionInvoice = JsonSerializer.Deserialize <AuctionInvoice>(invoice.Memo);
                using (var context = new AuctionContext())
                {
                    var auctionEntry = context.AuctionEntries.FirstOrDefault(e => e.PaymentRequest == invoice.PaymentRequest);
                    var auction      = GetAuction(Guid.Parse(auctionInvoice.AuctionId));
                    if (auction.FinishedAt != 0)
                    {
                        await _lndService.CancelHodlInvoice(invoice.RHash.ToByteArray());

                        return;
                    }

                    auctionEntry.ActivatedAt = Utility.Utility.DateTimeToUnix(DateTime.UtcNow);
                    auctionEntry.State       = AuctionEntryState.ACTIVATED;
                    context.AuctionEntries.Update(auctionEntry);

                    Console.WriteLine("activated auction entry {0}", auctionEntry);
                    await context.SaveChangesAsync();
                }
            }catch (Exception e)
            {
                Console.WriteLine("ERROR AT HOLD INVOICE ACTIVATED {0}", invoice);

                await _lndService.CancelHodlInvoice(invoice.RHash.ToByteArray());
            }
        }
Example #21
0
        public void LoadGlyphsData(string link, string hero)
        {
            HtmlWeb            web  = new HtmlWeb();
            HtmlDocument       doc  = web.Load(link);
            HtmlNodeCollection imgs = doc.DocumentNode.SelectNodes($"//div[@class={Strings.Chr(34)}glyph_container{Strings.Chr(34)}]");

            List <ItemClass> Itemlist = new List <ItemClass>();

            foreach (HtmlNode img in imgs)
            {
                Itemlist.Add(new ItemClass()
                {
                    Name   = System.Net.WebUtility.HtmlDecode(img.ChildNodes[1].GetAttributeValue("data-glyph-name", "Unknown")),
                    Rarity = System.Net.WebUtility.HtmlDecode(img.ChildNodes[1].GetAttributeValue("data-rarity-color", "Unknown")),
                    Slot   = "Glyph",
                    Image  = img.ChildNodes[3].GetAttributeValue("src", "Unknown"),
                    Special_Ability_Description = System.Net.WebUtility.HtmlDecode(img.ChildNodes[1].GetAttributeValue("data-glyph-description", "Unknown").Replace("&lt;font color=&#39;#CCFF66&#39;&gt;", "**").Replace("&lt;/font&gt;", "**").Replace("&#39", "'").Replace("&lt;font color=&quot;#EF4126&quot;&gt;", "**").Replace("&lt;font color=&quot;#87D9FF&quot;&gt;", "**").Replace("&lt;font color=&quot;#C25DFC&quot;&gt;", "**").Replace("&lt;font color=&quot;#5CCDF9&quot;&gt;", "**").Replace("&lt;font color=&quot;#69BC71&quot;&gt;", "**").Replace("color=&quot;#DDDDDD&quot;&gt;", "**").Replace("&lt;font color=&quot;#B5FFB7&quot;&gt;", "**")),
                    AlternativeName             = img.ChildNodes[3].GetAttributeValue("src", "Unknown").Replace("https://s3-us-west-2.amazonaws.com/roshpit-assets/glyphs/", "").Replace(".png", ""),
                    Required_level  = img.ChildNodes[1].GetAttributeValue("data-required-level", "Unknown"),
                    Special_Ability = hero
                });
            }
            using (AuctionContext a = new AuctionContext())
            {
                a.Items.AddRange(Itemlist);
                a.SaveChanges();
            }
        }
Example #22
0
 public ActionResult SendRegistrationMessage(string a)
 {
     if (User.Identity.Name != AppSettings.AdminName)
     {
         //Если текущий пользователь не является администратором аукциона, отпрвляем его на главную страницу
         return(RedirectToAction("Index", "Home"));
     }
     else
     {
         lock (_padLock)
             using (AuctionContext db = new AuctionContext())
             {
                 //Получаем список пользователей
                 List <User> users = db.Users.ToList();
                 if (users.Count != 0)
                 {
                     //Если список не пустой, начинаем отправлять сообщения
                     foreach (var user in users)
                     {
                         //Текст сообщения
                         string mailBody = "Для входа на аукцион #PROКАЧКА используйте Вашу учетную запись DeltaCredit.";
                         //Отпрака сообщения
                         SendEmail(user.Email, "Аукцион ДельтаКредит", mailBody);
                     }
                 }
                 //Все письма отправлены
                 ViewBag.SendSuccess = true;
                 return(View());
             }
     }
 }
Example #23
0
        public ActionResult Index(string auctionCategory, string searchString)
        {
            AuctionContext context = new AuctionContext();
            //var auctions = context.Auctions.ToList();

            var CategoryLst = new List <string>();
            var CategoryQry = from d in db.Auctions
                              select d.Category;

            CategoryLst.AddRange(CategoryQry.Distinct());
            ViewBag.auctionCategory = new SelectList(CategoryLst);


            var auctions = from m in db.Auctions
                           select m;

            if (!String.IsNullOrEmpty(searchString))
            {
                auctions = auctions.Where(s => s.Title.Contains(searchString));
            }

            if (!String.IsNullOrEmpty(auctionCategory))
            {
                auctions = auctions.Where(x => x.Category == auctionCategory);
            }


            return(View(auctions));
        }
Example #24
0
 //Функция для регистрации пользователей
 public Task RegisterAll(string Path, string GroupName)
 {
     return(Task.Run(() =>
     {
         //Получем массив пользователей группы с их монетами
         string[] Group = System.IO.File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory.ToString() + Path);
         if (Group.Length != 0)
         {
             //Если массив не пустой, начинаем регистрировать каждого пользователя
             foreach (string str in Group)
             {
                 //Разбиваем строку на логин пользователя и количество монет
                 string[] text = str.Split(':');
                 //Разбиваем логин пользователя на имя компьютера и имя самого пользователя, чтобы потом сделать из него Email
                 string[] email = text[0].Split('\\');
                 lock (_padLock)
                     using (AuctionContext db = new AuctionContext())
                     {
                         //Добавляем нового пользователя в БД
                         db.Users.Add(new User {
                             Login = text[0], Email = email[1] + "@deltacredit.ru", Group = GroupName, Coints = Convert.ToInt32(text[1])
                         });
                         //Сохраняем изменения
                         db.SaveChanges();
                     }
             }
         }
     }));
 }
Example #25
0
        public ActionResult Bid(Bid bid)
        {
            AuctionContext context = new AuctionContext();
            var            auction = db.Auctions.Find(bid.AuctionId);

            if (auction == null)
            {
                ModelState.AddModelError("AuctionId", "Auction not found!");
            }
            else if (auction.CurrentPrice >= bid.Amount)
            {
                ModelState.AddModelError("Amount", "Bid amount must exceed current bid");
            }
            else
            {
                bid.Username = User.Identity.Name;
                auction.Bids.Add(bid);
                auction.CurrentPrice = bid.Amount;
                db.SaveChanges();
            }

            if (!Request.IsAjaxRequest())
            {
                return(RedirectToAction("Auction", new { id = bid.AuctionId }));
            }

            return(Json(new
            {
                CurrentPrice = bid.Amount.ToString("C"),
                BidCount = auction.BidCount
            }));
        }
Example #26
0
        public UnitOfWork()
        {
            _context = new AuctionContext();

            //use this line for debug propose and check in console SQL requests
            //_context.Database.Log = Console.WriteLine;
        }
Example #27
0
        public async Task <LotModel> AddLot(LotModel lot)
        {
            if (lot == null)
            {
                throw new ArgumentNullException(nameof(lot));
            }

            using (var db = new AuctionContext())
            {
                var lotEntity = new Lot
                {
                    Id            = lot.Id,
                    Name          = lot.Name,
                    Description   = lot.Description,
                    Quantity      = lot.Quantity,
                    Unit          = lot.Unit,
                    StartingPrice = lot.StartingPrice,
                    CurrentPrice  = lot.CurrentPrice,
                    MinimalBid    = lot.MinimalBid,
                    BidCount      = lot.BidCount,
                    AuctionDate   = lot.AuctionDate
                };

                db.Lots.Add(lotEntity);
                await db.SaveChangesAsync();

                lot.Id = lotEntity.Id;
                return(lot);
            }
        }
Example #28
0
        public async Task <TradingHistoryModel> EditTradingHistory(TradingHistoryModel history)
        {
            if (history == null)
            {
                throw new ArgumentNullException(nameof(history));
            }

            using (var db = new AuctionContext())
            {
                var modifiedRecord = db.TradingHistories.FirstOrDefault(h => h.Id == history.Id);
                if (modifiedRecord == null)
                {
                    return(null);
                }

                var trader     = db.Traders.FirstOrDefault(t => t.Id == (history.Trader == null ? 0 : history.Trader.Id)) ?? modifiedRecord.Trader;
                var lot        = db.Lots.FirstOrDefault(L => L.Id == (history.Lot == null ? 0 : history.Lot.Id)) ?? modifiedRecord.Lot;
                var auctioneer = db.Auctioneers.FirstOrDefault(a => a.Id == (history.Auctioneer == null ? 0 : history.Auctioneer.Id)) ?? modifiedRecord.Auctioneer;


                modifiedRecord.Lot           = lot;
                modifiedRecord.Trader        = trader;
                modifiedRecord.Auctioneer    = auctioneer;
                modifiedRecord.LotId         = lot.Id;
                modifiedRecord.TraderId      = trader.Id;
                modifiedRecord.AuctioneerId  = auctioneer.Id;
                modifiedRecord.BidTime       = history.BidTime;
                modifiedRecord.BidOrder      = history.BidOrder;
                modifiedRecord.RecordedPrice = history.RecordedPrice;

                await db.SaveChangesAsync();

                return(history);
            }
        }
Example #29
0
        public async Task <LotModel> EditLot(LotModel lot)
        {
            if (lot == null)
            {
                throw new ArgumentNullException(nameof(lot));
            }

            using (var db = new AuctionContext())
            {
                var lotEntity = db.Lots.FirstOrDefault(L => L.Id == lot.Id);
                if (lotEntity == null)
                {
                    return(null);
                }

                lotEntity.Name          = lot.Name;
                lotEntity.Description   = lot.Description;
                lotEntity.Quantity      = lot.Quantity;
                lotEntity.Unit          = lot.Unit;
                lotEntity.StartingPrice = lot.StartingPrice;
                lotEntity.CurrentPrice  = lot.CurrentPrice;
                lotEntity.MinimalBid    = lot.MinimalBid;
                lotEntity.BidCount      = lot.BidCount;
                lotEntity.AuctionDate   = lot.AuctionDate;

                await db.SaveChangesAsync();

                return(lot);
            }
        }
Example #30
0
        public bool UpdatePayment(Payment newPayment)
        {
            CoreValidator.ThrowIfNull(newPayment, nameof(newPayment));
            CoreValidator.ThrowIfNegativeOrZero(newPayment.Id, nameof(newPayment.Id));
            CoreValidator.ThrowIfNullOrEmpty(newPayment.PaymentTypeCode, nameof(newPayment.PaymentTypeCode));
            CoreValidator.ThrowIfNegativeOrZero(newPayment.UserId, nameof(newPayment.UserId));

            using (var db = new AuctionContext())
            {
                var dbPayment = GetPayment(newPayment.Id);

                CoreValidator.ThrowIfNull(dbPayment, nameof(dbPayment));

                db.Payments.Attach(dbPayment);

                dbPayment.PaymentTypeCode = newPayment.PaymentTypeCode;
                dbPayment.Type            = newPayment.Type;
                dbPayment.UserId          = newPayment.UserId;


                db.Entry(dbPayment).State = EntityState.Modified;
                db.SaveChanges();

                return(true);
            }
        }