public async Task <IActionResult> GetByMaster([FromRoute] int id)
        {
            APIResult apiResult;

            #region 建立查詢物件
            DataRequest dataRequest = new DataRequest()
            {
                Skip   = 0,
                Take   = 0,
                Search = "",
                Sorted = null,
            };
            #endregion

            var records = await WorkingLogDetailService.GetByHeaderIDAsync(id, dataRequest);

            var result = mapper.Map <List <WorkingLogDetailDto> >(records.Result);
            apiResult = APIResultFactory.Build(true, StatusCodes.Status200OK,
                                               ErrorMessageEnum.None, payload: result);
            return(Ok(apiResult));
        }
        public async Task <IActionResult> Put([FromRoute] int id, [FromBody] CRUDDto data)
        {
            APIResult apiResult;

            #region 驗證 DTO 物件的資料一致性
            if (!ModelState.IsValid)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                   "傳送過來的資料有問題", payload: null);
                return(Ok(apiResult));
            }
            #endregion
            #region 更新物件
            await Task.Yield();

            CRUDDto CRUDDto = data;
            #endregion
            apiResult = APIResultFactory.Build(true, StatusCodes.Status202Accepted,
                                               ErrorMessageEnum.None, payload: null);
            return(Ok(apiResult));
        }
        public async Task <IActionResult> Post([FromBody] CRUDDto data)
        {
            APIResult apiResult;

            #region 驗證 DTO 物件的資料一致性
            if (!ModelState.IsValid)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                   "傳送過來的資料有問題", payload: null);
                return(Ok(apiResult));
            }
            #endregion
            #region 新增紀錄
            await Task.Yield();

            data.Id = new Random().Next(1, 99999);
            #endregion
            apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                               ErrorMessageEnum.None, payload: data);
            return(Ok(apiResult));
        }
        public async Task <IActionResult> Get()
        {
            APIResult apiResult;

            #region 建立查詢物件
            DataRequest dataRequest = new DataRequest()
            {
                Skip   = 0,
                Take   = 0,
                Search = "",
                Sorted = null,
            };
            #endregion

            var records = await OnCallPhoneService.GetAsync(dataRequest);

            var result = mapper.Map <List <OnCallPhoneDto> >(records.Result);
            apiResult = APIResultFactory.Build(true, StatusCodes.Status200OK,
                                               ErrorMessageEnum.None, payload: result);
            return(Ok(apiResult));
        }
Esempio n. 5
0
        public async Task <IActionResult> Post(LoginRequestDto loginRequestDTO)
        {
            APIResult apiResult;
            await Task.Yield();

            if (ModelState.IsValid == false)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                   ErrorMessageEnum.傳送過來的資料有問題);
                return(Ok(apiResult));
            }

            (MyUserAdapterModel user, string message) = await myUserService.CheckUser(loginRequestDTO.Account, loginRequestDTO.Password);

            if (user == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.帳號或密碼不正確);
                return(BadRequest(apiResult));
            }

            string token        = GenerateToken(user);
            string refreshToken = GenerateRefreshToken(user);

            LoginResponseDto LoginResponseDTO = new LoginResponseDto()
            {
                Account                = loginRequestDTO.Account,
                Id                     = user.Id,
                Name                   = loginRequestDTO.Account,
                Token                  = token,
                TokenExpireMinutes     = tokenConfiguration.JwtExpireMinutes,
                RefreshToken           = refreshToken,
                RefreshTokenExpireDays = tokenConfiguration.JwtRefreshExpireDays,
            };

            apiResult = APIResultFactory.Build(true, StatusCodes.Status200OK,
                                               ErrorMessageEnum.None, payload: LoginResponseDTO);
            return(Ok(apiResult));
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                string fooErrors = "";
                if (context.ModelState.ErrorCount > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    var           fooConnectChart = $"{Environment.NewLine}";
                    foreach (var item in context.ModelState)
                    {
                        sb.Append(fooConnectChart);
                        sb.Append($"{item.Key} : ");
                        var fooErrorConnectChart = $" ";

                        foreach (var errorItem in item.Value.Errors)
                        {
                            sb.Append(fooErrorConnectChart);
                            if (errorItem.ErrorMessage != null)
                            {
                                sb.Append($"{errorItem.ErrorMessage}");
                            }
                            else
                            {
                                sb.Append($"{errorItem.Exception.Message}");
                            }
                            fooErrorConnectChart = ", ";
                        }
                        fooConnectChart = ", ";
                    }
                    fooErrors = sb.ToString();
                }
                var apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                       ErrorMessageEnum.傳送過來的資料有問題,
                                                       exceptionMessage: fooErrors, replaceExceptionMessage: false);
                context.Result = new BadRequestObjectResult(apiResult);
            }
        }
Esempio n. 7
0
        public async Task <IActionResult> Post(LoginRequestDTO loginRequestDTO)
        {
            var fooUser = await context.LobUsers.Include(x => x.Department).FirstOrDefaultAsync(x => x.Account == loginRequestDTO.Account && x.Password == loginRequestDTO.Password);

            if (fooUser == null)
            {
                APIResult apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                             ErrorMessageEnum.帳號或密碼不正確);
                return(BadRequest(apiResult));
            }
            else
            {
                string token        = GenerateToken(fooUser);
                string refreshToken = GenerateRefreshToken(fooUser);

                LoginResponseDTO LoginResponseDTO = fooUser.ToLoginResponseDTO(
                    token, refreshToken,
                    configuration["Tokens:JwtExpireMinutes"], configuration["Tokens:JwtRefreshExpireDays"]);
                APIResult apiResult = APIResultFactory.Build(true, StatusCodes.Status200OK,
                                                             ErrorMessageEnum.None, payload: LoginResponseDTO);
                return(Ok(apiResult));
            }
        }
Esempio n. 8
0
        public async Task <IActionResult> RefreshToken()
        {
            APIResult apiResult;
            await Task.Yield();

            LoginRequestDto loginRequestDTO = new LoginRequestDto()
            {
                Account = User.FindFirst(ClaimTypes.Sid)?.Value,
            };

            MyUserAdapterModel user = await myUserService.GetAsync(Convert.ToInt32(loginRequestDTO.Account));

            if (user.Id == 0)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status401Unauthorized,
                                                   ErrorMessageEnum.沒有發現指定的該使用者資料);
                return(BadRequest(apiResult));
            }

            string token        = GenerateToken(user);
            string refreshToken = GenerateRefreshToken(user);

            LoginResponseDto LoginResponseDTO = new LoginResponseDto()
            {
                Account                = loginRequestDTO.Account,
                Id                     = 0,
                Name                   = loginRequestDTO.Account,
                Token                  = token,
                TokenExpireMinutes     = tokenConfiguration.JwtExpireMinutes,
                RefreshToken           = refreshToken,
                RefreshTokenExpireDays = tokenConfiguration.JwtRefreshExpireDays,
            };

            apiResult = APIResultFactory.Build(true, StatusCodes.Status200OK,
                                               ErrorMessageEnum.None, payload: LoginResponseDTO);
            return(Ok(apiResult));
        }
Esempio n. 9
0
        public async Task <IActionResult> GetSystemEnvironment()
        {
            SystemEnvironmentResponseDTO SystemEnvironmentResponseDTO = new SystemEnvironmentResponseDTO();
            var fooObject = await _context.SystemEnvironment.FirstAsync();

            if (fooObject != null)
            {
                SystemEnvironmentResponseDTO.Id             = fooObject.Id;
                SystemEnvironmentResponseDTO.AppName        = fooObject.AppName;
                SystemEnvironmentResponseDTO.AndroidVersion = fooObject.AndroidVersion;
                SystemEnvironmentResponseDTO.AndroidUrl     = fooObject.AndroidUrl;
                SystemEnvironmentResponseDTO.iOSVersion     = fooObject.iOSVersion;
                SystemEnvironmentResponseDTO.iOSUrl         = fooObject.iOSUrl;
                APIResult apiResult = APIResultFactory.Build(true, StatusCodes.Status200OK,
                                                             ErrorMessageEnum.None, payload: SystemEnvironmentResponseDTO);
                return(Ok(apiResult));
            }
            else
            {
                APIResult apiResult = APIResultFactory.Build(false, StatusCodes.Status404NotFound,
                                                             ErrorMessageEnum.沒有任何符合資料存在);
                return(NotFound(apiResult));
            }
        }
Esempio n. 10
0
        public async Task <IActionResult> Put([FromRoute] int id, [FromBody] ProductDto data)
        {
            APIResult apiResult;

            #region 驗證 DTO 物件的資料一致性
            if (!ModelState.IsValid)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                   ErrorMessageEnum.傳送過來的資料有問題, payload: data);
                return(Ok(apiResult));
            }
            #endregion

            var record = await ProductService.GetAsync(id);

            if (record != null && record.Id != 0)
            {
                ProductAdapterModel recordTarget = mapper.Map <ProductAdapterModel>(data);
                recordTarget.Id = id;
                var result = mapper.Map <ProductDto>(recordTarget);

                #region 修改記錄前的紀錄完整性檢查
                VerifyRecordResult verify = await ProductService.BeforeUpdateCheckAsync(record);

                if (verify.Success == false)
                {
                    apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                       ErrorMessageMappingHelper.Instance.GetErrorMessage(verify.MessageId),
                                                       payload: result);
                    return(Ok(apiResult));
                }
                #endregion

                var verifyRecordResult = await ProductService.UpdateAsync(recordTarget);

                if (verifyRecordResult.Success)
                {
                    apiResult = APIResultFactory.Build(true, StatusCodes.Status202Accepted,
                                                       ErrorMessageEnum.None, payload: null);
                }
                else
                {
                    if (verifyRecordResult.MessageId == ErrorMessageEnum.客製化文字錯誤訊息)
                    {
                        if (verifyRecordResult.Exception == null)
                        {
                            apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                               verifyRecordResult.Message, payload: result);
                        }
                        else
                        {
                            apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                               verifyRecordResult.Message, payload: result,
                                                               exceptionMessage: verifyRecordResult.Exception.Message,
                                                               replaceExceptionMessage: true);
                        }
                    }
                    else
                    {
                        apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                           verifyRecordResult.MessageId, payload: result);
                    }
                }
            }
            else
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                   ErrorMessageEnum.沒有任何符合資料存在, payload: data);
            }
            return(Ok(apiResult));
        }
Esempio n. 11
0
        public async Task <IActionResult> PutLeaveForm([FromRoute] int id, [FromBody] LeaveFormRequestDTO leaveForm)
        {
            var claimSID = User.FindFirst(JwtRegisteredClaimNames.Sid)?.Value;

            if (claimSID == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.杖中沒有發現指定使用者ID);
                return(BadRequest(apiResult));
            }
            UserID = Convert.ToInt32(claimSID);
            var fooUser = await _context.LobUsers.Include(x => x.Department).FirstOrDefaultAsync(x => x.Id == UserID);

            if (fooUser == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status404NotFound,
                                                   ErrorMessageEnum.沒有發現指定的該使用者資料);
                return(NotFound(apiResult));
            }

            if (!ModelState.IsValid)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.傳送過來的資料有問題, exceptionMessage: $"傳送過來的資料有問題 {ModelState}");
                return(BadRequest(apiResult));
            }

            if (leaveForm.id != id)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.紀錄更新所指定ID不一致);
                return(BadRequest(apiResult));
            }

            var fooLeaveFormType = await _context.LeaveFormTypes.FindAsync(leaveForm.leaveFormType.Id);

            if (fooLeaveFormType == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status404NotFound,
                                                   ErrorMessageEnum.沒有發現指定的請假單類別);
                return(NotFound(apiResult));
            }

            var leaveFormOnDB = await _context.LeaveForms.Include(x => x.LeaveFormType)
                                .Include(x => x.User).ThenInclude(x => x.Department)
                                .FirstOrDefaultAsync(x => x.Id == leaveForm.id);

            if (leaveFormOnDB == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status404NotFound,
                                                   ErrorMessageEnum.沒有發現指定的請假單);
                return(NotFound(apiResult));
            }
            else if (leaveFormOnDB.User.Id != UserID)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.杖Token上標示的使用者與傳送過來的使用者不一致);
                return(BadRequest(apiResult));
            }

            leaveFormOnDB.BeginTime             = leaveForm.BeginTime;
            leaveFormOnDB.Description           = leaveForm.Description;
            leaveFormOnDB.EndTime               = leaveForm.EndTime;
            leaveFormOnDB.TotalHours            = leaveForm.TotalHours;
            leaveFormOnDB.LeaveFormType         = fooLeaveFormType;
            _context.Entry(leaveFormOnDB).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!await LeaveFormExists(leaveForm.id))
                {
                    apiResult = APIResultFactory.Build(false, StatusCodes.Status409Conflict,
                                                       ErrorMessageEnum.要更新的紀錄_發生同時存取衝突_已經不存在資料庫上);
                    return(Conflict(apiResult));
                }
                else
                {
                    apiResult = APIResultFactory.Build(false, StatusCodes.Status409Conflict,
                                                       ErrorMessageEnum.紀錄更新時_發生同時存取衝突);
                    return(Conflict(apiResult));
                }
            }
            catch (Exception ex)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status500InternalServerError,
                                                   Helpers.ErrorMessageEnum.Exception,
                                                   exceptionMessage: $"({ex.GetType().Name}), {ex.Message}{Environment.NewLine}{ex.StackTrace}");
                return(StatusCode(StatusCodes.Status500InternalServerError, apiResult));
            }

            apiResult = APIResultFactory.Build(true, StatusCodes.Status202Accepted,
                                               ErrorMessageEnum.None, payload: leaveForm);
            return(Accepted(apiResult));
        }
Esempio n. 12
0
        public async Task <IActionResult> Get([FromRoute] int invoiceid)
        {
            var claimSID = User.FindFirst(JwtRegisteredClaimNames.Sid)?.Value;

            if (claimSID == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.杖中沒有發現指定使用者ID);
                return(BadRequest(apiResult));
            }
            UserID = Convert.ToInt32(claimSID);
            var fooUser = await _context.LobUsers.Include(x => x.Department).FirstOrDefaultAsync(x => x.Id == UserID);

            if (fooUser == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status404NotFound,
                                                   ErrorMessageEnum.沒有發現指定的該使用者資料);
                return(NotFound(apiResult));
            }

            if (!ModelState.IsValid)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.傳送過來的資料有問題, exceptionMessage: $"傳送過來的資料有問題 {ModelState}");
                return(BadRequest(apiResult));
            }

            var invoiceOnDB = await _context.Invoices
                              .Include(x => x.Details)
                              .FirstOrDefaultAsync(x => x.Id == invoiceid);

            if (invoiceOnDB == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status404NotFound,
                                                   ErrorMessageEnum.沒有發現指定的發票);
                return(NotFound(apiResult));
            }

            List <InvoiceDetailResponseDTO> fooInvoiceDetailResponseDTO = new List <InvoiceDetailResponseDTO>();

            foreach (var item in invoiceOnDB.Details)
            {
                InvoiceDetailResponseDTO fooObject = new InvoiceDetailResponseDTO()
                {
                    Id      = item.Id,
                    Invoice = new InvoiceDTO()
                    {
                        Id = item.Invoice.Id
                    },
                    Cnt         = item.Cnt,
                    Flag        = item.Flag,
                    Memo        = item.Memo,
                    PictureName = item.PictureName,
                    Price       = item.Price,
                    Qty         = item.Qty,
                    SubTotal    = item.SubTotal,
                    TDate       = item.TDate,
                };
                fooInvoiceDetailResponseDTO.Add(fooObject);
            }
            apiResult = APIResultFactory.Build(true, StatusCodes.Status200OK,
                                               ErrorMessageEnum.None, payload: fooInvoiceDetailResponseDTO);
            return(Ok(apiResult));
        }
Esempio n. 13
0
        public async Task <IActionResult> Put([FromRoute] int id, [FromBody] InvoiceDetailRequestDTO invoiceDetailRequestDTO)
        {
            var claimSID = User.FindFirst(JwtRegisteredClaimNames.Sid)?.Value;

            if (claimSID == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.杖中沒有發現指定使用者ID);
                return(BadRequest(apiResult));
            }
            UserID = Convert.ToInt32(claimSID);
            var fooUser = await _context.LobUsers.Include(x => x.Department).FirstOrDefaultAsync(x => x.Id == UserID);

            if (fooUser == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status404NotFound,
                                                   ErrorMessageEnum.沒有發現指定的該使用者資料);
                return(NotFound(apiResult));
            }

            if (!ModelState.IsValid)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.傳送過來的資料有問題, exceptionMessage: $"傳送過來的資料有問題 {ModelState}");
                return(BadRequest(apiResult));
            }

            if (invoiceDetailRequestDTO.Id != id)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.紀錄更新所指定ID不一致);
                return(BadRequest(apiResult));
            }

            var invoiceOnDB = await _context.Invoices
                              .FirstOrDefaultAsync(x => x.Id == invoiceDetailRequestDTO.Invoice.Id);

            if (invoiceOnDB == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status404NotFound,
                                                   ErrorMessageEnum.沒有發現指定的發票);
                return(NotFound(apiResult));
            }

            var invoiceDetailOnDB = await _context.InvoiceDetails
                                    .Include(x => x.Invoice)
                                    .FirstOrDefaultAsync(x => x.Id == invoiceDetailRequestDTO.Id);

            if (invoiceDetailOnDB == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status404NotFound,
                                                   ErrorMessageEnum.沒有發現指定的發票明細項目);
                return(NotFound(apiResult));
            }

            invoiceDetailOnDB.Cnt             = invoiceDetailRequestDTO.Cnt;
            invoiceDetailOnDB.Flag            = invoiceDetailRequestDTO.Flag;
            invoiceDetailOnDB.Memo            = invoiceDetailRequestDTO.Memo;
            invoiceDetailOnDB.PictureName     = invoiceDetailRequestDTO.PictureName;
            invoiceDetailOnDB.Price           = invoiceDetailRequestDTO.Price;
            invoiceDetailOnDB.Qty             = invoiceDetailRequestDTO.Qty;
            invoiceDetailOnDB.SubTotal        = invoiceDetailRequestDTO.SubTotal;
            invoiceDetailOnDB.TDate           = invoiceDetailRequestDTO.TDate;
            _context.Entry(invoiceOnDB).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!await InvoiceDetailExists(invoiceDetailRequestDTO.Id))
                {
                    apiResult = APIResultFactory.Build(false, StatusCodes.Status409Conflict,
                                                       ErrorMessageEnum.要更新的紀錄_發生同時存取衝突_已經不存在資料庫上);
                    return(Conflict(apiResult));
                }
                else
                {
                    apiResult = APIResultFactory.Build(false, StatusCodes.Status409Conflict,
                                                       ErrorMessageEnum.紀錄更新時_發生同時存取衝突);
                    return(Conflict(apiResult));
                }
            }
            catch (Exception ex)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status500InternalServerError,
                                                   Helpers.ErrorMessageEnum.Exception,
                                                   exceptionMessage: $"({ex.GetType().Name}), {ex.Message}{Environment.NewLine}{ex.StackTrace}");
                return(StatusCode(StatusCodes.Status500InternalServerError, apiResult));
            }

            apiResult = APIResultFactory.Build(true, StatusCodes.Status202Accepted,
                                               ErrorMessageEnum.None, payload: invoiceDetailRequestDTO);
            return(Accepted(apiResult));
        }
Esempio n. 14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient <APIResult>();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    RequireExpirationTime    = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = Configuration["Tokens:ValidIssuer"],
                    ValidAudience    = Configuration["Tokens:ValidAudience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:IssuerSigningKey"])),
                };
                options.Events = new JwtBearerEvents()
                {
                    OnChallenge = context =>
                    {
                        return(Task.CompletedTask);
                    },
                    OnMessageReceived = context =>
                    {
                        return(Task.CompletedTask);
                    },
                    OnAuthenticationFailed = context =>
                    {
                        context.NoResult();
                        if (context.Exception != null)
                        {
                            APIResult apiResult;
                            if (context.Exception is SecurityTokenExpiredException)
                            {
                                apiResult = APIResultFactory.Build(false, StatusCodes.Status401Unauthorized,
                                                                   Helpers.ErrorMessageEnum.SecurityTokenExpiredException);
                            }
                            else
                            {
                                apiResult = APIResultFactory.Build(false, StatusCodes.Status401Unauthorized,
                                                                   Helpers.ErrorMessageEnum.Exception,
                                                                   exceptionMessage: $"({context.Exception.GetType().Name}), {context.Exception.Message}");
                            }
                            context.Response.StatusCode  = StatusCodes.Status401Unauthorized;
                            context.Response.ContentType = "application/json";
                            context.Response.WriteAsync(JsonConvert.SerializeObject(apiResult)).Wait();
                        }
                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = context =>
                    {
                        Console.WriteLine("OnTokenValidated: " +
                                          context.SecurityToken);
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddEntityFrameworkSqlite().AddDbContext <LOBDatabaseContext>(options =>
            {
                options.UseSqlite(Configuration.GetConnectionString("MyDatabaseConnection"));
            });

            services.AddMvc(config =>
            {
                config.Filters.Add <ValidateModelAttribute>();
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .ConfigureApiBehaviorOptions(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            });
        }
Esempio n. 15
0
        public async Task <IActionResult> Put([FromRoute] int id, [FromBody] InvoiceRequestDTO invoiceRequestDTO)
        {
            var claimSID = User.FindFirst(JwtRegisteredClaimNames.Sid)?.Value;

            if (claimSID == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.杖中沒有發現指定使用者ID);
                return(BadRequest(apiResult));
            }
            UserID = Convert.ToInt32(claimSID);
            var fooUser = await _context.LobUsers.Include(x => x.Department).FirstOrDefaultAsync(x => x.Id == UserID);

            if (fooUser == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status404NotFound,
                                                   ErrorMessageEnum.沒有發現指定的該使用者資料);
                return(NotFound(apiResult));
            }

            if (!ModelState.IsValid)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.傳送過來的資料有問題, exceptionMessage: $"傳送過來的資料有問題 {ModelState}");
                return(BadRequest(apiResult));
            }

            if (invoiceRequestDTO.Id != id)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.紀錄更新所指定ID不一致);
                return(BadRequest(apiResult));
            }

            var invoiceOnDB = await _context.Invoices
                              .Include(x => x.User).ThenInclude(x => x.Department)
                              .FirstOrDefaultAsync(x => x.Id == invoiceRequestDTO.Id);

            if (invoiceOnDB == null)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status404NotFound,
                                                   ErrorMessageEnum.沒有發現指定的發票);
                return(NotFound(apiResult));
            }
            else if (invoiceOnDB.User.Id != UserID)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.杖Token上標示的使用者與傳送過來的使用者不一致);
                return(BadRequest(apiResult));
            }

            invoiceOnDB.InvoiceNo             = invoiceRequestDTO.InvoiceNo;
            invoiceOnDB.Date                  = invoiceRequestDTO.Date;
            invoiceOnDB.Memo                  = invoiceRequestDTO.Memo;
            _context.Entry(invoiceOnDB).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!await InvoiceExists(invoiceRequestDTO.Id))
                {
                    apiResult = APIResultFactory.Build(false, StatusCodes.Status409Conflict,
                                                       ErrorMessageEnum.要更新的紀錄_發生同時存取衝突_已經不存在資料庫上);
                    return(Conflict(apiResult));
                }
                else
                {
                    apiResult = APIResultFactory.Build(false, StatusCodes.Status409Conflict,
                                                       ErrorMessageEnum.紀錄更新時_發生同時存取衝突);
                    return(Conflict(apiResult));
                }
            }
            catch (Exception ex)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status500InternalServerError,
                                                   Helpers.ErrorMessageEnum.Exception,
                                                   exceptionMessage: $"({ex.GetType().Name}), {ex.Message}{Environment.NewLine}{ex.StackTrace}");
                return(StatusCode(StatusCodes.Status500InternalServerError, apiResult));
            }

            var fooItem = await _context.Invoices.FirstOrDefaultAsync(x => x.Id == invoiceRequestDTO.Id);

            InvoiceResponseDTO invoiceResponseDTO = new InvoiceResponseDTO()
            {
                Id        = fooItem.Id,
                InvoiceNo = fooItem.InvoiceNo,
                Date      = fooItem.Date,
                Memo      = fooItem.Memo,
                user      = new UserDTO()
                {
                    Id = fooUser.Id
                }
            };

            apiResult = APIResultFactory.Build(true, StatusCodes.Status202Accepted,
                                               ErrorMessageEnum.None, payload: invoiceResponseDTO);
            return(Accepted(apiResult));
        }
Esempio n. 16
0
        public async Task <IActionResult> Post([FromBody] OrderMasterDto data)
        {
            APIResult apiResult;

            #region 驗證 DTO 物件的資料一致性
            if (!ModelState.IsValid)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                   ErrorMessageEnum.傳送過來的資料有問題, payload: data);
                return(Ok(apiResult));
            }
            #endregion

            OrderMasterAdapterModel record = mapper.Map <OrderMasterAdapterModel>(data);
            if (record != null)
            {
                var result = mapper.Map <OrderMasterDto>(record);

                #region 新增記錄前的紀錄完整性檢查
                VerifyRecordResult verify = await OrderService.BeforeAddCheckAsync(record);

                if (verify.Success == false)
                {
                    apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                       ErrorMessageMappingHelper.Instance.GetErrorMessage(verify.MessageId),
                                                       payload: result);
                    return(Ok(apiResult));
                }
                #endregion

                var verifyRecordResult = await OrderService.AddAsync(record);

                if (verifyRecordResult.Success)
                {
                    apiResult = APIResultFactory.Build(true, StatusCodes.Status201Created,
                                                       ErrorMessageEnum.None, payload: null);
                }
                else
                {
                    if (verifyRecordResult.MessageId == ErrorMessageEnum.客製化文字錯誤訊息)
                    {
                        if (verifyRecordResult.Exception == null)
                        {
                            apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                               verifyRecordResult.Message, payload: result);
                        }
                        else
                        {
                            apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                               verifyRecordResult.Message, payload: result,
                                                               exceptionMessage: verifyRecordResult.Exception.Message,
                                                               replaceExceptionMessage: true);
                        }
                    }
                    else
                    {
                        apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                           verifyRecordResult.MessageId, payload: result);
                    }
                }
            }
            else
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK,
                                                   ErrorMessageEnum.傳送過來的資料有問題, payload: data);
            }
            return(Ok(apiResult));
        }
Esempio n. 17
0
        public async Task <IActionResult> Post(IFormFile file, [FromServices] IHostingEnvironment env)
        {
            //var claimSID = User.FindFirst(JwtRegisteredClaimNames.Sid)?.Value;
            //if (claimSID == null)
            //{
            //    apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
            //     ErrorMessageEnum.權杖中沒有發現指定使用者ID);
            //    return BadRequest(apiResult);
            //}
            //UserID = Convert.ToInt32(claimSID);
            //var fooUser = await _context.LobUsers.Include(x => x.Department).FirstOrDefaultAsync(x => x.Id == UserID);
            //if (fooUser == null)
            //{
            //    apiResult = APIResultFactory.Build(false, StatusCodes.Status404NotFound,
            //     ErrorMessageEnum.沒有發現指定的該使用者資料);
            //    return NotFound(apiResult);
            //}

            if (!ModelState.IsValid)
            {
                apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest,
                                                   ErrorMessageEnum.傳送過來的資料有問題, exceptionMessage: $"傳送過來的資料有問題 {ModelState}");
                return(BadRequest(apiResult));
            }

            string webRootPath = env.WebRootPath;

            if (string.IsNullOrWhiteSpace(webRootPath))
            {
                webRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
            }
            string workPath = Path.Combine(webRootPath, "Images");

            if (Directory.Exists(workPath) == false)
            {
                Directory.CreateDirectory(workPath);
            }
            string fileName = Path.Combine(workPath, file.FileName);

            using (FileStream fs = System.IO.File.Create(fileName))
            {
                file.CopyTo(fs);
                fs.Flush();
            }

            UriHelper.GetDisplayUrl(Request);
            var foo = Request.GetDisplayUrl();

            var bar = $"{Request.Scheme}://{Request.Host}/Images/{file.FileName}";


            //try
            //{
            //    await _context.SaveChangesAsync();
            //}
            //catch (Exception ex)
            //{
            //    apiResult = APIResultFactory.Build(false, StatusCodes.Status500InternalServerError,
            //        Helpers.ErrorMessageEnum.Exception,
            //        exceptionMessage: $"({ex.GetType().Name}), {ex.Message}{Environment.NewLine}{ex.StackTrace}");
            //    return StatusCode(StatusCodes.Status500InternalServerError, apiResult);
            //}

            apiResult = APIResultFactory.Build(true, StatusCodes.Status202Accepted,
                                               ErrorMessageEnum.None, payload: new UploadImageResponseDTO()
            {
                ImageUrl = bar
            });
            return(Accepted(apiResult));
        }