Esempio n. 1
0
        public ActionResult BuyPack(int id, string email)
        {
            Debug.WriteLine("POST - Shop - BuyCardPackages(id)");
            Writer.LogInfo("id: " + id.ToString());

            Models.Order o          = new Models.Order();
            var          dbPackages = ShopManager.GetCardPackById(id);


            //Models.Pack cardPack = new Models.Pack();
            //cardPack.ID = dbPackages.ID;
            //cardPack.Packname = dbPackages.Name;
            ////GetValueOrDefault eingefügt wegen DATENTYP decimal => Konvertierung da NULLABLE
            //cardPack.CardQuantity = dbPackages.Cardquantity.GetValueOrDefault();
            //cardPack.Packprice = dbPackages.Packprice.GetValueOrDefault();

            //o.CardPacks = ;
            o.OrderDate    = DateTime.Now;
            o.PackQuantity = 1;
            //o.UserBalance = UserManager.GetCurrencyBalanceByEmail(User.Identity.Name);

            email = User.Identity.Name;

            BuyResult rueck = ShopManager.BuyPack(id, email);

            o.UserBalance     = UserManager.GetCurrencyBalanceByEmail(User.Identity.Name);
            TempData["Order"] = o;

            return(RedirectToAction("OrderDetails"));
        }
        public static BuyResult ExecuteDiamantenOrder(int idPerson, int idDiaPack)
        {
            BuyResult result = BuyResult.Success;

            using (var db = new CardGame_v2Entities())
            {
                VirtualPurchase diaOrder = new VirtualPurchase();

                diaOrder.ID_DiamantenPack = idDiaPack;
                diaOrder.ID_User          = idPerson;
                diaOrder.PurchaseDate     = DateTime.Now;
                diaOrder.NumberOfPacks    = 1;
                db.AllVirtualPurchases.Add(diaOrder);
                db.SaveChanges();


                User          user = db.AllUsers.FirstOrDefault(x => x.ID == idPerson);
                DiamantenPack pack = db.AllDiamantenPacks.FirstOrDefault(x => x.ID == idDiaPack);

                if (user.AmountMoney < pack.PackPrice)
                {
                    result = BuyResult.NotEnoughMoney;
                }
                else
                {
                    /// ziehe Preis vom pack beim User ab!
                    user.AmountMoney += (int)pack.Diamanten;
                    db.SaveChanges();
                }
            }
            return(result);
        }
Esempio n. 3
0
 protected void SendFailed(Player player, BuyResult result)
 {
     player.Client.SendPacket(new networking.packets.outgoing.BuyResult
     {
         Result       = 1,
         ResultString = $"Purchase Error: {result.GetDescription()}"
     });
 }
Esempio n. 4
0
 public EzBuyResult(
     BuyResult result
     )
 {
     if (result.item != null)
     {
         Item = new EzSalesItem(result.item);
     }
     StampSheet = result.stampSheet;
     StampSheetEncryptionKeyId = result.stampSheetEncryptionKeyId;
 }
Esempio n. 5
0
        public ActionResult Buy(Buy model)
        {
            var user = _context.Users.Find(User.Identity.GetUserId());

            // Kullanıcı satın alma işlemini yapar ve bir sonuç döner.
            BuyResult result = BuyFromSupplier(model, user);

            // Eğer satın alma olduysa yani tutar > 0 ' ise komisyon alınır ve bu kullanıcının finans geçmişine eklenir.
            if (result.Amount > 0)
            {
                double commission = GetCommission(user, result.Amount);

                FinanceHistory financeHistory = new FinanceHistory()
                {
                    CustomerId = result.CustomerId, Money = result.Amount + commission, Date = DateTime.Now, FinanceTypeId = 4, MoneyTypeId = 1
                };
                _context.FinanceHistories.Add(financeHistory);

                _context.SaveChanges();

                ViewBag.Success = true;
                ViewBag.Message = $"{result.PurchasedQuantity} adet ürün {result.Amount} TL' den alındı. İşlem için {commission} TL ücret kesildi.";
            }
            // Eğer kullanıcı belirli bir fiyattan almak istiyorsa bu istek listesine eklenir.
            else if (model.Price > 0)
            {
                LimitBuy limitBuy = new LimitBuy {
                    Date = DateTime.Now, Price = model.Price, ProductId = model.ProductId, UserId = user.Id, Quantity = model.Quantity
                };
                _context.LimitBuys.Add(limitBuy);

                _context.SaveChanges();

                ViewBag.Success = true;
                ViewBag.Message = $" {model.Quantity} tane ürün {model.Price}TL' den alınmak üzere istek listesine eklendi.";
            }
            else
            {
                ViewBag.Success = false;
                ViewBag.Message = "Para yetmediği için ürün alınamadı.";
            }

            ViewBag.Product = _context.Products.Find(model.ProductId);
            return(View());
        }
Esempio n. 6
0
    private static void onEventBuy(string sRet)
    {
        BuyResult res = new BuyResult();

        res.intradeno = "";
        res.retCode   = -1;
        res.retMsg    = GetString("PurchaseConnectFailed");
        try {
            res = JsonUtility.FromJson <BuyResult>(sRet);
        }
        catch (Exception)
        {
            Debug.Log("onEventBuy " + sRet);
        }

        string txt;

        if (res.retCode != 0)
        {
            txt = String.Format(GetString("PurchaseFailed"), res.retMsg);
        }
        else
        {
            txt = String.Format(GetString("PurchaseSuccess"), res.intradeno);
        }

        if (_MsgboxBuy)
        {
            _MsgboxBuy.Reset("buy.done", GetString("Purchase"), txt, GetString("Close"), "");
        }
        else
        {
            MsgBox("buy.done", GetString("Purchase"), txt, GetString("Close"));
        }

        if (_BuyParam.cb != null)
        {
            _BuyParam.cb(_BuyParam.sItem, _BuyParam.sOutTradeNo, res.intradeno, res.retMsg);
        }
    }
Esempio n. 7
0
        public async Task <BuyResult> Put(int id, int balance)
        {
            Product product = productService.GetById(id);

            if (balance == 0)
            {
                BuyResult errBalBuyResult = new BuyResult
                {
                    Balance      = 0,
                    Error        = true,
                    ErrorMessage = "Balance cannot be 0"
                };
                return(errBalBuyResult);
            }

            if (product == null)
            {
                BuyResult errProdBuyResult = new BuyResult
                {
                    Balance      = 0,
                    Error        = true,
                    ErrorMessage = "Product was not found"
                };
                return(errProdBuyResult);
            }

            int remainBalance = balance - product.Price;

            BuyResult successBuyResult = new BuyResult
            {
                Balance      = remainBalance,
                Error        = false,
                ErrorMessage = null,
            };

            productService.Update(id);
            return(successBuyResult);
        }
        public ServiceResult <BuyResult> Buy(int playerId, int itemId)
        {
            var player = _playerService.Get(playerId);

            if (player == null)
            {
                return(new ServiceResult <BuyResult>().PlayerNotFound());
            }

            var item = _itemService.Get(itemId);

            if (item == null)
            {
                return(new ServiceResult <BuyResult>().ItemNotFound());
            }

            if (item.Price > player.Money)
            {
                return(new ServiceResult <BuyResult>().NotEnoughMoney());
            }

            _playerItemService.Create(playerId, itemId);

            player.Money -= item.Price;

            //SaveChanges
            _database.SaveChanges();

            var buyResult = new BuyResult
            {
                Player = player,
                Item   = item
            };

            return(new ServiceResult <BuyResult> {
                Data = buyResult
            });
        }
Esempio n. 9
0
        public static BuyResult ExecuteOrder(int idPerson, int idPack)
        {
            BuyResult result = BuyResult.Success;

            using (var db = new CardGame_v2Entities())
            {
                VirtualPurchase order = new VirtualPurchase();
                order.ID_CardPack   = idPack;
                order.ID_User       = idPerson;
                order.PurchaseDate  = DateTime.Now;
                order.NumberOfPacks = 1;

                db.AllVirtualPurchases.Add(order);
                db.SaveChanges();


                /// ermittle User und Pack für übergebene IDs
                User     user = db.AllUsers.FirstOrDefault(x => x.ID == idPerson);
                CardPack pack = db.AllCardPacks.FirstOrDefault(x => x.ID == idPack);

                // prüfe auf ungültige Daten
                if (user == null)
                {
                    throw new ArgumentException("Ungültige idPerson");
                }
                if (pack == null)
                {
                    throw new ArgumentException("Ungültige idPack");
                }

                /// prüfe ob user genügend IngameGeld hat!
                if (user.AmountMoney < pack.PackPrice)
                {
                    result = BuyResult.NotEnoughDiamonds;
                }
                else
                {
                    /// ziehe Preis vom pack beim User ab!
                    user.AmountMoney -= pack.PackPrice;

                    /// Ermittle die Karten die der User (im Pack) jetzt gekauft hat!
                    Random rnd = new Random();
                    int    numberOfAllCards = db.AllCards.Count();

                    for (int i = 0; i < pack.NumCards; i++)
                    {
                        /// ermittle einen zufälligen Index einer möglichen Karte
                        int rng = rnd.Next(0, numberOfAllCards);

                        /// überspringe alle karten VOR diesem Index (daher auch: rng-1)
                        /// und nimm danach die nächste Karte
                        var card = db.AllCards.OrderBy(x => x.ID).Skip(rng - 1).Take(1).Single();

                        /// ermittle nun ob der User DIESE Karte schon einmal hat
                        UserCardCollection coll = user.AllUserCardCollections.Where(x => x.ID_Card == card.ID).FirstOrDefault();

                        //card
                        if (coll != null) /// user hat diese karte schon einmal
                        {
                            coll.NumberOfCards++;
                        }
                        else /// user hat Karte noch nicht
                        {
                            /// also füge sie genau 1x hinzu
                            coll = new UserCardCollection()
                            {
                                ID_User       = user.ID,
                                ID_Card       = card.ID,
                                NumberOfCards = 1
                            };
                            db.AllUserCardCollections.Add(coll);
                        }
                    }

                    db.SaveChanges();
                }
            }
            return(result);
        }
Esempio n. 10
0
        public static BuyResult BuyPack(int id, string email)
        {
            BuyResult result = BuyResult.Success;

            if (id <= 0)
            {
                throw new ArgumentException("Invalid Value", nameof(id));
            }

            if (string.IsNullOrEmpty(email))
            {
                throw new ArgumentNullException(nameof(email));
            }

            try
            {
                using (var context = new ClonestoneFSEntities())
                {
                    Person user = context.AllPersons.FirstOrDefault(x => x.Email == email);
                    if (user == null)
                    {
                        throw new ArgumentException("Invalid value", nameof(email));
                    }

                    Pack cardPack = context.AllPacks.FirstOrDefault(x => x.ID == id);
                    if (cardPack == null)
                    {
                        throw new ArgumentException("Invalid value", nameof(id));
                    }


                    if (cardPack.IsMoney == false)
                    {
                        if (user.Currencybalance < cardPack.Packprice)
                        {
                            result = BuyResult.NotEnoughMoney;
                        }
                        else
                        {
                            user.Currencybalance -= (int)cardPack.Packprice;

                            Order purchase = new Order()
                            {
                                ID_Pack       = id,
                                ID_Person     = user.ID,
                                NumberOfPacks = 1,
                                Orderdate     = DateTime.Now
                            };
                            context.AllOrders.Add(purchase);


                            int count = context.AllCards.Count();

                            //List<Card> userCards = new List<Card>();

                            /// create cards at random
                            for (int numberOfCard = 0; numberOfCard < cardPack.Cardquantity; numberOfCard++)
                            {
                                /// get a valid idCard (generated by random)
                                Card randomCard = context.AllCards.OrderBy(x => x.ID).Skip(RandomNumberGenerator.Next(0, count)).Take(1).Single();

                                /// save new card to userCards

                                /// if card is already an userCard
                                /// increase number
                                PersonCard personCard = user.AllPersonCards.Where(x => x.ID == randomCard.ID).FirstOrDefault();
                                if (personCard != null)
                                {
                                    personCard.NumberOfCards++;
                                }
                                else /// else - add new userCard
                                {
                                    personCard = new PersonCard()
                                    {
                                        ID_Person     = user.ID,
                                        ID_Card       = randomCard.ID,
                                        NumberOfCards = 1
                                    };
                                    context.AllPersonCards.Add(personCard);
                                }
                            }
                            context.SaveChanges();
                        }
                    }

                    else if (cardPack.IsMoney == true)
                    {
                        Order purchase = new Order()
                        {
                            ID_Pack       = id,
                            ID_Person     = user.ID,
                            NumberOfPacks = 1,
                            Orderdate     = DateTime.Now
                        };
                        context.AllOrders.Add(purchase);


                        int currentBalance = UserManager.GetCurrencyBalanceByEmail(user.Email);

                        int sumBalance = ((int)(currentBalance + GetCardPackById(id).DiamondValue)) * (int)purchase.NumberOfPacks;

                        bool isUpdated = UserManager.BalanceUpdateByEmail(user.Email, sumBalance);

                        context.SaveChanges();
                    }
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }

            return(result);
        }
        public IqOptionWebSocketClient(Action <IqOptionWebSocketClient> initialSetup = null, string host = "iqoption.com")
        {
            Client = new WebSocket($"wss://{host}/echo/websocket");

            MessageReceivedObservable =
                Observable.Using(
                    () => Client,
                    _ => Observable
                    .FromEventPattern <EventHandler <MessageReceivedEventArgs>, MessageReceivedEventArgs>(
                        handler => _.MessageReceived += handler,
                        handler => _.MessageReceived -= handler))
                .Select(x => x.EventArgs.Message)
                .SubscribeOn(new EventLoopScheduler())
                .Publish()
                .RefCount();


            MessageReceivedObservable.Subscribe(x => {
                var a = x.JsonAs <WsMessageBase <object> >();
                switch (a.Name?.ToLower())
                {
                case "heartbeat": {
                    var value = x.JsonAs <HeartBeat>();
                    _heartbeat.OnNext(value.Message);
                    break;
                }

                case "timesync": {
                    var value  = x.JsonAs <ServerTime>();
                    ServerTime = value.Message;
                    break;
                }

                case "profile": {
                    if (!a.Message.Equals(false))
                    {
                        var profile = x.JsonAs <WsMessageBase <Profile> >().Message;
                        _profileSubject.OnNext(profile);
                    }

                    break;
                }

                case "instruments": {
                    var result = x.JsonAs <WsMessageBase <InstrumentsResult> >().Message;
                    _logger.Verbose($"Received Inst. => instruments ({result.Type.ToString()})");
                    _instrumentResultSet[result.Type] = result.Instruments;
                    _instrumentResultSetSubject.OnNext(_instrumentResultSet);

                    if (_instrumentResultSet.All(i => i.Value.Any()))
                    {
                        _instrumentResultSetSubject.OnCompleted();
                    }

                    break;
                }

                case "profit-top-user-moved-up":
                    {
                        break;
                    }

                case "activecommissionchange":
                    {
                        break;
                    }

                case "user-tournament-position-changed":
                    {
                        break;
                    }

                case "chat-state-updated":
                    {
                        break;
                    }

                case "front":
                    {
                        break;
                    }

                case "listinfodata": {
                    var result = x.JsonAs <WsMessageBase <InfoData[]> >();
                    _infoDataSubject.OnNext(result?.Message);
                    var info = result?.Message.FirstOrDefault();
                    if (info != null)
                    {
                        _logger.Information(
                            $"info-received  => {info.UserId} {info.Win} {info.Direction} {info.Sum} {info.Active} @{info.Value} exp {info.ExpTime}({info.Expired.ToShortTimeString()})");
                    }
                    break;
                }

                case "buycomplete": {
                    var result = x.JsonAs <WsMessageBase <WsMessageWithSuccessfulResult <object> > >().Message;
                    if (result.IsSuccessful)
                    {
                        var buyResult = x.JsonAs <WsMessageBase <WsMessageWithSuccessfulResult <BuyResult> > >().Message
                                        .Result;
                        _logger.Information(
                            $"buycompleted   => {buyResult.UserId} {buyResult.Type} {buyResult.Direction} {buyResult.Price} {(ActivePair) buyResult.Act} @{buyResult.Value} ");
                        _buyResulSjSubject.OnNext(buyResult);
                    }
                    else
                    {
                        var ex = string.Join(", ", result.Message?.ToList());
                        _logger.Information($"{this.Profile?.UserId}\t{ex}", ex);
                        _buyResulSjSubject.OnNext(BuyResult.BuyResultError(result.Message));
                    }

                    break;
                }

                case "candles": {
                    var result = x.JsonAs <GetCandleItemsResultMessage>();
                    if (result != null)
                    {
                        CandleCollections = result.Message;
                    }
                    break;
                }

                case "candle-generated": {
                    var candle = x.JsonAs <CurrentCandleInfoResultMessage>();
                    if (candle != null)
                    {
                        _candleInfoSubject.OnNext(candle.Message);
                        CurrentCandleInfo = candle.Message;
                    }

                    break;
                }

                default: {
                    _logger.Verbose(Profile?.Id + "    =>  " + a.AsJson());
                    break;
                }
                }
            }, ex => { _logger.Error(ex.Message); });


            initialSetup?.Invoke(this);
        }
Esempio n. 12
0
        /// <summary>
        /// creates a pack with a number of cards
        /// cards will be chosen at random
        /// random cards may be duplicates
        /// assign cards to user
        /// decrease money of user by price of pack
        /// add new virtual purchase entry
        /// </summary>
        /// <param name="idCardPack"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public static BuyResult BuyPack(int idCardPack, string username)
        {
            log.Info("ShopAdministration - BuyPack(idCardPack, username)");
            BuyResult result = BuyResult.Success;

            if (idCardPack <= 0)
            {
                throw new ArgumentException("Invalid Value", nameof(idCardPack));
            }
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException(nameof(username));
            }

            try
            {
                using (var context = new clonestoneEntities())
                {
                    User user = context.AllUsers.FirstOrDefault(x => x.Username == username);
                    if (user == null)
                    {
                        throw new ArgumentException("Invalid value", nameof(username));
                    }

                    CardPack cardPack = context.AllCardPacks.FirstOrDefault(x => x.ID == idCardPack);
                    if (cardPack == null)
                    {
                        throw new ArgumentException("Invalid value", nameof(idCardPack));
                    }

                    if (user.AmountMoney < cardPack.Price)
                    {
                        log.Debug($"User {username} has not enough money for Pack {idCardPack}");
                        result = BuyResult.NotEnoughMoney;
                    }
                    else
                    {
                        log.Debug($"Reduce money of user by {cardPack.Price}");
                        user.AmountMoney -= cardPack.Price;

                        VirtualPurchase purchase = new VirtualPurchase()
                        {
                            ID_CardPack   = idCardPack,
                            ID_User       = user.ID,
                            NumberOfPacks = 1,
                            PurchaseDate  = DateTime.Now
                        };
                        context.AllVirtualPurchases.Add(purchase);
                        log.Debug($"Added new VirtualPurchas for user {username}");

                        int count = context.AllCards.Count();

                        log.Debug($"Start creating random cards for pack {idCardPack}");
                        /// create cards at random
                        for (int numberOfCard = 0; numberOfCard < cardPack.NumberOfCards; numberOfCard++)
                        {
                            /// get a valid idCard (generated by random)
                            Card randomCard = context.AllCards.OrderBy(x => x.ID).Skip(RandomNumberGenerator.Next(0, count)).Take(1).Single();
                            log.Debug($"\tRandomCard {randomCard.Name} (ID: {randomCard.ID})");

                            /// save new card to userCards

                            /// if card is already an userCard
                            /// increase number
                            UserCard userCard = user.AllUserCards.Where(x => x.ID_Card == randomCard.ID).FirstOrDefault();
                            if (userCard != null)
                            {
                                log.Debug($"\t\tUserCard already exists - increase numberOfCards");
                                userCard.NumberOfCards++;
                            }
                            else       /// else - add new userCard
                            {
                                log.Debug($"\t\tAdd NEW UserCard");
                                userCard = new UserCard()
                                {
                                    ID_User       = user.ID,
                                    ID_Card       = randomCard.ID,
                                    NumberOfCards = 1
                                };
                                context.AllUserCards.Add(userCard);
                            }
                        }
                        context.SaveChanges();
                        log.Debug($"Finished adding random cards!");
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("ShopAdministration - BuyPack(idCardPack, username) - Exception", ex);
                if (ex.InnerException != null)
                {
                    log.Error("ShopAdministration - BuyPack(idCardPack, username) - Exception (inner)", ex.InnerException);
                }

                Debugger.Break();
                throw ex;
            }

            return(result);
        }