public ActionResult Bid(BidModel model)
        {
            var userId  = Guid.Parse(User.Identity.GetUserId());
            var bidding = new Bidding
            {
                Id        = Guid.NewGuid(),
                AuctionId = model.AuctionId,
                UserId    = userId,
                BidPrice  = model.BidPrice
            };

            var existingBid = db.Biddings.FirstOrDefault(x => x.UserId == userId && x.AuctionId == model.AuctionId);

            if (existingBid != default)
            {
                existingBid.BidPrice        = model.BidPrice;
                db.Entry(existingBid).State = EntityState.Modified;
            }
            else
            {
                db.Biddings.Add(bidding);
            }

            db.SaveChanges();

            return(RedirectToAction("Details", new { id = model.AuctionId }));
        }
Example #2
0
        public async Task GetById_ValidParams_ExpectSuccess()
        {
            var bidService = this._serviceProvider.GetRequiredService <IGenericRepository <BidModel> >();
            var bid        = new BidModel()
            {
                BettingId = 2, Amount = 1M, Side = false, BidId = 8, Coefficient = 2, Date = DateTime.Now, UserId = "TestUser", WalletId = 1, Paid = false, PaymentStatus = PaymentStatus.Confirmed, Status = false, PaymentAddress = "mhheFUrieWV2zVsdWXNZkqSmeSVjkbXWer"
            };
            var bidList = new List <BidModel>()
            {
                bid
            };

            bidService.Create(bidList[0]);

            var result = await this.bidController.GetById(2);

            var okResult = result as OkObjectResult;

            dynamic obj = new DynamicObjectResultValue(okResult.Value);

            Assert.IsNotNull(okResult);
            Assert.AreEqual(200, okResult.StatusCode);

            CollectionAssert.AreEqual(obj.list, bidList);
        }
Example #3
0
        internal AuctionItemViewModel ViewSellerAuction(string sellerEmail)
        {
            AuctionModel postedAuctionModel = new AuctionModel();
            BidModel     bidInfoModel       = new BidModel();
            ABUserModel  bidderInfoModel    = new ABUserModel();


            var sellerInfoObj = _abUserRepository.FindBy(x => x.Email == sellerEmail).FirstOrDefault();

            var postedAuctionObj = _auctionRepository.FindBy(x => x.AuctionGUID == sellerInfoObj.ABUser_AuctionGUID).FirstOrDefault();

            var bidInfoObj = _bidRepository.FindBy(x => x.Bid_AuctionGUID == postedAuctionObj.AuctionGUID).FirstOrDefault();

            try
            {
                var auctionBidderObj = _abUserRepository.FindBy(x => x.ABUserGUID == bidInfoObj.Bid_ABUserGUID && x.ABUser_AuctionGUID == bidInfoObj.Bid_AuctionGUID).FirstOrDefault();

                bidderInfoModel.Alias = auctionBidderObj.Alias;

                bidInfoModel.BidPlaced = bidInfoObj.BidPlaced;
            }
            catch
            {
                bidderInfoModel.Alias  = "No Bidders";
                bidInfoModel.BidPlaced = -1;
            }


            postedAuctionModel.AuctionGUID   = postedAuctionObj.AuctionGUID;
            postedAuctionModel.ItemName      = postedAuctionObj.ItemName;
            postedAuctionModel.StartingBid   = postedAuctionObj.StartingBid;
            postedAuctionModel.StartDate     = postedAuctionObj.StartDate;
            postedAuctionModel.EndDate       = postedAuctionObj.EndDate;
            postedAuctionModel.AuctionOver   = postedAuctionObj.AuctionOver;
            postedAuctionModel.SellerSent    = postedAuctionObj.SellerSent;
            postedAuctionModel.BuyerReceived = postedAuctionObj.BuyerReceived;


            if (postedAuctionObj != null)
            {
                if (bidInfoModel != null)
                {
                    return(new AuctionItemViewModel()
                    {
                        auctionItem = postedAuctionModel,
                        bidderInfo = bidderInfoModel,
                        bidInfo = bidInfoModel
                    });
                }
                else
                {
                    return(new AuctionItemViewModel()
                    {
                        auctionItem = postedAuctionModel
                    });
                }
            }

            return(null);
        }
Example #4
0
        public async Task SaveAuctionBidAsync(BidModel model)
        {
            AuctionBid bid = new AuctionBid {
                UserId        = model.UserId,
                AuctionItemId = model.AuctionItemId,
                Bid           = model.Bid,
                Timestamp     = DateTimeOffset.Now,
            };

            var itemFileName = Path.Combine(_itemsBasePath, bid.AuctionItemId + ItemsFileSuffix);
            var bidFileName  = Path.Combine(_bidsBasePath, bid.AuctionItemId + BidsFileSuffix);

            using (var releaser = await _asyncLock.LockAsync(bid.AuctionItemId)) {
                var item = await _auctionFileRepository.GetAuctionItemAsync(itemFileName);

                if (model.Bid > item.HighBid)
                {
                    item.HighBid  = model.Bid;
                    model.HighBid = true;
                    model.Bid    += item.Increment;
                    await _auctionFileRepository.SaveAuctionItemAsync(item, itemFileName);
                }
                else
                {
                    model.Bid = item.HighBid + item.Increment;
                }

                await _auctionFileRepository.SaveAuctionBidAsync(bid, bidFileName);
            }
        }
        public IActionResult Details(AuctionItemModel item)
        {
            if (item == null)
            {
                return(Redirect("Index"));
            }

            if (!ModelState.IsValid)
            {
                return(View(item));
            }

            var bidModelResult = new BidModel
            {
                ItemNumber  = item.ItemNumber,
                CustomName  = item.BidCustomName,
                CustomPhone = item.BidCustomPhone,
                Price       = item.BidPrice
            };

            if (_apiHelper.Post(bidModelResult, "api/auctions/provideBid"))
            {
                ViewBag.BidComepleted = true;
            }
            else
            {
                ViewBag.BidComepleted = false;
            }
            return(View(item));
            //return Redirect("Index");
        }
Example #6
0
        public ActionResult Index()
        {
            var top = LotModel.GetTopLots(1);

            ViewBag.Top = top;
            var secondTop = LotModel.GetTopLots(2);

            ViewBag.SecondTop = secondTop;
            var thirdTop = LotModel.GetTopLots(3);

            ViewBag.ThirdTop = thirdTop;
            var lots = LotModel.GetLotById(null);

            try{
                lots.RemoveAll(l => l.Id == top.Id);
                lots.RemoveAll(l => l.Id == secondTop.Id);
                lots.RemoveAll(l => l.Id == thirdTop.Id);
            }
            catch {
            }
            ViewBag.Categories = CategoryModel.GetCategoryById(null);
            if (Request.IsAuthenticated)
            {
                ViewBag.WinnedBids = BidModel.GetWinnerBids(User.Identity.GetUserId());
            }

            return(View(lots));
        }
Example #7
0
        public JsonResult CreateBid(BidModel bid)
        {
            try
            {
                LotModel lot = LotModel.GetLotById(bid.LotId).First();
                if (lot.DeadLine < DateTime.Now)
                {
                    return(Json("@Resource.LotDayPassed", JsonRequestBehavior.AllowGet));
                }

                if (bid.Amount < lot.CurrentBid + lot.Step)
                {
                    return(Json("Amount is low than the current bid's", JsonRequestBehavior.AllowGet));
                }
                else
                {
                    bid.UserId = User.Identity.GetUserId();
                    bid.Save();
                    return(Json("Bid made successfully. ", JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #8
0
 public ActionResult MakePayment(int id, int type)
 {
     try
     {
         BidModel bid     = BidModel.GetBidById(id).First();
         Payment  payment = new Payment();
         payment.Amount = bid.Amount;
         payment.BidId  = id;
         payment.Type   = type;
         payment.UserId = User.Identity.GetUserId();
         int paymentId = payment.Save();
         if (type == 1)
         {
             //Card payment actions
             return(RedirectToAction("Index", "Home"));
         }
         else
         {
             return(RedirectToAction("PaymentApproved", "Bid", new { id = paymentId }));
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        public async Task <IActionResult> Create([FromBody] BidModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest());
            }

            var bet = this.bettingService.GetById(model.BettingId);

            if (bet != null && bet.Status == BettingStatus.Continue)
            {
                model.Date          = DateTime.Now;
                model.UserId        = (await this.userManager.FindByNameAsync(this.User.Identity.Name)).Id;
                model.Coefficient   = BettingHelper.GetTimeCoefficient(bet.StartDate, bet.FinishDate, model.Date);
                model.PaymentStatus = PaymentStatus.None;


                var result = this.bidService.Create(model);
                model.PaymentAddress = this.bitcoinWalletService.GetAddressById(model.BidId).ToString();
                this.bidService.Update(model);

                if (result)
                {
                    return(this.Ok(new { result = true, bid = model }));
                }
            }

            return(this.Ok(new { result = false }));
        }
Example #10
0
        internal List <BidModel> getBidByLotId(int id)
        {
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                using (SqlCommand command = new SqlCommand("sp_GetBidByLot", sqlConnection))
                {
                    try
                    {
                        sqlConnection.Open();
                        command.CommandType = CommandType.StoredProcedure;

                        command.Parameters.AddWithValue("@LotId", id);
                        SqlDataReader   rdr     = command.ExecuteReader();
                        List <BidModel> bidList = new List <BidModel>();
                        while (rdr.Read())
                        {
                            BidModel bid = new BidModel();
                            bid.Id       = Convert.ToInt32(rdr["Id"]);
                            bid.LotId    = Convert.ToInt32(rdr["LotId"]);
                            bid.UserId   = rdr["UserId"].ToString();
                            bid.isWinner = Convert.ToBoolean(rdr["isWinner"]);

                            bid.Amount     = Convert.ToDecimal(rdr["Amount"]);
                            bid.CreateDate = Convert.ToDateTime(rdr["CreateDate"]);
                            bidList.Add(bid);
                        }
                        return(bidList);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
        public ActionResult Bid(BidModel model)
        {
            if (!ModelState.IsValid)
            {
                TempData["Errors"] = "Entered data is incorrect";
                return(RedirectToAction("Details", new { id = model.Id }));
            }
            var auction = _auctionRepository.FirstOrDefault(item => item.Id == model.Id);

            if (auction == null)
            {
                TempData["Errors"] = "No auction found";
                return(RedirectToAction("Details", new { id = model.Id }));
            }
            if (auction.DateEnd < DateTime.UtcNow)
            {
                TempData["Errors"] = "Auction has ended";
                return(RedirectToAction("Details", new { id = model.Id }));
            }
            if (model.NewBid < auction.LastBid + auction.MinStep)
            {
                TempData["Errors"] = $"Min step is {auction.MinStep}";
                return(RedirectToAction("Details", new { id = model.Id }));
            }
            auction.LastBid = model.NewBid;
            auction.BuyerId = User.Identity.GetUserId();
            _auctionRepository.SaveChanges();

            return(RedirectToAction("Details", new { id = model.Id }));
        }
Example #12
0
        public IActionResult Bid(BidModel bid)
        {
            bool bidPlaced = bidService.PlaceBid(bid, HttpContext.User.Identity.Name);

            SetMessage(new MessageViewModel()
            {
                Message = bidPlaced ? "Bid was successfully placed" : "There was an error placing your bid",
            });
            return(RedirectToAction("View", "Product", new { productID = bid.ProductID, }));
        }
Example #13
0
        public ActionResult Index(int id)
        {
            BidModel model = BidModel.GetBidById(id).First();

            if (!model.UserId.Equals(User.Identity.GetUserId()))
            {
                throw new HttpException(404, "Wrong user");
            }

            return(View(model));
        }
Example #14
0
        public BidModel MakeBidApiReady(OpenAuctionBidViewModel viewModel, string bidder)
        {
            BidModel model = new BidModel
            {
                Summa     = viewModel.BidPrice.ToString(),
                AuktionID = viewModel.AuctionId.ToString(),
                Budgivare = bidder
            };

            return(model);
        }
Example #15
0
        public BidModel MakeBidApiReady(BidViewModel viewModel, string userName = "******")
        {
            BidModel model = new BidModel
            {
                Summa     = viewModel.Bid.ToString(),
                AuktionID = viewModel.AuctionId.ToString(),
                Budgivare = userName
            };

            return(model);
        }
        public Bid ToEntity(BidModel bidModel)
        {
            Bid bid = new Bid();

            bid.id        = bidModel.ID;
            bid.companyid = bidModel.CompanyID;
            bid.price     = bidModel.Price;
            bid.productid = bidModel.ProductID;
            bid.userid    = bidModel.UserID;
            return(bid);
        }
Example #17
0
        public async Task <IActionResult> Create([FromBody] BidModel model)
        {
            // TODO: Validations
            // - Make sure user can bid
            // - Make sure last bid wasn't current user

            var product = await _dbContext.Products.FindAsync(model.ProductId);

            if (product == null)
            {
                _logger.LogInformation("Product {productId} not found", model.ProductId);
                return(NotFound());
            }

            var evt = await _dbContext.Events.FindAsync(product.EventId);

            if (evt == null)
            {
                _logger.LogInformation("Event {eventId} not found", product.EventId);
                return(NotFound());
            }

            var user = await _userManager.GetUserAsync(User);

            var placeBidRequest = new PlaceBidRequest
            {
                Event   = evt,
                Product = product,
                User    = user,
                Amount  = model.Amount
            };

            try
            {
                var bidResult = await _bidService.PlaceBidAsync(placeBidRequest);

                if (bidResult.ResultType == PlaceBidResultType.BiddingClosed)
                {
                    return(BadRequest("Bidding for event is not open"));
                }
                else if (bidResult.ResultType == PlaceBidResultType.InvalidAmount)
                {
                    return(BadRequest($"Bid amount must be {product.NextMinBidAmount} or greater"));
                }

                // Success
                return(Created("", model));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error placing bid for product ID {id} (User: {userId})", model.ProductId, user.Id);
                return(StatusCode(500)); // TODO: Return something different
            }
        }
Example #18
0
 public bool Update(BidModel model)
 {
     try
     {
         this.repository.Update(model);
         return(true);
     }
     catch (Exception e)
     {
         return(false);
     }
 }
Example #19
0
        public static int CreateBid(string card, DateTime date)
        {
            BidModel data = new BidModel
            {
                Card = card,
                Date = date
            };

            string sql = @"insert into dbo.Bid (Card, Date) values (@Card, @Date);";

            return(SqlDataAccess.SaveData(sql, data));
        }
Example #20
0
        public HttpResponseMessage MakeBid(BidModel bid)
        {
            using (HttpClient client = new HttpClient())
            {
                var modelJson = JsonConvert.SerializeObject(bid);

                var stringContent = new StringContent(modelJson, Encoding.UTF8, "application/json");

                HttpResponseMessage response = client.PostAsync(baseAddressBid, stringContent).Result;

                return(response);
            }
        }
Example #21
0
        public ActionResult <BidModel> GetBid(int id)
        {
            BidModel bid = mapper.Map <Bid, BidModel>(bidRepo.Get(id));;

            if (bid == null)
            {
                return(NotFound());
            }
            else
            {
                return(mapper.Map <Bid, BidModel>(bidRepo.Get(id)));
            }
        }
Example #22
0
        public JsonResult SetBidWinner(int id)
        {
            BidModel.SetWinner(id);
            BidModel  bid  = BidModel.GetBidById(id).First();
            MailModel mail = new MailModel();

            mail.Subject = "Դուք հաղթել եք";
            mail.Email   = UserManager.FindById(bid.UserId).Email;
            var callbackUrl = Url.Action("Index", "Bid", new { id = id }, protocol: Request.Url.Scheme);

            mail.Body = string.Format(Resource.EmailConfirmationBid, callbackUrl);
            mail.SendMail();
            return(Json(string.Format("Bid set as winner"), JsonRequestBehavior.AllowGet));
        }
Example #23
0
        public ActionResult _LotLastBidPartial(int id)
        {
            var bids = BidModel.GetBidByLotId(id);

            if (bids.Count >= 5)
            {
                List <BidModel> tops = bids.Take(5).ToList();
                return(PartialView(tops));
            }
            else
            {
                return(PartialView(bids));
            }
        }
Example #24
0
        public ActionResult PaymentApproved(int id)
        {
            BidModel bid = BidModel.GetBidById(id).First();

            if (bid.UserId.Equals(User.Identity.GetUserId()))
            {
                ViewBag.BidId = id;
                return(View());
            }
            else
            {
                throw new HttpException(404, "User not found");
            }
        }
        public async Task <List <BidModel> > GetAuctionBids(string id)
        {
            var item = await _auctionDAL.GetAuctionItemAsync(id);

            var modelList = item.AuctionBids.Select(bid => {
                var model = new BidModel {
                    UserId        = bid.UserId,
                    AuctionItemId = bid.AuctionItemId,
                    Bid           = bid.Bid
                };
                return(model);
            }).ToList();

            return(modelList);
        }
        public async Task <(bool, DateTime?)> AddBid(BidModel bid, string userName)
        {
            var auc = await _context.Auction.Include(x => x.AuctionBid).SingleOrDefaultAsync(x => x.Id == bid.AuctionId);

            (bool, DateTime?)validationResult = ValidateBid(bid, auc);

            AuctionBid item = new AuctionBid()
            {
                AuctionId     = bid.AuctionId,
                Bid           = bid.Bid,
                BidderId      = bid.BidderId,
                ClientTime    = bid.ClientTime,
                PreviousBidId = bid.PreviousBidId,
                ServerTime    = bid.ServerTime,
                TimeStamp     = bid.TimeStamp,
                TimeStampTime = bid.TimestampTime,
                Valid         = validationResult.Item1
            };

            AuctionBid prevBid = auc.AuctionBid.Where(x => x.Valid).LastOrDefault();

            if (prevBid != null)
            {
                prevBid = _context.AuctionBid.Find(bid.PreviousBidId);

                if (prevBid != null)
                {
                    prevBid.NextBid = item;
                }
            }

            await _context.AuctionBid.AddAsync(item);

            await _context.SaveChangesAsync();

            //TODO Set timestamp

            if (item.Valid)
            {
                await Log(bid.BidderId, bid.AuctionId, $"Нова цена от {bid.Bid} лв." + (prevBid != null ? $"Предишна цена {prevBid.Bid} лв." : ""));
            }
            else
            {
                await Log(bid.BidderId, bid.AuctionId, $"Невалидна цена от {bid.Bid} лв." + prevBid != null?$"Предишна цена {prevBid.Bid} лв." : "");
            }

            return(validationResult);
        }
        public void CreateBid_InvalidBids_ShouldCreateBidCorrectly()
        {
            // Arrange -> clean database, register new user, create an offer
            TestingEngine.CleanDatabase();
            var userSession = TestingEngine.RegisterUser("peter", "pAssW@rd#123456");
            var offerModel  = new OfferModel()
            {
                Title = "Title", Description = "Description", InitialPrice = 200, ExpirationDateTime = DateTime.Now.AddDays(5)
            };
            var httpResultOffer = TestingEngine.CreateOfferHttpPost(userSession.Access_Token, offerModel.Title, offerModel.Description, offerModel.InitialPrice, offerModel.ExpirationDateTime);

            Assert.AreEqual(HttpStatusCode.Created, httpResultOffer.StatusCode);
            var offer = httpResultOffer.Content.ReadAsAsync <OfferModel>().Result;

            // Act -> try to create a few bids
            var bids = new BidModel[]
            {
                new BidModel()
                {
                    BidPrice = 150, Comment = "Invalid: less than the initioal price"
                },
                new BidModel()
                {
                    BidPrice = null, Comment = "Invalid: null price"
                },
                new BidModel()
                {
                    BidPrice = 300, Comment = "Valid"
                },
                new BidModel()
                {
                    BidPrice = 280, Comment = "Invalid: less than the max price"
                },
            };
            var httpResultBid0 = TestingEngine.CreateBidHttpPost(userSession.Access_Token, offer.Id, bids[0].BidPrice, bids[0].Comment);
            var httpResultBid1 = TestingEngine.CreateBidHttpPost(userSession.Access_Token, offer.Id, bids[1].BidPrice, bids[1].Comment);
            var httpResultBid2 = TestingEngine.CreateBidHttpPost(userSession.Access_Token, offer.Id, bids[2].BidPrice, bids[2].Comment);
            var httpResultBid3 = TestingEngine.CreateBidHttpPost(userSession.Access_Token, offer.Id, bids[3].BidPrice, bids[3].Comment);

            // Assert -> valid bids are created, invalid not created
            Assert.AreEqual(HttpStatusCode.BadRequest, httpResultBid0.StatusCode);
            Assert.AreEqual(HttpStatusCode.BadRequest, httpResultBid1.StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, httpResultBid2.StatusCode);
            Assert.AreEqual(HttpStatusCode.BadRequest, httpResultBid3.StatusCode);
            var bidsCount = TestingEngine.GetBidsCountFromDb();

            Assert.AreEqual(1, bidsCount);
        }
        public void CreateBid_ValidBids_ShouldCreateBidsCorrectly()
        {
            // Arrange -> clean database, register new user, create an offer
            TestingEngine.CleanDatabase();
            var userSession = TestingEngine.RegisterUser("peter", "pAssW@rd#123456");
            var offerModel  = new OfferModel()
            {
                Title = "Title", Description = "Description", InitialPrice = 200, ExpirationDateTime = DateTime.Now.AddDays(5)
            };
            var httpResultOffer = TestingEngine.CreateOfferHttpPost(userSession.Access_Token, offerModel.Title, offerModel.Description, offerModel.InitialPrice, offerModel.ExpirationDateTime);

            Assert.AreEqual(HttpStatusCode.Created, httpResultOffer.StatusCode);
            var offer = httpResultOffer.Content.ReadAsAsync <OfferModel>().Result;

            // Act -> create a few bids
            var bidsToAdds = new BidModel[]
            {
                new BidModel()
                {
                    BidPrice = 250, Comment = "My initial bid"
                },
                new BidModel()
                {
                    BidPrice = 300, Comment = "My second bid"
                },
                new BidModel()
                {
                    BidPrice = 400, Comment = "My third bid"
                },
                new BidModel()
                {
                    BidPrice = 500
                }
            };

            foreach (var bid in bidsToAdds)
            {
                var httpResultBid = TestingEngine.CreateBidHttpPost(userSession.Access_Token, offer.Id, bid.BidPrice, bid.Comment);
                Assert.AreEqual(HttpStatusCode.OK, httpResultBid.StatusCode);
            }

            // Assert -> bids created successfully
            var bidsCount = TestingEngine.GetBidsCountFromDb();

            Assert.AreEqual(4, bidsCount);
        }
Example #29
0
        private void PrepareBidList()
        {
            XmlDocument xml = new XmlDocument();
            xml.Load(Server.MapPath("~/App_Data/bids.xml"));
            XmlNodeList bids = xml.SelectNodes("/bids/bid");
            foreach (XmlNode item in bids)
            {
                BidModel b = new BidModel();
                b.Id = int.Parse(item.Attributes["id"].Value);
                b.CustomerId = int.Parse(item.Attributes["customerid"].Value);
                b.ProductId = int.Parse(item.Attributes["productid"].Value);
                b.BidPrice = decimal.Parse(item.Attributes["bidprice"].Value);
                b.Time = DateTime.Parse(item.Attributes["time"].Value);

                BidList.Add(b);
            }
        }
Example #30
0
        public ActionResult VoteSubmit(String voteCheck)
        {
            string IP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (string.IsNullOrEmpty(IP))
            {
                IP = Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(IP))
            {
                IP = Request.UserHostAddress;
            }
            String[] VoteCon = voteCheck.Split(',');
            if (VoteCon.Count() > 5)
            {
                return(Json(new { success = false, message = "您选择了超过5位候选人,本次投票无效!" }));
            }
            DateTime            date = DateTime.Now.Date;
            bidRepository       br   = new bidRepository();
            CandidateRepository cr   = new CandidateRepository();

            if (!br.CheckDuplicate(IP, date))
            {
                return(Json(new { success = false, message = "您今天已经投过票了!" }));
            }
            try
            {
                BidModel bm = new BidModel();
                bm.VoterIP     = IP;
                bm.VoteDate    = DateTime.Now.Date;
                bm.VoteTime    = DateTime.Now;
                bm.VoteContent = voteCheck;
                foreach (String s in VoteCon)
                {
                    cr.BeVoted(Convert.ToInt32(s));
                }
                br.Insert(bm);
                br.Save();
                return(Json(new { success = true }));
            }
            catch (Exception e)
            {
                return(Json(new { success = false, message = "投票失败,请稍后重试。错误信息:" + e.Message }));
            }
        }
        public IActionResult MakeBidOnAuction(BidViewModel viewModel)
        {
            bool currentBidIsValid = _businessService.GetCurrentBidIsValid(viewModel.Bid, viewModel.AuctionId);

            if (currentBidIsValid == true)
            {
                string currentUserName = _userService.GetCurrentUserName();

                BidModel bid = _businessService.MakeBidApiReady(viewModel, currentUserName);

                HttpResponseMessage response = _businessService.MakeBid(bid);

                return(RedirectToAction("ViewAuctionDetails", "Auction", new { auctionId = viewModel.AuctionId, message = "Bid has successfully been made" }));
            }
            else
            {
                return(RedirectToAction("ViewAuctionDetails", "Auction", new { auctionId = viewModel.AuctionId, message = "Bid is too low" }));
            }
        }
Example #32
0
        private void InsertOrUpdateBid(BidModel model, bool insert)
        {
            XmlDocument xml = new XmlDocument();
            xml.Load(Server.MapPath("~/App_Data/bids.xml"));

            if (insert)
            {
                ZaZi.MvcApplication.BidList.Add(model);

                XmlNode customers = xml.SelectSingleNode("bids");
                XmlNode c = xml.CreateNode(XmlNodeType.Element, "bid", null);

                XmlAttribute id = xml.CreateAttribute("id");
                id.Value = model.Id.ToString();

                XmlAttribute customerid = xml.CreateAttribute("customerid");
                customerid.Value = model.CustomerId.ToString();

                XmlAttribute productid = xml.CreateAttribute("productid");
                productid.Value = model.ProductId.ToString();

                XmlAttribute bidprice = xml.CreateAttribute("bidprice");
                bidprice.Value = model.BidPrice.ToString();

                XmlAttribute time = xml.CreateAttribute("time");
                time.Value = String.Format("{0:dd/MM/yyyy hh:mm:ss tt}", model.Time);

                c.Attributes.Append(id);
                c.Attributes.Append(customerid);
                c.Attributes.Append(productid);
                c.Attributes.Append(bidprice);
                c.Attributes.Append(time);

                customers.AppendChild(c);

            }
            else
            {
                ZaZi.MvcApplication.BidList.Find(x => x.Id == model.Id).BidPrice = model.BidPrice;
                ZaZi.MvcApplication.BidList.Find(x => x.Id == model.Id).Time = model.Time;

                XmlNodeList bids = xml.SelectNodes("/bids/bid");
                foreach (XmlNode item in bids)
                {
                    if (int.Parse(item.Attributes["id"].Value) == model.Id)
                    {
                        item.Attributes["bidprice"].Value = model.BidPrice.ToString();
                        item.Attributes["time"].Value = String.Format("{0:dd/MM/yyyy hh:mm:ss tt}", model.Time);
                        break;
                    }
                }
            }
            xml.Save(Server.MapPath("~/App_Data/bids.xml"));
        }
Example #33
0
        private void UpdateProductPrice(BidModel model)
        {
            ZaZi.MvcApplication.ProductList.Find(x => String.Equals(x.Id, model.ProductId)).CurrentPrice = model.BidPrice;
            ZaZi.MvcApplication.ProductList.Find(y => String.Equals(y.Id, model.ProductId)).Bids = model.Id;
            XmlDocument xml = new XmlDocument();
            xml.Load(Server.MapPath("~/App_Data/products.xml"));
            XmlNodeList products = xml.SelectNodes("/products/product");

            foreach (XmlNode item in products)
            {
                if (int.Parse(item.ChildNodes[0].InnerText) == model.ProductId)
                {
                    // Lưu lại bid của người đấu giá thắng
                    item["bids"].InnerText = model.Id.ToString();
                    item.ChildNodes[3].InnerText = model.BidPrice.ToString();
                    break;
                }
            }
            xml.Save(Server.MapPath("~/App_Data/products.xml"));
        }
Example #34
0
        public ActionResult InsertBid(TempleModel model)
        {
            //int k = getNumUser();

            CustomerModel customer = getCustomerByEmail(model.Email);
            BidModel bid;
            // Nếu giá thấp hơn giá hiện tại thì next
            if (ZaZi.MvcApplication.ProductList[ZaZi.MvcApplication.productId].CurrentPrice >= model.BidPrice)
            {
                return Json(new { Status = 1 });
            }
            if (customer != null)
            {
                customer.FullName = model.Name;
                InsertOrUpdateCustomer(customer, false);
                if (model.remember != null)
                {
                    Session["id"] = customer.Id;
                    Session["name"] = customer.FullName;
                    Session["mail"] = customer.Email;
                }
                bid = getBidModel(customer.Id, model.Id);
                if (bid == null)
                {
                    bid = new BidModel();
                    bid.Id = ZaZi.MvcApplication.BidList.Count + 1;
                    bid.CustomerId = customer.Id;
                    bid.ProductId = model.Id;
                    bid.BidPrice = model.BidPrice;
                    bid.Time = DateTime.Now;
                    ZaZi.MvcApplication.WinnerName = customer.FullName;
                    InsertOrUpdateBid(bid, true);
                }
                else
                {
                    bid.BidPrice = model.BidPrice;
                    bid.Time = DateTime.Now;
                    ZaZi.MvcApplication.WinnerName = customer.FullName;
                    InsertOrUpdateBid(bid, false);
                }

            }
            else
            {
                //ZaZi.MvcApplication.currentUser += 1;
                customer = new CustomerModel();
                customer.Id = ZaZi.MvcApplication.CustomerList.Count + 1;
                customer.Email = model.Email;
                customer.FullName = model.Name;
                InsertOrUpdateCustomer(customer, true);
                // Dùng cho việc ghi nhớ thôgn tin đăng nhập
                if (model.remember != null)
                {
                    Session["id"] = customer.Id;
                    Session["name"] = customer.FullName;
                    Session["mail"] = customer.Email;
                }
                bid = new BidModel();
                bid.Id = ZaZi.MvcApplication.BidList.Count + 1;
                bid.CustomerId = customer.Id;
                bid.ProductId = model.Id;
                bid.BidPrice = model.BidPrice;
                bid.Time = DateTime.Now;
                ZaZi.MvcApplication.WinnerName = customer.FullName;
                InsertOrUpdateBid(bid, true);
            }

            UpdateProductPrice(bid);
            return Json(new { Status = 1});
        }