Esempio n. 1
0
        private ValidationDictionary <ViewModelNewsCategory> SaveNewsCategory(int clientId, ViewModelNewsCategory viewModelNewsCategory)
        {
            var validator = new ValidationDictionary <ViewModelNewsCategory>();

            if (viewModelNewsCategory == null)
            {
                validator.IsValid = false;
                validator.AddError("", "The XX you're trying to save is null");
                return(validator);
            }

            // rule based here
            var existingWithSameName = _newsCategoryRepository
                                       .FilterBy(o => o.NewsCategoryName.ToLower() == viewModelNewsCategory.NewsCategoryName.ToLower() &&
                                                 o.ClientId == clientId &&
                                                 !o.IsDeleted)
                                       .ToList();

            if (existingWithSameName.Any())
            {
                var haveSameId = viewModelNewsCategory.NewsCategoryId <= 0 ||
                                 (viewModelNewsCategory.NewsCategoryId > 0 &&
                                  existingWithSameName.Any(o => o.NewsCategoryId != viewModelNewsCategory.NewsCategoryId));
                if (haveSameId)
                {
                    validator.IsValid = false;
                    validator.AddError("", "News Category with same name is already existed");
                    return(validator);
                }
            }

            NewsCategory newsCategory;

            if (viewModelNewsCategory.NewsCategoryId > 0)
            {
                newsCategory = _newsCategoryRepository.FindBy(o => o.NewsCategoryId == viewModelNewsCategory.NewsCategoryId);
                var dateCreated = newsCategory.DateCreated;
                newsCategory.InjectFrom(viewModelNewsCategory);
                newsCategory.ClientId        = clientId;
                newsCategory.DateLastUpdated = DateTime.UtcNow;
                newsCategory.DateCreated     = dateCreated;
                _newsCategoryRepository.Update(newsCategory);
            }
            else
            {
                newsCategory = new NewsCategory();
                newsCategory.InjectFrom(viewModelNewsCategory);
                newsCategory.DateCreated     = DateTime.UtcNow;
                newsCategory.DateLastUpdated = DateTime.UtcNow;
                newsCategory.ClientId        = clientId;
                _newsCategoryRepository.Add(newsCategory);
            }

            var rawPinged = _newsCategoryRepository.FindBy(o => o.NewsCategoryId == newsCategory.NewsCategoryId && o.ClientId == clientId);
            var pinged    = new ViewModelNewsCategory().InjectFrom(rawPinged) as ViewModelNewsCategory;

            validator.IsValid       = true;
            validator.RelatedObject = pinged;
            return(validator);
        }
Esempio n. 2
0
 private void ValidateEmail(string email, int id)
 {
     if (UnitOfWork.UserRepository.GetAllNoTracking().Any(u => u.Email == email && u.Id != id))
     {
         ValidationDictionary.AddError("Email", "This email address is already registered to a user");
     }
 }
Esempio n. 3
0
 private void ValidateUserName(string name, int id)
 {
     if (UnitOfWork.UserRepository.GetAllNoTracking().Any(u => u.Username == name && u.Id != id))
     {
         ValidationDictionary.AddError("UserName", "This user name already exists");
     }
 }
Esempio n. 4
0
        public ValidationDictionary<DynamicPageDto> DeletePage(int clientId, int pageId)
        {
            var expression = _dynamicPageFilters.Init()
                .GetByPageId(pageId)
                .GetByClientId(clientId)
                .GetNotDeleted()
                .FilterExpression;

            var dPage = _pageRepository.FindBy(expression);

            var validator = new ValidationDictionary<DynamicPageDto>();
            if (dPage != null)
            {
                dPage.IsDeleted = true;
                _pageRepository.Update(dPage);
                validator.IsValid = true;
            }
            else
            {
                validator.IsValid = false;
                validator.AddError("", "The Page is not found in the database");
            }

            return validator;
        }
        public void AddErrorTwo()
        {
            // Arrange
            var inner         = new Dictionary <string, List <string> >();
            var dictionary    = new ValidationDictionary(inner);
            var propertyName1 = "Item1";
            var errorMessage1 = "ErrorMessage2.";
            var errorMessage2 = "ErrorMessage2.";

            // Act
            dictionary.AddError(propertyName1, errorMessage1);
            dictionary.AddError(propertyName1, errorMessage2);

            // Assert
            Assert.Equal(errorMessage2, inner[propertyName1][1]);
        }
Esempio n. 6
0
        public async Task <ReferralCodeServiceResult> GenerateReferralCodeForUserAsync(string userId)
        {
            Debug.Assert(!String.IsNullOrEmpty(userId));

            var code = GuidEncoder.Encode(Guid.NewGuid().ToString());

            bool success = false;

            try
            {
                db.Referrals.Add(new Referral()
                {
                    Code        = code,
                    UserId      = userId,
                    IsRedeemed  = false,
                    DateCreated = DateTime.Now
                });

                success = (await db.SaveChangesAsync()) > 0;
            }
            catch (DbUpdateException ex)
            {
                Log.Error("UserService.GenerateReferralCodeForUserAsync", ex, new { userId, code });
                ValidationDictionary.AddError(Guid.NewGuid().ToString(), ErrorMessages.ReferralCodeNotGenerated);
            }

            return(success ? ReferralCodeServiceResult.Success(code) : ReferralCodeServiceResult.Failed(ErrorMessages.ReferralCodeNotGenerated));
        }
Esempio n. 7
0
        public BaseResponseModel ResetPassword(ResetPasswordInputModel inputModel)
        {
            // Get existing user
            var vm = new BaseResponseModel();
            var validationState = new ValidationDictionary();

            inputModel.ValidateRequest(validationState);

            if (validationState.IsValid)
            {
                var user = UserService.GetUserByResetToken(inputModel.ResetToken);
                if (user != null)
                {
                    UserService.ResetPassword(user, inputModel.Password);
                    vm.Success = true;
                }
                else
                {
                    validationState.AddError("ResetToken", "Invalid reset token.");
                }
            }

            vm.Errors = validationState.Errors;

            return(vm);
        }
Esempio n. 8
0
        public ValidationDictionary <ViewModelArticleCategory> DeleteArticleCategory(int clientId, int articleCategoryId)
        {
            var validator = new ValidationDictionary <ViewModelArticleCategory>();
            var raw       = _articleCategoryRepository.FindBy(o => o.ArticleCategoryId == articleCategoryId && o.ClientId == clientId);

            if (raw != null)
            {
                raw.IsDeleted = true;
                _articleCategoryRepository.Update(raw);

                var articles = _articleItemRepository.FilterBy(a => a.ArticleCategory.ArticleCategoryId == articleCategoryId).ToList();
                foreach (var item in articles)
                {
                    //item.IsDeleted = true;
                    item.ArticleCategory = null;
                    _articleItemRepository.Update(item);
                }

                validator.IsValid = true;
            }
            else
            {
                validator.IsValid = false;
                validator.AddError("", "The XX is not available in the database");
            }
            return(validator);
        }
Esempio n. 9
0
        public ValidationDictionary <ViewModelPage> SavePage(int clientId, ViewModelPage viewModelPage)
        {
            // validation first
            var validator = new ValidationDictionary <ViewModelPage>();

            if (viewModelPage == null)
            {
                validator.IsValid = false;
                validator.AddError("", "Page you're trying to save is null");
                return(validator);
            }

            // rule based
            if (viewModelPage.IsHomePage)
            {
            }

            DynamicPage dPage;

            if (viewModelPage.PageId <= 0)
            {
                // prepare object to save
                dPage = new DynamicPage();
                dPage.InjectFrom(viewModelPage);
                dPage.ClientId        = clientId;
                dPage.DateCreated     = DateTime.UtcNow;
                dPage.DateLastUpdated = DateTime.UtcNow;

                _pageRepository.Add(dPage);
            }
            else
            {
                var gExpression = _dynamicPageFilters.Init()
                                  .GetByPageId(viewModelPage.PageId)
                                  .GetByClientId(clientId)
                                  .GetNotDeleted()
                                  .FilterExpression;

                dPage = _pageRepository.FindBy(gExpression);

                if (dPage != null)
                {
                    // excluded fields
                    var createdDate = dPage.DateCreated;
                    // update data
                    dPage.InjectFrom(viewModelPage);
                    dPage.DateCreated     = createdDate;
                    dPage.DateLastUpdated = DateTime.UtcNow;
                    dPage.IsDeleted       = false;

                    _pageRepository.Update(dPage);
                }
            }

            var pingedPaged = GetPage(clientId, dPage.PageId);

            validator.IsValid       = true;
            validator.RelatedObject = pingedPaged;
            return(validator);
        }
Esempio n. 10
0
        public ValidationDictionary <ViewModelPage> DeletePage(int clientId, int pageId)
        {
            var expression = _dynamicPageFilters.Init()
                             .GetByPageId(pageId)
                             .GetByClientId(clientId)
                             .GetNotDeleted()
                             .FilterExpression;

            var dPage = _pageRepository.FindBy(expression);

            var validator = new ValidationDictionary <ViewModelPage>();

            if (dPage != null)
            {
                dPage.IsDeleted = true;

                _pageRepository.Update(dPage);

                validator.IsValid = true;
            }
            else
            {
                validator.IsValid = false;
                validator.AddError("", "The Page is not found in the database");
            }

            return(validator);
        }
Esempio n. 11
0
        /// <summary>
        /// Validate form-level request
        /// </summary>
        /// <param name="validationDictionary"></param>
        public bool ValidateRequest(IValidationDictionary validationDictionary)
        {
            var requestDictionary = new ValidationDictionary();

            if (string.IsNullOrEmpty(ResetToken))
            {
                requestDictionary.AddError("ResetToken", "Reset token not specified.");
            }
            if (string.IsNullOrEmpty(Password))
            {
                requestDictionary.AddError("Password", "Password is required.");
            }
            if (Password != ConfirmPassword)
            {
                requestDictionary.AddError("Password", "Passwords do not match.");
            }
            validationDictionary.Merge(requestDictionary);
            return(requestDictionary.IsValid);
        }
Esempio n. 12
0
 public override void Update(Project project)
 {
     if (Repository.Get(t => t.ProjectNumber == project.ProjectNumber && t.Id != project.Id).Any())
     {
         ValidationDictionary.AddError("ProjectNumber", "Unique project number required");
     }
     else
     {
         base.Update(project);
     }
 }
Esempio n. 13
0
        /// <summary>
        /// Validate form-level request
        /// </summary>
        /// <param name="validationDictionary"></param>
        public bool ValidateRequest(IValidationDictionary validationDictionary)
        {
            var requestDictionary = new ValidationDictionary();

            if (Password != ConfirmPassword)
            {
                requestDictionary.AddError("Password", "Passwords do not match.");
            }
            validationDictionary.Merge(requestDictionary);
            return(requestDictionary.IsValid);
        }
Esempio n. 14
0
 public override void Update(ComponentSeries component)
 {
     if (Repository.GetAllNoTracking().Any(t => t.Name == component.Name && t.VendorId == component.VendorId && t.Id != component.Id))
     {
         ValidationDictionary.AddError("SeriesName", "Unique name required");
     }
     else
     {
         base.Update(component);
     }
 }
Esempio n. 15
0
        public ValidationDictionary <ViewModelDailyBreadItem> SaveDailyBreadItem(int clientId, ViewModelDailyBreadItem viewModelDailyBread)
        {
            var validator = new ValidationDictionary <ViewModelDailyBreadItem>();

            if (viewModelDailyBread == null)
            {
                validator.IsValid = false;
                validator.AddError("", "The XX you're trying to save is null");
                return(validator);
            }

            // rule based here


            DailyBreadItem dailyBreadItem;

            if (viewModelDailyBread.DailyBreadId <= 0)
            {
                dailyBreadItem = new DailyBreadItem();
                dailyBreadItem.InjectFrom(viewModelDailyBread);
                dailyBreadItem.DateCreated     = DateTime.UtcNow;
                dailyBreadItem.DateLastUpdated = DateTime.UtcNow;
                dailyBreadItem.ClientId        = clientId;

                _dailyBreadItemRepository.Add(dailyBreadItem);
            }
            else
            {
                dailyBreadItem = _dailyBreadItemRepository.FindBy(o => !o.IsDeleted &&
                                                                  o.DailyBreadId == viewModelDailyBread.DailyBreadId &&
                                                                  o.ClientId == clientId);

                if (dailyBreadItem != null)
                {
                    var createdDate = dailyBreadItem.DateCreated;
                    dailyBreadItem.InjectFrom(viewModelDailyBread);
                    dailyBreadItem.DateLastUpdated = DateTime.UtcNow;
                    dailyBreadItem.DateCreated     = createdDate;
                    dailyBreadItem.IsDeleted       = false;

                    _dailyBreadItemRepository.Update(dailyBreadItem);
                }
            }

            UpdateDailyBreadUrl(dailyBreadItem.DailyBreadId);

            var pinged = GetDailyBreadItem(clientId, dailyBreadItem.DailyBreadId);

            validator.IsValid       = true;
            validator.RelatedObject = pinged;
            return(validator);
        }
Esempio n. 16
0
        public ValidationDictionary <ViewModelNewsItem> SaveNewsItem(int clientId, ViewModelNewsItem viewModelNews)
        {
            var validator = new ValidationDictionary <ViewModelNewsItem>();

            if (viewModelNews == null)
            {
                validator.IsValid = false;
                validator.AddError("", "The News you're trying to save is null");
                return(validator);
            }

            // rule based here
            viewModelNews.DateExpired   = viewModelNews.DateExpired.DatePart();
            viewModelNews.DatePublished = viewModelNews.DatePublished.DatePart();

            NewsItem newsItem;

            if (viewModelNews.NewsId <= 0)
            {
                newsItem = new NewsItem();
                newsItem.InjectFrom <CloneInjection>(viewModelNews);
                newsItem.DateCreated     = DateTime.UtcNow;
                newsItem.DateLastUpdated = DateTime.UtcNow;
                newsItem.ClientId        = clientId;

                _newsRepository.Add(newsItem);
            }
            else
            {
                newsItem = _newsRepository.FindBy(o => !o.IsDeleted && o.NewsId == viewModelNews.NewsId && o.ClientId == clientId);
                if (newsItem != null)
                {
                    var createdDate = newsItem.DateCreated;
                    newsItem.InjectFrom <CloneInjection>(viewModelNews);
                    newsItem.DateLastUpdated = DateTime.UtcNow;
                    newsItem.DateCreated     = createdDate;
                    newsItem.IsDeleted       = false;

                    _newsRepository.Update(newsItem);
                }
            }

            // update news url
            UpdateNewsUrl(newsItem.NewsId);

            var pingedNews = GetNewsItem(clientId, newsItem.NewsId);

            validator.IsValid       = true;
            validator.RelatedObject = pingedNews;
            return(validator);
        }
        public void AddErrorOne()
        {
            // Arrange
            var inner        = new Dictionary <string, List <string> >();
            var dictionary   = new ValidationDictionary(inner);
            var propertyName = "Item";
            var errorMessage = "ErrorMessage.";

            // Act
            dictionary.AddError(propertyName, errorMessage);

            // Assert
            Assert.Equal(errorMessage, inner[propertyName][0]);
        }
Esempio n. 18
0
        public ValidationDictionary <ViewModelArticleItem> SaveArticleItem(int clientId, ViewModelArticleItem viewModelArticle)
        {
            var validator = new ValidationDictionary <ViewModelArticleItem>();

            if (viewModelArticle == null)
            {
                validator.IsValid = false;
                validator.AddError("", "The XX you're trying to save is null");
                return(validator);
            }

            // rule based here


            ArticleItem articleItem;

            if (viewModelArticle.ArticleId <= 0)
            {
                articleItem = new ArticleItem();
                articleItem.InjectFrom <CloneInjection>(viewModelArticle);
                articleItem.DateCreated     = DateTime.UtcNow;
                articleItem.DateLastUpdated = DateTime.UtcNow;
                articleItem.ClientId        = clientId;

                _articleItemRepository.Add(articleItem);
            }
            else
            {
                articleItem = _articleItemRepository.FindBy(o => !o.IsDeleted && o.ArticleId == viewModelArticle.ArticleId && o.ClientId == clientId);
                if (articleItem != null)
                {
                    var createdDate = articleItem.DateCreated;
                    articleItem.InjectFrom <CloneInjection>(viewModelArticle);
                    articleItem.DateLastUpdated = DateTime.UtcNow;
                    articleItem.DateCreated     = createdDate;
                    articleItem.IsDeleted       = false;

                    _articleItemRepository.Update(articleItem);
                }
            }

            UpdateArticleUrl(articleItem.ArticleId);

            var pinged = GetArticleItem(clientId, articleItem.ArticleId);

            validator.IsValid       = true;
            validator.RelatedObject = pinged;
            return(validator);
        }
Esempio n. 19
0
 public override void Update(Vendor vendor)
 {
     if (Repository.Get(t => t.Name == vendor.Name && t.Id != vendor.Id).Any())
     {
         ValidationDictionary.AddError("Name", "Unique name required");
     }
     else if (vendor.Id == 1)
     {
         ValidationDictionary.AddError("Name", "Default vendor is locked for editing");
     }
     else
     {
         base.Update(vendor);
     }
 }
Esempio n. 20
0
 public ValidationDictionary<DailyBreadItemDto> DeleteDailyBreadItem(int clientId, int dailybreadId)
 {
     var validator = new ValidationDictionary<DailyBreadItemDto>();
     var raw = _dailyBreadItemRepository.FindBy(o => o.DailyBreadId == dailybreadId && o.ClientId == clientId);
     if (raw != null)
     {
         raw.IsDeleted = true;
         _dailyBreadItemRepository.Update(raw);
         validator.IsValid = true;
     }
     else
     {
         validator.IsValid = false;
         validator.AddError("", "The Daily Bread is not available in the database");
     }
     return validator;
 }
        public bool SaveAvatarFile(int id, Stream stream, string extension)
        {
            extension = extension.StripExtension();
            var settings = GetSettings();

            if (stream.Length > settings.MaxFileSize)
            {
                ValidationDictionary.AddError(AvatarsServiceValidationKey.FileTooLarge, T("The file was too large for an avatar ({0}KB), maximum file size is {1}KB",
                                                                                          Math.Round((float)(stream.Length / 1024)),
                                                                                          Math.Round((float)(settings.MaxFileSize / 1024))));

                return(false);
            }

            var filePath = GetFilePath(id, extension);

            if (!IsFileAllowed(filePath))
            {
                ValidationDictionary.AddError(AvatarsServiceValidationKey.NotAllowedFileType, T("This file type is not allowed as an avatar."));

                return(false);
            }

            // This is the way to overwrite a file... We can't check its existence yet with IStorageProvider, but soon there will be such a method.
            try
            {
                _storageProvider.DeleteFile(filePath);
            }
            catch (Exception)
            {
            }

            _storageProvider.SaveStream(filePath, stream);

            var avatar = _contentManager.Get <AvatarProfilePart>(id);

            avatar.FileExtension = extension;
            _contentManager.Flush();

            return(true);
        }
Esempio n. 22
0
        public ValidationDictionary <ViewModelDailyBreadItem> DeleteDailyBreadItem(int clientId, int dailyBreadId)
        {
            var raw = _dailyBreadItemRepository.FindBy(o => o.DailyBreadId == dailyBreadId && o.ClientId == clientId);

            var validator = new ValidationDictionary <ViewModelDailyBreadItem>();

            if (raw != null)
            {
                raw.IsDeleted = true;

                _dailyBreadItemRepository.Update(raw);

                validator.IsValid = true;
            }
            else
            {
                validator.IsValid = false;
                validator.AddError("", "The XX is not available in the database");
            }

            return(validator);
        }
Esempio n. 23
0
        protected override bool Validate(User model)
        {
            if (string.IsNullOrEmpty(model.Email))
            {
                ValidationDictionary.AddError("email", "missing");
            }
            else if (model.Email.Length < 3 || model.Email.Length > 30)
            {
                ValidationDictionary.AddError("email", "invalid length");
            }
            else if (repository.Get(u => u.Id != model.Id && u.Email == model.Email) != null)
            {
                ValidationDictionary.AddError("email", "the given email is already taken");
            }

            if (string.IsNullOrEmpty(model.Password))
            {
                ValidationDictionary.AddError("password", "missing");
            }

            return(ValidationDictionary.IsValid);
        }
Esempio n. 24
0
        public async Task <bool> IsReferralCodeValidAsync(string referralCode)
        {
            Debug.Assert(!String.IsNullOrEmpty(referralCode));

            var referral = await db.Referrals.FindAsync(referralCode);

            bool success = false;

            if (referral == null)
            {
                ValidationDictionary.AddError(Guid.NewGuid().ToString(), ErrorMessages.ReferralCodeDoesNotExist);
            }
            else if (referral.IsRedeemed)
            {
                ValidationDictionary.AddError(Guid.NewGuid().ToString(), ErrorMessages.ReferralCodeAlreadyRedeemed);
            }
            else
            {
                success = true;
            }

            return(success);
        }
Esempio n. 25
0
        /// <summary>
        /// Adds a gift to a user's collection and reduces their points appropriately.
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="storeItemId"></param>
        /// <param name="buyCount"></param>
        /// <returns></returns>
        public async Task <ServiceResult> BuyGiftAsync(string userId, int storeItemId, int buyCount)
        {
            Debug.Assert(!String.IsNullOrEmpty(userId));
            Debug.Assert(storeItemId > 0);
            Debug.Assert(buyCount > 0);

            // check price of item and see if the user has enough points to buy the item with the count
            var gift = await db.StoreItems.FindAsync(storeItemId);

            var user = db.Users.Find(userId);

            // get any sales that this item is under
            int pointsCost = await GetAdjustedSalePrice(storeItemId, gift.PointPrice);

            bool   success     = false;
            string failMessage = String.Empty;

            if (user.CurrentPoints >= pointsCost * buyCount)
            {
                try
                {
                    // check if user already has an item of this type
                    var inventoryItem = await(from inventory in db.InventoryItems
                                              where inventory.StoreItemId == storeItemId
                                              where inventory.ApplicationUserId == userId
                                              select inventory).FirstOrDefaultAsync();

                    // if they do, increase the count of their item based on buyCount
                    if (inventoryItem != null)
                    {
                        inventoryItem.ItemCount += buyCount;
                    }
                    // if they don't, create a new item and add it to their inventory
                    else
                    {
                        InventoryItem item = new InventoryItem()
                        {
                            ApplicationUserId = userId,
                            StoreItemId       = storeItemId,
                            ItemCount         = buyCount
                        };

                        db.InventoryItems.Add(item);
                    }

                    LogStoreTransaction(userId, storeItemId, buyCount, pointsCost);

                    user.CurrentPoints -= pointsCost * buyCount;

                    success = (await db.SaveChangesAsync()) > 0;
                }
                catch (DbUpdateException ex)
                {
                    Log.Error("StoreService.BuyGiftAsync", ex, new { userId, storeItemId, buyCount });
                    ValidationDictionary.AddError(Guid.NewGuid().ToString(), ErrorMessages.GiftPurchaseFailed);
                }

                if (success)
                {
                    await AwardAchievedMilestonesForUserAsync(userId, (int)MilestoneTypeValues.GiftsPurchased);
                }
                else
                {
                    failMessage = ErrorMessages.GiftPurchaseFailed;
                }
            }
            else
            {
                failMessage = String.Format(ErrorMessages.UserDoesNotHaveEnoughPointsToPurchase, buyCount, gift.Name);
                ValidationDictionary.AddError(Guid.NewGuid().ToString(), failMessage);
            }

            return(success ? ServiceResult.Success : ServiceResult.Failed(failMessage));
        }
Esempio n. 26
0
        /// <summary>
        /// Adds a title to a user's collection and reduces their points appropriately.
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="storeItemId"></param>
        /// <returns></returns>
        public async Task <ServiceResult> BuyTitleAsync(string userId, int storeItemId)
        {
            var title = await db.StoreItems.FindAsync(storeItemId);

            var user = db.Users.Find(userId);

            // get any sales that this item is under
            int pointsCost = await GetAdjustedSalePrice(storeItemId, title.PointPrice);

            bool          success = false;
            List <string> errors  = new List <string>();

            if (user.CurrentPoints >= pointsCost)
            {
                try
                {
                    UserTitle userTitle = new UserTitle()
                    {
                        UserId       = userId,
                        StoreItemId  = storeItemId,
                        DateObtained = DateTime.Now
                    };

                    // if the user does not own the title, let them purchase it
                    bool doesUserAlreadyHaveTitle = await db.UserTitles.AnyAsync(a => a.StoreItemId == storeItemId && a.UserId == userId);

                    if (!doesUserAlreadyHaveTitle)
                    {
                        db.UserTitles.Add(userTitle);

                        LogStoreTransaction(userId, storeItemId, 1, pointsCost);

                        user.CurrentPoints -= pointsCost;

                        success = (await db.SaveChangesAsync()) > 0;
                    }
                    else
                    {
                        errors.Add(ErrorMessages.TitleAlreadyObtained);
                        ValidationDictionary.AddError(Guid.NewGuid().ToString(), ErrorMessages.TitleAlreadyObtained);
                    }
                }
                catch (DbUpdateException ex)
                {
                    Log.Error("StoreService.BuyGiftAsync", ex, new { userId, storeItemId });
                    errors.Add(ErrorMessages.TitleAlreadyObtained);
                }

                if (success)
                {
                    await AwardAchievedMilestonesForUserAsync(userId, (int)MilestoneTypeValues.TitlesPurchased);
                }
            }
            else
            {
                string error = String.Format(ErrorMessages.UserDoesNotHaveEnoughPointsToPurchase, 1, title.Name);
                errors.Add(error);
                ValidationDictionary.AddError(Guid.NewGuid().ToString(), error);
            }

            return(success ? ServiceResult.Success : ServiceResult.Failed(errors.ToArray()));
        }
Esempio n. 27
0
        public ValidationDictionary<DynamicPageDto> SavePage(int clientId, DynamicPageDto pageDto, bool setAsHomePage)
        {
            // validation first
            var validator = new ValidationDictionary<DynamicPageDto>();
            if (pageDto == null)
            {
                validator.IsValid = false;
                validator.AddError("", "Page you're trying to save is null");
                return validator;
            }

            // rule based
            if (setAsHomePage)
            {
                // get previous homepage, update it to another url path
            }

            DynamicPage dPage;

            if (pageDto.PageId <= 0)
            {
                // prepare object to save
                dPage = new DynamicPage();
                dPage.PageName = pageDto.PageName;
                dPage.PageMenuName = pageDto.PageMenuName;
                dPage.PageUrl = pageDto.PageUrl;
                dPage.PageDescription = pageDto.PageDescription;
                dPage.PageContent = pageDto.PageContent;
                dPage.MetaTitle = pageDto.MetaTitle;
                dPage.MetaDescription = pageDto.MetaDescription;
                dPage.ClientId = clientId;
                dPage.DateCreated = DateTime.UtcNow;
                dPage.DateLastUpdated = DateTime.UtcNow;

                _pageRepository.Add(dPage);
            }
            else
            {
                var gExpression = _dynamicPageFilters.Init()
                    .GetByPageId(pageDto.PageId)
                    .GetByClientId(clientId)
                    .GetNotDeleted()
                    .FilterExpression;

                dPage = _pageRepository.FindBy(gExpression);

                if (dPage != null)
                {
                    dPage.PageName = pageDto.PageName;
                    dPage.PageMenuName = pageDto.PageMenuName;
                    dPage.PageUrl = pageDto.PageUrl;
                    dPage.PageDescription = pageDto.PageDescription;
                    dPage.PageContent = pageDto.PageContent;
                    dPage.MetaTitle = pageDto.MetaTitle;
                    dPage.MetaDescription = pageDto.MetaDescription;
                    dPage.DateLastUpdated = DateTime.UtcNow;
                    dPage.IsDeleted = false;

                    _pageRepository.Update(dPage);
                }
            }

            dPage = dPage ?? new DynamicPage();
            var pingedPaged = GetPage(clientId, dPage.PageId);
            validator.IsValid = true;
            validator.RelatedObject = pingedPaged;

            return validator;
        }
Esempio n. 28
0
        public ValidationDictionary<DailyBreadItemDto> SaveDailyBreadItem(int clientId, DailyBreadItemDto dailyBreadDto)
        {
            var validator = new ValidationDictionary<DailyBreadItemDto>();
            if (dailyBreadDto == null)
            {
                validator.IsValid = false;
                validator.AddError("", "The XX you're trying to save is null");
                return validator;
            }

            // rule based here

            DailyBreadItem dailyBreadItem;

            if (dailyBreadDto.DailyBreadId <= 0)
            {
                dailyBreadItem = new DailyBreadItem();
                dailyBreadItem.DailyBreadTitle = dailyBreadDto.DailyBreadTitle;
                dailyBreadItem.DailyBreadUrl = dailyBreadDto.DailyBreadUrl;
                dailyBreadItem.DailyBreadSummary = dailyBreadDto.DailyBreadSummary;
                dailyBreadItem.DatePublished = dailyBreadDto.DatePublished;
                dailyBreadItem.DailyBreadBook = dailyBreadDto.DailyBreadBook;
                dailyBreadItem.DailyBreadBookChapter = dailyBreadDto.DailyBreadBookChapter;
                dailyBreadItem.DailyBreadBookVerse1 = dailyBreadDto.DailyBreadBookVerse1;
                dailyBreadItem.DailyBreadBookVerse2 = dailyBreadDto.DailyBreadBookVerse2;
                dailyBreadItem.DailyBreadBookContent = dailyBreadDto.DailyBreadBookContent;
                dailyBreadItem.DailyBreadContent = dailyBreadDto.DailyBreadContent;
                dailyBreadItem.DateCreated = DateTime.UtcNow;
                dailyBreadItem.DateLastUpdated = DateTime.UtcNow;
                dailyBreadItem.DailyBreadBookLang = dailyBreadDto.DailyBreadBookLang;
                dailyBreadItem.ClientId = clientId;

                _dailyBreadItemRepository.Add(dailyBreadItem);
            }
            else
            {
                dailyBreadItem = _dailyBreadItemRepository.FindBy(o => !o.IsDeleted
                    && o.DailyBreadId == dailyBreadDto.DailyBreadId
                    && o.ClientId == clientId);

                if (dailyBreadItem != null)
                {
                    dailyBreadItem.DailyBreadTitle = dailyBreadDto.DailyBreadTitle;
                    dailyBreadItem.DailyBreadUrl = dailyBreadDto.DailyBreadUrl;
                    dailyBreadItem.DailyBreadSummary = dailyBreadDto.DailyBreadSummary;
                    dailyBreadItem.DatePublished = dailyBreadDto.DatePublished;
                    dailyBreadItem.DailyBreadBook = dailyBreadDto.DailyBreadBook;
                    dailyBreadItem.DailyBreadBookChapter = dailyBreadDto.DailyBreadBookChapter;
                    dailyBreadItem.DailyBreadBookVerse1 = dailyBreadDto.DailyBreadBookVerse1;
                    dailyBreadItem.DailyBreadBookVerse2 = dailyBreadDto.DailyBreadBookVerse2;
                    dailyBreadItem.DailyBreadBookContent = dailyBreadDto.DailyBreadBookContent;
                    dailyBreadItem.DailyBreadContent = dailyBreadDto.DailyBreadContent;
                    dailyBreadItem.DateLastUpdated = DateTime.UtcNow;
                    dailyBreadItem.DailyBreadBookLang = dailyBreadDto.DailyBreadBookLang;
                    dailyBreadItem.IsDeleted = false;

                    _dailyBreadItemRepository.Update(dailyBreadItem);
                }
            }

            dailyBreadItem = dailyBreadItem ?? new DailyBreadItem();
            UpdateDailyBreadUrl(dailyBreadItem.DailyBreadId);

            var pinged = GetDailyBreadItem(clientId, dailyBreadItem.DailyBreadId);
            validator.IsValid = true;
            validator.RelatedObject = pinged;
            return validator;
        }