public void Delete(BusinessObjects.BizMsg model)
        {
            NiCris.DataAccess.SQL.LinqToSQL.BizMsg entity = BizMsgMapper.ToEntity(model);

            using (Database db = DataContextFactory.CreateContext())
            {
                try
                {
                    db.BizMsgs.Attach(entity, false);
                    db.BizMsgs.DeleteOnSubmit(entity);
                    db.SubmitChanges();
                }
                catch (ChangeConflictException)
                {
                    foreach (ObjectChangeConflict conflict in db.ChangeConflicts)
                    {
                        conflict.Resolve(RefreshMode.KeepCurrentValues);
                    }

                    try
                    {
                        db.SubmitChanges();
                    }
                    catch (ChangeConflictException)
                    {
                        throw new Exception("A concurrency error occurred!");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("There was an error updating the record! " + ex.Message);
                }
            }
        }
Ejemplo n.º 2
0
        public async Task <IWriterResult> UpdateWithdrawSettings(string userId, UpdateWithdrawModel model)
        {
            try
            {
                using (var context = DataContextFactory.CreateContext())
                {
                    var user = await context.Users.FirstOrDefaultAsync(u => u.Id == userId).ConfigureAwait(false);

                    if (user == null)
                    {
                        return(new WriterResult(false, "User not found."));
                    }

                    user.DisableWithdrawEmailConfirmation = model.DisableConfirmation;
                    user.IsUnsafeWithdrawEnabled          = !model.AddressBookOnly;
                    await context.SaveChangesWithAuditAsync().ConfigureAwait(false);

                    await UserSyncService.SyncUser(user.Id).ConfigureAwait(false);

                    return(new WriterResult(true, "Successfully updated withdrawal settings."));
                }
            }
            catch (Exception)
            {
                return(new WriterResult(false));
            }
        }
Ejemplo n.º 3
0
        public async Task <IWriterResult <bool> > CancelWithdraw(string userId, int withdrawId)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var withdraw = await context.Withdraw
                               .Include(x => x.User)
                               .Include(x => x.Currency)
                               .FirstOrDefaultAsync(x => x.Id == withdrawId && x.UserId == userId && x.WithdrawStatus == WithdrawStatus.Unconfirmed);

                if (withdraw == null || withdraw.WithdrawStatus != WithdrawStatus.Unconfirmed)
                {
                    return(WriterResult <bool> .ErrorResult("Withdraw #{0} not found or is already canceled.", withdrawId));
                }
                if (!withdraw.User.IsWithdrawEnabled)
                {
                    return(WriterResult <bool> .ErrorResult("Your withdrawals are currently disabled."));
                }


                withdraw.WithdrawStatus = WithdrawStatus.Canceled;
                await context.SaveChangesAsync();

                await AuditService.AuditUserCurrency(context, userId, withdraw.CurrencyId);

                return(WriterResult <bool> .SuccessResult());
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Gets list of customers in given sortorder.
 /// </summary>
 /// <param name="sortExpression">The required sort order.</param>
 /// <returns>List of customers.</returns>
 public List <Customer> GetCustomers(string sortExpression)
 {
     using (var context = DataContextFactory.CreateContext())
     {
         return(context.CustomerEntities.OrderBy(sortExpression).Select(c => Mapper.Map(c)).ToList());
     }
 }
Ejemplo n.º 5
0
        public async Task <IWriterResult <int> > CreateApiWithdraw(string userId, string currency, string address, decimal amount)
        {
            int currencyId = 0;

            using (var context = DataContextFactory.CreateContext())
            {
                var currencyEntity = await context.Currency.Where(w => w.Symbol == currency).FirstOrDefaultNoLockAsync();

                if (currencyEntity == null)
                {
                    return(WriterResult <int> .ErrorResult("Currency not found."));
                }

                currencyId = currencyEntity.Id;
            }

            return(await WithdrawService.QueueWithdraw(new CreateWithdraw
            {
                IsApi = true,
                UserId = userId,
                Address = address,
                Amount = amount,
                ConfirmationToken = "",
                CurrencyId = currencyId
            }));
        }
        public async Task <IWriterResult> DelistCurrency(string adminUserId, UpdateListingStatusModel model)
        {
            model.ListingStatus = CurrencyListingStatus.Delisted;
            var writerResult = await UpdateListingStatus(adminUserId, model);

            if (!writerResult.Success)
            {
                return(writerResult);
            }

            using (var context = ExchangeDataContextFactory.CreateContext())
            {
                // Checks for closing trade pairs only as it's expected to be in 'delisting' before it's delisted.
                var tradePairs = await context.TradePair.Where(t => t.Status == TradePairStatus.Closing && (t.CurrencyId1 == model.CurrencyId || t.CurrencyId2 == model.CurrencyId)).ToListNoLockAsync();

                foreach (var tradePair in tradePairs)
                {
                    tradePair.Status = TradePairStatus.Closed;
                }

                using (var adminContext = DataContextFactory.CreateContext())
                {
                    adminContext.LogActivity(adminUserId, $"Delisted Currency: {model.Name}");
                    await adminContext.SaveChangesAsync().ConfigureAwait(false);
                }

                await context.SaveChangesAsync().ConfigureAwait(false);

                await CacheService.InvalidateAsync(CacheKey.Currencies(), CacheKey.CurrencyInfo(), CacheKey.CurrencyDataTable(), CacheKey.CurrencySummary(model.CurrencyId)).ConfigureAwait(false);
            }

            writerResult.Message = "Successfully delisted currency.";

            return(writerResult);
        }
Ejemplo n.º 7
0
        public async Task <IWriterResult> UpdateTradePair(string adminUserId, UpdateTradePairModel model)
        {
            using (var context = ExchangeDataContextFactory.CreateContext())
            {
                var tradePair = await context.TradePair
                                .Include(x => x.Currency1)
                                .Include(x => x.Currency2)
                                .Where(x => x.Id == model.Id)
                                .FirstOrDefaultNoLockAsync().ConfigureAwait(false);

                if (tradePair == null)
                {
                    return(new WriterResult(false, $"TradePair {model.Id} not found."));
                }

                var oldStatus = tradePair.Status;
                tradePair.Status        = model.Status;
                tradePair.StatusMessage = model.StatusMessage;

                using (var dataContext = DataContextFactory.CreateContext())
                {
                    dataContext.LogActivity(adminUserId, $"Updating Trade Pair:{tradePair.Currency1.Symbol}_{tradePair.Currency2.Symbol} Old Status: {oldStatus}, New status {tradePair.Status}.");
                    await dataContext.SaveChangesAsync().ConfigureAwait(false);
                }

                await context.SaveChangesAsync().ConfigureAwait(false);

                await CacheService.InvalidateAsync(CacheKey.AllTradePairs(), CacheKey.TradePairs()).ConfigureAwait(false);

                return(new WriterResult(true, $"Successfully updated tradepair."));
            }
        }
Ejemplo n.º 8
0
        public async Task <IWriterResult> UpdateUser(UserModel model)
        {
            var userId = string.Empty;

            using (var context = DataContextFactory.CreateContext())
            {
                var user = await context.Users
                           .Where(x => x.UserName == model.UserName)
                           .FirstOrDefaultNoLockAsync().ConfigureAwait(false);

                if (user == null)
                {
                    return(new WriterResult(false, $"User '{model.UserName}' not found."));
                }

                userId                 = user.Id;
                model.UserId           = userId;
                user.RoleCss           = model.RoleCss;
                user.ChatBanEndTime    = model.ChatBanEndTime;
                user.ChatTipBanEndTime = model.ChatTipBanEndTime;
                await context.SaveChangesAsync().ConfigureAwait(false);
            }
            await UserSyncService.SyncUser(userId).ConfigureAwait(false);

            return(new WriterResult(true, "Successfully updated user."));
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Gets a product given a product identifier.
 /// </summary>
 /// <param name="productId">Product identifier.</param>
 /// <returns>The product.</returns>
 public Product GetProduct(int productId)
 {
     using (var context = DataContextFactory.CreateContext())
     {
         return(Mapper.Map(context.ProductEntities.SingleOrDefault(p => p.ProductId == productId)));
     }
 }
 public IList <BusinessObjects.BizMsg> GetAll()
 {
     using (Database db = DataContextFactory.CreateContext())
     {
         return(db.BizMsgs.Select(x => BizMsgMapper.ToBusinessObject(x)).ToList());
     }
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Gets list of product categories
 /// </summary>
 /// <returns>List of categories.</returns>
 public List <Category> GetCategories()
 {
     using (var context = DataContextFactory.CreateContext())
     {
         return(context.CategoryEntities.Select(c => Mapper.Map(c)).ToList());
     }
 }
Ejemplo n.º 12
0
        private async Task <List <INotification> > ProcessTransferNotifications(SubmitTransferResponse response)
        {
            var results = new List <INotification>();

            if (response.Notifications.IsNullOrEmpty())
            {
                return(results);
            }

            using (var context = DataContextFactory.CreateContext())
            {
                foreach (var notification in response.Notifications)
                {
                    context.Notifications.Add(new Entity.UserNotification
                    {
                        Title        = notification.Header,
                        Notification = notification.Notification,
                        Type         = notification.Type.ToString(),
                        UserId       = notification.UserId.ToString(),
                        Timestamp    = DateTime.UtcNow
                    });

                    results.Add(new NotificationModel
                    {
                        Header       = notification.Header,
                        Type         = notification.Type,
                        UserId       = notification.UserId,
                        Notification = notification.Notification
                    });
                }
                await context.SaveChangesAsync().ConfigureAwait(false);
            }
            return(results);
        }
Ejemplo n.º 13
0
        public async Task <IWriterResult> ResetAllTwoFactor(string userId, AdminResetTwoFactorModel model)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var user = await context.Users.FirstOrDefaultNoLockAsync(x => x.UserName == model.UserName);

                if (user == null)
                {
                    return(new WriterResult(false, $"User '{model.UserName}' not found"));
                }

                var approval = await context.ApprovalQueue.FirstOrDefaultNoLockAsync(x => x.DataUserId == user.Id && x.Type == Enums.ApprovalQueueType.ResetAllTwoFactor && x.Status == Enums.ApprovalQueueStatus.Pending);

                if (approval != null)
                {
                    return(new WriterResult(false, "Already awaiting approval."));
                }

                approval = new Entity.ApprovalQueue
                {
                    DataUserId    = user.Id,
                    RequestUserId = userId,
                    Type          = Enums.ApprovalQueueType.ResetAllTwoFactor,
                    Status        = Enums.ApprovalQueueStatus.Pending,
                    Created       = DateTime.UtcNow,
                    Data          = model.Type
                };

                context.ApprovalQueue.Add(approval);
                await context.SaveChangesAsync();

                return(new WriterResult(true, $"Reset Two Factor for user {user.UserName} added to Approval Queue"));
            }
        }
Ejemplo n.º 14
0
        public async Task <IWriterResult> DisableUser(string adminUserId, string userName)
        {
            var userId = "";

            using (var context = DataContextFactory.CreateContext())
            {
                var user = await context.Users.FirstOrDefaultNoLockAsync(u => u.UserName == userName).ConfigureAwait(false);

                if (user == null)
                {
                    return(new WriterResult(false, "User Not Found"));
                }

                userId             = user.Id;
                user.IsDisabled    = true;
                user.SecurityStamp = Guid.NewGuid().ToString();

                context.LogActivity(adminUserId, $"Disabling User {userName}");
                await context.SaveChangesAsync().ConfigureAwait(false);
            }

            await UserSyncService.SyncUser(userId);

            return(new WriterResult(true, $"User '{userName}' Successfully Disabled."));
        }
Ejemplo n.º 15
0
        public async Task <IWriterResult> UpdateApiSettings(string userId, UpdateApiModel model)
        {
            try
            {
                using (var context = DataContextFactory.CreateContext())
                {
                    var user = await context.Users.FirstOrDefaultAsync(u => u.Id == userId).ConfigureAwait(false);

                    if (user == null)
                    {
                        return(new WriterResult(false, "User not found."));
                    }

                    model.OldApiKey                 = user.ApiKey;
                    user.IsApiEnabled               = model.IsApiEnabled;
                    user.IsApiWithdrawEnabled       = model.IsApiWithdrawEnabled;
                    user.IsApiUnsafeWithdrawEnabled = model.IsApiUnsafeWithdrawEnabled;
                    user.ApiKey    = model.ApiKey;
                    user.ApiSecret = model.ApiSecret;

                    await context.SaveChangesWithAuditAsync().ConfigureAwait(false);

                    await UserSyncService.SyncUser(user.Id).ConfigureAwait(false);

                    return(new WriterResult(true, "Successfully updated API settings."));
                }
            }
            catch (Exception)
            {
                return(new WriterResult(false));
            }
        }
        public override async Task UpgradeAsync(DbTransaction?transaction = null, CancellationToken token = new CancellationToken())
        {
            await using var context = _contextFactory.CreateContext();
            foreach (var defaultUser in _configuration.DefaultUsers)
            {
                // создадим пользователей
                var user = new UserEntity
                {
                    Email          = defaultUser.Email,
                    EmailConfirmed = true,
                    UserName       = defaultUser.Email,
                    Sex            = SexType.Male,
                    TimeZoneId     = Constants.DefaultTimeZoneId,
                };

                if (await _userManager.Users.AnyAsync(x => x.NormalizedEmail == user.Email.ToUpper(), cancellationToken: token))
                {
                    _logger.LogWarning($"Пользователь \"{user.Email}\" уже существует");
                    continue;
                }

                var result = await _userManager.CreateAsync(user, defaultUser.Password);

                if (!result.Succeeded)
                {
                    foreach (var resultError in result.Errors)
                    {
                        Logger.LogError($"{resultError.Code}: {resultError.Description}");
                    }

                    throw new MigrationException(MigrationError.MigratingError, $"Failed to add user \"{defaultUser.Email}\"");
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Возвращает информацию о текущем пользователе, которую можно использовать внутри бизнес логики.
        /// Используется кеширование.
        /// </summary>
        public async Task <UserInfo> GetCachedUserAsync(HttpContext httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            // TODO: Add curiosity caching

            var userId = GetUserId(httpContext);

            using (var context = _contextFactory.CreateContext())
            {
                var user = await context.Users
                           .Where(x => x.Id == userId)
                           .Where(x => !x.IsDeleted) // сразу проверяет заблокирован пользователь или нет
                                                     //.Where(x => !x.Client!.IsBlocked)
                           .Select(x => new UserInfo
                {
                    Id         = x.Id,
                    Email      = x.Email,
                    TimeZoneId = x.TimeZoneId,
                })
                           .SingleOrDefaultAsync()
                           ?? throw new AuthException("Пользователь удалён или заблокирован");

                return(user);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Updates a customer record in the database.
        /// </summary>
        /// <param name="customer">The customer with updated values.</param>
        /// <returns>Number of rows affected.</returns>
        public int UpdateCustomer(Customer customer)
        {
            using (ActionDataContext db = DataContextFactory.CreateContext())
            {
                try
                {
                    CustomerEntity entity = Mapper.ToEntity(customer);
                    db.CustomerEntities.Attach(entity, true);
                    db.SubmitChanges();

                    // Update business object with new version
                    customer.Version = VersionConverter.ToString(entity.Version);

                    return(1);
                }
                catch (ChangeConflictException)
                {
                    throw new Exception("A change to customer record was made before your changes.");
                }
                catch
                {
                    return(0);
                }
            }
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Gets order given an order identifier.
 /// </summary>
 /// <param name="orderId">Order identifier.</param>
 /// <returns>The order.</returns>
 public Order GetOrder(int orderId)
 {
     using (var context = DataContextFactory.CreateContext())
     {
         return(Mapper.Map(context.OrderEntities.SingleOrDefault(o => o.OrderId == orderId)));
     }
 }
        public async Task <IWriterResult> UpdateBalanceFavoriteOnly(string userId, bool favoritesOnly)
        {
            try
            {
                using (var context = DataContextFactory.CreateContext())
                {
                    var user = context.Users
                               .Include(u => u.Settings)
                               .FirstOrDefault(x => x.Id == userId);
                    if (user == null)
                    {
                        return(new WriterResult(false, "User not found."));
                    }

                    user.Settings.ShowFavoriteBalance = favoritesOnly;
                    await context.SaveChangesAsync().ConfigureAwait(false);
                }

                return(new WriterResult(true, "Successfully updated balance settings."));
            }
            catch (Exception)
            {
                return(new WriterResult(false));
            }
        }
        public async Task <WriterResult> UpdateTheme(string userId, SiteTheme theme)
        {
            try
            {
                using (var context = DataContextFactory.CreateContext())
                {
                    var user = context.Users
                               .Include(u => u.Settings)
                               .FirstOrDefault(x => x.Id == userId);
                    if (user == null)
                    {
                        return(new WriterResult(false, "User not found."));
                    }

                    user.Settings.Theme = theme;
                    await context.SaveChangesAsync().ConfigureAwait(false);
                }

                return(new WriterResult(true, "Successfully updated theme."));
            }
            catch (Exception)
            {
                return(new WriterResult(false));
            }
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Gets list of product categories
 /// </summary>
 /// <returns>List of categories.</returns>
 public IList <Category> GetCategories()
 {
     using (ActionDataContext db = DataContextFactory.CreateContext())
     {
         return(db.CategoryEntities.Select(c => Mapper.ToBusinessObject(c)).ToList());
     }
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Gets a customer given a customer identifier.
 /// </summary>
 /// <param name="customerId">The customer identifier.</param>
 /// <returns>The customer.</returns>
 public Customer GetCustomer(int customerId)
 {
     using (var context = DataContextFactory.CreateContext())
     {
         return(Mapper.Map(context.CustomerEntities
                           .SingleOrDefault(p => p.CustomerId == customerId)));
     }
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Gets a customer given a customer identifier.
 /// </summary>
 /// <param name="customerId">The customer identifier.</param>
 /// <returns>The customer.</returns>
 public Customer GetCustomer(int customerId)
 {
     using (ActionDataContext db = DataContextFactory.CreateContext())
     {
         return(Mapper.ToBusinessObject(db.CustomerEntities
                                        .SingleOrDefault(p => p.CustomerId == customerId)));
     }
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Gets order given an order identifier.
 /// </summary>
 /// <param name="orderId">Order identifier.</param>
 /// <returns>The order.</returns>
 public Order GetOrder(int orderId)
 {
     using (ActionDataContext db = DataContextFactory.CreateContext())
     {
         return(Mapper.ToBusinessObject(db.OrderEntities
                                        .SingleOrDefault(o => o.OrderId == orderId)));
     }
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Gets a product given a product identifier.
 /// </summary>
 /// <param name="productId">Product identifier.</param>
 /// <returns>The product.</returns>
 public Product GetProduct(int productId)
 {
     using (ActionDataContext db = DataContextFactory.CreateContext())
     {
         return(Mapper.ToBusinessObject(db.ProductEntities
                                        .SingleOrDefault(p => p.ProductId == productId)));
     }
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Gets the orderdetails for a given order.
 /// </summary>
 /// <param name="orderId">Unique order identifier.</param>
 /// <returns>List of orderdetails.</returns>
 public List <OrderDetail> GetOrderDetails(int orderId)
 {
     using (var context = DataContextFactory.CreateContext())
     {
         return(context.OrderDetailEntities.Where(d => d.OrderId == orderId)
                .Select(d => Mapper.Map(d)).ToList());
     }
 }
Ejemplo n.º 28
0
        public async Task <Response <FileModel[]> > GetLicenses()
        {
            using (var context = _contextFactory.CreateContext())
            {
                var files = await context.Files
                            .OrderBy(x => x.Created)
                            .Select(x => new FileModel
                {
                    Id       = x.Id,
                    Created  = x.Created,
                    FileName = x.UserFileName,
                })
                            .ToArrayAsync();

                return(new Response <FileModel[]>(files));
            }
        }
Ejemplo n.º 29
0
        public async Task <AdminUserDetailsModel> GetUserDetails(string username)
        {
            using (var context = DataContextFactory.CreateContext())
            {
                var data = await context.Users
                           .Include(x => x.Profile).DefaultIfEmpty()
                           .Include(x => x.Settings).DefaultIfEmpty()
                           .Where(u => u.UserName == username)
                           .Select(user => new AdminUserDetailsModel
                {
                    Email                = user.Email,
                    UserName             = user.UserName,
                    RoleCss              = user.RoleCss,
                    TrustRating          = user.TrustRating,
                    ShareCount           = user.ShareCount,
                    KarmaTotal           = user.KarmaTotal,
                    EmailConfirmed       = user.EmailConfirmed,
                    DisableRewards       = user.DisableRewards,
                    DisableTips          = user.DisableTips,
                    LockoutEnd           = user.LockoutEndDateUtc,
                    MiningHandle         = user.MiningHandle,
                    ChatHandle           = user.ChatHandle,
                    ChatDisableEmoticons = user.ChatDisableEmoticons,
                    Theme                = user.Settings != null ? user.Settings.Theme.ToString() : SiteTheme.Light.ToString(),
                    Referrer             = user.Referrer,
                    RegisterDate         = user.RegisterDate,
                    IsDisabled           = user.IsDisabled,
                    VerificationLevel    = user.VerificationLevel.ToString(),
                    AboutMe              = user.Profile != null ? user.Profile.AboutMe : "",
                    Address              = user.Profile != null ? user.Profile.Address : "",
                    Birthday             = user.Profile != null ? user.Profile.Birthday : DateTime.UtcNow,
                    City         = user.Profile != null ? user.Profile.City : "",
                    ContactEmail = user.Profile != null ? user.Profile.ContactEmail : "",
                    Country      = user.Profile != null ? user.Profile.Country : "",
                    Education    = user.Profile != null ? user.Profile.Education : "",
                    Facebook     = user.Profile != null ? user.Profile.Facebook : "",
                    FirstName    = user.Profile != null ? user.Profile.FirstName : "",
                    Gender       = user.Profile != null ? user.Profile.Gender : "",
                    Hobbies      = user.Profile != null ? user.Profile.Hobbies : "",
                    LastName     = user.Profile != null ? user.Profile.LastName : "",
                    LinkedIn     = user.Profile != null ? user.Profile.LinkedIn : "",
                    Occupation   = user.Profile != null ? user.Profile.Occupation : "",
                    Postcode     = user.Profile != null ? user.Profile.Postcode : "",
                    State        = user.Profile != null ? user.Profile.State : "",
                    Twitter      = user.Profile != null ? user.Profile.Twitter : "",
                    Website      = user.Profile != null ? user.Profile.Website : "",
                    IsPublic     = user.Profile != null ? user.Profile.IsPublic : false,
                }).FirstOrDefaultNoLockAsync();

                if (data == null)
                {
                    return(null);
                }

                data.IsLocked = data.LockoutEnd > DateTime.UtcNow;
                return(data);
            }
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Gets the orders between a given data range.
 /// </summary>
 /// <param name="dateFrom">Start date.</param>
 /// <param name="dateThru">End date.</param>
 /// <returns></returns>
 public IList <Order> GetOrdersByDate(DateTime dateFrom, DateTime dateThru)
 {
     using (ActionDataContext db = DataContextFactory.CreateContext())
     {
         return(db.OrderEntities
                .Where(o => o.OrderDate >= dateFrom && o.OrderDate <= dateThru)
                .Select(c => Mapper.ToBusinessObject(c)).ToList());
     }
 }