public async Task <IActionResult> GetResourceByUserId(int Userid) { try { ReportDataAccess _reportAccess = new ReportDataAccess(_iconfiguration); DatabaseResponse response = await _reportAccess.GetResourceByUserID(Userid); if (response.ResponseCode == (int)DbReturnValue.RecordExists) { return(Ok(new OperationResponse { HasSucceeded = true, IsDomainValidationErrors = false, Message = EnumExtensions.GetDescription(DbReturnValue.RecordExists), ReturnedObject = response.Results })); } else { Log.Error(EnumExtensions.GetDescription(DbReturnValue.NoRecords)); return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = false, Message = EnumExtensions.GetDescription(DbReturnValue.NoRecords) })); } } catch (Exception ex) { Log.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, StatusCode = ((int)ResponseStatus.ServerError).ToString(), IsDomainValidationErrors = false })); } }
public async Task <IActionResult> GetWhiteListingRequests(bool isApproved) { try { UrlWhiteListingDataAccess _whitelistingAccess = new UrlWhiteListingDataAccess(_iconfiguration); DatabaseResponse response = await _whitelistingAccess.GetWhiteListedUrls(isApproved); if (response.ResponseCode == (int)DbReturnValue.RecordExists) { return(Ok(new OperationResponse { HasSucceeded = true, IsDomainValidationErrors = false, Message = EnumExtensions.GetDescription(DbReturnValue.RecordExists), ReturnedObject = response.Results })); } else { Log.Error(EnumExtensions.GetDescription(DbReturnValue.NoRecords)); return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = false, Message = EnumExtensions.GetDescription(DbReturnValue.NoRecords) })); } } catch (Exception ex) { Log.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, StatusCode = ((int)ResponseStatus.ServerError).ToString(), IsDomainValidationErrors = false, })); } }
public TransactionRetrieveResponseOperation GetPaymentTransaction(string receiptResponse) { TransactionResponseModel transactionResponseModel = null; try { transactionResponseModel = TransactionResponseModel.toPaywithTokenTransactionResponseModel(receiptResponse); } catch (Exception ex) { LogInfo.Error($" : { EnumExtensions.GetDescription(MPGSAPIResponse.HostedCheckoutReceiptError) + " " + JsonConvert.SerializeObject(ex)}"); throw ex; } return(new TransactionRetrieveResponseOperation { TrasactionResponse = transactionResponseModel }); }
public async Task <IActionResult> UpdateLastLogin(int userId) { try { ProfileDataAccess _profileAccess = new ProfileDataAccess(_iconfiguration); DatabaseResponse response = await _profileAccess.UpdateLastLogin(userId); if (response.ResponseCode == (int)DbReturnValue.UpdateSuccess) { return(Ok(new OperationResponse { HasSucceeded = true, IsDomainValidationErrors = false, Message = EnumExtensions.GetDescription(DbReturnValue.UpdateSuccess), ReturnedObject = null })); } else { return(Ok(new OperationResponse { HasSucceeded = true, IsDomainValidationErrors = false, Message = EnumExtensions.GetDescription(DbReturnValue.UpdationFailed) })); } } catch (Exception ex) { Log.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, StatusCode = ((int)ResponseStatus.ServerError).ToString(), IsDomainValidationErrors = false })); } }
public DataModelsMapping() { CreateMap <Developer, DeveloperDto>() .ReverseMap() .ForMember(dest => dest.Projects, opt => opt.Ignore()) .ForMember(dest => dest.Vacations, opt => opt.Ignore()); CreateMap <Project, ProjectDto>() .ReverseMap() .ForMember(dest => dest.Developers, opt => opt.Ignore()); CreateMap <Vacation, VacationDto>(); CreateMap <Vacation, VacationDto>() .ForMember(dest => dest.Status, opt => opt.MapFrom(src => EnumExtensions.GetDescription(src.Status))) .ReverseMap() .ForMember(dest => dest.Status, opt => opt.MapFrom(src => EnumExtensions.ParseDescriptionToEnum <VacationStatus>(src.Status))) .ForMember(dest => dest.Developer, opt => opt.Ignore()); }
public async Task GetRegionsBoardAsync_ReturnsRegionsBoard() { // Arrange _userManager .Setup(x => x.GetUserAsync(new System.Security.Claims.ClaimsPrincipal())).ReturnsAsync(new User()); _regionService .Setup(x => x.GetRegionByNameAsync(EnumExtensions.GetDescription(RegionsStatusType.RegionBoard), It.IsAny <User>())) .ReturnsAsync(new RegionProfileDTO() { Status = RegionsStatusTypeDTO.RegionBoard }); // Act var result = await _regionController.GetRegionsBoardAsync(); var actual = (result as ObjectResult).Value; // Assert Assert.IsInstanceOf <OkObjectResult>(result); Assert.IsInstanceOf <RegionProfileDTO>(actual); }
public List <dynamic> GetAPActions() { var values = Enum.GetValues(typeof(ApprovalActions)).Cast <ApprovalActions>().ToList(); List <dynamic> approvalActions = new List <dynamic>(); for (int i = 0; i < values.Count; i++) { dynamic action = new ExpandoObject(); action.action = values[i]; action.actionDescription = EnumExtensions.GetDescription(values[i]); action.allow = true; action.notes = new { field = true, isRequired = false }; action.attachments = new { field = true, isRequired = false }; action.saveToAttachment = false; approvalActions.Add(action); } return(approvalActions); }
public static Dictionary <int, string> GetSelectListDictionary(List <ushort> pixelTypes) { var resultDictionary = new Dictionary <int, string>(); foreach (var pixelType in pixelTypes) { TwainPixelType supportedPixelType; string description; try { supportedPixelType = (TwainPixelType)pixelType; description = EnumExtensions.GetDescription(supportedPixelType); } catch (Exception) { continue; } resultDictionary.Add((int)supportedPixelType, description); } return(resultDictionary); }
public async Task<PaginatedList<StaffModel>> GetStaffsAsync(int page, int limit, string sortColumn = null) => await _staffRepository.Query() .Include(s => s.State) .Select(s => new StaffModel { Id = s.Id, State = s.State.Name, BirthDate = s.BirthDate, RetirementDate = s.RetirementDate, PhoneNumber = s.PhoneNumber, Address = s.Address, FirstName = s.FirstName, LastName = s.LastName, MiddleName = s.MiddleName, ArmyNumber = s.ArmyNumber, Rank = EnumExtensions.GetDescription(s.Rank), DateCreated = s.DateCreated, DateLastModified = s.DateLastModified }) .ToPaginatedListAsync(page, limit, sortColumn);
public ActionResult PhieuChuyenKhoByCuaHang(int TrangThaiId) { var MaCH = int.Parse(User.TenCuaHang()); var get = db.PhieuChuyenKhos.Where(n => n.FromKho == MaCH && n.TrangThaiId == TrangThaiId || n.ToKho == MaCH && n.TrangThaiId == TrangThaiId).ToList(); List <PhieuChuyenKhoVM> lstPhieuCK = Session["PCKVM"] as List <PhieuChuyenKhoVM>; lstPhieuCK = new List <PhieuChuyenKhoVM>(); foreach (var item in get) { PhieuChuyenKhoVM PCK = new PhieuChuyenKhoVM(); PCK.vPhieuChuyenKhoId = item.PhieuChuyenKhoId; PCK.vSoLuongChuyen = item.SoLuongChuyen; PCK.vTrangThai = EnumExtensions.GetDescription(item.TrangThaiId == 0 ? Enumstatus.Open : Enumstatus.Close); PCK.vFromKho = db.cuaHangs.SingleOrDefault(n => n.CuaHangId == item.FromKho).displayName; PCK.vToKho = db.cuaHangs.SingleOrDefault(n => n.CuaHangId == item.ToKho).displayName; PCK.vConfirmFrom = EnumExtensions.GetDescription(item.ConfirmFrom == false ? Enumstatus.Confirm_False : Enumstatus.Confirm_True); PCK.vConfirmTo = EnumExtensions.GetDescription(item.ConfirmTo == false ? Enumstatus.Confirm_False : Enumstatus.Confirm_True); PCK.vNgayTao = item.NgayTao; lstPhieuCK.Add(PCK); } return(Json(lstPhieuCK, JsonRequestBehavior.AllowGet)); }
public ActionResult PhieuNhanHang() { ViewBag.TrangThaiId = new SelectList(db.TrangThais, "TrangThaiId", "TenTrangThai"); var MaCH = int.Parse(User.TenCuaHang()); var get = db.PhieuChuyenKhos.Where(n => n.ToKho == MaCH && n.TrangThaiId != 4).ToList(); List <PhieuChuyenKhoVM> lstPhieuCK = Session["PNHVM"] as List <PhieuChuyenKhoVM>; lstPhieuCK = new List <PhieuChuyenKhoVM>(); foreach (var item in get) { PhieuChuyenKhoVM PCK = new PhieuChuyenKhoVM(); PCK.vPhieuChuyenKhoId = item.PhieuChuyenKhoId; PCK.vSoLuongChuyen = item.SoLuongChuyen; PCK.vTrangThai = EnumExtensions.GetDescription(item.TrangThaiId == 0 ? Enumstatus.Open : Enumstatus.Close); PCK.vFromKho = db.cuaHangs.SingleOrDefault(n => n.CuaHangId == item.FromKho).displayName; PCK.vToKho = db.cuaHangs.SingleOrDefault(n => n.CuaHangId == item.ToKho).displayName; PCK.vConfirmFrom = EnumExtensions.GetDescription(item.ConfirmFrom == false ? Enumstatus.Confirm_False : Enumstatus.Confirm_True); PCK.vConfirmTo = EnumExtensions.GetDescription(item.ConfirmTo == false ? Enumstatus.Confirm_False : Enumstatus.Confirm_True); PCK.vNgayTao = item.NgayTao; lstPhieuCK.Add(PCK); } return(View(lstPhieuCK)); }
public override string ToString() { var sb = new StringBuilder(); sb.Append("This is a ") .Append(EnumExtensions.GetDescription(profession)) .Append(" named ") .Append(name); if (this.hairColor != null || hairType != null) { sb.Append(" with "); if (hairColor != null) { sb.Append(EnumExtensions.GetDescription(hairColor)).Append(' '); } if (hairType != null) { sb.Append(EnumExtensions.GetDescription(hairType)).Append(' '); } sb.Append(hairType != HairType.BALD ? "hair" : "head"); } if (armor != null) { sb.Append(" wearing ") .Append(EnumExtensions.GetDescription(armor)); } if (weapon != null) { sb.Append(" and wielding a ") .Append(EnumExtensions.GetDescription(weapon)); } sb.Append('.'); return(sb.ToString()); }
public string GetLogString(Exception ex, ErrorLevel level) { try { StackTrace st = new StackTrace(ex, true); //Get the first stack frame StackFrame frame = st.GetFrame(0); //JsonConvert.SerializeObject(); ExceptionLog exLog = new ExceptionLog { ExceptionLogId = Guid.NewGuid().ToString().ToLower(), ExceptionType = ex.GetType().FullName.ToString(), ExceptionInnerException = ex.InnerException == null ? "" : ex.InnerException.ToString(), ExceptionMessage = ex.Message, ExceptionSeverity = EnumExtensions.GetDescription(level), ExceptionFileName = frame.GetFileName() != null?Path.GetFileName((frame.GetFileName())) : "", //Get the file name ExceptionLineNumber = frame.GetFileLineNumber(), //Get the line number ExceptionColumnNumber = frame.GetFileColumnNumber(), //Get the column number ExceptionMethodName = ex.TargetSite.ReflectedType.FullName, // Get the method name ExceptionStackTrace = ex.StackTrace }; string excep = $"ExceptionLogId:{exLog.ExceptionLogId}, ExceptionType:{exLog.ExceptionType}, " + $"ExceptionInnerException:{exLog.ExceptionInnerException}, ExceptionMessage:{exLog.ExceptionMessage}, " + $"ExceptionSeverity:{exLog.ExceptionSeverity}, ExceptionFileName:{exLog.ExceptionFileName}, ExceptionMethodName:{exLog.ExceptionMethodName}, " + $"ExceptionLineNumber:{exLog.ExceptionLineNumber}, ExceptionColumnNumber:{exLog.ExceptionColumnNumber} , ExceptionStackTrace:{exLog.ExceptionStackTrace}"; return(excep); } catch (Exception e) { throw e; } }
public DTOSituacaoProcesso ObterSituacao(int statusResposta, EtapaResposta etapa) { StringBuilder situacaoNome = new StringBuilder(); if (etapa != null) { if (statusResposta == (int)enumStatusEtapaResposta.Aguardando && etapa.PermissoesNucleoEtapaResposta != null && etapa.PermissoesNucleoEtapaResposta.Count > 0) { situacaoNome.Append("Aguardando avaliação pelo Núcleo"); } else { situacaoNome.Append(EnumExtensions.GetDescription(((enumStatusEtapaResposta)statusResposta))); } } return(new DTOSituacaoProcesso() { ID = statusResposta, Nome = situacaoNome != null?situacaoNome.ToString() : "" }); }
public async Task Sugestao(IDialogContext context, LuisResult result) { var entity = result?.Entities?.Where(x => x.Type == "categoria").FirstOrDefault()?.Entity?.ToString(); Category category = Category.anyway; if (!String.IsNullOrEmpty(entity)) { category = (Category)Enum.Parse(typeof(Category), entity); } var movieService = new TheMovieDBService(); if (botMovieTipsService == null) { botMovieTipsService = new BotMovieTipsService(); } await botMovieTipsService.ConfigureAuthentication(); var favoriteMedias = await botMovieTipsService.GetFavoriteMedias(userId); if (favoriteMedias.Count == 0) { await context.PostAsync($@"Aaah, ainda não te conheço o suficiente para conseguir te indicar um filme que vc goste! ¯\_(⊙︿⊙)_/¯"); await context.PostAsync($@"Você pode me pedir criticas sobre filmes / serie e falar quais você gosta pra eu aprender mais sobre você S2"); return; } int random = new Random().Next(favoriteMedias.Count); var favoriteMediaChoiced = favoriteMedias[random]; var mediasRecommendated = await movieService.GetRecommendation(favoriteMediaChoiced.IdMedia, EnumExtensions.GetDescription(category)); var msg = context.MakeMessage(); msg.AttachmentLayout = AttachmentLayoutTypes.Carousel; foreach (var media in mediasRecommendated) { var card = new CardPersonalizedService().CreateCard(media); msg.Attachments.Add(card.ToAttachment()); } await context.PostAsync(msg); //Implementar Form @Migg //FormDialog<Form.Sugestao> sugestionForm = new FormDialog<Form.Sugestao>(new Form.Sugestao(), Form.Sugestao.BuildForm, FormOptions.PromptInStart); //context.Call(sugestionForm, SugestaoFormCompleteAsync); }
public void GetDescriptionTest() { Assert.AreEqual(EnumExtensions.GetDescription(TestDescriptionEnum.First), "The First One"); }
public async Task <IActionResult> GetOrderDetailsHistory([FromHeader(Name = "Grid-Authorization-Token")] string token, [FromRoute] int orderID) { try { if (string.IsNullOrEmpty(token)) { return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = EnumExtensions.GetDescription(CommonErrors.TokenEmpty) })); } AdminUsersDataAccess _adminUsersDataAccess = new AdminUsersDataAccess(_iconfiguration); DatabaseResponse tokenAuthResponse = await _adminUsersDataAccess.AuthenticateAdminUserToken(token); if (tokenAuthResponse.ResponseCode == (int)DbReturnValue.AuthSuccess) { if (!((AuthTokenResponse)tokenAuthResponse.Results).IsExpired) { if (!ModelState.IsValid) { return(StatusCode((int)HttpStatusCode.OK, new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = string.Join("; ", ModelState.Values .SelectMany(x => x.Errors) .Select(x => x.ErrorMessage)) })); } var orderList = await _adminOrderDataAccess.GetNRICOrderDetailsHistory(orderID); if (orderList == null || orderList.Count == 0) { return(Ok(new ServerResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.NotExists) })); } else { return(Ok(new ServerResponse { HasSucceeded = true, Message = StatusMessages.SuccessMessage, Result = orderList })); } } else { //Token expired LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.ExpiredToken)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenExpired), IsDomainValidationErrors = true })); } } else { // token auth failure LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed), IsDomainValidationErrors = false })); } } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, IsDomainValidationErrors = false })); } }
public async Task <IActionResult> GetOrdersList([FromHeader(Name = "Grid-Authorization-Token")] string token, string deliveryStatus, DateTime?fromDate, DateTime?toDate) { try { if (string.IsNullOrEmpty(token)) { return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = EnumExtensions.GetDescription(CommonErrors.TokenEmpty) })); } AdminUsersDataAccess _adminUsersDataAccess = new AdminUsersDataAccess(_iconfiguration); DatabaseResponse tokenAuthResponse = await _adminUsersDataAccess.AuthenticateAdminUserToken(token); if (tokenAuthResponse.ResponseCode == (int)DbReturnValue.AuthSuccess) { if (!((AuthTokenResponse)tokenAuthResponse.Results).IsExpired) { if (!ModelState.IsValid) { return(StatusCode((int)HttpStatusCode.OK, new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = string.Join("; ", ModelState.Values .SelectMany(x => x.Errors) .Select(x => x.ErrorMessage)) })); } int?deliveryStatusNumber = null; if (!string.IsNullOrWhiteSpace(deliveryStatus)) { if (deliveryStatus.Trim().ToLower() == IDVerificationStatus.PendingVerification.GetDescription().Trim().ToLower()) { deliveryStatusNumber = 0; } else if (deliveryStatus.Trim().ToLower() == IDVerificationStatus.AcceptedVerification.GetDescription().Trim().ToLower()) { deliveryStatusNumber = 1; } else if (deliveryStatus.Trim().ToLower() == IDVerificationStatus.RejectedVerification.GetDescription().Trim().ToLower()) { deliveryStatusNumber = 2; } } var orderList = await _adminOrderDataAccess.GetOrdersList(deliveryStatusNumber, fromDate, toDate); if (orderList == null || orderList.Count == 0) { return(Ok(new ServerResponse { HasSucceeded = true, Message = EnumExtensions.GetDescription(DbReturnValue.NotExists) })); } else { return(Ok(new ServerResponse { HasSucceeded = true, Message = StatusMessages.SuccessMessage, Result = orderList })); } } else { //Token expired LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.ExpiredToken)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenExpired), IsDomainValidationErrors = true })); } } else { // token auth failure LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed), IsDomainValidationErrors = false })); } } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, IsDomainValidationErrors = false })); } }
public async Task <IActionResult> UpdateNRICDetails([FromHeader(Name = "Grid-Authorization-Token")] string token, [FromForm] NRICDetails request) { try { if (string.IsNullOrEmpty(token)) { return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = EnumExtensions.GetDescription(CommonErrors.TokenEmpty) })); } AdminUsersDataAccess _adminUsersDataAccess = new AdminUsersDataAccess(_iconfiguration); DatabaseResponse tokenAuthResponse = await _adminUsersDataAccess.AuthenticateAdminUserToken(token); if (tokenAuthResponse.ResponseCode == (int)DbReturnValue.AuthSuccess) { if (!((AuthTokenResponse)tokenAuthResponse.Results).IsExpired) { if (!ModelState.IsValid) { return(StatusCode((int)HttpStatusCode.OK, new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = string.Join("; ", ModelState.Values .SelectMany(x => x.Errors) .Select(x => x.ErrorMessage)) })); } if (!string.IsNullOrEmpty(request.IdentityCardNumber)) { EmailValidationHelper _helper = new EmailValidationHelper(); if (!_helper.NRICValidation(null, request.IdentityCardNumber, out string _warningmsg)) { LogInfo.Warning("NRIC Validation with type: " + _warningmsg); return(Ok(new OperationResponse { HasSucceeded = false, Message = "Document details are invalid", IsDomainValidationErrors = false })); } } int deliveryStatusNumber = request.IDVerificationStatus; var authToken = (AuthTokenResponse)tokenAuthResponse.Results; MiscHelper configHelper = new MiscHelper(); CommonDataAccess _commonDataAccess = new CommonDataAccess(_iconfiguration); NRICDetailsRequest personalDetails = new NRICDetailsRequest { OrderID = request.OrderID, IdentityCardNumber = request.IdentityCardNumber, IdentityCardType = request.IdentityCardType, Nationality = request.Nationality, NameInNRIC = request.NameInNRIC, DOB = request.DOB, Expiry = request.Expiry, Remarks = request.Remarks, IDVerificationStatus = request.IDVerificationStatus, }; if (request.FrontImage != null || request.BackImage != null) { string IDCardNumberForImage = string.Empty; DatabaseResponse awsConfigResponse = await _commonDataAccess.GetConfiguration(ConfiType.AWS.ToString()); if (awsConfigResponse != null && awsConfigResponse.ResponseCode == (int)DbReturnValue.RecordExists) { GridAWSS3Config awsConfig = configHelper.GetGridAwsConfig((List <Dictionary <string, string> >)awsConfigResponse.Results); // Check for IdentityCardNumber //Start if (string.IsNullOrEmpty(request.IdentityCardNumber)) { var orderDetailsForIDCard = await _commonDataAccess.GetOrderDetails(request.OrderID); IDCardNumberForImage = orderDetailsForIDCard.IdentityCardNumber; } else { IDCardNumberForImage = request.IdentityCardNumber; } //End AmazonS3 s3Helper = new AmazonS3(awsConfig); if (request.FrontImage != null) { string fileNameFront = IDCardNumberForImage.Substring(1, IDCardNumberForImage.Length - 2) + "_Front_" + DateTime.Now.ToString("yyMMddhhmmss") + Path.GetExtension(request.FrontImage.FileName); //Grid_IDNUMBER_yyyymmddhhmmss.extension UploadResponse s3UploadResponse = await s3Helper.UploadFile(request.FrontImage, fileNameFront); if (s3UploadResponse.HasSucceed) { personalDetails.FrontImage = awsConfig.AWSEndPoint + s3UploadResponse.FileName; } else { LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.S3UploadFailed)); } } if (request.BackImage != null) { string fileNameBack = IDCardNumberForImage.Substring(1, IDCardNumberForImage.Length - 2) + "_Back_" + DateTime.Now.ToString("yyMMddhhmmss") + Path.GetExtension(request.BackImage.FileName); //Grid_IDNUMBER_yyyymmddhhmmss.extension UploadResponse s3UploadResponse = await s3Helper.UploadFile(request.BackImage, fileNameBack); if (s3UploadResponse.HasSucceed) { personalDetails.BackImage = awsConfig.AWSEndPoint + s3UploadResponse.FileName; } else { LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.S3UploadFailed)); } } } else { // unable to get aws config LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.FailedToGetConfiguration)); } } var returnResponse = await _commonDataAccess.UpdateNRICDetails(authToken.CustomerID, deliveryStatusNumber, personalDetails); if (returnResponse.ResponseCode == (int)DbReturnValue.UpdateSuccessSendEmail) { var emailDetails = (EmailResponse)returnResponse.Results; DatabaseResponse configResponse = new DatabaseResponse(); DatabaseResponse tokenCreationResponse = new DatabaseResponse(); string finalURL = string.Empty; // Fetch the URL if (emailDetails.VerificationStatus == 2) // Rejected then token { configResponse = ConfigHelper.GetValueByKey(ConfigKeys.NRICReUploadLink.GetDescription(), _iconfiguration); tokenCreationResponse = await _adminOrderDataAccess.CreateTokenForVerificationRequests(request.OrderID); var tokenCreation = (VerificationRequestResponse)tokenCreationResponse.Results; finalURL = configResponse.Results.ToString() + tokenCreation.RequestToken; } else { var result = await _commonDataAccess.UpdateTokenForVerificationRequests(request.OrderID); } //Sending message start // Send email to customer email ConfigDataAccess _configAccess = new ConfigDataAccess(_iconfiguration); DatabaseResponse registrationResponse = await _adminOrderDataAccess.GetEmailNotificationTemplate(emailDetails.VerificationStatus == 2?NotificationEvent.ICValidationReject.GetDescription() : NotificationEvent.ICValidationChange.GetDescription()); string[] changelog = emailDetails.ChangeLog.Split(";"); string finallog = ""; foreach (string log in changelog) { if (!string.IsNullOrWhiteSpace(log)) { finallog = finallog + "• " + log.Trim() + "<br/>"; } } var notificationMessage = MessageHelper.GetMessage(emailDetails.Email, emailDetails.Name, emailDetails.VerificationStatus == 2 ? NotificationEvent.ICValidationReject.GetDescription() : NotificationEvent.ICValidationChange.GetDescription(), ((EmailTemplate)registrationResponse.Results).TemplateName, _iconfiguration, string.IsNullOrWhiteSpace(finalURL) ? "-" : finalURL, string.IsNullOrWhiteSpace(emailDetails.Remark) ? "-" : emailDetails.Remark.Replace(";", "<br />"), string.IsNullOrWhiteSpace(emailDetails.ChangeLog) ? "-" : finallog); var notificationResponse = await _adminOrderDataAccess.GetConfiguration(ConfiType.Notification.ToString()); MiscHelper parser = new MiscHelper(); var notificationConfig = parser.GetNotificationConfig((List <Dictionary <string, string> >)notificationResponse.Results); Publisher customerNotificationPublisher = new Publisher(_iconfiguration, notificationConfig.SNSTopic); await customerNotificationPublisher.PublishAsync(notificationMessage); try { DatabaseResponse notificationLogResponse = await _adminOrderDataAccess.CreateEMailNotificationLogForDevPurpose( new NotificationLogForDevPurpose { EventType = NotificationEvent.OrderSuccess.ToString(), Message = JsonConvert.SerializeObject(notificationMessage) }); } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); } //Sending message Stop return(Ok(new ServerResponse { HasSucceeded = true, Message = StatusMessages.SuccessMessage, Result = null })); } else if (returnResponse.ResponseCode == (int)DbReturnValue.UpdateSuccess) { var emailDetails = (EmailResponse)returnResponse.Results; DatabaseResponse configResponse = new DatabaseResponse(); DatabaseResponse tokenCreationResponse = new DatabaseResponse(); string finalURL = string.Empty; if (emailDetails.VerificationStatus == 2) // Rejected then token { configResponse = ConfigHelper.GetValueByKey(ConfigKeys.NRICReUploadLink.GetDescription(), _iconfiguration); tokenCreationResponse = await _adminOrderDataAccess.CreateTokenForVerificationRequests(request.OrderID); var tokenCreation = (VerificationRequestResponse)tokenCreationResponse.Results; finalURL = configResponse.Results.ToString() + tokenCreation.RequestToken; DatabaseResponse registrationResponse = await _adminOrderDataAccess.GetEmailNotificationTemplate(NotificationEvent.ICValidationReject.GetDescription()); var notificationMessage = MessageHelper.GetMessage(emailDetails.Email, emailDetails.Name, NotificationEvent.ICValidationReject.GetDescription(), ((EmailTemplate)registrationResponse.Results).TemplateName, _iconfiguration, string.IsNullOrWhiteSpace(finalURL) ? "-" : finalURL, string.IsNullOrWhiteSpace(emailDetails.Remark) ? "-" : emailDetails.Remark.Replace(";", "<br />"), string.IsNullOrWhiteSpace(emailDetails.ChangeLog) ? "-" : emailDetails.ChangeLog); var notificationResponse = await _adminOrderDataAccess.GetConfiguration(ConfiType.Notification.ToString()); MiscHelper parser = new MiscHelper(); var notificationConfig = parser.GetNotificationConfig((List <Dictionary <string, string> >)notificationResponse.Results); Publisher customerNotificationPublisher = new Publisher(_iconfiguration, notificationConfig.SNSTopic); await customerNotificationPublisher.PublishAsync(notificationMessage); try { DatabaseResponse notificationLogResponse = await _adminOrderDataAccess.CreateEMailNotificationLogForDevPurpose( new NotificationLogForDevPurpose { EventType = NotificationEvent.OrderSuccess.ToString(), Message = JsonConvert.SerializeObject(notificationMessage) }); } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); } } else { var result = await _commonDataAccess.UpdateTokenForVerificationRequests(request.OrderID); } //Sending message start // Send email to customer email ConfigDataAccess _configAccess = new ConfigDataAccess(_iconfiguration); return(Ok(new ServerResponse { HasSucceeded = true, Message = StatusMessages.SuccessMessage, Result = null })); } else { LogInfo.Error("UpdateNRICDetails failed for " + request.OrderID + " Order Id " + DbReturnValue.UpdationFailed); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.UpdationFailed), IsDomainValidationErrors = false })); } } else { //Token expired LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.ExpiredToken)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenExpired), IsDomainValidationErrors = true })); } } else { // token auth failure LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed), IsDomainValidationErrors = false })); } } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, IsDomainValidationErrors = false })); } }
public async Task <IActionResult> GetOrderDetails([FromHeader(Name = "Grid-Authorization-Token")] string token, [FromRoute] int orderID) { try { if (string.IsNullOrEmpty(token)) { return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = EnumExtensions.GetDescription(CommonErrors.TokenEmpty) })); } AdminUsersDataAccess _adminUsersDataAccess = new AdminUsersDataAccess(_iconfiguration); DatabaseResponse tokenAuthResponse = await _adminUsersDataAccess.AuthenticateAdminUserToken(token); if (tokenAuthResponse.ResponseCode == (int)DbReturnValue.AuthSuccess) { if (!((AuthTokenResponse)tokenAuthResponse.Results).IsExpired) { if (!ModelState.IsValid) { return(StatusCode((int)HttpStatusCode.OK, new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = string.Join("; ", ModelState.Values .SelectMany(x => x.Errors) .Select(x => x.ErrorMessage)) })); } CommonDataAccess commonData = new CommonDataAccess(_iconfiguration); var orderList = await commonData.GetOrderDetails(orderID); if (orderList == null || orderList.OrderID == 0) { return(Ok(new ServerResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.NotExists) })); } else { // DownloadFile DatabaseResponse awsConfigResponse = await commonData.GetConfiguration(ConfiType.AWS.ToString()); if (awsConfigResponse != null && awsConfigResponse.ResponseCode == (int)DbReturnValue.RecordExists) { MiscHelper configHelper = new MiscHelper(); GridAWSS3Config awsConfig = configHelper.GetGridAwsConfig((List <Dictionary <string, string> >)awsConfigResponse.Results); AmazonS3 s3Helper = new AmazonS3(awsConfig); DownloadResponse FrontImageDownloadResponse = new DownloadResponse(); DownloadResponse BackImageDownloadResponse = new DownloadResponse(); if (!string.IsNullOrEmpty(orderList.DocumentURL)) { FrontImageDownloadResponse = await s3Helper.DownloadFile(orderList.DocumentURL.Remove(0, awsConfig.AWSEndPoint.Length)); if (FrontImageDownloadResponse.HasSucceed) { orderList.FrontImage = FrontImageDownloadResponse.FileObject != null?configHelper.GetBase64StringFromByteArray(FrontImageDownloadResponse.FileObject, orderList.DocumentURL.Remove(0, awsConfig.AWSEndPoint.Length)) : null; orderList.DocumentURL = ""; } else { orderList.DocumentURL = ""; orderList.FrontImage = ""; } } if (!string.IsNullOrEmpty(orderList.DocumentBackURL)) { BackImageDownloadResponse = await s3Helper.DownloadFile(orderList.DocumentBackURL.Remove(0, awsConfig.AWSEndPoint.Length)); if (BackImageDownloadResponse.HasSucceed) { orderList.BackImage = BackImageDownloadResponse.FileObject != null?configHelper.GetBase64StringFromByteArray(BackImageDownloadResponse.FileObject, orderList.DocumentBackURL.Remove(0, awsConfig.AWSEndPoint.Length)) : null; orderList.DocumentBackURL = ""; } else { orderList.DocumentBackURL = ""; orderList.BackImage = ""; } } return(Ok(new ServerResponse { HasSucceeded = true, Message = StatusMessages.SuccessMessage, Result = orderList })); } else { // unable to get aws config LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.FailedToGetConfiguration)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(CommonErrors.FailedToGetConfiguration) })); } } } else { //Token expired LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.ExpiredToken)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenExpired), IsDomainValidationErrors = true })); } } else { // token auth failure LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed), IsDomainValidationErrors = false })); } } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, IsDomainValidationErrors = false })); } }
public string FormatValue(Number value, EffectScalarType scalarType) { var type = MemberType.GetAssignmentType(); if (type == null) { return(value.UInt.ToString()); } var numberType = scalarType.ToNumberType(); if (type.IsEnum && scalarType == EffectScalarType.Int) { var enumValue = (Enum)Enum.ToObject(type, value.UInt); var description = EnumExtensions.GetDescription(enumValue); return(string.Format("{0} /* {1} */", description, value.UInt)); } else if (type.IsEnum) { return(value.ToString(numberType)); } if (type == typeof(float)) { return(value.ToString()); } if (type == typeof(byte)) { if (numberType == Shex.NumberType.UInt || numberType == Shex.NumberType.Int) { return(string.Format("0x{0:x2}", value.Byte0)); } else { return(value.ToString(numberType)); } } if (type == typeof(bool)) { if (scalarType == EffectScalarType.Bool) { return(string.Format("{0} /* {1} */", value.ToString(Shex.NumberType.Bool).ToUpper(), value.ToString(Shex.NumberType.Bool))); } else if (scalarType == EffectScalarType.Int) { return(string.Format("{0} /* {1} */", value.ToString(Shex.NumberType.Bool).ToUpper(), value.UInt)); } else { return(value.ToString(numberType)); } } if (type == typeof(uint)) { if (scalarType == EffectScalarType.UInt) { if (value.UInt > 10000) { return("0x" + value.UInt.ToString("x8")); } return(value.UInt.ToString()); } else { return(value.ToString(numberType)); } } return(value.ToString(numberType)); }
public async Task <IActionResult> UpdateContentStatus(SensoryContentStatus contentUpdate) { try { SensoryCheckDataAccess sensoryCheckDataAccess = new SensoryCheckDataAccess(_configuration); DatabaseResponse response = await sensoryCheckDataAccess.UpdateContentStatus(contentUpdate); if (response.ResponseCode == (int)DbReturnValue.Approved) { return(Ok(new OperationResponse { HasSucceeded = true, IsDomainValidationErrors = false, Message = EnumExtensions.GetDescription(DbReturnValue.Approved), ReturnedObject = response.Results })); } else if (response.ResponseCode == (int)DbReturnValue.Rejected) { return(Ok(new OperationResponse { HasSucceeded = true, IsDomainValidationErrors = false, Message = EnumExtensions.GetDescription(DbReturnValue.Rejected), ReturnedObject = response.Results })); } else if (response.ResponseCode == (int)DbReturnValue.ReviewedByOtherUsers) { Log.Error(EnumExtensions.GetDescription(DbReturnValue.ReviewedByOtherUsers)); return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = false, Message = EnumExtensions.GetDescription(DbReturnValue.ReviewedByOtherUsers), ReturnedObject = response.Results })); } else { Log.Error(EnumExtensions.GetDescription(DbReturnValue.ActionAlreadyTaken)); return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = false, Message = EnumExtensions.GetDescription(DbReturnValue.ActionAlreadyTaken) })); } } catch (Exception ex) { Log.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, StatusCode = ((int)ResponseStatus.ServerError).ToString(), IsDomainValidationErrors = false })); } }
public async Task <IActionResult> UpdateAdminProfile([FromHeader(Name = "Grid-Authorization-Token")] string token, [FromBody] AdminProfile adminuser) { try { if (string.IsNullOrEmpty(token)) { return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = EnumExtensions.GetDescription(CommonErrors.TokenEmpty) })); } AdminUsersDataAccess _adminUsersDataAccess = new AdminUsersDataAccess(_iconfiguration); DatabaseResponse tokenAuthResponse = await _adminUsersDataAccess.AuthenticateAdminUserToken(token); if (tokenAuthResponse.ResponseCode == (int)DbReturnValue.AuthSuccess) { if (!((AuthTokenResponse)tokenAuthResponse.Results).IsExpired) { int _AdminUserID = ((AuthTokenResponse)tokenAuthResponse.Results).CustomerID; if (!ModelState.IsValid) { LogInfo.Warning(StatusMessages.DomainValidationError); new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = string.Join("; ", ModelState.Values .SelectMany(x => x.Errors) .Select(x => x.ErrorMessage)) }; } DatabaseResponse response = await _adminUsersDataAccess.UpdateAdminProfile(_AdminUserID, adminuser); if (response.ResponseCode == ((int)DbReturnValue.EmailNotExists)) { return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.EmailNotExists), IsDomainValidationErrors = true })); } else { return(Ok(new OperationResponse { HasSucceeded = true, Message = EnumExtensions.GetDescription(DbReturnValue.CreateSuccess), IsDomainValidationErrors = false, ReturnedObject = response.Results })); } } else { //Token expired LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.ExpiredToken)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenExpired), IsDomainValidationErrors = true })); } } else { // token auth failure LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed), IsDomainValidationErrors = false })); } } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, IsDomainValidationErrors = false })); } }
public async Task <IActionResult> GetAdminRoles([FromHeader(Name = "Grid-Authorization-Token")] string token) { try { if (string.IsNullOrEmpty(token)) { return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = EnumExtensions.GetDescription(CommonErrors.TokenEmpty) })); } AdminUsersDataAccess _adminUsersDataAccess = new AdminUsersDataAccess(_iconfiguration); DatabaseResponse tokenAuthResponse = await _adminUsersDataAccess.AuthenticateAdminUserToken(token); if (tokenAuthResponse.ResponseCode == (int)DbReturnValue.AuthSuccess) { if (!((AuthTokenResponse)tokenAuthResponse.Results).IsExpired) { List <Roles> AdminUsersList = new List <Roles>(); AdminUsersList = await _adminUsersDataAccess.GetAdminRoles(); if (AdminUsersList == null || AdminUsersList.Count == 0) { LogInfo.Error(EnumExtensions.GetDescription(DbReturnValue.NotExists)); return(Ok(new ServerResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.NotExists) })); } else { return(Ok(new ServerResponse { HasSucceeded = true, Message = StatusMessages.SuccessMessage, Result = AdminUsersList })); } } else { //Token expired LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.ExpiredToken)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenExpired), IsDomainValidationErrors = true })); } } else { // token auth failure LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed), IsDomainValidationErrors = false })); } } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, IsDomainValidationErrors = false })); } }
public async Task <IActionResult> Delete(int id) { try { if (!ModelState.IsValid) { return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, StatusCode = ((int)ResponseStatus.BadRequest).ToString(), Message = string.Join("; ", ModelState.Values .SelectMany(x => x.Errors) .Select(x => x.ErrorMessage)) })); } SubCategoryDataAccess _subCategoryAccess = new SubCategoryDataAccess(_iconfiguration); DatabaseResponse response = await _subCategoryAccess.DeleteSubCategory(id); if (response.ResponseCode == (int)DbReturnValue.DeleteSuccess) { return(Ok(new OperationResponse { HasSucceeded = true, IsDomainValidationErrors = false, Message = EnumExtensions.GetDescription(DbReturnValue.DeleteSuccess), ReturnedObject = response.Results })); } else if (response.ResponseCode == (int)DbReturnValue.ActiveTryNotDelete) { Log.Error(EnumExtensions.GetDescription(DbReturnValue.ActiveTryNotDelete)); return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = false, Message = EnumExtensions.GetDescription(DbReturnValue.ActiveTryNotDelete), ReturnedObject = response.Results })); } else { Log.Error(EnumExtensions.GetDescription(DbReturnValue.NotExists)); return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = false, Message = EnumExtensions.GetDescription(DbReturnValue.NotExists), ReturnedObject = response.Results })); } } catch (Exception ex) { Log.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, StatusCode = ((int)ResponseStatus.ServerError).ToString(), IsDomainValidationErrors = false })); } }
public void GetDescription_Throws_ArgumentNullException() { EnumExtensions.GetDescription(null); }
public void GetDescription_Throws_ArgumentException() { EnumExtensions.GetDescription((TestEnum)10); }
public async Task <IActionResult> UpdateAdminAccountAccessibility([FromHeader(Name = "Grid-Authorization-Token")] string token, [FromRoute] int AdminUserID, int Status) { try { if (string.IsNullOrEmpty(token)) { return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = EnumExtensions.GetDescription(CommonErrors.TokenEmpty) })); } if (!(Status == 1 || Status == 0)) { return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = EnumExtensions.GetDescription(CommonErrors.InvalidStatus) })); } AdminUsersDataAccess _adminUsersDataAccess = new AdminUsersDataAccess(_iconfiguration); DatabaseResponse tokenAuthResponse = await _adminUsersDataAccess.AuthenticateAdminUserToken(token); if (tokenAuthResponse.ResponseCode == (int)DbReturnValue.AuthSuccess) { if (!((AuthTokenResponse)tokenAuthResponse.Results).IsExpired) { if (!ModelState.IsValid) { return(Ok(new OperationResponse { HasSucceeded = false, IsDomainValidationErrors = true, Message = string.Join("; ", ModelState.Values .SelectMany(x => x.Errors) .Select(x => x.ErrorMessage)) })); } DatabaseResponse updateAdminResponse = await _adminUsersDataAccess.UpdateAdminAccountAccessibility(token, AdminUserID, Status); if (updateAdminResponse.ResponseCode == (int)DbReturnValue.UpdateSuccess) { //update success return(Ok(new ServerResponse { HasSucceeded = true, Message = Status == 0? EnumExtensions.GetDescription(CommonErrors.AccountDeactivated): EnumExtensions.GetDescription(CommonErrors.AccountActivated), })); } if (updateAdminResponse.ResponseCode == (int)DbReturnValue.UpdationFailed) { //failed to update return(Ok(new ServerResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(CommonErrors.FailedToUpdateAccessibility), })); } if (updateAdminResponse.ResponseCode == (int)DbReturnValue.AdminTokenNotExists) { //admin token not exists return(Ok(new ServerResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(CommonErrors.TokenNotExists), })); } else { //admin user not exists return(Ok(new ServerResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(CommonErrors.UserNotExists), })); } } else { //Token expired LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.ExpiredToken)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenExpired), IsDomainValidationErrors = true })); } } else { // token auth failure LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed), IsDomainValidationErrors = false })); } } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, IsDomainValidationErrors = false })); } }
public async Task <IActionResult> GetVASes([FromHeader(Name = "Grid-Authorization-Token")] string token) { try { AuthHelper helper = new AuthHelper(_iconfiguration); DatabaseResponse tokenAuthResponse = await helper.AuthenticateCustomerToken(token, APISources.Customer_SharedVASPurchaseScreen); if (tokenAuthResponse.ResponseCode == (int)DbReturnValue.AuthSuccess) { if (!((AuthTokenResponse)tokenAuthResponse.Results).IsExpired) { int customerID = ((AuthTokenResponse)tokenAuthResponse.Results).CustomerID; SharedVASDataAccess _vasSharedAccess = new SharedVASDataAccess(_iconfiguration); return(Ok(new ServerResponse { HasSucceeded = true, Message = StatusMessages.SuccessMessage, Result = await _vasSharedAccess.GetVASes(customerID) })); } else { //Token expired LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.ExpiredToken)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenExpired), IsDomainValidationErrors = true })); } } else { // token auth failure LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed)); return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed), IsDomainValidationErrors = false })); } } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, IsDomainValidationErrors = false })); } }
public async Task <IActionResult> GetAdminLoginAuthentication([FromHeader(Name = "Grid-General-Token")] string Token, [FromBody] AdminUserLoginRequest userdetails) { try { if ((string.IsNullOrEmpty(userdetails.Email)) || (string.IsNullOrEmpty(userdetails.Password))) { LogInfo.Warning(StatusMessages.MissingRequiredFields); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.MissingRequiredFields, IsDomainValidationErrors = true })); } TokenValidationHelper tokenValidationHelper = new TokenValidationHelper(); if (!tokenValidationHelper.ValidateGenericToken(Token, _iconfiguration)) { return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed), IsDomainValidationErrors = true })); } AdminUsersDataAccess _AdminUsersDataAccess = new AdminUsersDataAccess(_iconfiguration); DatabaseResponse response = await _AdminUsersDataAccess.GetLoginAuthentication(userdetails); if (response.ResponseCode == ((int)DbReturnValue.EmailNotExists)) { return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.EmailNotExists), IsDomainValidationErrors = true })); } else if (response.ResponseCode == ((int)DbReturnValue.PasswordIncorrect)) { return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.PasswordIncorrect), IsDomainValidationErrors = true })); } else if (response.ResponseCode == ((int)DbReturnValue.AccountDeactivated)) { return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.AccountDeactivated), IsDomainValidationErrors = true })); } else if (response.ResponseCode == ((int)DbReturnValue.AuthSuccess)) { //Authentication success var adminuser = new AdminUsers(); adminuser = (AdminUsers)response.Results; var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes("stratagile grid adminuser signin jwt hashing secret"); DatabaseResponse configResponse = ConfigHelper.GetValueByKey(ConfigKeys.CustomerTokenExpiryInDays.ToString(), _iconfiguration); int expiryDay = 0; if (configResponse.ResponseCode == (int)DbReturnValue.RecordExists) { expiryDay = int.Parse(configResponse.Results.ToString()); } var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, adminuser.AdminUserID.ToString()) }), Expires = DateTime.Now.AddDays(expiryDay), // need to check with business needs SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); DatabaseResponse tokenResponse = new DatabaseResponse(); tokenResponse = await _AdminUsersDataAccess.LogAdminUserToken(adminuser.AdminUserID, tokenString); // return basic user info (without password) and token to store client side return(Ok(new OperationResponse { HasSucceeded = true, Message = EnumExtensions.GetDescription(DbReturnValue.AuthSuccess), ReturnedObject = new LoggedInPrinciple { AdminUser = adminuser, IsAuthenticated = true, Token = tokenString } } )); } else { return(Ok(new OperationResponse { HasSucceeded = false, Message = EnumExtensions.GetDescription(DbReturnValue.ReasonUnknown), IsDomainValidationErrors = true })); } } catch (Exception ex) { LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical)); return(Ok(new OperationResponse { HasSucceeded = false, Message = StatusMessages.ServerError, IsDomainValidationErrors = false })); } }