示例#1
0
        public string Login(string email, string password)
        {
            if (Session["user"] != null)
            {
                return("#Error: Could not log in.");
            }

            using (var db = new AuctionHouseDB())
            {
                try
                {
                    User user = db.FindUserByEmailAndPassword(email, password, out var isAdmin);

                    if (user == null)
                    {
                        return("#Error: Invalid email/password.");
                    }

                    Session["user"]    = user;
                    Session["isAdmin"] = isAdmin;

                    return("Successfully logged in.");
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message, ex);
                    return("#Error: Unknown error occured.");
                }
            }
        }
        public string ChangeSystem([Bind(Include = "RecentAuctions,DefaultAuctionTime,SilverPackage,GoldPackage,PlatinumPackage,Currency,PriceRate")] SystemParameters parameters)
        {
            if (!ModelState.IsValid)
            {
                return("#Error: One or more parameters are not valid.");
            }

            using (var db = new AuctionHouseDB())
            {
                try
                {
                    var current = db.GetCurrentSystemParameters();

                    current.RecentAuctions     = parameters.RecentAuctions;
                    current.DefaultAuctionTime = parameters.DefaultAuctionTime;
                    current.SilverPackage      = parameters.SilverPackage;
                    current.GoldPackage        = parameters.GoldPackage;
                    current.PlatinumPackage    = parameters.PlatinumPackage;
                    current.Currency           = parameters.Currency;
                    current.PriceRate          = parameters.PriceRate;

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

                    return("Successfully changed parameters!");
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message, ex);
                    return("#Error: Could change parameters.");
                }
            }
        }
示例#3
0
        public string Register([Bind(Include = "FirstName,LastName,Email,Password")] User user)
        {
            if (!ModelState.IsValid)
            {
                foreach (var state in ModelState.Values)
                {
                    foreach (var error in state.Errors)
                    {
                        return("#Error: " + error.ErrorMessage);
                    }
                }

                return("#Error: Unknown error.");
            }

            using (var db = new AuctionHouseDB())
            {
                try
                {
                    user.ID       = Guid.NewGuid();
                    user.Password = user.Password.ToMD5();

                    db.Users.Add(user);
                    db.SaveChanges();

                    return("Successfully registered!");
                }
                catch (Exception ex)
                {
                    log.Warn(ex.Message, ex);
                    return("#Error: Could not register. Email already in use.");
                }
            }
        }
示例#4
0
        public string Manage(string guid, bool approve)
        {
            if (Session["user"] == null || !(bool)Session["isAdmin"])
            {
                return(string.Empty);
            }

            if (string.IsNullOrWhiteSpace(guid) || !Guid.TryParse(guid, out var id))
            {
                return("#Error: Invalid auction id.");
            }

            using (var db = new AuctionHouseDB())
            {
                using (var transaction = db.Database.BeginTransaction(IsolationLevel.Serializable))
                {
                    try
                    {
                        var auction = db.FindAuctionById(id);

                        if (auction == null)
                        {
                            throw new TransactionException("Could not find auction with such id.");
                        }

                        if (auction.OpenedOn != null)
                        {
                            throw new TransactionException("Auction was already managed.");
                        }

                        auction.OpenedOn = DateTime.Now;
                        if (!approve)
                        {
                            auction.CompletedOn = auction.OpenedOn;
                        }

                        db.Entry(auction).State = EntityState.Modified;

                        db.SaveChanges();
                        transaction.Commit();

                        try { AuctionHub.HubContext.Clients.All.onAuctionManaged(auction.ID.ToString(), auction.Title, approve ? auction.AuctionTime : 0, auction.StartingPrice, string.Empty, "[No bidder]", "<b>" + auction.OpenedOn.Value.ToString(Settings.DateTimeFormat) + "</b>", auction.CompletedOn != null ? "<b>" + auction.CompletedOn.Value.ToString(Settings.DateTimeFormat) + "</b>" : "<b style=\"color: red;\">Not complete</b>"); }
                        catch (Exception ex) { log.Error(ex); }

                        return("Auction successfully managed.");
                    }
                    catch (TransactionException ex)
                    {
                        transaction.Rollback();
                        return("#Error: " + ex.Message);
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        log.Error(ex.Message, ex);
                        return("#Error: Unknown error occured.");
                    }
                }
            }
        }
示例#5
0
        public string OrderTokens(int package)
        {
            if (Session["user"] == null)
            {
                return(string.Empty);
            }

            using (var db = new AuctionHouseDB())
            {
                try
                {
                    var parameters = db.GetCurrentSystemParameters();

                    decimal amount = 0;

                    switch (package)
                    {
                    case 0: amount = parameters.SilverPackage; break;

                    case 1: amount = parameters.GoldPackage; break;

                    case 2: amount = parameters.PlatinumPackage; break;

                    default: return("#Error: Such package does not exist.");
                    }

                    var order = new TokenOrder
                    {
                        ID        = Guid.NewGuid(),
                        Buyer     = ((User)Session["user"]).ID,
                        Amount    = amount,
                        Currency  = parameters.Currency,
                        PriceRate = parameters.PriceRate,
                        Status    = null
                    };

                    try
                    {
                        db.TokenOrders.Add(order);
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.Message, ex);
                        return("#Error: Could not initiate order. Please, try again.");
                    }

                    AuctionHub.HubContext.Clients.All.onTokenOrderCreated(order.Buyer.ToString(), order.ID.ToString(), order.Amount.ToString(Settings.DecimalFormat), order.Currency, order.PriceRate.ToString(Settings.DecimalFormat));

                    return("<a id=\"c-mobile-payment-widget\" href=\"https://stage.centili.com/payment/widget?apikey=b23180535003ba668fe3d1d2876ad928&reference=" + order.ID + "&country=rs&package=" + package + "\" target=\"_blank\"><img src=\"https://www.centili.com/images/centili-widget-button.png\"/></a>");
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message, ex);
                    return("#Error: Unknown error occured.");
                }
            }
        }
示例#6
0
 public ActionResult Index()
 {
     using (var db = new AuctionHouseDB())
     {
         try
         {
             ViewBag.NavIndex       = 0;
             ViewBag.RecentAuctions = db.GetCurrentSystemParameters().RecentAuctions;
             return(View(db.FindActiveAndCompletedAuctions(true)));
         }
         catch (Exception ex)
         {
             log.Error(ex.Message, ex);
             return(View("Error"));
         }
     }
 }
        public ActionResult System()
        {
            if (Session["user"] == null || !(bool)Session["isAdmin"])
            {
                return(HttpNotFound());
            }

            using (var db = new AuctionHouseDB())
            {
                try
                {
                    ViewBag.NavIndex = 4;
                    return(View(db.GetCurrentSystemParameters()));
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message, ex);
                    return(View("Error"));
                }
            }
        }
示例#8
0
        public ActionResult ViewProfile(string id)
        {
            using (var db = new AuctionHouseDB())
            {
                try
                {
                    if (Session["user"] == null)
                    {
                        return(HttpNotFound());
                    }

                    User user = null;

                    if (Guid.TryParse(id, out var userid))
                    {
                        user = db.FindUserById(userid);
                    }
                    else
                    {
                        user = db.FindUserById(((User)Session["user"]).ID);
                    }

                    if (user == null)
                    {
                        user = Models.User.Dummy;
                    }
                    else if (user.ID == ((User)Session["user"]).ID)
                    {
                        ViewBag.TokenOrders = db.FindUserTokenOrders(user);
                    }

                    return(View(user));
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message, ex);
                    return(View("Error"));
                }
            }
        }
        public void PaymentProcessed(string clientId, string status)
        {
            using (var db = new AuctionHouseDB())
            {
                using (var transaction = db.Database.BeginTransaction(IsolationLevel.Serializable))
                {
                    try
                    {
                        TokenOrder order = null;
                        if (Guid.TryParse(clientId, out var id))
                        {
                            order = db.FindTokenOrderByGuid(id);
                        }
                        if (order == null)
                        {
                            throw new TransactionException("Invalid payment id.");
                        }

                        if (order.Status != null)
                        {
                            throw new TransactionException("Payment already proccessed.");
                        }

                        order.Status          = status == "success";
                        db.Entry(order).State = EntityState.Modified;

                        var     user    = db.FindUserById(order.Buyer);
                        decimal balance = -1;

                        if (order.Status.Value)
                        {
                            user.Balance        += order.Amount;
                            balance              = user.Balance;
                            db.Entry(user).State = EntityState.Modified;
                        }

                        db.SaveChanges();
                        transaction.Commit();

                        try
                        {
                            AuctionHub.HubContext.Clients.All.onTokenOrderCompleted(order.Buyer.ToString(), order.ID.ToString(), balance, order.Status.Value);

                            Mailer.SendMail(Settings.SMTPUsername, "Auction House", user.Email, user.FirstName + " " + user.LastName, "Auction House - Token Order",
                                            "Dear " + user.FirstName + "," + Environment.NewLine +
                                            Environment.NewLine +
                                            "This e-mail has been sent to inform you that your token order" + Environment.NewLine +
                                            "has been processed and marked as [" + (order.Status.Value ? "COMPLETE" : "FAILED") + "]." + Environment.NewLine +
                                            Environment.NewLine +
                                            "Please, do not reply to this e-mail as you will not get any response." + Environment.NewLine +
                                            Environment.NewLine +
                                            "Kind regards," + Environment.NewLine +
                                            "Auction House"
                                            );
                        }
                        catch (Exception ex) { log.Error(ex.Message, ex); }
                    }
                    catch (TransactionException ex)
                    {
                        transaction.Rollback();
                        log.Warn(ex.Message, ex);
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        log.Error(ex.Message, ex);
                    }
                }
            }
        }
示例#10
0
        public string ChangeInfo(string oldpassword, string firstname, string lastname, string email, string password)
        {
            if (Session["user"] == null)
            {
                return(string.Empty);
            }

            using (var db = new AuctionHouseDB())
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(oldpassword))
                    {
                        return("#Error: You must supply your old password!");
                    }

                    User user = (User)Session["user"];
                    if (user.Password != oldpassword.ToMD5())
                    {
                        return("#Error: Old password does not match your current one.");
                    }

                    user = db.FindUserById(user.ID);

                    StringBuilder sb = new StringBuilder("Success: [");

                    if (!string.IsNullOrWhiteSpace(firstname))
                    {
                        user.FirstName = firstname;
                        sb.Append("First Name,");
                    }

                    if (!string.IsNullOrWhiteSpace(lastname))
                    {
                        user.LastName = lastname;
                        sb.Append("Last Name,");
                    }

                    if (!string.IsNullOrWhiteSpace(email) && db.FindUserByEmail(email) == null)
                    {
                        user.Email = email;
                        sb.Append("Email,");
                    }

                    if (!string.IsNullOrWhiteSpace(password))
                    {
                        user.Password = password;
                        sb.Append("Password,");
                    }

                    sb[sb.Length - 1] = ']';

                    if (!ModelState.IsValid)
                    {
                        foreach (var state in ModelState.Values)
                        {
                            foreach (var error in state.Errors)
                            {
                                return("#Error: " + error.ErrorMessage);
                            }
                        }

                        return("#Error: Unknown error.");
                    }

                    user.Password        = user.Password.ToMD5();
                    db.Entry(user).State = EntityState.Modified;

                    try { db.SaveChanges(); }
                    catch { return("#Error: One or more fields are not in a correct format (eg. invalid email)."); }

                    Session["user"] = user;
                    return(sb.ToString());
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message, ex);
                    return("#Error: Unknown error occured.");
                }
            }
        }
示例#11
0
        public string Create(string title, int time, decimal price)
        {
            if (Session["user"] == null)
            {
                return(string.Empty);
            }

            using (var db = new AuctionHouseDB())
            {
                try
                {
                    var sysparams = db.GetCurrentSystemParameters();

                    if (title == null || string.IsNullOrWhiteSpace(title))
                    {
                        return("#Error: Invalid title.");
                    }
                    if (time <= 0)
                    {
                        time = sysparams.DefaultAuctionTime;
                    }
                    if (price < 0)
                    {
                        return("#Error: Invalid price.");
                    }

                    var uploadFailed = true;

                    var guid = Guid.NewGuid();

                    for (int i = 0; i < Request.Files.Count; ++i)
                    {
                        if (Request.Files[i].ContentType == "image/png")
                        {
                            Directory.CreateDirectory(Server.MapPath("~/assets/storage/auctions/" + guid.ToString() + "/"));
                            Request.Files[i].SaveAs(Server.MapPath("~/assets/storage/auctions/" + guid.ToString() + "/" + i + ".png"));
                            uploadFailed = false;
                        }
                    }

                    if (uploadFailed)
                    {
                        return("#Error: You must supply at least one image.");
                    }

                    var user = (User)Session["user"];

                    var auction = new Auction
                    {
                        ID            = guid,
                        Title         = title,
                        AuctionTime   = time,
                        CreatedOn     = DateTime.Now,
                        OpenedOn      = null,
                        CompletedOn   = null,
                        StartingPrice = price,
                        Currency      = sysparams.Currency,
                        PriceRate     = sysparams.PriceRate,
                        Holder        = user.ID
                    };

                    try
                    {
                        db.Auctions.Add(auction);
                        db.SaveChanges();
                    }
                    catch { return("#Error: Could not create the auction. Some of the values are invalid."); }

                    AuctionHub.HubContext.Clients.All.onAuctionCreated(auction.ID.ToString(), auction.Title, auction.AuctionTime, auction.StartingPrice, auction.CreatedOn.ToString(Settings.DateTimeFormat), user.FirstName + " " + user.LastName);
                    return(auction.ID.ToString());
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message, ex);
                    return("#Error: Unknown error occured.");
                }
            }
        }
示例#12
0
        public string Claim(string guid)
        {
            var user = Session["user"] as User;

            if (user == null)
            {
                return(string.Empty);
            }

            using (var db = new AuctionHouseDB())
            {
                using (var transaction = db.Database.BeginTransaction(IsolationLevel.Serializable))
                {
                    try
                    {
                        Auction auction = null;
                        if (Guid.TryParse(guid, out var id))
                        {
                            auction = db.FindAuctionById(id);
                        }

                        if (auction == null)
                        {
                            throw new TransactionException("Invalid auction.");
                        }

                        if (auction.Holder != user.ID)
                        {
                            throw new TransactionException("Can't claim auction prize.");
                        }

                        if (auction.OpenedOn == null)
                        {
                            throw new TransactionException("Auction is not opened.");
                        }

                        var now = DateTime.Now;

                        if (now < auction.OpenedOn.Value.AddSeconds(auction.AuctionTime))
                        {
                            throw new TransactionException("Auction is not finished yet.");
                        }

                        if (auction.CompletedOn != null)
                        {
                            throw new TransactionException("Auction is completed, no prize left to claim.");
                        }

                        auction.CompletedOn     = now;
                        db.Entry(auction).State = EntityState.Modified;

                        var lastBid = auction.LastBid;

                        if (lastBid != null)
                        {
                            user                 = db.FindUserById(user.ID);
                            user.Balance        += lastBid.Amount;
                            db.Entry(user).State = EntityState.Modified;
                        }

                        db.SaveChanges();
                        transaction.Commit();

                        return("Successfully claimed auction prize. Please, check your balance.");
                    }
                    catch (TransactionException ex)
                    {
                        transaction.Rollback();
                        return("#Error: " + ex.Message);
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        log.Error(ex.Message, ex);
                        return("#Error: Unknown error occured.");
                    }
                }
            }
        }
示例#13
0
        public string Bid(string guid, decimal amount)
        {
            var user = Session["user"] as User;

            if (user == null)
            {
                return("#Error: Please, log in!");
            }

            if (!Guid.TryParse(guid, out var id))
            {
                return("#Error: Invalid guid.");
            }

            using (var db = new AuctionHouseDB())
            {
                using (var transaction = db.Database.BeginTransaction(IsolationLevel.Serializable))
                {
                    try
                    {
                        var auction = db.FindAuctionById(id);
                        if (auction == null)
                        {
                            throw new TransactionException("Auction does not exist (to bid on such).");
                        }

                        if (auction.OpenedOn == null)
                        {
                            throw new TransactionException("Auction is not opened yet.");
                        }

                        if (auction.CompletedOn != null || DateTime.Now >= auction.OpenedOn.Value.AddSeconds(auction.AuctionTime))
                        {
                            throw new TransactionException("Auctions is closed.");
                        }

                        if (auction.Holder == user.ID)
                        {
                            throw new TransactionException("Cannot bid on owning auction.");
                        }

                        var lastBid = auction.LastBid;
                        if (lastBid != null)
                        {
                            if (amount <= lastBid.Amount)
                            {
                                throw new TransactionException("Cannot bid with lower price than current.");
                            }
                        }
                        else
                        {
                            if (amount <= auction.StartingPrice)
                            {
                                throw new TransactionException("Cannot bid with lower price than current.");
                            }
                        }

                        user = db.FindUserById(user.ID);
                        if (user.Balance < amount)
                        {
                            throw new TransactionException("Insufficient funds.");
                        }

                        if (lastBid != null)
                        {
                            lastBid.User.Balance        += lastBid.Amount;
                            db.Entry(lastBid.User).State = EntityState.Modified;
                        }

                        user.Balance        -= amount;
                        db.Entry(user).State = EntityState.Modified;

                        var bid = new Bid
                        {
                            ID      = Guid.NewGuid(),
                            Bidder  = user.ID,
                            Auction = auction.ID,
                            BidOn   = DateTime.Now,
                            Amount  = amount
                        };

                        db.Bids.Add(bid);
                        db.SaveChanges();
                        transaction.Commit();

                        try { AuctionHub.HubContext.Clients.All.onBid(auction.ID.ToString(), user.ID.ToString(), user.FirstName + " " + user.LastName, bid.BidOn.ToString(Settings.DateTimeFormat), amount); }
                        catch (Exception ex) { log.Error(ex); }

                        return("Bidding successful.");
                    }
                    catch (TransactionException ex)
                    {
                        transaction.Rollback();
                        return("#Error: " + ex.Message);
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        log.Error(ex.Message, ex);
                        return("#Error: Unknown error occured.");
                    }
                }
            }
        }
示例#14
0
        public ActionResult Show(string id)
        {
            using (var db = new AuctionHouseDB())
            {
                try
                {
                    if (!Guid.TryParse(id, out var guid))
                    {
                        return(HttpNotFound());
                    }
                    var auction = db.FindAuctionById(guid, true);
                    if (auction == null)
                    {
                        return(HttpNotFound());
                    }

                    if (auction.OpenedOn == null &&
                        (Session["user"] == null || !(bool)Session["isAdmin"] && ((User)Session["user"]).ID != auction.Holder))
                    {
                        return(HttpNotFound());
                    }

                    if (auction.OpenedOn != null && auction.CompletedOn == null)
                    {
                        var completedOn = auction.OpenedOn.Value.AddSeconds(auction.AuctionTime);
                        if (DateTime.Now >= completedOn)
                        {
                            auction.CompletedOn = completedOn;
                        }
                    }

                    var images = new List <string>(16);
                    var path   = "/assets/storage/auctions/" + auction.ID.ToString() + "/";
                    foreach (var file in Directory.EnumerateFiles(Server.MapPath("~" + path)))
                    {
                        if (file.EndsWith(".png"))
                        {
                            images.Add(path + Path.GetFileName(file));
                        }
                    }

                    ViewBag.ImageSources = images;

                    var lastBid = auction.LastBid;
                    if (lastBid != null)
                    {
                        ViewBag.Bidder       = lastBid.User;
                        ViewBag.CurrentPrice = lastBid.Amount;
                    }
                    else
                    {
                        ViewBag.CurrentPrice = auction.StartingPrice;
                    }

                    return(View(auction));
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message, ex);
                    return(View("Error"));
                }
            }
        }