コード例 #1
0
        public async void CreateAdminAsync_Throw_Exception_If_Password_Length_Greater_Then_23()
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < 24; i++)
            {
                sb.Append(i);
            }
            AdminDto admin = new AdminDto
            {
                Email    = "*****@*****.**",
                FullName = "brian2",
                Gender   = true,
                Mobile   = "18817617807",
                UserName = "******",
                UserType = (int)UserType.Admin,
                Password = sb.ToString()
            };
            UserFriendlyException ex = await Assert
                                       .ThrowsAsync <UserFriendlyException>(
                () => _iAdminAppSerice.CreateAdminAsync(admin)
                );

            (ex != null).ShouldBe(true);
        }
コード例 #2
0
        public async Task <ActivateAccountResultModel> ActivateAccount([FromBody] ActivateAccountModel model)
        {
            if (model.ActivateType == ActivateType.NewAccount)
            {
                await ActivateWithNewAccount(model);
            }
            else
            {
                await ActivateWithExistAccount(model);
            }

            var loginResult = await GetLoginResultAsync(
                model.EmailAddress,
                model.Password,
                GetTenancyNameOrNull()
                );

            if (loginResult.Result != AbpLoginResultType.Success)
            {
                var ex = new UserFriendlyException("ActivateAccountFailed");
                Logger.Warn(new { loginResult.Result, loginResult.User.Id }.ToJsonString(), ex);
                throw ex;
            }

            var accessToken = CreateAccessToken(await CreateJwtClaims(loginResult.Identity, loginResult.User));

            return(new ActivateAccountResultModel
            {
                AccessToken = accessToken,
                EncryptedAccessToken = GetEncrpyedAccessToken(accessToken),
                ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds,
                UserId = loginResult.User.Id,
            });
        }
コード例 #3
0
ファイル: ExceptionHandler.cs プロジェクト: kapy90/App
        public static async Task Invoke(HttpContext context)
        {
            Exception exception = context.Features.Get <IExceptionHandlerPathFeature>()?.Error;

            if (exception == null)
            {
                await context.Response.WriteAsync(null);

                context.Response.Clear();
                return;
            }
            exception.ToString();
            int statusCode = context.Response.StatusCode;

            if (exception is UserFriendlyException)
            {
                statusCode = 400;
            }
            context.RequestServices.GetService <IExceptionLog>().Invoke(exception, statusCode);

            context.Response.ContentType = "text/plain; charset=utf-8";
            if (exception is UserFriendlyException)
            {
                UserFriendlyException userFriendlyException = exception as UserFriendlyException;
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync(userFriendlyException.Message);
            }
            else
            {
                context.Response.StatusCode = 500;
                await context.Response.WriteAsync("服务器内部错误");
            }
        }
コード例 #4
0
        /// <inheritdoc />
        public override void OnException(ExceptionContext context)
        {
            var exception = context.Exception;

            if (!(exception is UserFriendlyException friendlyException))
            {
                friendlyException = new UserFriendlyException(
                    ErrorCode.InternalServerError,
                    exception.Message);
            }
            var httpStatusCode = int.Parse(((int)friendlyException.Code).ToString().Substring(0, 3));

            if (httpStatusCode == 422)
            {
                httpStatusCode = 400;
            }

            var logStr = new StringBuilder();

            logStr.Append($"LogId: {friendlyException.Id}, Message: {friendlyException.Message}");
            logStr.AppendLine();
            logStr.Append($"Exception: {exception.ToString()}");
            _logger.LogError(logStr.ToString());

            context.HttpContext.Response.StatusCode = httpStatusCode;
            context.Result = new JsonResult(friendlyException);
        }
コード例 #5
0
        public override void OnException(ExceptionContext context)
        {
            var originalException    = context.Exception;
            UserFriendlyException ex = null;

            if (originalException is UserFriendlyException)
            {
                ex = originalException as UserFriendlyException;
            }
            else
            {
                ex = new UserFriendlyException(originalException.Message, errorCode: "");
            }

            context.ExceptionHandled = true;
            int    status = 500;
            string msg    = "服务器正忙";

            if (ex != null)
            {
                status = (int)ex.HttpStatus;
                msg    = ex.Message;
            }
            if (context.HttpContext.Request.Headers["X-Requested-With"] != "XMLHttpRequest")
            {
                context.Result = new RedirectResult("/Home/Error");
            }
            else
            {
                context.Result = new ContentResult {
                    Content = msg
                };
            }
        }
コード例 #6
0
        public void CreateOrder_Throw_Exception_If_Orderref_Exists()
        {
            var institution = UsingDbContext(ctx => ctx.Institution.Add(InitFakeEntity.GetFakeInstitution()));
            var adminEntity = InitFakeEntity.GetFakeAdmin();

            adminEntity.InstitutionId = institution.Id;
            var   admin = UsingDbContext(ctx => ctx.Admin.Add(adminEntity));
            Order order = InitFakeEntity.GetFakeOrder();

            order.UserId = admin.UserId;
            UsingDbContext(ctx => ctx.Order.Add(order));
            OrderDto createOrder = new OrderDto()
            {
                DeliveryCharge = 1000,
                Discount       = 1000,
                OrderRef       = "1234567",
                Subtotal       = 1000,
                Timestamp      = DateTime.Now,
                Total          = 10000,
                TotalQuantity  = 100,
                UserId         = admin.UserId
            };

            UserFriendlyException ex = Should.Throw <UserFriendlyException>(
                () => _orderAppService.CreateOrder(createOrder)
                );

            Assert.True(ex != null);
        }
コード例 #7
0
        public virtual async Task <JsonResult> ChangeProfilePicture()
        {
            JsonResult jsonResult;

            try
            {
                if (this.Request.Files.Count <= 0 || this.Request.Files[0] == null)
                {
                    throw new UserFriendlyException(this.L("ProfilePicture_Change_Error"));
                }
                HttpPostedFileBase item = this.Request.Files[0];
                if (item.ContentLength > 512000)
                {
                    throw new UserFriendlyException(this.L("ProfilePicture_Warn_SizeLimit"));
                }
                FuelWerx.Authorization.Users.User userByIdAsync = await this._userManager.GetUserByIdAsync(this.AbpSession.GetUserId());

                FuelWerx.Authorization.Users.User nullable = userByIdAsync;
                if (nullable.ProfilePictureId.HasValue)
                {
                    await this._binaryObjectManager.DeleteAsync(nullable.ProfilePictureId.Value);
                }
                BinaryObject binaryObject = new BinaryObject(item.InputStream.GetAllBytes());
                await this._binaryObjectManager.SaveAsync(binaryObject);

                nullable.ProfilePictureId = new Guid?(binaryObject.Id);
                jsonResult = this.Json(new MvcAjaxResponse());
            }
            catch (UserFriendlyException userFriendlyException1)
            {
                UserFriendlyException userFriendlyException = userFriendlyException1;
                jsonResult = this.Json(new MvcAjaxResponse(new ErrorInfo(userFriendlyException.Message), false));
            }
            return(jsonResult);
        }
コード例 #8
0
        public void UpdatePwd_Throw_If_User_Not_Found()
        {
            string pwd = "1111";
            UserFriendlyException ex = Should.Throw <UserFriendlyException>(
                () => _iAdminAppSerice.UpdatePwd(new Guid(), "123456", pwd));

            Assert.True(ex != null);
        }
コード例 #9
0
        public void UserFriendlyException_Default_Log_Severity_Change_Test()
        {
            // change log severity ...
            UserFriendlyException.DefaultLogSeverity = LogSeverity.Error;

            var exception = new UserFriendlyException("Test exception !");

            exception.Severity.ShouldBe(LogSeverity.Error);
        }
コード例 #10
0
        /// <summary>
        /// The HandleUserFriendlyException
        /// </summary>
        /// <param name="userFriendlyException">The userFriendlyException<see cref="UserFriendlyException"/></param>
        /// <param name="failCallback">The failCallback<see cref="Exception"/></param>
        /// <returns>The <see cref="Task"/></returns>
        private static async Task HandleUserFriendlyException(UserFriendlyException userFriendlyException,
                                                              Func <System.Exception, Task> failCallback)
        {
            await UserDialogs.Instance.AlertAsync(string.IsNullOrEmpty(userFriendlyException.Details)
                                                  ?userFriendlyException.Message.Translate()
                                                      : userFriendlyException.Details);

            await failCallback(userFriendlyException);
        }
コード例 #11
0
        public void UpdatePwd_Throw_If_OldPwd_Error()
        {
            Admin  admin             = InitFakeEntity.GetFakeAdmin();
            string pwd               = "1112221";
            var    admin2            = UsingDbContext(ctx => ctx.Admin.Add(admin));
            UserFriendlyException ex = Should.Throw <UserFriendlyException>(() => _iAdminAppSerice.UpdatePwd(admin2.UserId, pwd, pwd));

            Assert.True(ex != null);
        }
コード例 #12
0
        public void CreateStudent_Throw_Exception_If_UserName_Exists()
        {
            Student student = InitFakeEntity.GetFakeStudent();

            UsingDbContext(ctx => ctx.Student.Add(student));
            Student student2         = InitFakeEntity.GetFakeStudent();
            UserFriendlyException ex = Assert.Throws <UserFriendlyException>(() => _studentAppService.CreateStudent(student2));

            Assert.True(ex != null);
        }
コード例 #13
0
        public async void CreateInstitutionAsync_Should_Error_If_Name_Exist()
        {
            var institution = InitFakeEntity.GetFakeInstitution();

            UsingDbContext(ctx => ctx.Institution.Add(institution));
            UserFriendlyException ex = await Assert.ThrowsAsync <UserFriendlyException>(
                () => _institutionAppService.CreateInstitutionAsync(institution)
                );

            Assert.True(ex != null);
        }
コード例 #14
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        /// </summary>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(
                options =>
            {
                options.Filters.Add(typeof(CustomExceptionFilter));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddDbContext <DbContextBase, ProjectNameDbContext>(
                options =>
            {
                options.UseSqlServer(
                    _configuration.GetConnectionString("Default"),
                    option => option.UseRowNumberForPaging());
            });
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory =
                    actionContext =>
                {
                    var userFriendlyException = new UserFriendlyException(
                        ErrorCode.UnprocessableEntity,
                        "参数输入不正确");
                    actionContext.ModelState
                    .Where(e => e.Value.Errors.Count > 0).ToList()
                    .ForEach(
                        e =>
                    {
                        userFriendlyException.Errors.Add(e.Key, e.Value.Errors.Select(v => v.ErrorMessage));
                    });
                    throw userFriendlyException;
                };
            });
            services.AddSwaggerGen(
                options =>
            {
                options.SwaggerDoc("v1", new Info {
                    Version = "v1", Title = "ProjectName API"
                });
                var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                options.IncludeXmlComments(Path.Combine(baseDirectory, "CompanyName.ProjectName.Application.xml"));
                options.IncludeXmlComments(Path.Combine(baseDirectory, "CompanyName.ProjectName.Api.xml"));
            });

            return(services.AddCreekdream(
                       options =>
            {
                options.UseWindsor();
                options.UseEfCore();
                options.AddProjectNameCore();
                options.AddProjectNameEfCore();
                options.AddProjectNameApplication();
            }));
        }
コード例 #15
0
ファイル: SetAppServiceTest.cs プロジェクト: sunshine2548/Amy
        public void CreateSet_Throw_Exception_If_Name_Exists()
        {
            var set       = InitFakeEntity.GetFakeSet();
            var createSet = InitFakeEntity.GetFakeSetDto();

            createSet.SetName = set.SetName;
            UsingDbContext(ctx => ctx.Sets.Add(set));
            UserFriendlyException ex = Should.Throw <UserFriendlyException>(
                () => _setAppService.CreateSet(createSet));

            Assert.True(ex != null);
        }
コード例 #16
0
        public async Task SplitInputValid_Test()
        {
            UserFriendlyException result = null;
            var request = new SplitRequest()
            {
                OrderId = "18040300110001",
                ProList = new List <Product>()
                {
                    new Product()
                    {
                        ProNo    = "",
                        SkuNo    = "26098951",
                        Quantity = 1,
                        ProName  = "MAMIA婴幼儿奶粉二段900G二段",
                        ProPrice = 100,
                        Weight   = 100,
                        PTId     = "1010703"
                    },
                    new Product()
                    {
                        ProNo    = "",
                        SkuNo    = "26113807",
                        Quantity = 2,
                        ProName  = "MAMIA婴幼儿奶粉三段900G三段",
                        ProPrice = 100,
                        Weight   = 100,
                        PTId     = "1010704"
                    }
                },
                TotalQuantity = 1,
                Type          = 3
            };

            //商品重量不能为0
            request.ProList.ForEach(o => o.Weight = 0);
            result = await Assert.ThrowsAsync <UserFriendlyException>(() => this._splitService.Split(request, this._context.GetTenantId()));

            Assert.Equal((int)ResultCode.BadRequest_ParamConstraint, result.Code);
            Assert.Equal("product's weight must more then zero", result.Message);
            //商品价格不能为0
            request.ProList.ForEach(o => { o.ProPrice = 0; o.Weight = 100; });
            result = await Assert.ThrowsAsync <UserFriendlyException>(() => this._splitService.Split(request, this._context.GetTenantId()));

            Assert.Equal((int)ResultCode.BadRequest_ParamConstraint, result.Code);
            Assert.Equal("product's price must more then zero", result.Message);
            //商品数量不能为0
            request.ProList.ForEach(o => { o.Quantity = 0; o.ProPrice = 100; });
            result = await Assert.ThrowsAsync <UserFriendlyException>(() => this._splitService.Split(request, this._context.GetTenantId()));

            Assert.Equal((int)ResultCode.BadRequest_ParamConstraint, result.Code);
            Assert.Equal("product's quantity must more then zero", result.Message);
        }
コード例 #17
0
        private static async Task HandleUserFriendlyException(UserFriendlyException userFriendlyException,
                                                              Func <Exception, Task> failCallback)
        {
            if (string.IsNullOrEmpty(userFriendlyException.Details))
            {
                dialogService.ShowMessage(Local.Localize("Error"), userFriendlyException.Message);
            }
            else
            {
                dialogService.ShowMessage(userFriendlyException.Message, userFriendlyException.Details);
            }

            await failCallback(userFriendlyException);
        }
コード例 #18
0
        private static async Task HandleUserFriendlyException(UserFriendlyException userFriendlyException,
                                                              Func <System.Exception, Task> failCallback)
        {
            if (string.IsNullOrEmpty(userFriendlyException.Details))
            {
                UserDialogs.Instance.Alert(userFriendlyException.Message, L.Localize("Error"));
            }
            else
            {
                UserDialogs.Instance.Alert(userFriendlyException.Details, userFriendlyException.Message);
            }

            await failCallback(userFriendlyException);
        }
コード例 #19
0
        public void CreateAdmin_Throw_Exception_If_UserName_Is_Null()
        {
            AdminDto admin = new AdminDto
            {
                Email    = "*****@*****.**",
                FullName = "brian2",
                Gender   = true,
                Mobile   = "18817617807",
                Password = "******",
                UserType = (int)UserType.Admin
            };
            UserFriendlyException ex = Should.Throw <UserFriendlyException>(() => _iAdminAppSerice.CreateAdmin(admin));

            (ex != null).ShouldBe(true);
        }
コード例 #20
0
        protected string GetMessageFromException(Exception ex)
        {
            var message = ex switch
            {
                UserFriendlyException e => e.Message,
                AbpIdentityResultException e => e.LocalizeMessage(new LocalizationContext(ServiceProvider))
                .Replace(",", "\n"),
                AbpValidationException e => e.ValidationErrors.Select(error => error.ErrorMessage).JoinAsString("\n"),
                BusinessException e => L[e.Code, ex.Data["Email"]],
                _ => ex.Message
            };

            return(message);
        }
    }
        public static Exception GetExceptionByStatusCode(this RemoteInvokeResultMessage message)
        {
            Exception exception = null;

            switch (message.StatusCode)
            {
            case StatusCode.BusinessError:
                exception = new BusinessException(message.ExceptionMessage);
                break;

            case StatusCode.CommunicationError:
                exception = new CommunicationException(message.ExceptionMessage);
                break;

            case StatusCode.RequestError:
            case StatusCode.CPlatformError:
            case StatusCode.UnKnownError:
                exception = new CPlatformException(message.ExceptionMessage, message.StatusCode);
                break;

            case StatusCode.DataAccessError:
                exception = new DataAccessException(message.ExceptionMessage);
                break;

            case StatusCode.UnAuthentication:
                exception = new UnAuthenticationException(message.ExceptionMessage);
                break;

            case StatusCode.UnAuthorized:
                exception = new UnAuthorizedException(message.ExceptionMessage);
                break;

            case StatusCode.UserFriendly:
                exception = new UserFriendlyException(message.ExceptionMessage);
                break;

            case StatusCode.ValidateError:
                exception = new ValidateException(message.ExceptionMessage);
                break;

            default:
                exception = new CPlatformException(message.ExceptionMessage, message.StatusCode);
                break;
            }

            return(exception);
        }
コード例 #22
0
        public virtual async Task <JsonResult> UpdateSupplierLogo(SupplierLogoUploadModel model)
        {
            JsonResult jsonResult;
            Guid?      logoId;

            try
            {
                if (this.Request.Files.Count <= 0 || this.Request.Files[0] == null)
                {
                    throw new UserFriendlyException(this.L("SupplierLogo_Change_Error"));
                }
                HttpPostedFileBase item = this.Request.Files[0];
                if (item.ContentLength > 512000)
                {
                    throw new UserFriendlyException(this.L("SupplierLogo_Warn_SizeLimit"));
                }
                GetSupplierForEditOutput supplierForEdit = await this._supplierAppService.GetSupplierForEdit(new NullableIdInput <long>(new long?((long)model.SupplierId)));

                GetSupplierForEditOutput nullable = supplierForEdit;
                if (nullable.Supplier.LogoId.HasValue)
                {
                    IBinaryObjectManager binaryObjectManager = this._binaryObjectManager;
                    logoId = nullable.Supplier.LogoId;
                    await binaryObjectManager.DeleteAsync(logoId.Value);
                }
                BinaryObject binaryObject = new BinaryObject(item.InputStream.GetAllBytes());
                await this._binaryObjectManager.SaveAsync(binaryObject);

                nullable.Supplier.LogoId = new Guid?(binaryObject.Id);
                model.Id = nullable.Supplier.LogoId;
                UpdateSupplierLogoInput updateSupplierLogoInput = new UpdateSupplierLogoInput()
                {
                    SupplierId = nullable.Supplier.Id.Value
                };
                logoId = nullable.Supplier.LogoId;
                updateSupplierLogoInput.LogoId = new Guid?(logoId.Value);
                await this._supplierAppService.SaveLogoAsync(updateSupplierLogoInput);

                jsonResult = this.Json(new MvcAjaxResponse());
            }
            catch (UserFriendlyException userFriendlyException1)
            {
                UserFriendlyException userFriendlyException = userFriendlyException1;
                jsonResult = this.Json(new MvcAjaxResponse(new ErrorInfo(userFriendlyException.Message), false));
            }
            return(jsonResult);
        }
コード例 #23
0
ファイル: TitlesController.cs プロジェクト: zberg007/fuelwerx
        public virtual async Task <JsonResult> UpdateTitleImage(long titleId)
        {
            JsonResult jsonResult;
            Guid?      imageId;

            try
            {
                if (this.Request.Files.Count <= 0 || this.Request.Files[0] == null)
                {
                    throw new UserFriendlyException(this.L("TitleImage_Change_Error"));
                }
                HttpPostedFileBase item = this.Request.Files[0];
                if (item.ContentLength > 512000)
                {
                    throw new UserFriendlyException(this.L("TitleImage_Warn_SizeLimit"));
                }
                GetTitleForEditOutput titleForEdit = await this._titleAppService.GetTitleForEdit(new NullableIdInput <long>(new long?(titleId)));

                GetTitleForEditOutput nullable = titleForEdit;
                if (nullable.Title.ImageId.HasValue)
                {
                    IBinaryObjectManager binaryObjectManager = this._binaryObjectManager;
                    imageId = nullable.Title.ImageId;
                    await binaryObjectManager.DeleteAsync(imageId.Value);
                }
                BinaryObject binaryObject = new BinaryObject(item.InputStream.GetAllBytes());
                await this._binaryObjectManager.SaveAsync(binaryObject);

                nullable.Title.ImageId = new Guid?(binaryObject.Id);
                UpdateTitleImageInput updateTitleImageInput = new UpdateTitleImageInput()
                {
                    TitleId = nullable.Title.Id.Value
                };
                imageId = nullable.Title.ImageId;
                updateTitleImageInput.ImageId = new Guid?(imageId.Value);
                await this._titleAppService.SaveTitleImageAsync(updateTitleImageInput);

                jsonResult = this.Json(new MvcAjaxResponse());
            }
            catch (UserFriendlyException userFriendlyException1)
            {
                UserFriendlyException userFriendlyException = userFriendlyException1;
                jsonResult = this.Json(new MvcAjaxResponse(new ErrorInfo(userFriendlyException.Message), false));
            }
            return(jsonResult);
        }
コード例 #24
0
        public async void CreateAdminAsync_Throw_Exception_If_UserName_Already_Exist()
        {
            Admin    adminTemp = UsingDbContext(ctx => ctx.Admin.First());
            AdminDto admin     = new AdminDto
            {
                Email    = "*****@*****.**",
                FullName = "brian2",
                Gender   = true,
                Mobile   = "18817617807",
                Password = "******",
                UserName = adminTemp.UserName,
                UserType = (int)UserType.Admin
            };
            UserFriendlyException ex = await Assert
                                       .ThrowsAsync <UserFriendlyException>(
                () => _iAdminAppSerice.CreateAdminAsync(admin)
                );

            (ex != null).ShouldBe(true);
        }
コード例 #25
0
        private static string GetLoginErrorMessage(int loginErrorCode, UserFriendlyException friendlyException)
        {
            switch (loginErrorCode)
            {
            case (int)AbpLoginResultType.InvalidPassword:
                return($"{"FailedLogin".Translate()}: {"InvalidUserNameOrPassword".Translate()}");

            case (int)AbpLoginResultType.LockedOut:
                return($"{"FailedLogin".Translate()}: {"UserLockedOut".Translate()}");

            case (int)AbpLoginResultType.InvalidUserNameOrEmailAddress:
                return($"{"FailedLogin".Translate()}: {"InvalidUserNameOrEmailAddress".Translate()}");

            case (int)AbpLoginResultType.UserEmailIsNotConfirmed:
                return($"{"FailedLogin".Translate()}: {"UserEmailIsNotConfirmed".Translate()}");

            default:
                return($"{friendlyException.Message}: {friendlyException.Details}");
            }
        }
コード例 #26
0
        public async void CreateAdminAsync_Throw_Exception_If_InstitutionId_Not_Exists()
        {
            AdminDto admin = new AdminDto
            {
                Email         = "*****@*****.**",
                FullName      = "brian2",
                Gender        = true,
                Mobile        = "18817617807",
                Password      = "******",
                UserName      = "******",
                InstitutionId = 100,
                UserType      = (int)UserType.Admin
            };
            UserFriendlyException ex = await Assert
                                       .ThrowsAsync <UserFriendlyException>(
                () => _iAdminAppSerice.CreateAdminAsync(admin)
                );

            (ex != null).ShouldBe(true);
        }
コード例 #27
0
        public override void OnException(ExceptionContext context)
        {
            var originalException    = context.Exception;
            UserFriendlyException ex = null;

            if (originalException is UserFriendlyException)
            {
                ex = originalException as UserFriendlyException;
            }
            else
            {
                ex = new UserFriendlyException(originalException.Message, errorCode: "");
            }

            context.HttpContext.Response.StatusCode = (int)ex.HttpStatus;
            MemoryStream mStrm = new MemoryStream(Encoding.UTF8.GetBytes("出现了错误"));

            context.HttpContext.Response.Body = mStrm;

            base.OnException(context);
        }
コード例 #28
0
        public void CreateAdmin_Throw_Exception_If_UserName_Length_Greater_Then_30()
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < 31; i++)
            {
                sb.Append(i);
            }
            AdminDto admin = new AdminDto
            {
                Email    = "*****@*****.**",
                FullName = "brian2",
                Gender   = true,
                Mobile   = "18817617807",
                UserName = sb.ToString(),
                UserType = (int)UserType.Admin,
                Password = "******"
            };
            UserFriendlyException ex = Should.Throw <UserFriendlyException>(() => _iAdminAppSerice.CreateAdmin(admin));

            (ex != null).ShouldBe(true);
        }
コード例 #29
0
ファイル: ServiceController.cs プロジェクト: goupviet/MiniAbp
 public object GetMethoParam(MethodInfo info, object param)
 {
     if (param is string)
     {
         object paraObject = null;
         try
         {
             paraObject = GetStringObject(info, param.ToString());
         }
         catch (Exception ex)
         {
             var friendlyEx = new UserFriendlyException("{0} 方法的请求参数出错".Fill(info.ToString()));
             friendlyEx.InnerException = ex;
             throw friendlyEx;
         }
         return(paraObject);
     }
     else if (param is FileInput)
     {
         return(GetFileObject(info, param));
     }
     throw new UserFriendlyException("请求的参数类型错误, 目前只支持文件和数据类型");
 }
コード例 #30
0
        public async Task SplitWithExp1InputValid_Test()
        {
            UserFriendlyException result = null;
            var request = new SplitWithExpRequest1()
            {
                OrderId = "18040300110001",
                ProList = new List <Product>()
                {
                    new Product()
                    {
                        ProNo    = "",
                        SkuNo    = "26098951",
                        Quantity = 1,
                        ProName  = "MAMIA婴幼儿奶粉二段900G二段",
                        ProPrice = 100,
                        Weight   = 100,
                        PTId     = "1010703"
                    },
                    new Product()
                    {
                        ProNo    = "",
                        SkuNo    = "26113807",
                        Quantity = 2,
                        ProName  = "MAMIA婴幼儿奶粉三段900G三段",
                        ProPrice = 100,
                        Weight   = 100,
                        PTId     = "1010704"
                    }
                },
                TotalQuantity = 1,
                logistics     = new List <string> {
                    "AOLAU EXPRESS"
                }
            };

            //商品重量不能为0
            request.ProList.ForEach(o => o.Weight = 0);
            result = await Assert.ThrowsAsync <UserFriendlyException>(() => this._splitService.SplitWithOrganization1(request, this._context.GetTenantId()));

            Assert.Equal((int)ResultCode.BadRequest_ParamConstraint, result.Code);
            Assert.Equal("product's weight must more then zero", result.Message);
            //商品价格不能为0
            request.ProList.ForEach(o => { o.ProPrice = 0; o.Weight = 100; });
            result = await Assert.ThrowsAsync <UserFriendlyException>(() => this._splitService.SplitWithOrganization1(request, this._context.GetTenantId()));

            Assert.Equal((int)ResultCode.BadRequest_ParamConstraint, result.Code);
            Assert.Equal("product's price must more then zero", result.Message);
            //商品数量不能为0
            request.ProList.ForEach(o => { o.Quantity = 0; o.ProPrice = 100; });
            result = await Assert.ThrowsAsync <UserFriendlyException>(() => this._splitService.SplitWithOrganization1(request, this._context.GetTenantId()));

            Assert.Equal((int)ResultCode.BadRequest_ParamConstraint, result.Code);
            Assert.Equal("product's quantity must more then zero", result.Message);
            //指定物流商不存在
            request.ProList.ForEach(o => o.Quantity = 1);
            request.logistics = new List <string> {
            };
            result            = await Assert.ThrowsAsync <UserFriendlyException>(() => this._splitService.SplitWithOrganization1(request, this._context.GetTenantId()));

            Assert.Equal((int)ResultCode.BadRequest_ParamConstraint, result.Code);
            Assert.Equal("logistic must more then zero", result.Message);
            request.logistics = new List <string> {
                "123", "1"
            };
            result = await Assert.ThrowsAsync <UserFriendlyException>(() => this._splitService.SplitWithOrganization1(request, this._context.GetTenantId()));

            Assert.Equal((int)ResultCode.BadRequest_ParamConstraint, result.Code);
            Assert.Equal("the following logistics providers do not exist:123,1", result.Message);
            request.ProList.ForEach(o => { o.PTId = "0"; });
            result = await Assert.ThrowsAsync <UserFriendlyException>(() => this._splitService.SplitWithOrganization1(request, this._context.GetTenantId()));

            Assert.Equal((int)ResultCode.BadRequest_ParamConstraint, result.Code);
            Assert.Equal("the following logistics providers do not exist:123,1", result.Message);
            //无效的PTId
            request.logistics = new List <string> {
                "AOLAU EXPRESS"
            };
            result = await Assert.ThrowsAsync <UserFriendlyException>(() => this._splitService.SplitWithOrganization1(request, this._context.GetTenantId()));

            Assert.Equal((int)ResultCode.BadRequest_ParamConstraint, result.Code);
            Assert.Equal("the following ptid no corresponding rules:0", result.Message);
        }
コード例 #31
0
ファイル: ServiceController.cs プロジェクト: rickxie/MiniAbp
 public object GetMethoParam(MethodInfo info, object param)
 {
     if (param is string)
     {
         object paraObject = null;
         try
         {
             paraObject = GetStringObject(info, param.ToString());
         }
         catch (Exception ex)
         {
             var friendlyEx = new UserFriendlyException("{0} 方法的请求参数出错".Fill(info.ToString()));
             friendlyEx.InnerException = ex;
             throw friendlyEx;
         }
         return paraObject;
     }
     else if (param is List<HttpPostedFile>)
     {
         return GetFileObject(info, param);
     }           
     throw new UserFriendlyException("请求的参数类型错误, 目前只支持文件和数据类型");
 }