Пример #1
0
        public object ChangeStatus(ChangeStatus model)
        {
            ResponseDetails responseDetails = new ResponseDetails();

            try
            {
                BugViewModel bug = bugService.Get(model.Id);
                bug.StatusId = model.StatusId;

                if (model.StatusId == 2004)
                {
                    // if you are changing bug status to open => we need to change project status to under development
                    ProjectViewModel project = projectService.Get(bug.ProjectId);
                    project.ProjectStatusId = 1004;
                    projectService.Update(project);
                }
                else if (model.StatusId == 2005)
                {
                    // if you are changing bug status to Fixed => we need to change project status to under finished
                    ProjectViewModel project = projectService.Get(bug.ProjectId);
                    project.ProjectStatusId = 1007;
                    projectService.Update(project);
                }

                bugService.Update(bug);

                responseDetails = Helper.SetResponseDetails("Bug status updated successfully.", true, null, MessageType.Success);
            }
            catch (Exception ex)
            {
                responseDetails = Helper.SetResponseDetails("Exception encountered : " + ex.Message, false, ex, MessageType.Error);
            }

            return(responseDetails);
        }
        public ResponseDetails <T, ulong> PullMessage <T>(IModel channel)
        {
            var response = new ResponseDetails <T, ulong>();

            try
            {
                _logger.LogInformation("Pull Message From Service Bus Is Starting");

                var data = channel.BasicGet(queueName, false);
                if (data == null)
                {
                    _logger.LogInformation("No Messages Exist");
                    response.StatusCode = CommonEnums.ResponseStatusCode.NotFound;
                    return(response);
                }
                var message = Encoding.UTF8.GetString(data.Body);
                var command = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(message);
                response.DetailsObject       = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(message);
                response.StatusCode          = CommonEnums.ResponseStatusCode.Success;
                response.SecondDetailsObject = data.DeliveryTag;
                _logger.LogInformation("Pull Message From Service Bus Is Completed");
                return(response);
            }
            catch (Exception ex)
            {
                response = new ResponseDetails <T, ulong>(ex);
                return(response);
            }
        }
Пример #3
0
        public IActionResult Register(UserViewModel model)
        {
            if (ModelState.IsValid)
            {
                // Remove hardcoded role Id in future
                model.RoleId = 4;

                ResponseDetails response = _apiHelper.SendApiRequest(model, "auth/register", HttpMethod.Post);

                if (response.Success)
                {
                    HttpContext.Session.SetString("token", response.Data.ToString());
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("", response.Data.ToString());
                }
            }
            else
            {
                ModelState.AddModelError("", "Validation error.");
            }

            return(View(model));
        }
Пример #4
0
        public IActionResult Receipt(string id)
        {
            int newId = _dataProtector.Unprotect(id);

            ResponseDetails response = _apiHelper.SendApiRequest("", "booking/get/" + newId, HttpMethod.Get);

            if (response.Success)
            {
                BookingViewModel model = JsonConvert.DeserializeObject <BookingViewModel>
                                             (response.Data.ToString());

                _dataProtector.ProtectBookingRouteValues(model);

                return(View(model));
            }
            else
            {
                ErrorViewModel model = new ErrorViewModel
                {
                    Message = response.Data.ToString()
                };

                return(View("Error", model));
            }
        }
Пример #5
0
        private void CompareErrors(DataServiceContextWrapper <DefaultContainer>[] contexts, Action <DataServiceContextWrapper <DefaultContainer> > test)
        {
            Debug.Assert(contexts.Length == 2);

            var results = new ResponseDetails[2];
            int i       = 0;

            foreach (var context in contexts)
            {
                var responseDetails = new ResponseDetails();

                try
                {
                    test(context);
                }
                catch (Exception ex)
                {
                    responseDetails.Exception = ex;
                }

                Assert.IsNotNull(responseDetails.Exception, "Expected exception but none was thrown");
                responseDetails.StatusCode = this.lastResponseStatusCode;
                results[i++] = responseDetails;
            }

            Assert.AreEqual(results[0].StatusCode, results[1].StatusCode);
            AssertExceptionsAreEqual(results[0].Exception, results[1].Exception);
        }
        public IActionResult Images(string id)
        {
            int newId = _dataProtector.Unprotect(id);

            ResponseDetails response = _apiHelper.SendApiRequest("", "parkingLot/all-images/" + newId, HttpMethod.Get);

            if (response.Success)
            {
                List <string> model = JsonConvert.DeserializeObject <List <string> > (response.Data.ToString());

                ParkingImageModel ImageModel = new ParkingImageModel()
                {
                    ParkingLotId = newId,
                    Images       = model
                };

                return(View(ImageModel));
            }
            else
            {
                ErrorViewModel model = new ErrorViewModel
                {
                    Message = response.Data.ToString()
                };

                return(View("Error", model));
            }
        }
        public IActionResult UploadImage(ParkingImageModel model)
        {
            if (ModelState.IsValid)
            {
                string base64EncodedImage = ImageProcessing.ProcessIFormFile(model.Image);

                UploadLotImageModel dataModel = new UploadLotImageModel
                {
                    Image        = base64EncodedImage,
                    ImageName    = model.Image.FileName,
                    ParkingLotId = model.ParkingLotId
                };

                ResponseDetails response = _apiHelper.SendApiRequest(dataModel, "parkingLot/upload-image", HttpMethod.Post);

                if (response.Success)
                {
                    return(RedirectToAction("Images", new { id = _dataProtector.Protect(model.ParkingLotId) }));
                }
                else
                {
                    ErrorViewModel errorModel = new ErrorViewModel
                    {
                        Message = response.Data.ToString()
                    };

                    return(View("Error", errorModel));
                }
            }

            ModelState.AddModelError("", "Validation Error.");
            return(View(model));
        }
        public IActionResult Details(string id)
        {
            int newId = _dataProtector.Unprotect(id);

            ResponseDetails response = _apiHelper.SendApiRequest("", "parkinglot/get/" + newId, HttpMethod.Get);

            if (response.Success)
            {
                ParkingLotViewModel model = JsonConvert.DeserializeObject <ParkingLotViewModel> (response.Data.ToString());

                model = CalculateHourlyRate(model);
                _dataProtector.ProtectParkingLotRouteValues(model);

                return(View(model));
            }
            else
            {
                ErrorViewModel model = new ErrorViewModel
                {
                    Message = response.Data.ToString()
                };

                return(View("Error", model));
            }
        }
        public IActionResult Update(ParkingLotViewModel model)
        {
            if (ModelState.IsValid)
            {
                ResponseDetails response = _apiHelper.SendApiRequest(model, "parkinglot/update", HttpMethod.Post);

                if (response.Success)
                {
                    return(RedirectToAction("Details", new { id = _dataProtector.Protect(model.Id) }));
                }
                else
                {
                    ErrorViewModel errorModel = new ErrorViewModel
                    {
                        Message = response.Data.ToString()
                    };

                    return(View("Error", errorModel));
                }
            }
            else
            {
                ModelState.AddModelError("Error", "Validation Error");
                return(View(model));
            }
        }
Пример #10
0
        public IActionResult ParkingLot(string id)
        {
            int newId = _dataProtector.Unprotect(id);

            ResponseDetails response = _apiHelper.SendApiRequest("", "parkinglot/get/" + newId, HttpMethod.Get);

            if (response.Success)
            {
                ParkingLotViewModel model = JsonConvert.DeserializeObject <ParkingLotViewModel>
                                                (response.Data.ToString());

                _dataProtector.ProtectParkingLotRouteValues(model);

                model.SlotViewModels = model.SlotViewModels.Select(x =>
                {
                    // populate can book property logic
                    x.CanBook = CanBookSlot(x);

                    _dataProtector.ProtectSlotRouteValues(x);

                    return(x);
                }).ToList();

                return(View(model));
            }
            else
            {
                ErrorViewModel model = new ErrorViewModel
                {
                    Message = response.Data.ToString()
                };

                return(View("Error", model));
            }
        }
Пример #11
0
        public IActionResult ConfirmEmail()
        {
            ResponseDetails response = _apiHelper.SendApiRequest("", "user/get/" + _tokenDecoder.UserId, HttpMethod.Get);

            if (response.Success)
            {
                UserViewModel userModel = JsonConvert.DeserializeObject <UserViewModel> (response.Data.ToString());

                string encryptedOTP = _mailSender.GanerateAndSendOTP(userModel.Email);

                HttpContext.Session.SetString("OTP", encryptedOTP);

                ConfirmEmailModel model = new ConfirmEmailModel()
                {
                    Id    = userModel.Id,
                    Email = userModel.Email
                };

                return(View(model));
            }
            else
            {
                ErrorViewModel errorModel = new ErrorViewModel()
                {
                    Message = response.Data.ToString()
                };

                return(View("Error", errorModel));
            }
        }
Пример #12
0
 public AppointmentModel()
 {
     //availabiltyModel = new AvailableRequestDetails();
     //availabiltyResponseModel = new AvailableResponseDetails();
     availabiltyModel         = new RequestDetails();
     availabiltyResponseModel = new ResponseDetails();
     //   Visitcodes =  new List<SelectListItem>();
 }
Пример #13
0
        public IActionResult Confirm(ConfirmBookingModel model)
        {
            if (ModelState.IsValid)
            {
                string VehicalNumber = model.StateCode + "-" + model.DistrictCode
                                       + "-" + model.SeriesCode + " " + model.Number;

                model.StartDate = model.StartDate.AddHours(model.StartHour).AddMinutes(model.StartMinute);

                if ((DateTime.Now.Subtract(model.StartDate).TotalMinutes) > 0)
                {
                    ModelState.AddModelError("", "Booking time must be after current moment.");

                    return(View(model));
                }

                DateTime EndDate = model.StartDate.AddHours(model.DurationHour).AddMinutes(model.DurationMinute);

                BookingViewModel bookingModel = new BookingViewModel()
                {
                    CustomerId    = model.UserId,
                    SlotId        = model.SlotId,
                    StartDateTime = model.StartDate,
                    EndDateTime   = EndDate,
                    VehicleNumber = VehicalNumber,
                    IsActive      = true,
                    IsConfirmed   = false,
                    Amount        = Convert.ToInt32((EndDate - model.StartDate).TotalHours * model.HourlyRate)
                };

                ResponseDetails response = _apiHelper.SendApiRequest(bookingModel, "booking/add", HttpMethod.Post);

                if (response.Success)
                {
                    bookingModel = JsonConvert.DeserializeObject <BookingViewModel>
                                       (response.Data.ToString());

                    _dataProtector.ProtectBookingRouteValues(bookingModel);

                    return(RedirectToAction("Payment", new { id = _dataProtector.Protect(bookingModel.Id) }));
                }
                else
                {
                    ErrorViewModel errorModel = new ErrorViewModel
                    {
                        Message = response.Data.ToString()
                    };

                    return(View("Error", errorModel));
                }
            }
            else
            {
                ModelState.AddModelError("", "Validation error");
                return(View(model));
            }
        }
Пример #14
0
        public async Task <IActionResult> UpdateAvatar([FromBody] UpdateUserAvatarDto updateUserAvatarDto)
        {
            try
            {
                var apiKeyAuthenticate = APICredentialAuth.APIKeyCheck(Request.Headers[NamePars.APIKeyStr]);

                if (apiKeyAuthenticate.StatusCode == ResponseCode.Error)
                {
                    return(BadRequest(new ResponseDetails()
                    {
                        StatusCode = ResponseCode.Exception, Message = apiKeyAuthenticate.Message
                    }));
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest("Các trường dữ liệu nhập vào chưa chính xác!"));
                }

                if (updateUserAvatarDto.HinhAnh == "")
                {
                    return(BadRequest("Hình ảnh không được để trống!"));
                }

                var userRepo = await _repository.User.GetUserByIDAsync(updateUserAvatarDto.UserID);

                if (userRepo == null)
                {
                    return(BadRequest("Tài khoản không tồn tại!"));
                }

                //Ta cập nhật lại bảng user nhưng chỉ với trường dữ liệu là HinhAnh
                ResponseDetails response = _repository.User.UpdateUser(new User()
                {
                    UserID                 = userRepo.UserID,
                    ApplicationUserID      = userRepo.ApplicationUserID,
                    Quyen                  = userRepo.Quyen,
                    TinhTrang              = userRepo.TinhTrang,
                    HinhAnh                = updateUserAvatarDto.HinhAnh,
                    RefreshToken           = userRepo.RefreshToken,
                    RefreshTokenExpiryTime = userRepo.RefreshTokenExpiryTime,
                    UserName               = userRepo.UserName
                });

                if (response.StatusCode == ResponseCode.Success)
                {
                    _repository.Save();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Lỗi khi cập nhật avatar cho user với id {updateUserAvatarDto.UserID}: ${ex}");
            }

            return(Ok());
        }
Пример #15
0
        public async void Delete_InvalidId400_Test(string id)
        {
            // 1: Call DELETE Action passing id of establishment to be deleted
            var query = await establishmentsController.Delete(id);

            ResponseDetails result = (ResponseDetails)query.Result.GetType().GetProperty("Value").GetValue(query.Result);

            Assert.Equal(400, result.StatusCode);
            Assert.Equal(controllerMessages.IncorretIdFormat, result.Message);
        }
Пример #16
0
        public IActionResult Index()
        {
            ResponseDetails response = _apiHelper.SendApiRequest("", "role/get-all", HttpMethod.Get);

            List <RoleViewModel> model = JsonConvert.DeserializeObject <List <RoleViewModel> > (response.Data.ToString());

            _dataProtector.ProtectRoleRouteValues(model);

            return(View(model));
        }
Пример #17
0
        /// <summary>
        ///  Validates the document during briefcase operations. Returns not supported message if the document in operation is not relevant to Matter Center.
        /// </summary>
        /// <param name="sourceURL">List of File names</param>
        /// <returns>Returns response for not supported files</returns>
        internal static string GetNotSupportedMessage(List <string> sourceURL)
        {
            string          response        = string.Empty;
            ResponseDetails responseDetails = new ResponseDetails();

            responseDetails.Status    = ConstantStrings.FALSE;
            responseDetails.FileNames = sourceURL;
            response = new JavaScriptSerializer().Serialize(responseDetails);
            return(response);
        }
        public IActionResult Add(AddParkingLotModel model)
        {
            if (ModelState.IsValid)
            {
                ParkingLotViewModel lot = new ParkingLotViewModel()
                {
                    Name             = model.Name,
                    IsActive         = true,
                    IsAproved        = false,
                    OwnerId          = _tokenDecoder.UserId,
                    AddressViewModel = model.AddressViewModel
                };

                for (int i = 0; i < model.NoOf2WheelSlot; i++)
                {
                    lot.SlotViewModels.Add(new SlotViewModel()
                    {
                        IsBooked   = false,
                        SlotTypeId = 1,
                        HourlyRate = model.TwoWheelerHourlyRate
                    });
                }

                for (int i = 0; i < model.NoOf4WheelSlot; i++)
                {
                    lot.SlotViewModels.Add(new SlotViewModel()
                    {
                        IsBooked   = false,
                        SlotTypeId = 2,
                        HourlyRate = model.FourWheelerHourlyRate
                    });
                }

                ResponseDetails response = _apiHelper.SendApiRequest(lot, "parkinglot/add", HttpMethod.Post);

                if (response.Success)
                {
                    return(RedirectToAction("Dashboard"));
                }
                else
                {
                    ErrorViewModel errorModel = new ErrorViewModel
                    {
                        Message = response.Data.ToString()
                    };

                    return(View("Error", errorModel));
                }
            }
            else
            {
                ModelState.AddModelError("Error", "Validation Error");
                return(View(model));
            }
        }
Пример #19
0
        public IActionResult CreateTacGia([FromBody] IEnumerable <TacGiaForCreationDto> tacGia)
        {
            try
            {
                var apiKeyAuthenticate = APICredentialAuth.APIKeyCheck(Request.Headers[NamePars.APIKeyStr]);

                if (apiKeyAuthenticate.StatusCode == ResponseCode.Error)
                {
                    return(BadRequest(new ResponseDetails()
                    {
                        StatusCode = ResponseCode.Exception, Message = apiKeyAuthenticate.Message
                    }));
                }

                if (tacGia == null)
                {
                    return(NotFound(new ResponseDetails()
                    {
                        StatusCode = ResponseCode.Error, Message = "Thông tin trống"
                    }));
                }

                if (!ModelState.IsValid)
                {
                    return(NotFound(new ResponseDetails()
                    {
                        StatusCode = ResponseCode.Error, Message = "Các trường dữ liệu chưa đúng"
                    }));
                }

                var tacGiaEntity = _mapper.Map <IEnumerable <TacGia> >(tacGia);

                ResponseDetails response = _repository.TacGia.CreateTacGia(tacGiaEntity);
                if (response.StatusCode == ResponseCode.Success)
                {
                    _repository.Save();
                }
                else
                {
                    return(BadRequest(response));
                }

                var createdTacGia = _mapper.Map <IEnumerable <TacGiaDto> >(tacGiaEntity);

                return(Ok(createdTacGia));
            }
            catch (Exception ex)
            {
                _logger.LogError("Gặp lỗi khi tạo mới tác giả: " + ex);
                return(BadRequest(new ResponseDetails()
                {
                    StatusCode = ResponseCode.Exception, Message = "Lỗi execption ở hàm CreateTacGia"
                }));
            }
        }
Пример #20
0
        public async Task <IActionResult> UpdateTheLoai(int id, [FromBody] TheLoaiForUpdateDto theLoai)
        {
            try
            {
                var apiKeyAuthenticate = APICredentialAuth.APIKeyCheck(Request.Headers[NamePars.APIKeyStr]);

                if (apiKeyAuthenticate.StatusCode == ResponseCode.Error)
                {
                    return(BadRequest(new ResponseDetails()
                    {
                        StatusCode = ResponseCode.Exception, Message = apiKeyAuthenticate.Message
                    }));
                }

                if (theLoai == null)
                {
                    return(BadRequest("TheLoai object is null"));
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest("Invalid model object"));
                }

                var theLoaiEntity = await _repository.TheLoai.GetTheLoaiByIdAsync(id);

                if (theLoaiEntity == null)
                {
                    return(NotFound());
                }

                _mapper.Map(theLoai, theLoaiEntity);

                ResponseDetails response = _repository.TheLoai.UpdateTheLoai(theLoaiEntity);

                if (response.StatusCode == ResponseCode.Success)
                {
                    _repository.Save();
                }
                else
                {
                    return(BadRequest(response));
                }

                return(Ok(response));
            }
            catch (Exception ex)
            {
                _logger.LogError("Gặp lỗi khi cập nhật thể loại có ID " + id + ": " + ex);
                return(BadRequest(new ResponseDetails()
                {
                    StatusCode = ResponseCode.Exception, Message = "Lỗi execption ở hàm UpdateTheLoai"
                }));
            }
        }
Пример #21
0
        public async Task <IActionResult> LoginVerification([FromBody] TwoFactorDto twoFactorDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var userApp = await _userManager.FindByEmailAsync(twoFactorDto.Email);

            if (userApp == null)
            {
                return(BadRequest(new AuthResponseDto {
                    Message = "Tài khoản không tồn tại!"
                }));
            }

            var validVerification = await _userManager.VerifyTwoFactorTokenAsync(userApp, twoFactorDto.Provider, twoFactorDto.Token);

            if (!validVerification)
            {
                return(BadRequest(new AuthResponseDto {
                    Message = "Token để xác thực đăng nhập không hợp lệ!"
                }));
            }

            var user = await _repository.User.GetUserByApplicationUserIDAsync(userApp.Id);

            var claims = await _jwtHandler.GenerateClaims(userApp, user);

            await _userManager.ResetAccessFailedCountAsync(userApp);

            var accessToken  = _tokenService.GenerateAccessToken(claims, _config);
            var refreshToken = _tokenService.GenerateRefreshToken();

            ResponseDetails response = _repository.User.UpdateUserRefreshToken(
                user,
                refreshToken,
                DateTime.Now.AddMinutes(Convert.ToDouble(_config[$"{NamePars.JwtSettings}:{NamePars.ExpireTime}"]))
                );

            if (response.StatusCode == ResponseCode.Success)
            {
                _repository.Save();
            }
            else
            {
                _logger.LogError($"Lỗi khi cấp refresh token khi xác thực đăng nhập cho user với id {user.UserID}");
            }

            return(Ok(new
            {
                Token = accessToken,
                RefreshToken = refreshToken
            }));
        }
Пример #22
0
        public IActionResult UpdatePhuLuc([FromBody] IEnumerable <PhuLucForUpdateDto> phuLuc)
        {
            try
            {
                var apiKeyAuthenticate = APICredentialAuth.APIKeyCheck(Request.Headers[NamePars.APIKeyStr]);

                if (apiKeyAuthenticate.StatusCode == ResponseCode.Error)
                {
                    return(BadRequest(new ResponseDetails()
                    {
                        StatusCode = ResponseCode.Exception, Message = apiKeyAuthenticate.Message
                    }));
                }

                if (phuLuc == null)
                {
                    return(NotFound(new ResponseDetails()
                    {
                        StatusCode = ResponseCode.Error, Message = "Thông tin trống"
                    }));
                }

                if (!ModelState.IsValid)
                {
                    return(NotFound(new ResponseDetails()
                    {
                        StatusCode = ResponseCode.Error, Message = "Các trường dữ liệu chưa đúng"
                    }));
                }

                var phuLucsResult = _mapper.Map <IEnumerable <PhuLuc> >(phuLuc);

                ResponseDetails response = _repository.PhuLuc.UpdatePhuLuc(phuLucsResult);

                if (response.StatusCode == ResponseCode.Success)
                {
                    _repository.Save();
                }
                else
                {
                    return(BadRequest(response));
                }

                return(Ok(response));
            }
            catch (Exception ex)
            {
                _logger.LogError("Gặp lỗi khi cập nhật danh sách phụ lục của truyện: " + ex);
                return(BadRequest(new ResponseDetails()
                {
                    StatusCode = ResponseCode.Exception, Message = "Lỗi execption ở hàm UpdatePhuLuc"
                }));
            }
        }
        public IActionResult List(string query)
        {
            ResponseDetails response = _apiHelper.SendApiRequest("", "home/search/" + query, HttpMethod.Get);

            List <ParkingLotViewModel> model = JsonConvert.DeserializeObject <List <ParkingLotViewModel> > (response.Data.ToString());

            model = CalculateHourlyRate(model);
            _dataProtector.ProtectParkingLotRouteValues(model);

            return(View(model));
        }
Пример #24
0
        public IActionResult AddAdmin()
        {
            ResponseDetails response = _apiHelper.SendApiRequest("", "role/get-all", HttpMethod.Get);

            AddAdminModel model = new AddAdminModel()
            {
                Roles = JsonConvert.DeserializeObject <List <RoleViewModel> > (response.Data.ToString())
            };

            return(View(model));
        }
Пример #25
0
        public async Task <IActionResult> Revoke(TokenApiModel tokenApiModel)
        {
            var apiKeyAuthenticate = APICredentialAuth.APIKeyCheck(Request.Headers[NamePars.APIKeyStr]);

            if (apiKeyAuthenticate.StatusCode == ResponseCode.Error)
            {
                return(BadRequest(new ResponseDetails()
                {
                    StatusCode = ResponseCode.Exception, Message = apiKeyAuthenticate.Message
                }));
            }

            if (tokenApiModel is null)
            {
                return(BadRequest(new ResponseDetails()
                {
                    Message = "Token body truyền vào không hợp lệ", StatusCode = ResponseCode.Error
                }));
            }
            var principal = _tokenService.GetPrincipalFromExpiredToken(tokenApiModel.AccessToken, _config);

            if (principal == null)
            {
                return(BadRequest(new ResponseDetails()
                {
                    Message = "Token không được cấp quyền", StatusCode = ResponseCode.Error
                }));
            }

            var userID = principal.Claims?.FirstOrDefault(x => x.Type.Equals(NamePars.ClaimSid, StringComparison.OrdinalIgnoreCase))?.Value;

            var user = await _repository.User.GetUserByIDAsync(userID);

            if (user == null || user.RefreshToken != tokenApiModel.RefreshToken)
            {
                return(BadRequest(new ResponseDetails()
                {
                    Message = "các giá trị token không khớp với dữ liệu trong database", StatusCode = ResponseCode.Error
                }));
            }

            ResponseDetails response = _repository.User.UpdateUserRefreshToken(user, null, null);

            if (response.StatusCode == ResponseCode.Success)
            {
                _repository.Save();
            }
            else
            {
                _logger.LogError($"Lỗi khi revoke token cho user với id {user.UserID}");
            }
            return(Ok());
        }
        public IActionResult Details(string id)
        {
            int newId = _dataProtector.Unprotect(id);

            ResponseDetails response = _apiHelper.SendApiRequest("", "parkinglot/get/" + newId, HttpMethod.Get);

            if (response.Success)
            {
                ParkingLotViewModel parkingLotViewModel = JsonConvert.DeserializeObject <ParkingLotViewModel>
                                                              (response.Data.ToString());

                _dataProtector.ProtectParkingLotRouteValues(parkingLotViewModel);

                ParkingLotRequestdetailsModel model = new ParkingLotRequestdetailsModel()
                {
                    ParkingLot = parkingLotViewModel
                };

                if (model.ParkingLot.ParkingLotImageViewModels.Any())
                {
                    response = _apiHelper.SendApiRequest("", "parkinglot/all-images/" + newId, HttpMethod.Get);

                    if (response.Success)
                    {
                        model.Images = JsonConvert.DeserializeObject <List <string> > (response.Data.ToString());

                        return(View(model));
                    }
                    else
                    {
                        ErrorViewModel errorModel = new ErrorViewModel
                        {
                            Message = response.Data.ToString()
                        };

                        return(View("Error", errorModel));
                    }
                }
                else
                {
                    return(View(model));
                }
            }
            else
            {
                ErrorViewModel model = new ErrorViewModel
                {
                    Message = response.Data.ToString()
                };

                return(View("Error", model));
            }
        }
Пример #27
0
        public IActionResult All()
        {
            ResponseDetails response = _apiHelper.SendApiRequest("", "booking/get/user/" +
                                                                 _tokenDecoder.UserId, HttpMethod.Get);

            List <BookingViewModel> model = JsonConvert.DeserializeObject <List <BookingViewModel> >
                                                (response.Data.ToString());

            _dataProtector.ProtectBookingRouteValues(model);

            return(View(model));
        }
        public override Task <ResponseDetails> ProcessUnauthenticatedResponseAsync()
        {
            // A response is coming back from Infiniti saying the user is unauthenticated.
            // Redirect the request to an IDP site

            var result = new ResponseDetails();

            result.ResponseAction = ResponseAction.Redirect;
            result.RedirectUrl    = "https://my-external-idp-site.com/?callback=" +
                                    UrlEncode("account/externalcallback/sample?returnurl=" + GetRequestUrl());

            return(Task.FromResult(result));
        }
Пример #29
0
        public IActionResult CreateTheLoai([FromBody] IEnumerable <TheLoaiForCreationDto> theLoai)
        {
            try
            {
                var apiKeyAuthenticate = APICredentialAuth.APIKeyCheck(Request.Headers[NamePars.APIKeyStr]);

                if (apiKeyAuthenticate.StatusCode == ResponseCode.Error)
                {
                    return(BadRequest(new ResponseDetails()
                    {
                        StatusCode = ResponseCode.Exception, Message = apiKeyAuthenticate.Message
                    }));
                }

                if (theLoai == null)
                {
                    return(BadRequest("TheLoai object is null"));
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest("Invalid model object"));
                }

                var theLoaiEntity = _mapper.Map <IEnumerable <TheLoai> >(theLoai);

                ResponseDetails response = _repository.TheLoai.CreateTheLoai(theLoaiEntity);
                if (response.StatusCode == ResponseCode.Success)
                {
                    _repository.Save();
                }
                else
                {
                    return(BadRequest(response));
                }

                var createdTheLoai = _mapper.Map <IEnumerable <TheLoaiDto> >(theLoaiEntity);

                return(Ok(createdTheLoai));
            }
            catch (Exception ex)
            {
                _logger.LogError("Gặp lỗi khi tạo mới danh sách thể loại: " + ex);
                return(BadRequest(new ResponseDetails()
                {
                    StatusCode = ResponseCode.Exception, Message = "Lỗi execption ở hàm CreateTheLoai"
                }));
            }
        }
Пример #30
0
        public async void Delete_Returns404_IdNotFound_Test()
        {
            await releasesService.RemoveAll();

            // 1: Request body, given id is not found on database
            string id = "5dcaad2526235a471cfcccad";

            // 2: Call DELETE Action passing id request of release to be deleted
            var query = await releasesController.Delete(id);

            ResponseDetails result = (ResponseDetails)query.Result.GetType().GetProperty("Value").GetValue(query.Result);

            Assert.Equal(404, result.StatusCode);
            Assert.Equal(controllerMessages.NotFoundGivenId.Replace("$", "lançamento"), result.Message);
        }
        public static ApiConfiguration ToApiConfiguration(UpdateConfigurationRequest updateConfigurationRequest)
        {
            var config = new ApiConfiguration
                             {
                                 ChaosInterval = new TimeSpan(0, 0, updateConfigurationRequest.ChaosInterval),
                                 ConfigurationRotationInterval = new TimeSpan(0, 0, updateConfigurationRequest.ConfigurationRotationInterval),
                                 Enabled = updateConfigurationRequest.Enabled
                             };

            foreach (var updateChaosSettings in updateConfigurationRequest.ChaosSettings)
            {
                var chaosConfiguration = new ChaosSettings
                                             {
                                                 Name = updateChaosSettings.Name,
                                                 MaxResponseDelayTime = updateChaosSettings.MaxResponseDelayTime,
                                                 MinResponseDelayTime = updateChaosSettings.MinResponseDelayTime,
                                                 PercentageOfChaos = updateChaosSettings.PercentageOfChaos,
                                                 PercentageOfSlowResponses = updateChaosSettings.PercentageOfSlowResponses,
                                                 ResponseTypeMediaType = updateChaosSettings.ResponseTypeMediaType
                                             };

                if (updateChaosSettings.IgnoreUrls != null)
                {
                    foreach (var url in updateChaosSettings.IgnoreUrls)
                    {
                        chaosConfiguration.IgnoreUrlPattern.Add(url.Pattern);
                    }                    
                }
                
                foreach (var updateResponse in updateChaosSettings.HttpResponses)
                {
                    var httpResponse = new ResponseDetails { StatusCode = updateResponse.StatusCode };

                    foreach (var payload in updateResponse.Payloads.Select(chaosResponsePayload => new ChaosResponsePayload { Code = chaosResponsePayload.Code, Content = chaosResponsePayload.Content }))
                    {
                        httpResponse.Payloads.Add(payload);
                    }

                    chaosConfiguration.HttpResponses.Add(httpResponse);
                }

                config.ChaosSettings.Add(chaosConfiguration);
            }

            return config;
        }
Пример #32
0
        public ApiConfiguration(ChaosConfigurationSection chaosConfigurationSection)
        {
            if (chaosConfigurationSection == null)
            {
                throw new ArgumentNullException("chaosConfigurationSection");
            }

            Enabled = chaosConfigurationSection.GlobalSettings.Enabled;
            ChaosInterval = new TimeSpan(0, 0, chaosConfigurationSection.GlobalSettings.ChaosIntervalSeconds);
            ConfigurationRotationInterval = new TimeSpan(0, 0, chaosConfigurationSection.GlobalSettings.RotationIntervalSeconds);

            foreach (ChaosConfiguration chaosConfiguration in chaosConfigurationSection.ChaosConfigurations)
            {
                var settings = new ChaosSettings
                                   {
                                       Name = chaosConfiguration.Name,
                                       MinResponseDelayTime = chaosConfiguration.MinResponseDelayTime,
                                       MaxResponseDelayTime = chaosConfiguration.MaxResponseDelayTime,
                                       PercentageOfSlowResponses = chaosConfiguration.PercentageOfSlowResponses,
                                       PercentageOfChaos = chaosConfiguration.PercentageOfChaos,
                                       ResponseTypeMediaType = chaosConfiguration.ResponsePayloadMediaType
                                   };

                foreach (Response httpResponse in chaosConfiguration.HttpResponses)
                {
                    var responseDetails = new ResponseDetails { StatusCode = httpResponse.StatusCode };
                    if (httpResponse.Payloads.Count > 0)
                    {
                        foreach (ResponsePayload payload in httpResponse.Payloads)
                        {
                            responseDetails.Payloads.Add(new ChaosResponsePayload { Content = payload.Content, Code = payload.Code });
                        }
                    }

                    settings.HttpResponses.Add(responseDetails);
                }

                ChaosSettings.Add(settings);
            }
        }
Пример #33
0
        private void ProcessBankcardTransactionResponse(ResponseDetails _Response)
        {
            var _BCResponse = new BankcardTransactionResponse();
            _BCResponse = (BankcardTransactionResponse) _Response.Response;
            //Note : IMPORTANT Always verify the approved amount was the same as the requested approval amount for "AuthorizeAndCapture" as well as "Authorize"
            if (_Response.TransactionType == "AuthorizeAndCapture" | _Response.TransactionType == "Authorize")
            {
                if (_BCResponse.Amount != _Response.TxnAmount)
                {
            //                    log.Debug("The transaction was approved for " + _BCResponse.Amount +
            //                                               " which is an amount less than the requested amount of " +
            //                                               _Response.TxnAmount +
            //                                               ". Please provide alternate payment to complete transaction");
                }
            }

            if (!_Response.Verbose)
            {
                // In this case don't present to the user all of the data.
                if (_BCResponse.Status == Status.Successful)
                {
                    //The transaction was approved
                    //NOTE : Please reference the developers guide for a more complete explination of the return fields
                    //Note Highly recommended to save
                    //The unique id of the transaction. TransactionId is required for all subsequent transactions such as Return, Undo, etc.
                    //Must be stored with the TransactionId in order to identify which merchant sent which transaction. Required to support multi-merchant.
                    //Note Optional but recommended to save
                    //Status code generated by the Service Provider. This code should be displayed to the user as verification of the transaction.
                    //Explains the StatusCode which is generated by the Service Provider. This message should be displayed to the user as verification of the transaction.
                    //A value returned when a transaction is approved. This value should be printed on the receipt, and also recorded for every off-line transaction, such as a voice authorization. This same data element and value must be provided during settlement. Required.
                    //Specifies the authorization amount of the transaction. This is the actual amount authorized.
            //                    log.Debug(((((((("Your transaction type of " + _Response.TransactionType.ToString() +
            //                                                     " was APPROVED" + "\r\n" +
            //                                                     "TransactionId : ") + _BCResponse.TransactionId + "\r\n" + "MerchantProfileId : " + HID_strProfileID +
            //                                                    "\r\n" + "Status Code : ") +
            //                                                   _BCResponse.StatusCode.ToString() + "\r\n" +
            //                                                   "Status Message : ") + _BCResponse.StatusMessage.ToString() +
            //                                                  "\r\n" + "ApprovalCode : ") +
            //                                                 _BCResponse.ApprovalCode.ToString() + "\r\n" +
            //                                                 "Amount : ") + _BCResponse.Amount.ToString())));
                }
                if (_BCResponse.Status == Status.Failure)
                {
                    //The transaction was declined
                    //NOTE : Please reference the developers guide for a more complete explination of the return fields
                    //Note Highly recommended to save
                    //The unique id of the transaction. TransactionId is required for all subsequent transactions such as Return, Undo, etc.
                    //Must be stored with the TransactionId in order to identify which merchant sent which transaction. Required to support multi-merchant.
                    //Note Optional but recommended to save
                    //Status code generated by the Service Provider. This code should be displayed to the user as verification of the transaction.
                    //Explains the StatusCode which is generated by the Service Provider. This message should be displayed to the user as verification of the transaction.
            //                    log.Debug(((("Your transaction type of " + _Response.TransactionType.ToString() +
            //                                                  " was DECLINED" + "\r\n" + "TransactionId : ") +
            //                                                 _BCResponse.TransactionId + "\r\n" +
            //                                                 "MerchantProfileId : " + HID_strProfileID + "\r\n" + "Status Code : ") + _BCResponse.StatusCode +
            //                                                "\r\n" + "Status Message : ") +
            //                                               _BCResponse.StatusMessage);
                }
                return;
            }
            if (_BCResponse.Status == Status.Successful)
            {
                //The transaction was approved
                string strMessage = "";
                //NOTE : Please reference the developers guide for a more complete explination of the return fields
                strMessage = "Your transaction type of " + _Response.TransactionType + " was APPROVED";
                //Note Highly recommended to save
                strMessage = (strMessage + "\r\n" + "TransactionId : ") +
                             _BCResponse.TransactionId;
                //The unique id of the transaction. TransactionId is required for all subsequent transactions such as Return, Undo, etc.
                strMessage = strMessage + "\r\n" + "MerchantProfileId : " + strProfileID;
                //Must be stored with the TransactionId in order to identify which merchant sent which transaction. Required to support multi-merchant.
                //Note Highly recommended to save if Tokenization will be used
                //+  vbCrLf + "PaymentAccountDataToken : " + _BCResponse.PaymentAccountDataToken //If tokenization purchased this field represents the actual token returned in the transaction for future use.
                //Note Optional but recommended to save
                strMessage = (strMessage + "\r\n" + "Status Code : ") +
                             _BCResponse.StatusCode;
                //Status code generated by the Service Provider. This code should be displayed to the user as verification of the transaction.
                strMessage = (strMessage + "\r\n" + "Status Message : ") +
                             _BCResponse.StatusMessage;
                //Explains the StatusCode which is generated by the Service Provider. This message should be displayed to the user as verification of the transaction.
                strMessage = (strMessage + "\r\n" + "ApprovalCode : ") +
                             _BCResponse.ApprovalCode;
                //A value returned when a transaction is approved. This value should be printed on the receipt, and also recorded for every off-line transaction, such as a voice authorization. This same data element and value must be provided during settlement. Required.
                strMessage = (strMessage + "\r\n" + "Amount : ") + _BCResponse.Amount;
                //Specifies the authorization amount of the transaction. This is the actual amount authorized.
                //Note Optional but recommended if AVS is supported
                if (_BCResponse.AVSResult != null)
                {
                    strMessage = (strMessage + "\r\n" + "AVSResult ActualResult : ") +
                                 _BCResponse.AVSResult.ActualResult;
                    //Specifies the actual result of AVS from the Service Provider.
                    strMessage = (strMessage + "\r\n" + "AVSResult AddressResult : ") +
                                 _BCResponse.AVSResult.AddressResult;
                    //Specifies the result of AVS as it pertains to Address matching
                    //Specifies the result of AVS as it pertains to Postal Code matching
                    strMessage = (strMessage + "\r\n" + "AVSResult PostalCodeResult : ") +
                                 _BCResponse.AVSResult.PostalCodeResult;
                }
                //Note Optional but recommended if CV data is supported
                strMessage = (strMessage + "\r\n" + "CVResult : ") +
                             _BCResponse.CVResult;
                //Response code returned by the card issuer indicating the result of Card Verification (CVV2/CVC2/CID).
                //Note Optional
                strMessage = (strMessage + "\r\n" + "OrderId : ") +
                             _BCResponse.OrderId;
                //A unique ID used to identify a specific order.  This is used to process further transactions on Virtual Terminals.
                strMessage = (strMessage + "\r\n" + "BatchId : ") +
                             _BCResponse.BatchId;
                //A unique ID used to identify a specific batch settlement
                strMessage = (strMessage + "\r\n" + "DowngradeCode : ") +
                             _BCResponse.DowngradeCode;
                //Indicates downgrade reason.
                strMessage = (strMessage + "\r\n" + "FeeAmount : ") +
                             _BCResponse.FeeAmount;
                //Fee amount charged for the transaction.
                strMessage = (strMessage + "\r\n" + "FinalBalance : ") +
                             _BCResponse.FinalBalance;
                //Fee amount charged for the transaction.
                strMessage = (strMessage + "\r\n" + "Resubmit : ") +
                             _BCResponse.Resubmit;
                //Specifies whether resubmission is supported for PIN Debit transactions.
                strMessage = (strMessage + "\r\n" + "ServiceTransactionId : ") +
                             _BCResponse.ServiceTransactionId;

                //+  vbCrLf + "SettlementDate : " + _BCResponse.SettlementDate //Settlement date. Conditional, if present in the authorization response, this same data element and value must be provided during settlement

                //Token generated
                strMessage = (strMessage + "\r\n" + "Token : ") +
                             _BCResponse.PaymentAccountDataToken;

            //                log.Debug(strMessage);
            }
            if (_BCResponse.Status == Status.Failure)
            {
                //The transaction was declined
                //NOTE : Please reference the developers guide for a more complete explination of the return fields
                //Note Highly recommended to save
                //The unique id of the transaction. TransactionId is required for all subsequent transactions such as Return, Undo, etc.
                //Must be stored with the TransactionId in order to identify which merchant sent which transaction. Required to support multi-merchant.
                //Note Optional but recommended to save
                //Status code generated by the Service Provider. This code should be displayed to the user as verification of the transaction.
                //Explains the StatusCode which is generated by the Service Provider. This message should be displayed to the user as verification of the transaction.
                //Note Optional but recommended if CV data is supported
                //Response code returned by the card issuer indicating the result of Card Verification (CVV2/CVC2/CID).
                //Note Optional
            //                log.Debug(((((("Your transaction type of " + _Response.TransactionType.ToString() +
            //                                                " was DECLINED" + "\r\n" + "TransactionId : ") +
            //                                               _BCResponse.TransactionId.ToString() + "\r\n" +
            //                                               "MerchantProfileId : " + HID_strProfileID + "\r\n" + "Status Code : ") + _BCResponse.StatusCode.ToString() +
            //                                              "\r\n" + "Status Message : ") +
            //                                             _BCResponse.StatusMessage.ToString() + "\r\n" +
            //                                             "CVResult : ") + _BCResponse.CVResult.ToString() + "\r\n" + "ServiceTransactionId : ") +
            //                                           _BCResponse.ServiceTransactionId.ToString());
            }
        }
Пример #34
0
 private void ProcessResponse(ResponseDetails _Response)
 {
     if (_Response.Response is BankcardTransactionResponsePro)
     {
         //In the 1.17.11 release all response objects are BankcardTransactionResponsePro
         ProcessBankcardTransactionResponse(_Response);
     }
     //Future functionality as a BankcardTransactionResponse is presently not returned
     if (_Response.Response is BankcardTransactionResponse)
     {
     }
     if (_Response.Response is BankcardCaptureResponse)
     {
         //BankcardCaptureResponse
         ProcessBankcardCaptureResponse((BankcardCaptureResponse) _Response.Response, _Response.Verbose);
     }
 }
        private void CompareErrors(DataServiceContextWrapper<DefaultContainer>[] contexts, Action<DataServiceContextWrapper<DefaultContainer>> test)
        {
            Debug.Assert(contexts.Length == 2);

            var results = new ResponseDetails[2];
            int i = 0;

            foreach (var context in contexts)
            {
                var responseDetails = new ResponseDetails();

                try
                {
                    test(context);
                }
                catch (Exception ex)
                {
                    responseDetails.Exception = ex;
                }

                Assert.IsNotNull(responseDetails.Exception, "Expected exception but none was thrown");
                responseDetails.StatusCode = this.lastResponseStatusCode;
                results[i++] = responseDetails;
            }

            Assert.AreEqual(results[0].StatusCode, results[1].StatusCode);
            AssertExceptionsAreEqual(results[0].Exception, results[1].Exception);
        }
Пример #36
0
 public ResponseEventArgs(RequestDetails request, ResponseDetails response) : base(request)
 {
     _response = response;
 }