public ActionResult AddNewWalletAndBank(WalletAndBank newWalletAndBank)
        {
            var           userId        = User.Identity.GetUserId();
            WalletAndBank walletAndBank = new WalletAndBank
            {
                Name         = newWalletAndBank.Name,
                InitialValue = newWalletAndBank.InitialValue,
                BalanceValue = newWalletAndBank.InitialValue,
                //todo add the image to the new wb
                UserId = userId
            };

            _context.WalletAndBanks.Add(walletAndBank);
            _context.SaveChanges();
            return(RedirectToAction("WalletAndBanks", "WalletAndBanks"));
        }
Example #2
0
        /// <summary>
        /// 提现申请
        /// </summary>
        /// <returns></returns>
        public bool AuditApply(Guid id)
        {
            using (var dbContext = new WalletDbContext())
            {
                CrashApply crashApply = dbContext.CrashApplys.FirstOrDefault(c => c.Id == id);
                if (crashApply == null)
                {
                    throw new Exception("找不到提现的记录");
                }
                crashApply.ApplyState = ApplyState.ApplyPassed;
                crashApply.AuditTime  = DateTime.Now;
                dbContext.Set <CrashApply>().Attach(crashApply);
                dbContext.Entry(crashApply).State = EntityState.Modified;

                Models.Wallet wallet = GetWalletByMemberId(crashApply.MemberId);
                if (wallet == null)
                {
                    throw new Exception("钱包是空的");
                }
                else if (crashApply.Money > wallet.Frozen)
                {
                    throw new Exception("提现的金额不能大于冻结的金额");
                }

                return(dbContext.SaveChanges() > 0);
            }
        }
Example #3
0
        public bool Thaw(string memberId, WalletType walletType, decimal money, string remark, out string error)
        {
            error = string.Empty;
            if (money == 0)
            {
                return(true);
            }
            using (var dbContext = new WalletDbContext())
            {
                var wallet =
                    dbContext.Set <Models.Wallet>()
                    .FirstOrDefault(w => w.WalletType == walletType && w.MemberId.Equals(memberId, StringComparison.OrdinalIgnoreCase));
                if (wallet == null)
                {
                    error = "冻结金额不足";
                    return(false);
                }
                else
                {
                    if (wallet.Frozen < money)
                    {
                        error = "冻结金额不足";
                        return(false);
                    }
                    wallet.Available += money;
                    wallet.Frozen    -= money;
                    dbContext.Set <Models.Wallet>().Attach(wallet);
                    dbContext.Entry(wallet).State = EntityState.Modified;
                }

                dbContext.SaveChanges();
                return(true);
            }
        }
Example #4
0
        private void SaveToDb <T>(List <T> collectionToInsert) where T : class
        {
            WalletDbContext context = null;

            try
            {
                context = new WalletDbContext(DbContextOptionsFactory.DbContextOptions());
                context.ChangeTracker.AutoDetectChangesEnabled = false;

                int count = 0;
                foreach (var entity in collectionToInsert)
                {
                    ++count;
                    context = AddToContext(context, entity, count, 100, true);
                }

                context.SaveChanges();
            }
            finally
            {
                if (context != null)
                {
                    context.Dispose();
                }
            }
        }
Example #5
0
        //this method is used to add the new records to the table of daily records. this method uses json.
        public JsonResult AddNewRecord(
            DateTime transactionDate,
            int selectedSubcategory,
            int selectedCategory,
            decimal transactionValue,
            string transactionComment,
            int walletAndBanks

            )
        {
            string      userId         = User.Identity.GetUserId();
            var         typeOfCategory = (int)db.Categories.Where(c => c.Id == selectedCategory).Select(c => c.TypeOfCategory).First();
            Transaction tr             = new Transaction();

            if (db.Subcategories.Select(x => x.Id).Contains(selectedSubcategory))
            {
                tr.TransactionDate = transactionDate;
                tr.AddedDate       = DateTime.Now;
                tr.CategoryId      = selectedCategory;
                tr.SubcategoryId   = selectedSubcategory;
                //check the category type and then add it as a positive or negative number
                if (typeOfCategory == 1)
                {
                    tr.TransationValue = transactionValue;
                }
                else if (typeOfCategory == 2)
                {
                    tr.TransationValue = -transactionValue;
                }

                tr.Comment         = transactionComment;
                tr.WalletAndBankId = walletAndBanks;
                tr.UserId          = userId;
                db.Transactions.Add(tr);
                db.SaveChanges();
                return(Json(true));
            }
            else
            {
                return(Json(false));
            }
        }
Example #6
0
        public bool Draw(string memberId, WalletType walletType, decimal money, string remark, out string error, string tag = null, string toMemberId = null, bool drawFrozen = false)
        {
            error = string.Empty;
            if (money == 0)
            {
                return(true);
            }

            using (var dbContext = new WalletDbContext())
            {
                var wallet =
                    dbContext.Set <Models.Wallet>()
                    .FirstOrDefault(w => w.WalletType == walletType && w.MemberId == memberId);

                if (drawFrozen)
                {
                    if (wallet == null || wallet.Frozen < money)
                    {
                        error = "冻结余额不足";
                        return(false);
                    }

                    wallet.Frozen -= money;
                }
                else
                {
                    if (wallet == null || wallet.Available < money)
                    {
                        error = "余额不足";
                        return(false);
                    }

                    wallet.Available -= money;
                }
                dbContext.Set <Models.Wallet>().Attach(wallet);
                dbContext.Entry(wallet).State = EntityState.Modified;

                WalletBill walletBill = new WalletBill();
                walletBill.Id           = KeyGenerator.GetGuidKey();
                walletBill.MemberId     = memberId;
                walletBill.BillType     = BillType.TakeOut;
                walletBill.WalletType   = walletType;
                walletBill.Money        = money;
                walletBill.Remark       = remark;
                walletBill.BillTag      = tag;
                walletBill.CreateTime   = DateTime.Now;
                walletBill.FromMemberId = toMemberId;
                dbContext.WalletBills.Add(walletBill);
                dbContext.SaveChanges();
                return(true);
            }
        }
Example #7
0
        private WalletDbContext AddToContext <T>(WalletDbContext context,
                                                 T entity, int count, int commitCount, bool recreateContext) where T : class
        {
            context.Set <T>().Add(entity);

            if (count % commitCount == 0)
            {
                context.SaveChanges();
                if (recreateContext)
                {
                    context.Dispose();
                    context = new WalletDbContext(DbContextOptionsFactory.DbContextOptions());
                    context.ChangeTracker.AutoDetectChangesEnabled = false;
                }
            }

            return(context);
        }
Example #8
0
        public bool Deposit(string memberId, WalletType walletType, decimal money, string remark, out string error, string tag = null, string fromMemberId = null)
        {
            error = string.Empty;
            if (money == 0)
            {
                return(true);
            }
            using (var dbContext = new WalletDbContext())
            {
                var wallet =
                    dbContext.Set <Models.Wallet>()
                    .FirstOrDefault(w => w.WalletType == walletType && w.MemberId.Equals(memberId, StringComparison.OrdinalIgnoreCase));
                if (wallet == null)
                {
                    wallet            = new Models.Wallet();
                    wallet.Id         = KeyGenerator.GetGuidKey();
                    wallet.MemberId   = memberId;
                    wallet.WalletType = walletType;
                    wallet.Frozen     = 0;
                    wallet.Available  = money;
                    dbContext.Wallets.Add(wallet);
                }
                else
                {
                    wallet.Available += money;
                    dbContext.Set <Models.Wallet>().Attach(wallet);
                    dbContext.Entry(wallet).State = EntityState.Modified;
                }

                WalletBill walletBill = new WalletBill();
                walletBill.Id           = KeyGenerator.GetGuidKey();
                walletBill.MemberId     = memberId;
                walletBill.BillType     = BillType.TakeIn;
                walletBill.WalletType   = walletType;
                walletBill.Money        = money;
                walletBill.Remark       = remark;
                walletBill.BillTag      = tag;
                walletBill.CreateTime   = DateTime.Now;
                walletBill.FromMemberId = fromMemberId;
                dbContext.WalletBills.Add(walletBill);
                dbContext.SaveChanges();
                return(true);
            }
        }
Example #9
0
        /// <summary>
        /// 申请提现
        /// </summary>
        public bool ApplyCrash(string memberId, string account, decimal money, PaymentType paymentType, string name)
        {
            using (var dbContext = new WalletDbContext())
            {
                CrashApply crashApply = new CrashApply();
                crashApply.Id            = KeyGenerator.GetGuidKey();
                crashApply.MemberId      = memberId;
                crashApply.Account       = account;
                crashApply.TransactionNo = KeyGenerator.GetOrderNumber();
                crashApply.RealName      = name;
                crashApply.Money         = money;
                crashApply.PaymentType   = paymentType;
                crashApply.ApplyState    = ApplyState.Applying;
                crashApply.CreateTime    = DateTime.Now;
                dbContext.CrashApplys.Add(crashApply);

                if (paymentType == PaymentType.WeiXin)
                {
                    //判断是否绑定了微信
                }

                Models.Wallet wallet = GetWalletByMemberId(memberId);
                if (wallet == null)
                {
                    throw new WebApiInnerException("0003", "钱包没有可以提现的余额");
                }
                else
                {
                    if (money > wallet.Available)
                    {
                        throw new WebApiInnerException("0004", "提现的金额不能大于钱包的余额");
                    }
                    wallet.Frozen    += money;
                    wallet.Available -= money;
                }
                dbContext.Set <Models.Wallet>().Attach(wallet);
                dbContext.Entry(wallet).State = EntityState.Modified;

                return(dbContext.SaveChanges() > 0);
            }
        }
Example #10
0
 public void Complete()
 {
     _context.SaveChanges();
 }
    public async Task Register()
    {
        var  user_id  = this.Context.Message.Author.AvatarId;
        long guild_id = (long)this.Context.Guild.Id;

        using (var db = new DatabaseContext())
        {
            db.Database.Initialize(true);
        }
        using (var db = new UserDbContext())
        {
            var user = new User
            {
                User_id    = user_id,
                Guild_id   = guild_id,
                Status     = 1,
                Created_on = DateTime.Now
            };
            db.Database.CreateIfNotExists();

            var row = db.Users.Count(u => u.User_id == user_id && u.Guild_id == guild_id);
            if (row > 0)
            {
                this.Context.Channel.SendMessageAsync("User Already Exists On This Server");
            }
            else
            {
                db.Users.Add(user);
                db.SaveChanges();
                this.Context.Channel.SendMessageAsync("User successfully saved");
            }
        }
        using (var db = new WalletDbContext())
        {
            var wallet = new Wallet
            {
                Guid     = Guid.NewGuid(),
                User_id  = user_id,
                Guild_id = guild_id
            };

            var row = db.Wallets.Count(w => w.User_id == user_id && w.Guild_id == guild_id);
            if (row > 0)
            {
                this.Context.Channel.SendMessageAsync("Wallet Already Exists For This User On This Server");
            }
            else
            {
                db.Wallets.Add(wallet);
                db.SaveChanges();
                this.Context.Channel.SendMessageAsync("User Wallet successfully saved");
                using (var wdb = new WalletInfoDbContext())
                {
                    var walletInfo = new WalletInfo()
                    {
                        Guid        = wallet.Guid,
                        Created_on  = DateTime.Now,
                        Modified_on = DateTime.Now
                    };
                    wdb.Database.CreateIfNotExists();
                    wdb.WalletInfos.Add(walletInfo);
                    wdb.SaveChanges();
                    this.Context.Channel.SendMessageAsync("User Wallet Info successfully saved");
                }
            }
        }
    }
Example #12
0
        private void DoWork(object state)
        {
            try
            {
                if (isRunning)
                {
                    return;
                }

                isRunning = true;

                List <ERC20Token> tokens;
                using (var dbContext = new WalletDbContext(DbContextOptionsFactory.DbContextOptions()))
                {
                    tokens = dbContext.Erc20Tokens.ToList();
                }

                foreach (var token in tokens)
                {
                    if (token.IsSynchronized)
                    {
                        continue;
                    }

                    var lastBlockNumber = (int)(_explorer.GetLastAvailableBlockNumber().Result.Value);

                    var logs = _explorer.GetFullEventLogs(token, lastBlockNumber).Result;

                    var holders = EventLogsExplorer.GetInfoFromLogs(logs);

                    for (int i = 0; i < holders.Count; i++)
                    {
                        try
                        {
                            var balance = _explorer.GetTokenHolderBalance(holders[i].Address, token.Address).Result;
                            holders[i].Quantity     = Web3.Convert.FromWei(balance, token.DecimalPlaces);
                            holders[i].ERC20TokenId = token.Id;
                        }
                        catch (Exception e)
                        {
                            i--;
                        }
                    }

                    SaveToDb(logs);
                    SaveToDb(holders);

                    using (var dbContext = new WalletDbContext(DbContextOptionsFactory.DbContextOptions()))
                    {
                        token.LastSynchronizedBlockNumber = lastBlockNumber;
                        token.IsSynchronized = true;
                        dbContext.Erc20Tokens.Update(token);
                        dbContext.SaveChanges();
                    }
                }
                isRunning = false;
            }
            catch (Exception e)
            {
                isRunning = false;
            }
        }
Example #13
0
        public async Task <IActionResult> SaveLatestTransactions()
        {
            var status = _dbContext.PageData.FirstOrDefault();

            if (status != null && status.IsTransactionsSaved)
            {
                return(Ok());
            }

            var lastKnownBlockNumber = (int)(await _explorer.GetLastAvailableBlockNumber()).Value;
            var tasks = new List <Task <List <BlockChainTransaction> > >();

            for (int i = lastKnownBlockNumber - 5000; i < lastKnownBlockNumber; i += 100)
            {
                var i1   = i;
                var task = Task.Run(() => _explorer.GetLatestTransactions(i1, i1 + 99));
                tasks.Add(task);
            }

            await Task.WhenAll(tasks);

            var result = new List <BlockChainTransaction>();

            foreach (var task in tasks)
            {
                task.Result.ForEach(t => result.Add(t));
            }

            _dbContext.ChangeTracker.AutoDetectChangesEnabled = false;

            var tempList = new List <BlockChainTransaction>();

            foreach (var transact in result)
            {
                tempList.Add(transact);
                if (tempList.Count == 100)
                {
                    try
                    {
                        _dbContext.BlockChainTransactions.AddRange(tempList);
                        _dbContext.SaveChanges();
                        tempList.Clear();
                    }
                    catch (Exception e)
                    {
                        tempList.Clear();
                    }
                }
            }

            _dbContext.ChangeTracker.AutoDetectChangesEnabled = true;

            var lastSavedNumber = (int)(_dbContext.BlockChainTransactions
                                        .Max(w => w.BlockNumber));

            lastKnownBlockNumber = (int)(await _explorer.GetLastAvailableBlockNumber()).Value;
            var newTransacts = _explorer.GetLatestTransactions(lastSavedNumber, lastKnownBlockNumber);

            _dbContext.BlockChainTransactions.AddRange(newTransacts);
            _dbContext.SaveChanges();

            var data = _dbContext.PageData.FirstOrDefault();

            if (data != null)
            {
                data.IsTransactionsSaved = true;
                _dbContext.PageData.Update(data);
            }

            _dbContext.SaveChanges();

            return(Ok());
        }
Example #14
0
 public int SaveChanges()
 {
     return(Db.SaveChanges());
 }
Example #15
0
        private async void DoWork(object state)
        {
            try
            {
                if (_isRunning)
                {
                    return;
                }

                _isRunning = true;


                List <ERC20Token> tokens;
                using (var dbContext = new WalletDbContext(DbContextOptionsFactory.DbContextOptions()))
                {
                    tokens = dbContext.Erc20Tokens.ToList();
                }

                foreach (var token in tokens)
                {
                    if (!token.IsSynchronized)
                    {
                        continue;
                    }

                    var lastBlockNumber = (int)(_explorer.GetLastAvailableBlockNumber().Result.Value);

                    var logs = await _explorer.GetFullEventLogs(token, lastBlockNumber,
                                                                token.LastSynchronizedBlockNumber + 1);

                    var holders = EventLogsExplorer.GetInfoFromLogs(logs);

                    for (int i = 0; i < holders.Count; i++)
                    {
                        try
                        {
                            var balance = _explorer.GetTokenHolderBalance(holders[i].Address, token.Address).Result;
                            holders[i].Quantity     = Web3.Convert.FromWei(balance, token.DecimalPlaces);
                            holders[i].ERC20TokenId = token.Id;
                        }
                        catch (Exception e)
                        {
                            i--;
                        }
                    }

                    using (var dbContext = new WalletDbContext(DbContextOptionsFactory.DbContextOptions()))
                    {
                        foreach (var h in holders)
                        {
                            var holder = dbContext.TokenHolders.FirstOrDefault(e =>
                                                                               e.Address.Equals(h.Address, StringComparison.CurrentCultureIgnoreCase));
                            if (holder != null)
                            {
                                holder.Quantity = h.Quantity;
                                holder.GeneralTransactionsNumber  += h.GeneralTransactionsNumber;
                                holder.SentTransactionsNumber     += h.SentTransactionsNumber;
                                holder.ReceivedTransactionsNumber += h.ReceivedTransactionsNumber;
                                holder.TokensSent     += h.TokensSent;
                                holder.TokensReceived += h.TokensReceived;
                                dbContext.TokenHolders.Update(holder);
                            }
                            else
                            {
                                dbContext.TokenHolders.Add(h);
                            }
                        }

                        token.LastSynchronizedBlockNumber = GetNewLastSearchedBlockNumber(lastBlockNumber,
                                                                                          token.LastSynchronizedBlockNumber + 1);

                        dbContext.Erc20Tokens.Update(token);
                        dbContext.SaveChanges();
                    }

                    SaveToDb(logs);

                    _isRunning = false;
                }
            }

            catch (Exception e)
            {
                _isRunning = false;
            }
        }