示例#1
0
        public ActionResult IndexGet(int?page, MessageInfo?message)
        {
            log.Info("Auction/IndexGet has been fired.");
            ViewBag.StatusMessage =
                message == MessageInfo.ChangeSuccess ? "Successfully opened a auction."
               : message == MessageInfo.ChangeUnsuccess ? "Error, something went wrong."
               : message == MessageInfo.AuctionFinished ? "Error, the auction is not in the READY state."
               : message == MessageInfo.AuctionClosed ? "Auction has been successfully closed."
                : message == MessageInfo.AuctionOver ? "The auction has finished."
                 : message == MessageInfo.BidSuccess ? "Your bid has been successfully placed."
                 : message == MessageInfo.NoTokens ? "Not enough tokens."
                 : message == MessageInfo.RequiredFields ? "All fields are required."
                 : message == MessageInfo.SuccessCreation ? "Auction successfully created."
               : "";
            int pageSize = AdminParams.N;
            int pageNum  = 1;

            if (page != null)
            {
                pageNum = (int)page;
            }
            using (var cont = new AuctionsDB())
            {
                //??????
                return(View("Index", cont.auction.OrderByDescending(a => a.title).ToPagedList(pageNum, pageSize)));
            }
        }
示例#2
0
        public ActionResult Won(int?page)
        {
            log.Info("Auction/Show has been fired.");
            int pageSize = AdminParams.N;
            int pageNum  = 1;

            if (page != null)
            {
                pageNum = (int)page;
            }
            string user = User.Identity.GetUserId();

            using (var context = new AuctionsDB())
            {
                /*
                 * var completedAuctions = context.auction
                 *  .Where(a => a.status == "COMPLETE")
                 *  .OrderByDescending(a => a.closedAt);*/
                IPagedList <auction> won = (from a in context.auction
                                            join b in context.bid
                                            on a.bidId equals b.id
                                            where a.status == "COMPLETED"
                                            where b.idUser == user
                                            orderby a.closedAt
                                            select a).ToPagedList(pageNum, pageSize);
                return(View(won));
            }
        }
示例#3
0
        public ActionResult StatusCentili(Guid clientid, string status)
        {
            log.Info("Token/StatusCentili has been fired.");
            Guid id = clientid;

            using (var context = new AuctionsDB())
            {
                using (var trans = context.Database.BeginTransaction(IsolationLevel.Serializable))
                {
                    try
                    {
                        tokenOrder to = context.tokenOrder.Find(id);
                        if (to != null)
                        {
                            //menjamo status u ono sto je prosledjeno
                            User user = context.User.Find(to.idUser);
                            if (user != null)
                            {
                                if (to.status != "SUBMITTED           ")
                                {
                                    return(RedirectToAction("ListOrders", "Token"));
                                }
                                if (status.Equals("success"))
                                {
                                    user.NumberOfTokens += (int)to.numTokens;
                                    to.status            = "COMPLETED";
                                }
                                else
                                {
                                    to.status = "CANCELED";
                                }
                                context.Entry(user).State = System.Data.Entity.EntityState.Modified;
                                context.Entry(to).State   = System.Data.Entity.EntityState.Modified;
                                sendMail(user.Email, "Centili payment", "Your payment was successful.");
                                context.SaveChanges();
                                trans.Commit();
                            }
                            else
                            {
                                throw new Exception();
                            }
                        }
                        else
                        {
                            throw new Exception();
                        }
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        log.Error("Centili payment exception caught");
                    }
                }
            }
            return(RedirectToAction("ListOrders", "Token"));
        }
示例#4
0
        //get za confirmation
        public string Get(string clientid, string status)
        {
            log.Info("Api/Status has been fired");

            using (var context = new AuctionsDB())
            {
                using (var trans = context.Database.BeginTransaction(IsolationLevel.Serializable))
                {
                    try
                    {
                        tokenOrder to = context.tokenOrder.Find(Guid.Parse(clientid));
                        if (to == null)
                        {
                            log.Error("API with wrong token id called");
                            throw new Exception();
                        }

                        User user = context.User.Find(to.idUser);
                        if (user != null)
                        {
                            if (to.status != "SUBMITTED           ")
                            {
                                log.Error("API already called");
                                throw new Exception();
                            }
                            if (status.Equals("success"))
                            {
                                user.NumberOfTokens += (int)to.numTokens;
                                to.status            = "COMPLETED";
                            }
                            else
                            {
                                to.status = "CANCELED";
                            }
                            TokenController.sendMail(user.Email, "Centili payment", "Your payment was successful.");
                            context.Entry(user).State = System.Data.Entity.EntityState.Modified;
                            context.Entry(to).State   = System.Data.Entity.EntityState.Modified;
                            context.SaveChanges();
                            trans.Commit();
                        }
                        else
                        {
                            log.Error("API user not found.");
                            throw new Exception();
                        }
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        return("failed!");
                    }
                }
            }
            return("success!");
        }
示例#5
0
        public ActionResult ConfirmCreate(E_Commerce.Models.auctionNEW model)
        {
            log.Info("Auction/ConfirmCreate has been fired.");
            if (ModelState.IsValid)
            {
                DateTime curr  = DateTime.Now;
                byte[]   image = null;

                if (model.picture != null)
                {
                    // Convert HttpPostedFileBase to byte array.
                    image = new byte[model.picture.ContentLength];
                    model.picture.InputStream.Read(image, 0, image.Length);
                }

                using (var context = new AuctionsDB())
                {
                    using (var trans = context.Database.BeginTransaction(IsolationLevel.Serializable))
                    {
                        try
                        {
                            var newAuction = new auction()
                            {
                                id           = Guid.NewGuid(),
                                title        = model.title,
                                duration     = model.duration,
                                startPrice   = model.startPrice,
                                currentPrice = model.startPrice,
                                createdAt    = curr,
                                status       = "READY",
                                picture      = image
                            };

                            context.auction.Add(newAuction);
                            context.SaveChanges();
                            trans.Commit();
                        }
                        catch (Exception e)
                        {
                            log.Error("Error with creating auction.");
                            trans.Rollback();
                        }
                    }
                }
                return(RedirectToAction("Home", new { Message = MessageInfo.SuccessCreation }));
            }
            return(RedirectToAction("Home", new { Message = MessageInfo.RequiredFields }));
        }
示例#6
0
        public ActionResult OpenConfirm(Guid idAukcije)
        {
            log.Info("Auction/OpenConfirm has been fired.");
            if (idAukcije == null)
            {
                log.Error("Auction/Home idAuction is null.");
                return(RedirectToAction("Home", new { Message = MessageInfo.ChangeUnsuccess }));
            }
            using (var context = new AuctionsDB())
            {
                using (var trans = context.Database.BeginTransaction(IsolationLevel.Serializable))
                {
                    try
                    {
                        auction auction = context.auction.Find(idAukcije);
                        if (auction == null)
                        {
                            throw new Exception();
                        }
                        if (!auction.status.Contains("READY"))
                        {
                            log.Error("Auction/Home auction is not ready.");
                            throw new Exception();
                        }

                        //otvaranje
                        auction.status               = "OPENED";
                        auction.openedAt             = DateTime.Now;
                        auction.closedAt             = DateTime.Now.AddSeconds((double)auction.duration);
                        context.Entry(auction).State = System.Data.Entity.EntityState.Modified;
                        context.SaveChanges();
                        trans.Commit();
                        var myHub = GlobalHost.ConnectionManager.GetHubContext <AuctionsHub>();
                        myHub.Clients.All.updateStatus(idAukcije);
                        return(RedirectToAction("Home", new { Message = MessageInfo.ChangeSuccess }));
                    }
                    catch (Exception ex)
                    {
                        log.Error("Error with opening auction");
                        trans.Rollback();
                    }
                }
            }
            return(RedirectToAction("Home", new { Message = MessageInfo.ChangeUnsuccess }));
        }
示例#7
0
        public string AuctionOver(Guid id)
        {
            string  result  = "";
            auction auction = null;

            using (var context = new AuctionsDB())
            {
                auction = context.auction.Find(id);
            }


            if (auction != null)
            {
                if (!auction.status.Equals("OPENED"))
                {
                    result = auction.status;
                }
                else
                {
                    auction.status = "COMPLETE";

                    result = auction.status;

                    using (var context = new AuctionsDB())
                    {
                        context.Entry(auction).State = System.Data.Entity.EntityState.Modified;
                        context.SaveChanges();

                        if (result == "COMPLETE")
                        {
                            /* kako dodati poslednji bid??
                             * Bid bid = context.Bids.Find(aukcija.BidID);
                             * Korisnik korisnik = context.Korisniks.Find(bid.KorisnikID);
                             *
                             * korisnik.Aukcijas.Add(auction);
                             * context.SaveChanges();
                             */
                        }
                    }
                }
            }

            return(result);
        }
示例#8
0
        public ActionResult Show(Guid idAukcije, MessageInfo?message)
        {
            log.Info("Auction/Show has been fired.");

            ViewBag.StatusMessage =
                message == MessageInfo.ChangeSuccess ? "Successfully opened an auction."
               : message == MessageInfo.ChangeUnsuccess ? "Error, something went wrong."
               : message == MessageInfo.AuctionFinished ? "Error, the auction is not in the READY state."
               : message == MessageInfo.AuctionClosed ? "Auction has been successfully closed."
                : message == MessageInfo.AuctionOver ? "The auction has finished."
                 : message == MessageInfo.BidSuccess ? "Your bid has been successfully placed."
                 : message == MessageInfo.NoTokens ? "Not enough tokens."
                 : message == MessageInfo.RequiredFields ? "All fields are required."
                 : message == MessageInfo.SuccessCreation ? "Auction successfully created."
               : "";
            auction auction = null;

            using (var context = new AuctionsDB())
            {
                auction = context.auction.Find(idAukcije);
                if (auction == null)
                {
                    return(HttpNotFound());
                }

                //dohvati bids i korisnike--izlistaj
                var bids = context.bid
                           .Where(b => b.idAuction.Equals(idAukcije))
                           .OrderByDescending(b => b.numTokens)
                           .Take(20);

                //foreachbid get user info
                IEnumerable <bid> allBids = bids.ToArray();
                var model = new AuctionAndBidsModel {
                    auction = auction, bids = allBids
                };

                return(View(model));
            }
        }
示例#9
0
        public void FinishAuction(Guid id)
        {
            //da li mora actionresult da vrati----check
            log.Info("Auction/FinishAuction has been fired.");
            if (id == null)
            {
                return;
            }
            using (var context = new AuctionsDB())
            {
                using (var trans = context.Database.BeginTransaction(IsolationLevel.Serializable))
                {
                    try
                    {
                        auction auction = context.auction.Find(id);
                        if (auction == null)
                        {
                            return;
                        }
                        if (!auction.status.Contains("OPENED"))
                        {
                            return;
                        }

                        //otvaranje
                        auction.status = "COMPLETED";
                        context.Entry(auction).State = System.Data.Entity.EntityState.Modified;
                        context.SaveChanges();
                        trans.Commit();
                        var myHub = GlobalHost.ConnectionManager.GetHubContext <AuctionsHub>();
                        myHub.Clients.All.closeAuction(id);
                    }
                    catch (Exception e)
                    {
                        log.Error("Error with finnishing auction(called)");
                        trans.Rollback();
                    }
                }
            }
        }
示例#10
0
        /*
         * public void ChangePrice(int? id, string newPrice)
         * {
         *
         *  try
         *  {
         *      double doubleValue = Convert.ToDouble(newPrice);
         *      Aukcija editAukcija;
         *
         *      using (var context = new AukcijaEntities())
         *      {
         *          editAukcija = context.Aukcijas.Find(id);
         *      }
         *
         *      if (editAukcija != null)
         *      {
         *          editAukcija.PocetnaCena = doubleValue;
         *          editAukcija.TrenutnaCena = doubleValue;
         *      }
         *
         *      using (var context = new AukcijaEntities())
         *      {
         *          context.Entry(editAukcija).State = System.Data.Entity.EntityState.Modified;
         *          context.SaveChanges();
         *
         *          logger.Error("AUCTION PRICE CHANGE: AuctionID: " + editAukcija.AukcijaID + ", AuctionStatus: " + editAukcija.Status + ", AuctionStartPrice: " + editAukcija.PocetnaCena);
         *      }
         *  }
         *  catch (FormatException)
         *  {
         *      Console.WriteLine("Unable to convert '{0}' to a Double.", newPrice);
         *  }
         *  catch (OverflowException)
         *  {
         *      Console.WriteLine("'{0}' is outside the range of a Double.", newPrice);
         *  }
         *
         *  //return RedirectToAction("Index", "Admin", new { id = id });
         * }
         */
        //not used
        public void OpenAuction(Guid?id)
        {
            if (id == null)
            {
                return;
            }

            try
            {
                auction auction = null;

                using (var context = new AuctionsDB())
                {
                    auction = context.auction.Find(id);
                }

                if (auction != null)
                {
                    DateTime startTime = DateTime.Now;
                    DateTime endTime   = startTime.AddSeconds((int)auction.duration);

                    auction.status   = "OPENED";
                    auction.closedAt = endTime;
                    auction.openedAt = startTime;
                }


                using (var context = new AuctionsDB())
                {
                    context.Entry(auction).State = System.Data.Entity.EntityState.Modified;
                    context.SaveChanges();
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to open auction");
            }
        }
示例#11
0
        public void CheckFinish()
        {
            var myHub = GlobalHost.ConnectionManager.GetHubContext <AuctionsHub>();

            //provera da li su zatvorene neke od otvorenih aukcija
            using (var context = new AuctionsDB())
            {
                using (var trans = context.Database.BeginTransaction(IsolationLevel.Serializable))
                {
                    try
                    {
                        IEnumerable <auction> auctions = (from a in context.auction
                                                          where a.status == "OPENED"
                                                          select a).ToList();
                        foreach (var auction in auctions)
                        {
                            DateTime now     = DateTime.Now;
                            DateTime closing = (DateTime)auction.closedAt;
                            if (now > closing)
                            {
                                auction.status = "COMPLETED";
                                context.Entry(auction).State = System.Data.Entity.EntityState.Modified;
                                context.SaveChanges();
                                myHub.Clients.All.closeAuction(auction.id);
                            }
                        }
                        trans.Commit();
                    }
                    catch (Exception e)
                    {
                        log.Error("Error with finnishing auction.");
                        trans.Rollback();
                    }
                }
            }
        }
示例#12
0
        private static Task GetAuctionSnap()
        {
            return(Task.Run(() =>
            {
                using (HttpClient client = GetAuthorizedClient().Result)
                    using (AuctionsDB db = new AuctionsDB())
                    {
                        var response = client.GetAsync("https://us.api.blizzard.com/wow/auction/data/Korgath?locale=en_US").Result;
                        var files = AhFiles.FromJson(response.Content.ReadAsStringAsync().Result);

                        foreach (var f in files.Files)
                        {
                            Console.WriteLine($"Found file: {f.Url}");
                            if (db.AuctionSnaps.Where(x => x.TimeStamp == f.LastModified && x.Url == f.Url.ToString()).Count() > 0)
                            {
                                Console.WriteLine("File already exists in the database");
                                //already exists
                                continue;
                            }
                            Console.WriteLine("Downloading auction data...");
                            Stopwatch sw = new Stopwatch();
                            Stopwatch swtotal = new Stopwatch();
                            sw.Start();
                            swtotal.Start();
                            AuctionSnap snap = DeserializeAHSnap.FromJson(client.GetAsync(f.Url).Result.Content.ReadAsStringAsync().Result);
                            snap.Url = f.Url.ToString();
                            snap.TimeStamp = f.LastModified;

                            Action <string> timetaken = (string msg) =>
                            {
                                Console.WriteLine($"{sw.Elapsed} taken to {msg}");
                                sw.Restart();
                            };

                            timetaken("download and parse data");
                            Console.WriteLine("Adding Snap...");
                            db.Add(snap);
                            db.SaveChanges();
                            timetaken("add snap");

                            db.RealmDatas.AddRange(snap.RealmDatas.Except(db.RealmDatas));
                            db.SaveChanges();
                            timetaken("add add auctions");

                            if (snap.AuctionSnapRealmDatas == null)
                            {
                                snap.AuctionSnapRealmDatas = new List <AuctionSnapRealmData>();
                            }
                            snap.AuctionSnapRealmDatas.AddRange(snap.RealmDatas.Select(x => new AuctionSnapRealmData {
                                AuctionSnap = snap, RealmData = db.RealmDatas.Where(rd => rd.Realm == x.Realm && rd.Slug == x.Slug).First()
                            }));
                            db.SaveChanges();
                            timetaken("link autions and realms");

                            db.Modifiers.AddRange(snap.Auctions
                                                  .Where(x => x.Modifiers != null)
                                                  .SelectMany(x => x.Modifiers)
                                                  .Except(db.Modifiers));
                            db.SaveChanges();
                            timetaken("add new modifiers");

                            db.BonusLists.AddRange(snap.Auctions
                                                   .Where(x => x.BonusLists != null)
                                                   .SelectMany(x => x.BonusLists)
                                                   .Except(db.BonusLists));
                            db.SaveChanges();
                            timetaken("add new bonuslists");

                            db.AuctionModifiers.AddRange(snap.Auctions
                                                         .Where(x => x.Modifiers != null)
                                                         .SelectMany(x => db.Modifiers.Where(m => x.Modifiers.Any(om => om.Type == m.Type && om.Value == m.Value))
                                                                     .Select(am => new AuctionModifier {
                                Auction = x, Modifier = am
                            })));
                            db.SaveChanges();
                            timetaken("link autions and modifiers");

                            db.AuctionBonusLists.AddRange(snap.Auctions
                                                          .Where(x => x.BonusLists != null)
                                                          .SelectMany(x => db.BonusLists.Where(b => x.BonusLists.Any(ob => ob.BonusListId == b.BonusListId))
                                                                      .Select(ab => new AuctionBonusList {
                                Auction = x, BonusList = ab
                            })));

                            db.SaveChanges();
                            timetaken("link auctions and bonus lists");

                            Console.WriteLine($"Total time taken to save {snap.Auctions.Count}: {swtotal.Elapsed}");
                        }
                    }
            }));
        }
示例#13
0
        public void BidAuction(Guid auctionID, string userID, out string fullName, out string newPrice, out bool tokens, out double timeRemaining)
        {
            try
            {
                auction auction = null;
                User    user    = null;
                using (var context = new AuctionsDB())
                {
                    using (var trans = context.Database.BeginTransaction(IsolationLevel.Serializable))
                    {
                        try
                        {
                            auction = context.auction.Find(auctionID);
                            user    = context.User.Find(userID);


                            if ((auction != null) && (user != null))
                            {
                                //cena da ulozimo jos jedan token
                                int minNext   = (int)(auction.currentPrice + AdminParams.T);
                                int userMoney = (int)(user.NumberOfTokens * AdminParams.T);
                                if ((userMoney >= minNext) && (auction.status.Contains("OPENED")))
                                {
                                    tokens = false;
                                    //kako korisnik da bira koliko?
                                    int price        = minNext;
                                    int tokensNeeded = (int)Math.Ceiling(minNext / AdminParams.T);

                                    /*
                                     * double remaining = ((DateTime)auction.closedAt - DateTime.Now).TotalSeconds;
                                     *
                                     * DateTime newClosed = (DateTime)auction.closedAt;
                                     * if (remaining <= 10)
                                     * {
                                     *  double increment = remaining * (-1);
                                     *  increment += 10;
                                     *
                                     *  newClosed = newClosed.AddSeconds(increment);
                                     * }
                                     *
                                     * auction.closedAt = newClosed;
                                     * timeRemaining =  ((DateTime)auction.closedAt - DateTime.Now).TotalSeconds;
                                     */
                                    timeRemaining = 1;
                                    //umanjujemo za onoliko koliko potrebno tokena
                                    user.NumberOfTokens       = user.NumberOfTokens - tokensNeeded;
                                    context.Entry(user).State = System.Data.Entity.EntityState.Modified;
                                    context.SaveChanges();
                                    bid latestBid = new bid()
                                    {
                                        id        = Guid.NewGuid(),
                                        numTokens = tokensNeeded,
                                        placedAt  = DateTime.Now,
                                        idUser    = userID,
                                        idAuction = auctionID
                                    };
                                    auction.bidId = latestBid.id;
                                    //mozda povecamo za 10 posto?
                                    auction.currentPrice = price;
                                    //? sta je ovo auction.bid.Add(latestBid);

                                    context.Entry(auction).State = System.Data.Entity.EntityState.Modified;
                                    context.SaveChanges();

                                    context.bid.Add(latestBid);
                                    context.SaveChanges();
                                    trans.Commit();
                                    fullName = user.FirstName + " " + user.LastName;
                                    newPrice = "" + price;
                                }
                                else
                                {
                                    fullName = newPrice = null;

                                    if (!auction.status.Contains("OPENED"))
                                    {
                                        tokens        = false;
                                        timeRemaining = -1;
                                    }
                                    else
                                    {
                                        tokens        = true;
                                        timeRemaining = 1;
                                    }
                                }
                            }
                            else
                            {
                                fullName      = newPrice = null;
                                tokens        = true;
                                timeRemaining = -1;
                                throw new Exception();
                            }
                        }
                        catch (Exception ex)
                        {
                            trans.Rollback();
                            fullName      = newPrice = null;
                            tokens        = true;
                            timeRemaining = -1;
                        }
                    }
                }
            }
            catch (FormatException)
            {
                fullName      = newPrice = null;
                tokens        = true;
                timeRemaining = -1;
                Console.WriteLine("Error with bidding.");
            }
        }