コード例 #1
0
ファイル: RoomDAL.cs プロジェクト: vuhieu2610/Sorium-API
        public ApiResult <RoomResult> Delete(int RoomId, int UserId = 0)
        {
            ApiResult <RoomResult> rs = new ApiResult <RoomResult>();

            try
            {
                DbProvider.SetCommandText2("sp_Room_delete", CommandType.StoredProcedure);

                DbProvider.AddParameter("RoomId", RoomId, SqlDbType.Int);
                DbProvider.AddParameter("UserId", UserId, SqlDbType.Int);

                DbProvider.AddParameter("ErrorCode", DBNull.Value, SqlDbType.NVarChar, 100, ParameterDirection.Output);
                DbProvider.AddParameter("ReturnMsg", DBNull.Value, SqlDbType.NVarChar, 4000, ParameterDirection.Output);

                DbProvider.ExecuteNonQuery();

                string errorCode = DbProvider.Command.Parameters["ErrorCode"].Value.ToString();

                if (!errorCode.Equals(Constants.SUCCESS))
                {
                    rs.Failed(new ErrorObject()
                    {
                        Code        = DbProvider.Command.Parameters["ErrorCode"].Value.ToString(),
                        Description = DbProvider.Command.Parameters["ReturnMsg"].Value.ToString()
                    });
                }
            }
            catch (Exception ex)
            {
                rs.Failed(new ErrorObject()
                {
                    Code        = Constants.ERR_EXCEPTION,
                    Description = ex.Message
                });
            }

            return(rs);
        }
コード例 #2
0
        public ApiResult <bool> Deactivate(int HotelId, int UserId)
        {
            ApiResult <bool> Rs = new ApiResult <bool>();

            try
            {
                DbProvider.SetCommandText("sp_hotel_deactivate", CommandType.StoredProcedure);
                DbProvider.AddParameter("HotelId", HotelId, SqlDbType.Int);
                DbProvider.AddParameter("UserId", UserId, SqlDbType.Int);

                // Output params
                DbProvider.AddParameter("ErrorCode", DBNull.Value, SqlDbType.NVarChar, 100, ParameterDirection.Output);
                DbProvider.AddParameter("ReturnMsg", DBNull.Value, SqlDbType.NVarChar, 4000, ParameterDirection.Output);

                DbProvider.ExecuteNonQuery();

                // Kiểm tra kết quả trả về
                string errorCode = DbProvider.Command.Parameters["ErrorCode"].Value.ToString();
                if (!errorCode.Equals(Constants.SUCCESS))
                {
                    Rs.Failed(new ErrorObject()
                    {
                        Code        = DbProvider.Command.Parameters["ErrorCode"].Value.ToString(),
                        Description = DbProvider.Command.Parameters["ReturnMsg"].Value.ToString()
                    });
                }
            }
            catch (Exception ex)
            {
                Rs.Failed(new ErrorObject()
                {
                    Code        = Constants.ERR_EXCEPTION,
                    Description = ex.Message
                });
            }

            return(Rs);
        }
コード例 #3
0
        protected async Task <ApiResult <T> > HandleErrorAsync <T>(HttpResponseMessage response)
        {
            try
            {
                var errors = await ParseErrorsAsync(response).ConfigureAwait(false);

                return(ApiResult <T> .Failed(response.StatusCode, errors.ToArray()));
            }
            catch
            { }

            return(ApiResult <T> .Failed(response.StatusCode,
                                         new ApiError { Message = "An unknown error has occured." }));
        }
コード例 #4
0
        public ApiResult <Project> GetProjectById(int?id)
        {
            if (id == null)
            {
                return(ApiResult <Project> .Failed(StatusCode.BadRequest, "The Project Id is empty"));
            }

            var options = new SearchProjectOptions()
            {
                ProjectId = id
            };

            return(ApiResult <Project> .Successful(SearchProjects(options).Data.SingleOrDefault()));
        }
コード例 #5
0
        public ApiResult <Package> GetPackageById(int?id)
        {
            if (id == null)
            {
                return(ApiResult <Package> .Failed(StatusCode.BadRequest, "Null Package Id"));
            }

            var options = new SearchPackageOptions()
            {
                PackageId = id
            };

            return(ApiResult <Package> .Successful(SearchPackage(options).Data.SingleOrDefault()));
        }
コード例 #6
0
        public ApiResult <District> GetByProvinceCode(string ProvinceCode)
        {
            var Rs = new ApiResult <District>();

            try
            {
                DbProvider.SetCommandText2("sp_District_GetByProvinceCode", CommandType.StoredProcedure);
                DbProvider.AddParameter("ProvinceCode", ProvinceCode, SqlDbType.NVarChar);

                DbProvider.AddParameter("ErrorCode", DBNull.Value, SqlDbType.Int, ParameterDirection.Output);
                DbProvider.AddParameter("ReturnMsg", DBNull.Value, SqlDbType.NVarChar, 4000, ParameterDirection.Output);
                DbProvider.AddParameter("TotalRecords", DBNull.Value, SqlDbType.Int, ParameterDirection.Output);

                Rs.DataList     = DbProvider.ExecuteListObject <District>();
                Rs.TotalRecords = Int32.Parse(DbProvider.Command.Parameters["TotalRecords"].Value.ToString());
                string errorCode = DbProvider.Command.Parameters["ErrorCode"].Value.ToString();

                if (!errorCode.Equals(Constants.SUCCESS))
                {
                    Rs.Failed(new ErrorObject()
                    {
                        Code        = DbProvider.Command.Parameters["ErrorCode"].Value.ToString(),
                        Description = DbProvider.Command.Parameters["ReturnMsg"].Value.ToString()
                    });
                }
            }
            catch (Exception ex)
            {
                Rs.Failed(new ErrorObject()
                {
                    Code        = Constants.ERR_EXCEPTION,
                    Description = ex.Message
                });
            }

            return(Rs);
        }
コード例 #7
0
        public ApiResult <ForgetPasswordViewModel> ForgetPassword(ForgetPasswordViewModel model)
        {
            var    dbResult     = new ApiResult <ForgetPasswordViewModel>();
            string errorMessage = string.Empty;

            try
            {
                // Kiểm tra dữ liệu
                var ValidPassword = ValidateForgetPassword(model);
                if (!ValidPassword.Succeeded)
                {
                    return(ValidPassword);
                }

                // Tạo token code và thời gian hết hạn
                string   tokenCode = EncryptCore.Md5Get(DateTime.Now.Ticks + model.Email + EncryptCore.KeyEncrypt);;
                DateTime tokenExp  = DateTime.Now.AddDays(1);

                // Lấy kết quả trả về từ DB
                dbResult = userDAL.ForgetPassword(model, tokenCode, tokenExp);

                // Kiểm tra kết quả
                if (dbResult.Succeeded)
                {
                    // Tạo nội dung của email
                    var otpEmailFormat =
                        new
                    {
                        HoTen = dbResult.Data.FirstName,
                        Link  = model.UrlForm + "?Token=" + tokenCode
                    };
                    var msgEmailOtp = EmailContentHtml.EmailContentFormat(otpEmailFormat, "ResetPassword.html");

                    // Gửi email cho user
                    var emailSendStt = EmailUtility.SendMail(ConfigUtil.Email_DisplayName, model.Email, "Quên mật khẩu", msgEmailOtp);
                }

                return(dbResult);
            }
            catch (Exception ex)
            {
                dbResult.Failed(new ErrorObject()
                {
                    Code        = Constants.ERR_EXCEPTION,
                    Description = ex.Message
                });
                return(dbResult);
            }
        }
コード例 #8
0
        private ApiResult <ForgetPasswordViewModel> ValidateForgetPassword(ForgetPasswordViewModel model)
        {
            var result = new ApiResult <ForgetPasswordViewModel>();

            // Validate dữ liệu input
            if (string.IsNullOrEmpty(model.Email))
            {
                result.Failed(new ErrorObject()
                {
                    Code        = "EMAIL_EMPTY",
                    Description = "Email không được để trống"
                });

                return(result);
            }

            if (!ValidateUtil.ValidateEmail(model.Email))
            {
                result.Failed(new ErrorObject()
                {
                    Code        = "EMAIL_INCORRECT_FORMAT",
                    Description = "Email không đúng định dạng"
                });
            }

            if (string.IsNullOrEmpty(model.UrlForm))
            {
                result.Failed(new ErrorObject()
                {
                    Code        = "UrlForm_EMPTY",
                    Description = "UrlForm không được để trống"
                });
            }

            return(result);
        }
コード例 #9
0
        public ApiResult <IQueryable <Client> > SearchClient(SearchClientOptions options)
        {
            if (options == null)
            {
                return(ApiResult <IQueryable <Client> > .Failed(StatusCode.BadRequest, "Null options"));
            }

            var query = context_
                        .Set <Client>()
                        .AsQueryable();

            if (options.ClientId != null)
            {
                query = query.Where(c => c.ClientId == options.ClientId);
            }

            if (!string.IsNullOrWhiteSpace(options.Firstname))
            {
                query = query.Where(c => c.Firstname == options.Firstname);
            }

            if (!string.IsNullOrWhiteSpace(options.Lastname))
            {
                query = query.Where(c => c.Lastname == options.Lastname);
            }

            if (!string.IsNullOrWhiteSpace(options.Email))
            {
                query = query.Where(c => c.Email == options.Email);
            }

            if (!string.IsNullOrWhiteSpace(options.Phone))
            {
                query = query.Where(c => c.Phone == options.Phone);
            }

            if (options.CreatedFrom != null)
            {
                query = query.Where(c => c.Created >= options.CreatedFrom);
            }

            if (options.CreatedTo != null)
            {
                query = query.Where(c => c.Created < options.CreatedTo);
            }

            return(ApiResult <IQueryable <Client> > .Successful(query.Take(500)));
        }
コード例 #10
0
        public async Task <ApiResult <MailingGroupDto> > Handle(Command request, CancellationToken cancellationToken)
        {
            IdentityUser user = await _context.Users.FirstOrDefaultAsync(x => x.Id == request.UserId, cancellationToken);

            if (user is null)
            {
                return(ApiResult <MailingGroupDto> .Failed("User not found", 404));
            }

            string newName = request.Name.Trim();

            if (string.IsNullOrEmpty(newName))
            {
                return(ApiResult <MailingGroupDto> .Failed("Name is required", 400));
            }

            var updatedGroup = await _context.MailingGroups
                               .Where(x => x.UserId == request.UserId)
                               .Where(x => x.Id == request.Id)
                               .FirstOrDefaultAsync(cancellationToken);

            if (updatedGroup is null)
            {
                return(ApiResult <MailingGroupDto> .Failed("This mailing group is not exist", 404));
            }

            bool nameIsTaken = await _context.MailingGroups
                               .Where(x => x.UserId == request.UserId)
                               .Where(x => x.Id != request.Id)
                               .Where(x => x.Name == newName).AnyAsync(cancellationToken);

            if (nameIsTaken)
            {
                return(ApiResult <MailingGroupDto> .Failed("This mailing group name is already exists", 401));
            }


            updatedGroup.Name = newName;

            _context.Update(updatedGroup);
            await _context.SaveChangesAsync(cancellationToken);

            return(ApiResult <MailingGroupDto> .Success(request));
        }
コード例 #11
0
        public ApiResult <IQueryable <Package> > SearchPackage(SearchPackageOptions options)
        {
            if (options == null)
            {
                return(ApiResult <IQueryable <Package> > .Failed(StatusCode.BadRequest, "Null options"));
            }

            var query = context_
                        .Set <Package>()
                        .AsQueryable();

            if (options.PackageId != null)
            {
                query = query.Where(p => p.PackageId == options.PackageId);
            }

            if (!string.IsNullOrWhiteSpace(options.Description))
            {
                query = query.Where(p => p.Description == options.Description);
            }

            if (options.Reward != null)
            {
                query = query.Where(p => p.Reward == options.Reward);
            }

            if (options.IsActive != null)
            {
                query = query.Where(p => p.IsActive == options.IsActive);
            }

            if (options.CreatedFrom != null)
            {
                query = query.Where(c => c.Created >= (options.CreatedFrom));
            }

            if (options.CreatedTo != null)
            {
                query = query.Where(c => c.Created <= options.CreatedTo);
            }

            return(ApiResult <IQueryable <Package> > .Successful(query.Take(500)));
        }
コード例 #12
0
ファイル: TagDAL.cs プロジェクト: vuhieu2610/Sorium-API
        public ApiResult <Tag> GetAll(int type = 0)
        {
            var result = new ApiResult <Tag>();

            try
            {
                DbProvider.SetCommandText("sp_tags_getall", CommandType.StoredProcedure);
                DbProvider.AddParameter("Type", type, SqlDbType.Int);
                result.DataList = DbProvider.ExecuteListObject <Tag>();
            }
            catch (Exception ex) {
                result.Failed(new ErrorObject {
                    Code        = Constants.ERR_EXCEPTION,
                    Description = ex.ToString()
                });
            }

            return(result);
        }
コード例 #13
0
        public ApiResult <UpdatePasswordViewModel> UpdatePassword(UpdatePasswordViewModel model)
        {
            var result = new ApiResult <UpdatePasswordViewModel>();

            try
            {
                DbProvider.SetCommandText2("sp_User_UpdatePassword", CommandType.StoredProcedure);

                // Input Parameter
                DbProvider.AddParameter("TokenCode", model.TokenCode, SqlDbType.NVarChar);
                DbProvider.AddParameter("NewPassword", model.NewPassword, SqlDbType.NVarChar);

                // Output Parameter
                DbProvider.AddParameter("Email", DBNull.Value, SqlDbType.NVarChar, 255, ParameterDirection.Output);
                DbProvider.AddParameter("ErrorCode", DBNull.Value, SqlDbType.Int, ParameterDirection.Output);
                DbProvider.AddParameter("ReturnMessage", DBNull.Value, SqlDbType.NVarChar, 255, ParameterDirection.Output);

                // Xử lý kết quả trả về
                DbProvider.ExecuteNonQuery();
                string errorCode = DbProvider.Command.Parameters["ErrorCode"].Value.ToString();
                if (!errorCode.Equals(Constants.SUCCESS))
                {
                    result.Failed(new ErrorObject()
                    {
                        Code        = errorCode,
                        Description = DbProvider.Command.Parameters["ReturnMessage"].Value.ToString()
                    });
                }
                else
                {
                    result.Data = new UpdatePasswordViewModel()
                    {
                        Email = DbProvider.Command.Parameters["Email"].Value.ToString()
                    };
                }

                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #14
0
        /// <summary>
        /// 校验验证码是否有效
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task <ApiResult> ValidateCodeAsync(string guid, string code)
        {
            var cacheValue = await _cacheServices.GetAsync(guid);

            if (cacheValue.IsNull())
            {
                return(ApiResult.Failed("验证码无效"));
            }

            if (!cacheValue.Equals(code))
            {
                return(ApiResult.Failed("验证码错误"));
            }
            else
            {
                await _cacheServices.RemoveAsync(guid);

                return(ApiResult.OK());
            }
        }
コード例 #15
0
        public ApiResult <bool> Checkout(int Id)
        {
            ApiResult <bool> Rs = new ApiResult <bool>();

            try
            {
                DbProvider.SetCommandText("sp_order_Checkout", CommandType.StoredProcedure);
                DbProvider.AddParameter("OrderId", Id, SqlDbType.Int);

                DbProvider.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Rs.Failed(new ErrorObject()
                {
                    Code        = Constants.ERR_EXCEPTION,
                    Description = ex.Message
                });
            }
            return(Rs);
        }
コード例 #16
0
ファイル: FileController.cs プロジェクト: lulzzz/file-store
        public async Task <IActionResult> UploadPackage([FromForm] FileUploadInput input)
        {
            if (Request.Form.Files == null || Request.Form.Files.Count == 0)
            {
                return(BadRequest(ApiResult.Failed("未上传有效文件")));
            }

            if (Request.Form.Files.Count > _uploadOption.MaxUpload)
            {
                return(BadRequest(ApiResult.Failed($"超过单次上传数量限制:{_uploadOption.MaxUpload}")));
            }

            if (string.IsNullOrWhiteSpace(input.Extension) &&
                Request.Form.Files.Any(x => string.IsNullOrWhiteSpace(x.FileName) ||
                                       string.IsNullOrWhiteSpace(Path.GetExtension(x.FileName))))
            {
                return(BadRequest(ApiResult.Failed("请手动设置文件扩展名")));
            }

            return(await DecompressionUpload(input));
        }
コード例 #17
0
        public async Task <ApiResult <EmailDto> > Handle(Command request, CancellationToken cancellationToken)
        {
            Model.Entity.MailingGroup mailingGroup = await _context.MailingGroups
                                                     .Include(x => x.Emails)
                                                     .Where(x => x.UserId == request.UserId)
                                                     .Where(x => x.Id == request.GroupId)
                                                     .FirstOrDefaultAsync(cancellationToken);

            if (mailingGroup is null)
            {
                return(ApiResult <EmailDto> .Failed("Mailing group is not exists", 404));
            }

            string newEmail     = request.Email.Trim();
            bool   isValidEmail = EmailValidator.ValidateEmail(newEmail);

            if (!isValidEmail)
            {
                return(ApiResult <EmailDto> .Failed("Email is wrong format", 400));
            }

            if (mailingGroup.Emails.Any(x => x.Name == newEmail))
            {
                return(ApiResult <EmailDto> .Failed("Email is already exists", 409));
            }

            Email email = new Email
            {
                Name           = newEmail,
                MailingGroup   = mailingGroup,
                MailingGroupId = mailingGroup.Id
            };

            await _context.AddAsync(email, cancellationToken);

            await _context.SaveChangesAsync(cancellationToken);

            return(ApiResult <EmailDto> .Success(new EmailDto(email)));
        }
コード例 #18
0
        public async Task <ApiResult <MailingGroupItemListDto> > Handle(Command request, CancellationToken cancellationToken)
        {
            AppUser user = await _context.Users.FirstOrDefaultAsync(x => x.Id == request.UserId, cancellationToken);

            if (user is null)
            {
                return(ApiResult <MailingGroupItemListDto> .Failed("User not found", 404));
            }

            string newName = request.Name.Trim();

            if (string.IsNullOrEmpty(newName))
            {
                return(ApiResult <MailingGroupItemListDto> .Failed("Name is required", 400));
            }

            bool isExist = await _context.MailingGroups
                           .Where(x => x.UserId == request.UserId)
                           .Where(x => x.Name == newName)
                           .AnyAsync(cancellationToken);

            if (isExist)
            {
                return(ApiResult <MailingGroupItemListDto> .Failed("This mailing group is already exists", 409));
            }

            Model.Entity.MailingGroup newEntity = new Model.Entity.MailingGroup
            {
                Name   = newName,
                UserId = request.UserId,
                User   = user
            };

            await _context.AddAsync(newEntity, cancellationToken);

            await _context.SaveChangesAsync(cancellationToken);

            return(ApiResult <MailingGroupItemListDto> .Success(new MailingGroupItemListDto(newEntity)));
        }
コード例 #19
0
        public IHttpActionResult GetUserByTokenCode(string TokenCode = "")
        {
            var        Rs       = new ApiResult <UserResult>();
            UserResult userInfo = CacheUtil.GetCacheObject(TokenCode);

            if (userInfo != null)
            {
                var Rq = userDAL.GetById(userInfo.Id).Data;

                Rs.Data = new UserResult
                {
                    Id             = Rq.Id,
                    Email          = Rq.Email,
                    AccessToken    = TokenCode,
                    Address        = Rq.Address,
                    DistrictCode   = Rq.DistrictCode,
                    EmailConfirmed = Rq.EmailConfirmed,
                    FirstName      = Rq.FirstName,
                    LastName       = Rq.LastName,
                    PhoneNumber    = Rq.PhoneNumber,
                    ProvinceCode   = Rq.ProvinceCode,
                    RoleDesc       = Rq.RoleDesc,
                    RoleId         = Rq.RoleId,
                    UserAvatar     = Rq.UserAvatar
                };

                return(Ok(Rs));
            }
            else
            {
                Rs.Failed(new ErrorObject
                {
                    Code        = "400",
                    Description = "Sai TokenCode"
                });
                return(Content(HttpStatusCode.Unauthorized, Rs));
            }
        }
コード例 #20
0
ファイル: Query.cs プロジェクト: Napeithe/MailingGroup
        public async Task <ApiResult <MailingGroupDto> > Handle(Query request, CancellationToken cancellationToken)
        {
            MailingGroupDto mailingGroupDto = await _context.MailingGroups
                                              .Where(x => x.Id == request.Id)
                                              .Where(x => x.UserId == request.UserId)
                                              .Include(x => x.Emails)
                                              .Select(x => new MailingGroupDto(x.Id, x.Name)
            {
                Emails = x.Emails.Select(e => new EmailDto
                {
                    Name = e.Name,
                    Id   = e.Id
                }).OrderBy(e => e.Name).ToList()
            })
                                              .FirstOrDefaultAsync(cancellationToken);

            if (mailingGroupDto is null)
            {
                return(ApiResult <MailingGroupDto> .Failed("Mail group not exists", 404));
            }

            return(ApiResult <MailingGroupDto> .Success(mailingGroupDto));
        }
コード例 #21
0
        public ApiResult <ForgetPasswordViewModel> ForgetPassword(
            ForgetPasswordViewModel model,
            string tokenCode,
            DateTime tokenExp)
        {
            try
            {
                var result = new ApiResult <ForgetPasswordViewModel>();
                DbProvider.SetCommandText2("sp_User_ForgetPassword", CommandType.StoredProcedure);

                // Input Parameter
                DbProvider.AddParameter("Email", model.Email, SqlDbType.NVarChar);
                DbProvider.AddParameter("TokenCode", tokenCode, SqlDbType.NVarChar);
                DbProvider.AddParameter("TokenExp", tokenExp, SqlDbType.DateTime);

                // Output Parameter
                DbProvider.AddParameter("ErrorCode", DBNull.Value, SqlDbType.NVarChar, 100, ParameterDirection.Output);
                DbProvider.AddParameter("ErrorMessage", DBNull.Value, SqlDbType.NVarChar, 400, ParameterDirection.Output);

                // Xứ lý thủ tục và trả về kết quả
                result.Data = DbProvider.ExecuteObject <ForgetPasswordViewModel>();
                string errorCode = DbProvider.Command.Parameters["ErrorCode"].Value.ToString();
                if (!errorCode.Equals(Constants.SUCCESS))
                {
                    result.Failed(new ErrorObject()
                    {
                        Code        = errorCode,
                        Description = DbProvider.Command.Parameters["ErrorMessage"].Value.ToString()
                    });
                }
                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #22
0
ファイル: FileController.cs プロジェクト: lulzzz/file-store
        public async Task <IActionResult> Download([FromBody] FilesDownloadModel input)
        {
            if (string.IsNullOrEmpty(input.FileName) || !(input.Files?.Count > 0))
            {
                return(BadRequest(ApiResult.Failed("参数无效")));
            }
            if (Regex.IsMatch(input.FileName, @"[\\/:*?""<>|&]"))
            {
                return(BadRequest(ApiResult.Failed("filename含有非法字符")));
            }
            //英文 ? 作为嵌套压缩包的识别,可以有
            //为防止 / \ 路径分隔符在key中不同,但实际为同一个文件的情况,统一使用 / 作为路径分隔符
            if (input.Files.Any(x => string.IsNullOrWhiteSpace(x.Value) ||
                                Regex.IsMatch(x.Key, @"[\\:*""<>|]")))
            {
                return(BadRequest(ApiResult.Failed("files中的文件名含有非法字符")));
            }
            if (input.Files.Any(x => Regex.IsMatch(x.Key, @"\?[^/-/]") || //英文 ? 压缩包作为路径层级,后面必须跟 /
                                Regex.IsMatch(x.Key, @" [?/]") ||         //空格   后面 不能有 ? /
                                Regex.IsMatch(x.Key, @"/[?/ ]") ||       //斜杠 / 后面 不能有 ? / 空格
                                Regex.IsMatch(x.Key, @"^[?/ ]") ||       //首尾        不能有 ? / 空格
                                Regex.IsMatch(x.Key, @"[?/ ]$")))
            {
                return(BadRequest(ApiResult.Failed("files中的文件名含有非法路径")));
            }

            var zipFile = await _fileStorageService.DownloadAsync(input.Files);

            var fileName = input.FileName;

            if (!fileName.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase))
            {
                fileName += ".zip"; //只支持zip压缩
            }

            return(File(System.IO.File.OpenRead(zipFile), "application/zip", fileName));
        }
コード例 #23
0
ファイル: FileController.cs プロジェクト: lulzzz/file-store
        public async Task <IActionResult> Upload([FromForm] FileUploadInput input)
        {
            if (Request.Form.Files == null || Request.Form.Files.Count == 0)
            {
                return(BadRequest(ApiResult.Failed("未上传有效文件")));
            }

            if (Request.Form.Files.Count > _uploadOption.MaxUpload)
            {
                return(BadRequest(ApiResult.Failed($"超过单次上传数量限制:{_uploadOption.MaxUpload}")));
            }

            if (string.IsNullOrWhiteSpace(input.Extension) &&
                Request.Form.Files.Any(x => string.IsNullOrWhiteSpace(x.FileName) ||
                                       string.IsNullOrWhiteSpace(Path.GetExtension(x.FileName))))
            {
                return(BadRequest(ApiResult.Failed("请手动设置文件扩展名")));
            }

            var tasks = Request.Form.Files
                        .Select(file =>
            {
                string ext = null;
                if (!string.IsNullOrWhiteSpace(file.FileName))
                {
                    ext = Path.GetExtension(file.FileName);
                }
                var model = new UploadFileModel(file.OpenReadStream(),
                                                ext ?? input.Extension,
                                                input.Group);
                return(_fileStorageService.UploadAsync(model));
            })
                        .ToArray();
            await Task.WhenAll(tasks);

            return(Json(new ApiResult <List <string> >(tasks.Select(x => x.Result).ToList())));
        }
コード例 #24
0
        public async Task <ApiResult <List <Claim> > > Handle(AuthenticationModel request, CancellationToken cancellationToken)
        {
            AppUser user = await _userManager.Users.Where(x => x.UserName == request.UserName).FirstOrDefaultAsync(cancellationToken);

            if (user is null)
            {
                return(ApiResult <List <Claim> > .Failed("Username or password is invalid", 400));
            }

            var isValidPassword = await _userManager.CheckPasswordAsync(user, request.Password);

            if (!isValidPassword)
            {
                return(ApiResult <List <Claim> > .Failed("Username or password is invalid", 400));
            }

            IList <Claim> claims = await _userManager.GetClaimsAsync(user);

            claims.Add(new Claim(ClaimTypes.Name, user.UserName));
            claims.Add(new Claim("UserName", user.UserName));
            claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id));

            return(ApiResult <List <Claim> > .Success(claims.ToList()));
        }
コード例 #25
0
 protected ApiResult <T> HandledWebException <T>()
 {
     return(ApiResult <T> .Failed(HttpStatusCode.BadGateway,
                                  new ApiError { Message = "There is a problem connecting to the server." }));
 }
コード例 #26
0
 protected ApiResult <T> HandledNotConnected <T>()
 {
     return(ApiResult <T> .Failed(HttpStatusCode.RequestTimeout,
                                  new ApiError { Message = "Not connected to the internet." }));
 }
コード例 #27
0
        public ApiResult <CommentModels> GetPaging(BaseCondition <CommentModels> condition)
        {
            var result = new ApiResult <CommentModels>();

            try
            {
                //Đặt tên cho stored procedures
                DbProvider.SetCommandText2("sp_Comment_GetPaging", CommandType.StoredProcedure);

                // Input params
                DbProvider.AddParameter("StartRow", condition.FromRecord, SqlDbType.Int);
                DbProvider.AddParameter("PageSize", condition.PageSize, SqlDbType.Int);

                // Sắp xếp dữ liệu
                if (!string.IsNullOrEmpty(condition.IN_SORT))
                {
                    DbProvider.AddParameter("IN_SORT", condition.IN_SORT, SqlDbType.NVarChar);
                }

                // Điều kiện tìm kiếm
                if (condition.HasCondition && !string.IsNullOrEmpty(condition.IN_WHERE))
                {
                    DbProvider.AddParameter("IN_WHERE", condition.IN_WHERE, SqlDbType.NVarChar);
                }

                // Output params
                DbProvider.AddParameter("TotalRecords", DBNull.Value, SqlDbType.Int, ParameterDirection.Output);
                DbProvider.AddParameter("ErrorCode", DBNull.Value, SqlDbType.NVarChar, 100, ParameterDirection.Output);
                DbProvider.AddParameter("ReturnMsg", DBNull.Value, SqlDbType.NVarChar, 4000, ParameterDirection.Output);


                result.DataList = DbProvider.ExecuteListObject <CommentModels>();
                try
                {
                    result.TotalRecords = int.Parse(DbProvider.Command.Parameters["TotalRecords"].Value.ToString());
                }
                catch (Exception)
                {
                    result.TotalRecords = 0;
                }

                // Kiểm tra kết quả trả về
                string errorCode = DbProvider.Command.Parameters["ErrorCode"].Value.ToString();
                if (!errorCode.Equals(Constants.SUCCESS))
                {
                    result.Failed(new ErrorObject()
                    {
                        Code        = DbProvider.Command.Parameters["ErrorCode"].Value.ToString(),
                        Description = DbProvider.Command.Parameters["ReturnMsg"].Value.ToString()
                    });
                }
            }
            catch (Exception ex)
            {
                result.Failed(new ErrorObject()
                {
                    Code        = Constants.ERR_EXCEPTION,
                    Description = ex.Message
                });
            }
            return(result);
        }
コード例 #28
0
        public ApiResult <Client> CreateClient(CreateClientOptions options)
        {
            if (options == null)
            {
                return(ApiResult <Client> .Failed(StatusCode.BadRequest, "Null options"));
            }

            if (string.IsNullOrWhiteSpace(options.Firstname))
            {
                return(ApiResult <Client> .Failed(StatusCode.BadRequest, "Firstname is empty"));
            }

            if (string.IsNullOrWhiteSpace(options.Lastname))
            {
                return(ApiResult <Client> .Failed(StatusCode.BadRequest, "Lastname is empty"));
            }

            if (string.IsNullOrWhiteSpace(options.Email))
            {
                return(ApiResult <Client> .Failed(StatusCode.BadRequest, "Email is empty"));
            }

            if (!Client.IsValidEmail(options.Email))
            {
                return(ApiResult <Client> .Failed(StatusCode.BadRequest, "Email not valid"));
            }

            if (string.IsNullOrWhiteSpace(options.Phone))
            {
                return(ApiResult <Client> .Failed(StatusCode.BadRequest, "Phone is empty"));
            }



            var client = new Client()
            {
                Firstname = options.Firstname,
                Lastname  = options.Lastname,
                Email     = options.Email,
                Phone     = options.Phone,
                IsActive  = true
            };

            context_.Add(client);

            try
            {
                var rows = context_.SaveChanges();
                if (rows <= 0)
                {
                    return(ApiResult <Client> .Failed(
                               StatusCode.InternalServerError, "Client could not be created"));
                }
            }
            catch (Exception ex)
            {
                return(ApiResult <Client> .Failed(StatusCode.InternalServerError, ex.ToString()));
            }

            return(ApiResult <Client> .Successful(client));
        }
コード例 #29
0
        public ApiResult <bool> UpdateClient(int?id, UpdateClientOptions options)
        {
            if (options == null)
            {
                return(ApiResult <bool> .Failed(StatusCode.BadRequest, "Null options"));
            }

            if (id == null)
            {
                return(ApiResult <bool> .Failed(StatusCode.BadRequest, "Id is empty"));
            }

            if (!Client.IsValidEmail(options.Email))
            {
                return(ApiResult <bool> .Failed(StatusCode.BadRequest, "Email is not valid"));
            }


            var updateClient = context_
                               .Set <Client>()
                               .Where(c => c.ClientId == id)
                               .SingleOrDefault();

            if (updateClient == null)
            {
                return(ApiResult <bool> .Failed(
                           StatusCode.NotFound, $"Could not retrieve Client with this {id}!"));
            }

            if (options.Firstname != null)
            {
                updateClient.Firstname = options.Firstname;
            }

            if (options.Lastname != null)
            {
                updateClient.Lastname = options.Lastname;
            }

            if (options.Email != null)
            {
                updateClient.Email = options.Email;
            }

            if (options.Phone != null)
            {
                updateClient.Phone = options.Phone;
            }

            if (options.IsActive != null)
            {
                updateClient.IsActive = options.IsActive.Value;
            }


            try
            {
                var rows = context_.SaveChanges();
                if (rows <= 0)
                {
                    return(ApiResult <bool> .Failed(
                               StatusCode.InternalServerError, "Client could not be updated"));
                }
            }
            catch (Exception ex)
            {
                return(ApiResult <bool> .Failed(StatusCode.InternalServerError, ex.ToString()));
            }

            return(ApiResult <bool> .Successful(true));
        }
コード例 #30
0
        public IHttpActionResult UploadAvatar(string UserAvatar = "")
        {
            var Rs = new ApiResult <UserAvatarViewModel>()
            {
                Data = new UserAvatarViewModel()
            };

            var httpRequest = HttpContext.Current.Request;
            var file        = httpRequest.Files["UserAvatar"];

            if (file == null)
            {
                Rs.Failed(new ErrorObject
                {
                    Code        = "FILE_IS_REQUIRED",
                    Description = "File upload not null"
                });
                return(Content(HttpStatusCode.BadRequest, Rs));
            }
            string ImageRegex = ".(image)*"; // Match tất cả các loại file chứa ký tự image

            if (!Regex.IsMatch(file.ContentType, ImageRegex))
            {
                Rs.Failed(new ErrorObject
                {
                    Code        = "FILE_TYPE",
                    Description = "You must upload image file"
                });
                return(Content(HttpStatusCode.BadRequest, Rs));
            }
            //==========================//
            String Dic       = String.Format(ConfigUtil.UserAvatarDirectory, UserInfo.Id);
            var    objUpload = CommonUtil.UploadFile(file, Dic, file.FileName);

            if (objUpload.HasError)
            {
                Rs.Failed(new ErrorObject
                {
                    Code        = objUpload.ErrorCode,
                    Description = objUpload.ErrorMessage
                });
                return(Content(HttpStatusCode.BadRequest, Rs));
            }

            UserAvatarViewModel Item = new UserAvatarViewModel
            {
                ImagePath = objUpload.FilePath
            };

            var Req = userDAL.ChangeAvatar(UserInfo.Id, Item);

            if (Req.Succeeded)
            {
                Rs.Data.ImagePath = ConfigUtil.DomainBaseHttp + Item.ImagePath;
                return(Ok(Rs));
            }
            else
            {
                return(Content(HttpStatusCode.BadRequest, Rs));
            }
        }