Example #1
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"));
        }
Example #2
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!");
        }
Example #3
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 }));
        }
Example #4
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 }));
        }
Example #5
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);
        }
Example #6
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();
                    }
                }
            }
        }
Example #7
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");
            }
        }
Example #8
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();
                    }
                }
            }
        }
Example #9
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}");
                        }
                    }
            }));
        }
Example #10
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.");
            }
        }