Beispiel #1
0
        [Authorize(AppConst.AccessPolicies.Secret)] /// Done
        public async Task <IActionResult> AllTemplate()
        {
            try
            {
                List <EmailTemplate> templateList = await _DbContext.EmailTemplates
                                                    .OrderByDescending(et => et.TemplateType)
                                                    .ToListAsync()
                                                    .ConfigureAwait(false);

                EmailTemplate copyDefaultTemplate = null;
                foreach (EmailTemplate item in templateList)
                {
                    if (item.TemplateType == EmailTemplateTypes.DefaultTemplate)
                    {
                        copyDefaultTemplate = item;
                    }
                    item.PrepareDesign(WebHost.WebRootPath);
                    item.PrepareHtml(WebHost.WebRootPath);
                }

                if (copyDefaultTemplate != null)
                {
                    templateList.Remove(copyDefaultTemplate);
                    templateList = templateList.Prepend(copyDefaultTemplate).ToList();
                }
                return(Ok(templateList));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));;
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #2
0
        /// Done
        public async Task <IActionResult> Delete(int productId)
        {
            try
            {
                Product product = await _DbContext.Products.SingleOrDefaultAsync(d => d.Id == productId).ConfigureAwait(false);

                if (product is null)
                {
                    CoreFunc.Error(ref ErrorsList, "Product not found");
                    return(NotFound(ErrorsList));
                }

                _DbContext.Products.Remove(product);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                try
                {
                    CoreFunc.DeleteFromWWWRoot(product.ImagePath, _WebHost.WebRootPath);
                    CoreFunc.DeleteFromWWWRoot(product.OriginalImagePath, _WebHost.WebRootPath);
                    CoreFunc.ClearEmptyImageFolders(_WebHost.WebRootPath);
                }
                catch (Exception ex)
                {
                    _LoggingService.LogException(Request.Path, ex, User, AppLogType.FileModification);
                }
                return(Ok($"Product '{product.Name}' was deleted"));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #3
0
        public async Task <IActionResult> SalesStatistics(SalesPeriod salePeriod)
        {
            try
            {
                MultiResult <List <string>, List <decimal>, List <int> > result = new MultiResult <List <string>, List <decimal>, List <int> >();
                switch (salePeriod)
                {
                case SalesPeriod.Daily:
                    result = await GetDaily(CoreFunc.GetCustomAttributeTypedArgument(this.ControllerContext));

                    break;

                case SalesPeriod.Monthly:
                    result = await GetMonthly(CoreFunc.GetCustomAttributeTypedArgument(this.ControllerContext));

                    break;

                case SalesPeriod.Yearly:
                    result = await GetYearly(CoreFunc.GetCustomAttributeTypedArgument(this.ControllerContext));

                    break;

                default:
                    break;
                }
                ;
                return(Ok(result));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #4
0
        public async Task <IActionResult> GetDisputeSecret(string disputeKey)
        {
            try
            {
                Communication dispute = await _DbContext.Communications
                                        .Include(c => c.Order)
                                        .ThenInclude(o => o.User)
                                        .Include(c => c.Order)
                                        .ThenInclude(o => o.OrderItems)
                                        .Include(c => c.Messages)
                                        .SingleOrDefaultAsync(c => c.Type == ContactType.Dispute && c.Id == disputeKey)
                                        .ConfigureAwait(false);

                if (dispute is null)
                {
                    CoreFunc.Error(ref ErrorsList, "Dispute Not Found.");
                    return(StatusCode(412, ErrorsList));
                }

                return(Ok(dispute));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #5
0
        public async Task <IActionResult> Search(
            int selectedPage,
            int maxNumberPerItemsPage,
            string searchValue = "",
            bool isSortAsce    = true,
            string sortName    = "Name")
        {
            try
            {
                int totalCount = await _DbContext.Categories
                                 .CountAsync(c => searchValue.Equals(CoreConst.GetAllRecords)?true : c.Name.Contains(searchValue))
                                 .ConfigureAwait(false);

                List <Category> list = await _DbContext.Categories
                                       .Where(c => searchValue.Equals(CoreConst.GetAllRecords)?true : c.Name.Contains(searchValue))
                                       .OrderByDynamic(sortName, isSortAsce)
                                       .Skip((selectedPage - 1) * maxNumberPerItemsPage)
                                       .Take(maxNumberPerItemsPage)
                                       .ToListAsync()
                                       .ConfigureAwait(false);

                foreach (var category in list)
                {
                    category.TotalProducts = await _DbContext.Products
                                             .CountAsync(p => p.Category.Id == category.Id)
                                             .ConfigureAwait(false);
                }
                return(Ok(new MultiResult <List <Category>, int>(list, totalCount, CoreFunc.GetCustomAttributeTypedArgument(this.ControllerContext))));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #6
0
        public void Configuration(IAppBuilder app)
        {
            //读取任务调度的配置信息Section,配置了redis的存储信息和执行队列的信息,各个任务在加入hangfire时,会分配在相应设置的queue队列,若执行队列未初始化,那么任务不能执行
            var taskScheduler = ConfigurationManager.GetSection("taskscheduler") as TaskSchedulerSection;

            GlobalConfiguration.Configuration.UseRedisStorage(taskScheduler.Redis.ConnectionString)
            .UseDashboardMetric(DashboardMetrics.ScheduledCount)
            .UseDashboardMetric(DashboardMetrics.SucceededCount)
            .UseDashboardMetric(DashboardMetrics.FailedCount)
            .UseDashboardMetric(DashboardMetrics.ProcessingCount)
            .UseDashboardMetric(DashboardMetrics.RetriesCount)
            .UseDashboardMetric(DashboardMetrics.RecurringJobCount);

            //Hangfire服务器配置,后台任务选项:队列初始化
            app.UseHangfireServer(new BackgroundJobServerOptions()
            {
                Queues      = taskScheduler.Queues.Value.Split(',').Select(p => p.ToLower()).ToArray(),
                WorkerCount = Environment.ProcessorCount * 5
            });

            //5次重试后不成功,进入fail
            GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute {
                Attempts = 3
            });

            //仪表板显示配置
            app.UseHangfireDashboard("/hangfire", new DashboardOptions {
                AppPath = VirtualPathUtility.ToAbsolute("~") + "hangfire"
            });
            //加载任务
            CoreFunc.LoanTasks();
        }
Beispiel #7
0
        /// Ready For Test
        public async Task <IActionResult> Post([FromBody] Coupon newCoupon)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                if (!newCoupon.IsValid(ref ErrorsList))
                {
                    return(UnprocessableEntity(ErrorsList));
                }
                if (await _DbContext.Coupons.AnyAsync(c => c.Code == newCoupon.Code)
                    .ConfigureAwait(false))
                {
                    CoreFunc.Error(ref ErrorsList, "Coupon Code already exists.");
                    return(StatusCode(412, ErrorsList));
                }

                await _DbContext.Coupons.AddAsync(newCoupon).ConfigureAwait(false);

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

                return(Created("Success", newCoupon));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
        public async Task <IActionResult> Delete(string key)
        {
            try
            {
                /// if the Newsletter record with the same id is not found
                Newsletter newsletter = _DbContext.Newsletters.Find(key);
                if (newsletter != null)
                {
                    /// now delete the Newsletter record
                    _DbContext.Newsletters.Remove(newsletter);

                    /// save the changes to the database
                    await _DbContext.SaveChangesAsync().ConfigureAwait(false);
                }
                else
                {
                    CoreFunc.Error(ref ErrorsList, "Your key is invalid.");
                    return(StatusCode(412, ErrorsList));
                }
                /// return 200 OK status
                return(Ok($"{newsletter.Email} is now unsubscribed"));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #9
0
        public bool IsValid(ref List <Error> ErrorsList)
        {
            switch (this.Type)
            {
            case CouponType.FreeDelivery:
                this.DiscountAmount = 0;
                break;

            case CouponType.PercentageOfTotal:
                if (this.DiscountAmount > 100)
                {
                    CoreFunc.Error(ref ErrorsList, $"Discount Amount must be less than 100");
                    return(false);
                }
                break;

            case CouponType.DiscountPrice:
                break;

            default:
                break;
            }


            return(true);
        }
Beispiel #10
0
        [Authorize(AppConst.AccessPolicies.Secret)] /// Ready for test
        public async Task <IActionResult> Search(
            int selectedPage,
            int maxNumberPerItemsPage,
            string searchValue = "",
            string filterType  = CoreConst.GetAllRecords,
            bool isSortAsce    = true,
            string sortName    = "Code")
        {
            try
            {
                int totalCount = await _DbContext.Coupons
                                 .Where(r => filterType.Equals(CoreConst.GetAllRecords)?
                                        true : r.Type.Equals((CouponType)Enum.Parse(typeof(CouponType), filterType, true)))
                                 .CountAsync(c => searchValue.Equals(CoreConst.GetAllRecords) ? true : c.Code.Contains(searchValue))
                                 .ConfigureAwait(false);

                List <Coupon> list = await _DbContext.Coupons
                                     .Where(r => filterType.Equals(CoreConst.GetAllRecords)?true : r.Type.Equals((CouponType)Enum.Parse(typeof(CouponType), filterType, true)))
                                     .OrderByDynamic(sortName, isSortAsce)
                                     .Where(c => searchValue.Equals(CoreConst.GetAllRecords) ? true : c.Code.Contains(searchValue))
                                     .Skip((selectedPage - 1) * maxNumberPerItemsPage)
                                     .Take(maxNumberPerItemsPage)
                                     .ToListAsync()
                                     .ConfigureAwait(false);

                return(Ok(new MultiResult <List <Coupon>, int>(list, totalCount, CoreFunc.GetCustomAttributeTypedArgument(this.ControllerContext))));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #11
0
        private async Task <User> UpdatePassword(User selectedUser)
        {
            User userDetails = await _DbContext.Users.FindAsync(selectedUser.Id).ConfigureAwait(false);

            if (userDetails == null)
            {
                CoreFunc.Error(ref ErrorsList, "User not found!");
                return(null);
            }
            string passResetToken = await _UserManager.GeneratePasswordResetTokenAsync(userDetails).ConfigureAwait(false);

            IdentityResult result = await _UserManager.ResetPasswordAsync(
                userDetails, passResetToken, selectedUser.Password).ConfigureAwait(false);

            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    ErrorsList.Add(new Error(error.Code, error.Description));
                }
                return(null);
            }

            return(userDetails);
        }
Beispiel #12
0
        [Authorize(AppConst.AccessPolicies.Official)] /// Ready For Test
        public async Task <IActionResult> Delete(int addressId)
        {
            try
            {
                Address address = await _DbContext.Addresses.SingleAsync(a => a.Id == addressId).ConfigureAwait(false);

                if (address is null)
                {
                    CoreFunc.Error(ref ErrorsList, "Address not found");
                    return(NotFound(ErrorsList));
                }

                if (address.IsDefault == true)
                {
                    CoreFunc.Error(ref ErrorsList, "Unable to Delete default Address.");
                    return(StatusCode(412, ErrorsList));
                }

                _DbContext.Addresses.Remove(address);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Ok($"Address was deleted"));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #13
0
        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var core         = new CoreFunc();
            var categoryName = ((ListBoxItem)this.CategoryListBox.SelectedItem).Content.ToString();
            var messages     = new List <Message>();

            if (categoryName.Contains("Входящие"))
            {
                messages = core.GetIncomingMessages();
            }
            else if (categoryName.Contains("Исходящие"))
            {
                messages = core.GetOutgoingMessages();
            }
            else if (categoryName.Contains("Требуется ответ"))
            {
                messages = core.GetNeedAnswerMessages();
            }
            else if (categoryName.Contains("Архив"))
            {
                messages = core.GetArchiveMessages();
            }

            FillMessageGrid(messages);
        }
Beispiel #14
0
        public async Task <IActionResult> UpdateCurrentUserPassword([FromBody] UpdateCurrentUserData data)
        {
            try
            {
                _ = int.TryParse(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value, out int userId);
                User user = _DbContext.Users.Find(userId);


                if (!await _UserManager.CheckPasswordAsync(user, data.CurrentPassword).ConfigureAwait(false))
                {
                    CoreFunc.Error(ref ErrorsList, "Current Password is incorrect.");
                    return(StatusCode(412, ErrorsList));
                }


                user.Password = data.User.Password;
                User result = await UpdatePassword(user).ConfigureAwait(false);

                if (result == null)
                {
                    return(StatusCode(412, ErrorsList));
                }
                return(Ok(result));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
        /// Ready For Test
        public async Task <IActionResult> Delete(int deliveyOptionId)
        {
            try
            {
                DeliveryOption currentDeliveryOption = await _DbContext.DeliveryOptions.SingleOrDefaultAsync(d => d.Id == deliveyOptionId)
                                                       .ConfigureAwait(false);

                if (currentDeliveryOption is null)
                {
                    CoreFunc.Error(ref ErrorsList, "Delivery Option not found");
                    return(NotFound(ErrorsList));
                }

                if (currentDeliveryOption.IsPremitive)
                {
                    /// extract the errors and return bad request containing the errors
                    CoreFunc.Error(ref ErrorsList, "Delivery Option is primitive.");
                    return(StatusCode(412, ErrorsList));
                }

                _DbContext.DeliveryOptions.Remove(currentDeliveryOption);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Ok("Delivery Option was deleted"));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #16
0
        public async Task <IActionResult> Validate(string couponCode)
        {
            try
            {
                Coupon coupon = await _DbContext.Coupons.FindAsync(couponCode);

                if (coupon == null)
                {
                    CoreFunc.Error(ref ErrorsList, $"'{couponCode}' not found");
                    return(StatusCode(412, ErrorsList));
                }

                if (coupon.MaxUseQuantity == 0 || coupon.ExpiryDate < DateTime.UtcNow)
                {
                    CoreFunc.Error(ref ErrorsList, $"'{couponCode}' has expired");
                    return(StatusCode(412, ErrorsList));
                }

                return(Ok(coupon));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #17
0
        public async Task <IActionResult> All(int productId,
                                              int selectedPage,
                                              int maxItemsPerPage)
        {
            try
            {
                int totalCount = await _DbContext.Comments.CountAsync()
                                 .ConfigureAwait(false);

                List <Comment> list = await _DbContext.Comments.Include(c => c.Product).Include(c => c.User)
                                      .Where(c => c.Product.Id == productId)
                                      .OrderBy(c => c.Date)
                                      .Skip((selectedPage - 1) * maxItemsPerPage)
                                      .Take(maxItemsPerPage)
                                      .ToListAsync()
                                      .ConfigureAwait(false);

                return(Ok(new MultiResult <List <Comment>, int>(list, totalCount, CoreFunc.GetCustomAttributeTypedArgument(ControllerContext))));
            }
            catch (Exception ex)
            {
                /// in the case any exceptions return the following error
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #18
0
        public async Task <IActionResult> Summary()
        {
            try
            {
                int newOrderCount = await _DbContext.Orders
                                    .CountAsync(o => o.Status == OrderStatusType.InProgress).ConfigureAwait(false);

                int openDisputeCount = await _DbContext.Communications
                                       .CountAsync(o => o.Type == ContactType.Dispute && o.Status == true).ConfigureAwait(false);

                int openMessageCount = await _DbContext.Communications
                                       .CountAsync(o => o.Type == ContactType.Message && o.Status == true).ConfigureAwait(false);

                decimal totalPrice = await _DbContext.Orders
                                     .Where(o => o.Status == OrderStatusType.InProgress ||
                                            o.Status == OrderStatusType.Confirmed ||
                                            o.Status == OrderStatusType.Delivered ||
                                            o.Status == OrderStatusType.PartialyRefunded)
                                     .SumAsync(o => o.TotalPrice).ConfigureAwait(false);

                decimal totalPartialRefund = await _DbContext.Payments
                                             .Where(p => p.Type == PaymentType.PartialyRefunded)
                                             .SumAsync(p => p.RefundAmount).ConfigureAwait(false);

                return(Ok(new MultiResult <int, int, int, decimal>(newOrderCount, openDisputeCount, openMessageCount, totalPrice - totalPartialRefund, CoreFunc.GetCustomAttributeTypedArgument(this.ControllerContext))));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #19
0
        public async Task <IActionResult> Put([FromBody] Address modifiedAddress)
        {
            try
            {
                if (modifiedAddress != null)
                {
                    modifiedAddress.User = await _DbContext.Users.AsTracking().Include(u => u.Role)
                                           .Include(u => u.RegistrationMethod).SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User));
                }
                ModelState.Clear();
                if (!TryValidateModel(modifiedAddress))
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                _DbContext.Addresses.Update(modifiedAddress);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Ok(modifiedAddress));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
        /// Ready For Test
        public async Task <IActionResult> Delete(string communicationId)
        {
            try
            {
                Communication currentDeliveryOption = await _DbContext.Communications.SingleOrDefaultAsync(d => d.Id == communicationId)
                                                      .ConfigureAwait(false);

                if (currentDeliveryOption is null)
                {
                    CoreFunc.Error(ref ErrorsList, "Communication not found");
                    return(NotFound(ErrorsList));
                }

                if (currentDeliveryOption.Type == Extras.CustomTypes.ContactType.Dispute)
                {
                    /// extract the errors and return bad request containing the errors
                    CoreFunc.Error(ref ErrorsList, "Dispute can't be delete.");
                    return(StatusCode(412, ErrorsList));
                }
                _DbContext.Communications.Remove(currentDeliveryOption);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                return(Ok("Communication was deleted"));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #21
0
        public async Task <IActionResult> Post([FromBody] Newsletter newsletter)
        {
            try
            {
                if (_DbContext.Newsletters.Find(newsletter.Email) != null)
                {
                    return(Created("Success", "Thank you for your subscription."));
                }

                TryValidateModel(newsletter);
                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                await _DbContext.Newsletters.AddAsync(newsletter).ConfigureAwait(false);

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

                return(Created("Success", "Thank you for your subscription."));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #22
0
        public async Task <IActionResult> ConfirmEmail([FromBody] string pathName)
        {
            try
            {
                string tokenValue = "";

                for (int i = pathName.Length - 1; i >= 0; i--)
                {
                    if (pathName[i] == '/')
                    {
                        i = -1;
                    }
                    else
                    {
                        tokenValue = pathName[i] + tokenValue;
                    }
                }

                Token token = await _DbContext.Tokens
                              .Include(t => t.User)
                              .FirstOrDefaultAsync(t => t.Url.Contains(pathName) && t.Value.Equals(tokenValue))
                              .ConfigureAwait(false);

                if (token == null || token.Type != Extras.CustomTypes.TokenTypes.ConfirmEmail)
                {
                    ErrorsList.Add(new Error("0", "Invalid Request/Token."));
                    return(StatusCode(412, ErrorsList));
                }

                if (token.ExpiaryDateTime < DateTime.UtcNow)
                {
                    ErrorsList.Add(new Error("0", "Token Expired"));
                    return(StatusCode(412, ErrorsList));
                }

                IdentityResult result = await _UserManager.ConfirmEmailAsync(token.User,
                                                                             await _UserManager.GenerateEmailConfirmationTokenAsync(token.User).ConfigureAwait(false))
                                        .ConfigureAwait(false);

                _DbContext.Entry(token.User).State = EntityState.Unchanged;
                _DbContext.Remove(entity: token);
                await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                if (result.Succeeded)
                {
                    return(Ok());
                }
                else
                {
                    ErrorsList.Add(new Error("0", "Unable to process your request."));
                    return(StatusCode(412, ErrorsList));
                }
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #23
0
        private async Task <IActionResult> PrivateCreateUser(User newUser)
        {
            try
            {
                newUser.PasswordHash = newUser.Password;
                if (newUser.RegistrationMethod.Type != RegistrationTypes.Application)
                {
                    newUser.PasswordHash   = CoreFunc.StringGenerator(40, 10, 10, 10, 10);
                    newUser.EmailConfirmed = true;
                }
                ModelState.Clear();
                if (!TryValidateModel(newUser))
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }
                if (await _DbContext.Users.AnyAsync(u => u.NormalizedEmail == newUser.Email.ToUpper()).ConfigureAwait(false))
                {
                    CoreFunc.Error(ref ErrorsList, "This email is already registered.");
                    return(StatusCode(412, ErrorsList));
                }

                newUser.Id = 0;
                IdentityResult newUserResult = await _UserManager.CreateAsync(newUser, newUser.PasswordHash)
                                               .ConfigureAwait(false);

                if (!newUserResult.Succeeded)
                {
                    foreach (var error in newUserResult.Errors)
                    {
                        CoreFunc.Error(ref ErrorsList, error.Description, error.Code);
                    }
                    return(StatusCode(417, ErrorsList));
                }
                IdentityResult addedClaimResult = await _UserManager.AddClaimAsync(
                    newUser,
                    new Claim(AppConst.AccessClaims.Type, newUser.Role.AccessClaim)
                    ).ConfigureAwait(false);

                if (!addedClaimResult.Succeeded)
                {
                    _DbContext.Users.Remove(newUser);
                    await _DbContext.SaveChangesAsync().ConfigureAwait(false);

                    CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, null, User));
                    return(StatusCode(417, ErrorsList));
                }
                await _UserManager.SetLockoutEnabledAsync(newUser, false);

                IsUserCreated = true;
                return(Created("Success", newUser));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #24
0
        public async Task <IActionResult> RequestPasswordReset([FromBody] string email)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(email))
                {
                    CoreFunc.Error(ref ErrorsList, "Email is required!");
                    return(StatusCode(412, ErrorsList));
                }

                User user = await _UserManager
                            .FindByEmailAsync(email).ConfigureAwait(false);

                if (user == null)
                {
                    CoreFunc.Error(ref ErrorsList, "Email not registered");
                    return(StatusCode(412, ErrorsList));
                }
                RegistrationMethod registrationMethod = await _DbContext.RegistrationMethods.FirstOrDefaultAsync(rm => rm.User.Id == user.Id).ConfigureAwait(false);

                if (registrationMethod.Type != RegistrationTypes.Application)
                {
                    CoreFunc.Error(ref ErrorsList, $"Your account is linked to your {registrationMethod.Type} account.");
                    return(StatusCode(412, ErrorsList));
                }

                if (user.LockoutEnabled)
                {
                    var currentLockoutDate =
                        await _UserManager.GetLockoutEndDateAsync(user).ConfigureAwait(false);

                    if (user.LockoutEnd > DateTimeOffset.UtcNow)
                    {
                        CoreFunc.Error(ref ErrorsList, string.Format("Account Locked for {0}"
                                                                     , CoreFunc.CompareWithCurrentTime(user.LockoutEnd)));
                        return(StatusCode(412, ErrorsList));
                    }
                    await _UserManager.SetLockoutEnabledAsync(user, false).ConfigureAwait(false);

                    await _UserManager.ResetAccessFailedCountAsync(user).ConfigureAwait(false);
                }

                Request.Headers.TryGetValue("Origin", out StringValues OriginValue);
                if (!await _EmailService.PasswordResetAsync(user, OriginValue).ConfigureAwait(false))
                {
                    CoreFunc.Error(ref ErrorsList, "Unable to send email.");
                    return(StatusCode(417, ErrorsList));
                }

                return(Created("", "Created"));
            }

            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #25
0
        [Authorize(AppConst.AccessPolicies.Secret)] /// Done
        public async Task <IActionResult> Put([FromBody] DeliveryOption modifiedDeliveryOption)
        {
            try
            {
                /// get the current category
                DeliveryOption currentDeliveryOption = await _DbContext.DeliveryOptions
                                                       .SingleOrDefaultAsync(c => c.Id == modifiedDeliveryOption.Id)
                                                       .ConfigureAwait(false);

                // if the current category does not exists
                if (currentDeliveryOption == null)
                {
                    CoreFunc.Error(ref ErrorsList, "Category Not Found");
                    return(NotFound(ErrorsList));
                }

                if (await _DbContext.DeliveryOptions
                    .AnyAsync(d => d.Name.Equals(modifiedDeliveryOption.Name) && d.Id != modifiedDeliveryOption.Id).ConfigureAwait(false))
                {
                    /// extract the errors and return bad request containing the errors
                    CoreFunc.Error(ref ErrorsList, "Delivery Option Name already exists.");
                    return(StatusCode(412, ErrorsList));
                }

                currentDeliveryOption.Name = modifiedDeliveryOption.Name;
                if (!(currentDeliveryOption.IsPremitive && currentDeliveryOption.MinimumOrderTotal == 0))
                {
                    currentDeliveryOption.MinimumOrderTotal = modifiedDeliveryOption.MinimumOrderTotal;
                }
                if (!(currentDeliveryOption.IsPremitive && currentDeliveryOption.Price == 0))
                {
                    currentDeliveryOption.Price = modifiedDeliveryOption.Price;
                }


                TryValidateModel(currentDeliveryOption);

                if (!ModelState.IsValid)
                {
                    CoreFunc.ExtractErrors(ModelState, ref ErrorsList);
                    return(UnprocessableEntity(ErrorsList));
                }

                _DbContext.DeliveryOptions.Update(currentDeliveryOption);

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


                return(Ok(currentDeliveryOption));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #26
0
        public async Task <IActionResult> DownloadData([FromBody] string currentPassword)
        {
            try
            {
                User user = await _DbContext.Users
                            .Include(u => u.Role)
                            .Include(u => u.RegistrationMethod)
                            .SingleOrDefaultAsync(u => u.Id == AppFunc.GetUserId(User)).ConfigureAwait(false);


                if (user.RegistrationMethod.Type == RegistrationTypes.Application &&
                    !await _UserManager.CheckPasswordAsync(user, currentPassword).ConfigureAwait(false))
                {
                    CoreFunc.Error(ref ErrorsList, "Current Password is incorrect.");
                    return(StatusCode(412, ErrorsList));
                }

                List <Order> orders = await _DbContext.Orders
                                      .Include(o => o.User)
                                      .Include(o => o.OrderItems)
                                      .Include(o => o.Dispute)
                                      .ThenInclude(c => c.Messages)
                                      .Include(o => o.Payment)
                                      .Include(o => o.Coupon)
                                      .Where(u => u.User.Id == AppFunc.GetUserId(User)).ToListAsync().ConfigureAwait(false);

                List <Communication> questions = await _DbContext.Communications
                                                 .Include(c => c.Messages)
                                                 .Where(c => c.Email.ToUpper() == user.NormalizedEmail).ToListAsync().ConfigureAwait(false);

                List <Comment> comments = await _DbContext.Comments
                                          .Include(c => c.User)
                                          .Where(c => c.User.Id == user.Id).ToListAsync().ConfigureAwait(false);

                List <Address> addresses = await _DbContext.Addresses
                                           .Include(c => c.User)
                                           .Where(c => c.User.Id == user.Id).ToListAsync().ConfigureAwait(false);

                dynamic userData = new { userInfo = user, orders, questions, comments, addresses };
                return(Ok(JsonConvert.SerializeObject(userData, Formatting.Indented,
                                                      new JsonSerializerSettings
                {
                    Converters = new List <JsonConverter> {
                        new StringEnumConverter(), new DecimalFormatConverter()
                    },
                    ContractResolver = new DynamicContractResolver("Id", "Password", "AccessClaim", "OrderLength", "HasOrder"
                                                                   , "DeliveryOption", "Order_Id", "captchaToken", "AddressId", "UserId", "ProductId", "ImagePath", "ExternalLinkedId")
                })));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #27
0
        public async Task <IActionResult> Get(
            int selectedPage    = 1,
            int maxItemsPerPage = 5,
            string searchValue  = CoreConst.GetAllRecords,
            string filterRole   = CoreConst.GetAllRecords,
            bool isSortAsce     = true,
            string sortName     = "Name"
            )
        {
            try
            {
                _ = int.TryParse(filterRole, out int filterRoleId);
                int totalCount = await _DbContext.Users
                                 .Include(u => u.Role)
                                 .Where(u => filterRole.Equals(CoreConst.GetAllRecords) || u.Role.Id == filterRoleId)
                                 .CountAsync(u => searchValue.Equals(CoreConst.GetAllRecords) || (u.FirstName.Contains(searchValue) ||
                                                                                                  searchValue.Equals(CoreConst.GetAllRecords) || u.Surname.Contains(searchValue) ||
                                                                                                  searchValue.Equals(CoreConst.GetAllRecords) || u.Id.ToString().Equals(searchValue) ||
                                                                                                  searchValue.Equals(CoreConst.GetAllRecords) || u.Email.Contains(searchValue) ||
                                                                                                  searchValue.Equals(CoreConst.GetAllRecords) || u.PhoneNumber.Contains(searchValue))
                                             ).ConfigureAwait(false);

                List <User> list = await _DbContext.Users
                                   .Include(u => u.Role)
                                   .Include(u => u.RegistrationMethod)
                                   .Where(u => filterRole.Equals(CoreConst.GetAllRecords) || u.Role.Id == filterRoleId)
                                   .Where(u => searchValue.Equals(CoreConst.GetAllRecords) || u.FirstName.Contains(searchValue) ||
                                          searchValue.Equals(CoreConst.GetAllRecords) || u.Surname.Contains(searchValue) ||
                                          searchValue.Equals(CoreConst.GetAllRecords) || u.Id.ToString().Equals(searchValue) ||
                                          searchValue.Equals(CoreConst.GetAllRecords) || u.Email.Contains(searchValue) ||
                                          searchValue.Equals(CoreConst.GetAllRecords) || u.PhoneNumber.Contains(searchValue))
                                   .OrderByDynamic(sortName, isSortAsce)
                                   .Skip((selectedPage - 1) * maxItemsPerPage)
                                   .Take(maxItemsPerPage)
                                   .Include(u => u.Orders)
                                   .ToListAsync()
                                   .ConfigureAwait(false);

                list.ForEach(u =>
                {
                    u.OrderLength = u.Orders.Count(o => o.Status == OrderStatusType.Confirmed ||
                                                   o.Status == OrderStatusType.InProgress ||
                                                   (o.Dispute != null && o.Dispute.Status));
                    u.HasOrder = u.Orders.Count > 0;
                });

                return(Ok(new MultiResult <List <User>, int>(list, totalCount, CoreFunc.GetCustomAttributeTypedArgument(this.ControllerContext))));
            }
            catch (Exception ex)
            {
                CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
                return(StatusCode(417, ErrorsList));
            }
        }
Beispiel #28
0
        private void MessageGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var core   = new CoreFunc();
            var dialog = new List <Dialog>();

            if (e.AddedItems != null && e.AddedItems.Count > 0)
            {
                var message = e.AddedItems[0] as Message;

                if (message == null)
                {
                    return;
                }

                var messageId = message.ID;

                dialog = core.GetDialog((Guid)messageId);

                DialogGrid.ItemsSource = dialog;

                DialogGrid.Columns[0].Visibility = Visibility.Collapsed;
                DialogGrid.Columns[4].Visibility = Visibility.Collapsed;
                DialogGrid.Columns[6].Visibility = Visibility.Collapsed;

                DialogGrid.Columns[1].Header = "Сообщение";
                DialogGrid.Columns[2].Header = "Диагноз";
                DialogGrid.Columns[3].Header = "План Лечения";
                DialogGrid.Columns[5].Header = "Пациент";
                DialogGrid.Columns[7].Header = "От кого";
                DialogGrid.Columns[8].Header = "Дата";

                DialogGrid.Columns[1].Width = 90;
                DialogGrid.Columns[2].Width = 170;
                DialogGrid.Columns[3].Width = 170;
                DialogGrid.Columns[4].Width = 90;
                DialogGrid.Columns[6].Width = 100;
                DialogGrid.Columns[7].Width = 110;

                DataGridTextColumn infoColumn        = DialogGrid.Columns[1] as DataGridTextColumn;
                DataGridTextColumn diagnosisColumn   = DialogGrid.Columns[2] as DataGridTextColumn;
                DataGridTextColumn therapyPlanColumn = DialogGrid.Columns[3] as DataGridTextColumn;

                Style style = DialogGrid.Resources["wordWrapStyle"] as Style;

                infoColumn.ElementStyle        = style;
                infoColumn.EditingElementStyle = style;

                diagnosisColumn.ElementStyle        = style;
                diagnosisColumn.EditingElementStyle = style;

                therapyPlanColumn.ElementStyle        = style;
                therapyPlanColumn.EditingElementStyle = style;
            }
        }
Beispiel #29
0
 /// <summary>
 /// Initializes the BSoD equivalent, getting the error level,
 /// error description and the error itself
 /// </summary>
 /// <param name="errlvl"></param>
 /// <param name="errdsc"></param>
 /// <param name="err"></param>
 public static void Init(int errlvl, string errdsc, string err)
 {
     Console.BackgroundColor = ConsoleColor.DarkRed;
     Console.Clear();
     Console.WriteLine(Msg + err);
     Console.WriteLine("This means that: "); Console.WriteLine(errdsc);
     Console.WriteLine("Press any key to restart.");
     Console.ReadKey(true);
     Console.ForegroundColor = ConsoleColor.White;
     Console.BackgroundColor = ConsoleColor.Black;
     CoreFunc.Reboot();
 }
Beispiel #30
0
 [Authorize(AppConst.AccessPolicies.Public)] /// Ready For Test
 public async Task <IActionResult> All()
 {
     try
     {
         return(Ok(await _DbContext.DeliveryOptions.ToListAsync()));
     }
     catch (Exception ex)
     {
         CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User));
         return(StatusCode(417, ErrorsList));
     }
 }