public Task <bool> Handle(InsertNewApprovalCommand request, CancellationToken cancellationToken) { if (!request.IsValid()) { NotifyValidationErrors(request); return(Task.FromResult(false)); } var approval = new ApprovalEntity(Guid.NewGuid() , request.CategoryId , request.Subject , request.Description , request.EmailApproval , DateTime.Now); _approvalRepository.Add(approval); if (Commit()) { Bus.RaiseEvent(new ApprovalInsertEvent(approval.Id , approval.CategoryId , approval.Subject , approval.Description , approval.EmailApproval , approval.DateCreate)); } return(Task.FromResult(true)); }
public static ActivityResult SendSmsChallenge( [ActivityTrigger] VerificationParameter phone, [Microsoft.Azure.WebJobs.Table("approval", "AzureWebJobsStorage")] CloudTable table, ILogger log, [TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "%TwilioPhoneNumber%")] out CreateMessageOptions message) { try { int challengeCode = GetChallengeCode(); log.LogInformation($"Sending verification code {challengeCode} to {phone.Payload}."); var entity = new ApprovalEntity(phone.OrchestrationId, "NewMember", challengeCode, EventNameSms); log.LogInformation(SimpleJson.SimpleJson.SerializeObject(entity)); table.AddToTableStorageASync(entity).GetAwaiter().GetResult(); message = new CreateMessageOptions(new PhoneNumber(phone.Payload)); message.Body = $"Your verification code is {challengeCode:0000}"; return(new ActivityResult { HasError = false, Value = challengeCode }); } catch (Exception ex) { message = null; return(new ActivityResult { HasError = true, Value = ex.Message }); } }
public async void Should_CreateApprovalAsync_Valid() { var newAccountEntity = new ApprovalEntity { AccountId = Guid.NewGuid() }; var newCreatedAccountEntity = await _service.CreateApprovalAsync(newAccountEntity); Assert.NotNull(newCreatedAccountEntity); }
public async void Should_AddAsync_Valid() { await using var context = new TestContext(ContextOptions); var repository = new ApprovalsRepository( new Mock <ILogger <AbstractRepository <ApprovalsContext, ApprovalEntity> > >().Object, context ); var newEntity = new ApprovalEntity(); var result = await repository.AddAsync(newEntity); Assert.NotNull(result); }
public static async Task <ActivityResult> SendEMailVerification( [ActivityTrigger] VerificationParameter eMail, [Microsoft.Azure.WebJobs.Table("approval", "AzureWebJobsStorage")] CloudTable table, ILogger log, Microsoft.Azure.WebJobs.ExecutionContext context) { var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", true, true) .AddEnvironmentVariables() .Build(); string uriFlow = config["flowRESTTarget"]; log.LogInformation(config.ToString()); int challengeCode = GetChallangeCode(); try { var valueObject = new SendMail { emailadress = eMail.Payload, emailSubject = "Confirmation of membership - " + challengeCode, emailBody = $"http://{Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME")}/api/approve/{challengeCode}" }; var entity = new ApprovalEntity(eMail.OrchestrationId, "NewMember", challengeCode, EventNameEMail); await table.AddToTableStorageASync(entity); var client = new RestClient(uriFlow); var request = new RestRequest(Method.POST); request.AddHeader("Cache-Control", "no-cache"); request.AddHeader("Content-Type", "application/json"); request.AddParameter("undefined", SimpleJson.SimpleJson.SerializeObject(valueObject), ParameterType.RequestBody); IRestResponse response = client.Execute(request); if (!response.IsSuccessful) { log.LogError(new EventId(1, "EMail not sent"), $"EMail to receiver {valueObject.emailadress} could not be sent. Error: {response.Content}"); } return(new ActivityResult { HasError = false, Value = challengeCode }); } catch (Exception ex) { return(new ActivityResult { HasError = true, Value = ex.Message }); } }
public async void Should_GetOneByParameterAsync_Valid() { await using var context = new TestContext(ContextOptions); var repository = new ApprovalsRepository( new Mock <ILogger <AbstractRepository <ApprovalsContext, ApprovalEntity> > >().Object, context ); var newEntity = new ApprovalEntity { Version = 99 }; var _ = await repository.AddAsync(newEntity); var result = await repository.GetOneByParameterAsync( e => e.Version == 99 ); Assert.NotNull(result); }
/// <summary> /// method to add/upadte Request entity to azure table /// </summary> /// <param name="approval">takes approval entity as input</param> public void AddUpdateApproval(ApprovalEntity approval) { //Get Caller Method name string callerMethodName = string.Empty; try { //Get Caller Method name from CallerInformation class callerMethodName = CallerInformation.TrackCallerMethodName(); //call dataprovider method to insert entity into azure table DataProvider.InsertReplaceEntity <ApprovalEntity>(CoreConstants.AzureTables.RequestTransactions, approval); } catch (Exception exception) { //write exception into application insights InsightLogger.Exception(exception.Message + " - Error while inserting approval into requestTransactions azure table in DAL ", exception, callerMethodName); throw new DataAccessException(); } }
public static TModel ToAccountModel <TModel>(this ApprovalEntity approvalEntity, IAccountModel accountModel) where TModel : class, IAccountModel, new() { return(new TModel { Id = accountModel.Id, Version = accountModel.Version, Balance = accountModel.Balance, ProfileId = accountModel.ProfileId, Approved = approvalEntity.Approved, Pending = approvalEntity.Pending, Blocked = approvalEntity.Blocked, LastSequentialNumber = accountModel.LastSequentialNumber }); }
public Task <bool> Handle(UpdateApprovalCommand request, CancellationToken cancellationToken) { if (!request.IsValid(_user)) { NotifyValidationErrors(request); return(Task.FromResult(false)); } var approval = new ApprovalEntity(request.Id , request.CategoryId , request.Subject , request.Description , request.EmailApproval , request.DateCreate) .SetIsApproval(request.IsApproval) .SetDateApproval(request.DateApproval) .SetJustification(request.Justification) .SetDateRead(request.DateRead); _approvalRepository.Attach(approval); if (Commit()) { Bus.RaiseEvent(new ApprovalUpdateEvent(approval.Id , approval.Subject , approval.Description , approval.IsApproval , approval.Justification , approval.CategoryId , approval.EmailApproval , approval.DateCreate , approval.DateApproval , approval.DateRead)); } return(Task.FromResult(true)); }
public UserBackendDTO AddRequsetsTasksCountToSynchResponse(List <RequestEntity> userbackendrequestslist, List <ApprovalEntity> userbackendapprovalslist, UserBackendEntity userbackend, SynchRequestDTO query, UserBackendDTO userbackenddto) { string callerMethodName = string.Empty; try { //Get Caller Method name from CallerInformation class callerMethodName = CallerInformation.TrackCallerMethodName(); List <ApprovalRequestDTO> approvalrequestlist = new List <ApprovalRequestDTO>(); InsightLogger.TrackEvent("SyncAPIController :: endpoint - api/synch/users/{userID}/backends, action: Loop through all requests in backend"); //loop through each request in the userbackend foreach (RequestEntity request in userbackendrequestslist) { ApprovalRequestDTO approvalrequest = new ApprovalRequestDTO(); RequestDTO requestdto = new RequestDTO(); //get approval associated to request ApprovalEntity approval = userbackendapprovalslist.Find(x => x.RequestId == request.ID); if (approval != null) { ApprovalDTO approvaldto = new ApprovalDTO(); approvaldto = DataProvider.ResponseObjectMapper <ApprovalDTO, ApprovalEntity>(approval); approvalrequest.approval = approvaldto; userbackenddto.approvalsCount.Count = userbackenddto.approvalsCount.Count + 1; //if request is updated if (Rules.IsRequestUpdated(request, userbackend.DefaultUpdateFrequency)) { InsightLogger.TrackEvent("SyncAPIController :: endpoint - api/synch/users/{userID}/backends, action: check request update, response: true"); //get request synch entity RequestSynchEntity requestsynch = GetRequestSynch(request); //check if requests which have changed since the last synch need to send in response or all requests. if (Rules.IsTargetRequest(query, request, approval, requestsynch)) { InsightLogger.TrackEvent("SyncAPIController :: endpoint - api/synch/users/{userID}/backends, action: Target request, response: true"); requestdto = DataProvider.ResponseObjectMapper <RequestDTO, RequestEntity>(request); approvalrequest.request = requestdto; InsightLogger.TrackEvent("SyncAPIController :: endpoint - api/synch/users/{userID}/backends, action: add request header to response, response: success"); //code here to populate extended depth //code here to update request synch time stamp AddUpdateRequestSynch(request, requestsynch, query.userId); InsightLogger.TrackEvent("SyncAPIController :: endpoint - api/synch/users/{userID}/backends, action: Update request synch timestamp, response: success"); //requestsfulfilled = true; } } else { InsightLogger.TrackEvent("SyncAPIController :: endpoint - api/synch/users/{userID}/backends, action: check request update, response: false"); //check if request update is in progress in service layer then send the latency in response if (Rules.IsRequestUpdateInProgress(request)) { InsightLogger.TrackEvent("SyncAPIController :: endpoint - api/synch/users/{userID}/backends, action: update in-progress, response: true"); approvalrequest.retryAfter = request.ExpectedLatency; InsightLogger.TrackEvent("SyncAPIController :: endpoint - api/synch/users/{userID}/backends, action: Add expected request latancy to resposne as retry time, response: Success"); } else { InsightLogger.TrackEvent("SyncAPIController :: endpoint - api/synch/users/{userID}/backends, action: update in-progress, response: false"); TriggerRequestUpdate(request, query.userId); InsightLogger.TrackEvent("SyncAPIController :: endpoint - api/synch/users/{userID}/backends, action: trigger a Request update, response: success"); approvalrequest.retryAfter = Convert.ToInt32(Rules.RequestRetryTime(userbackend)); InsightLogger.TrackEvent("SyncAPIController :: endpoint - api/synch/users/{userID}/backends, action: Add request retrytime to response, response: success"); } //requestsunfulfilled = true; } //add approval request to list which will be added to corresponding backend approvalrequestlist.Add(approvalrequest); } } userbackenddto.requests = approvalrequestlist; return(userbackenddto); } catch (DataAccessException DALexception) { throw DALexception; } catch (Exception exception) { InsightLogger.Exception(exception.Message, exception, callerMethodName); //LoggerHelper.WriteToLog(exception + " - Error in BL while adding all approvals count to response : " //+ exception.ToString(), CoreConstants.Priority.High, CoreConstants.Category.Error); throw new BusinessLogicException(); } }
/// <summary> /// This method updates approval object status /// </summary> /// <param name="objApprQry"></param> /// <returns></returns> public void UpdateApprovalObjectStatus(ApprovalQuery objApprQry) { string callerMethodName = string.Empty; try { //Get Caller Method name from CallerInformation class callerMethodName = CallerInformation.TrackCallerMethodName(); //ApprovalResponse objApprovalResponse = null; string acknowledgement = string.Empty; string backendID = string.Empty; string domain = string.Empty; //reading ApprovalQuery request object properties and assign the values to below variables. string userID = objApprQry.UserID; string taskID = objApprQry.ApprovalRequestID; string status = objApprQry.ApprovalDecision.Status; //string comment = objApprQry.ApprovalDecision.Comment; string comment = string.Format(taskApprovedComment, status, objApprQry.DeviceID); DateTime decisionDate = objApprQry.ApprovalDecision.DecisionDate; string requestID = string.Empty; string approverOrder = string.Empty; string[] taskIDArr = taskID.Split('_'); if (taskIDArr != null && (taskIDArr.Length == 2)) { approverOrder = Convert.ToString(taskIDArr[1]); } //get approvalrequest object from RequestTransactions azure table based on partitionkey and rowkey(requestID) ApprovalEntity apprReqEntity = DataProvider.Retrieveentity <ApprovalEntity>(CoreConstants.AzureTables.RequestTransactions, string.Concat(CoreConstants.AzureTables.ApprovalPK, userID), taskID); if (apprReqEntity != null) { backendID = apprReqEntity.BackendID; domain = apprReqEntity.Domain; requestID = apprReqEntity.RequestId; //update status,decisiondate,comment column values in approvalrequest object apprReqEntity.Status = status; apprReqEntity.DecisionDate = decisionDate; apprReqEntity.Comment = comment; //updating the backend confirmed flag set to false apprReqEntity.BackendConfirmed = false; //call dataprovider method to update entity to azure table DataProvider.UpdateEntity <ApprovalEntity>(CoreConstants.AzureTables.RequestTransactions, apprReqEntity); InsightLogger.TrackEvent("ApprovalAPIController :: Endpoint : api/approval/requests/{ " + requestID + "} , Action :: Update Approval object data in Azure table, Response :: Success ,Details are ApprovalRequestID=" + requestID + " Approver:" + userID + " status:" + status); InsightLogger.TrackEvent("ApprovalAPIController :: Endpoint : api/approval/requests/{ " + requestID + "} , Action :: Cleared Backend-Confirmed flag(set Backend-Confirmed value to false), Response :: Success "); //get domain,backendid details from service layer objApprQry.Domain = domain; objApprQry.BackendID = backendID; objApprQry.ApprovalRequestID = requestID; objApprQry.ApproverOrder = approverOrder; Decision apprDecision = objApprQry.ApprovalDecision; apprDecision.Comment = comment; objApprQry.ApprovalDecision = apprDecision; //call backend requestApproval/ api var result = apiController.UpdateApprovalRequest(objApprQry, backendID, requestID); //if (string.IsNullOrEmpty(result.ToString())) //{ // acknowledgement = result.ToString(); //} } else { InsightLogger.TrackEvent("ApprovalAPIController :: Endpoint : api/approval/requests/{ requestID } , Action :: Update Approval object data in Azure table, Response :: Error ,Details are ApprovalRequestID=" + requestID + " Approver:" + userID + " status:" + status); } //return acknowledgement; } //catch (ServiceLayerException serException) //{ // throw serException; //} catch (Exception exception) { InsightLogger.Exception(exception.Message, exception, callerMethodName); //throw new DataAccessException("Error while updating the approval object staus in ApprovalDAL :: UpdateApprovalObjectStatus() method,Error Message : " + exception.Message, exception.InnerException); } }
/// <summary> /// method to deicede only the filtered requests are sent back or all /// </summary> /// <param name="query">takes qury as input</param> /// <param name="request">takes request as input</param> /// <param name="approvalStatus">takes approvalStatus as input</param> /// <param name="requestsynch">takes requestsynch as input</param> /// <returns>returns whether filtered requests are sent back or all</returns> public static Boolean IsTargetRequest(SynchRequestDTO query, RequestEntity request, ApprovalEntity approval, RequestSynchEntity requestsynch) { string QueryRequestStatus = query.parameters.filters.reqStatus; string QueryApprovalStatus = query.parameters.filters.apprStatus; string approvalStatus = null; if (approval != null) { approvalStatus = approval.Status; } if (requestsynch != null) { return(((string.IsNullOrEmpty(QueryRequestStatus) && (request.Status == QueryRequestStatus)) || (!string.IsNullOrEmpty(QueryRequestStatus))) && ((string.IsNullOrEmpty(QueryApprovalStatus) && (approvalStatus == QueryApprovalStatus)) || (!string.IsNullOrEmpty(QueryApprovalStatus))) && ((query.parameters.filters.onlyChangedReq && request.LastUpdate != null && (request.LastUpdate > requestsynch.LastChange)) || (!query.parameters.filters.onlyChangedReq))); } else { return(((string.IsNullOrEmpty(QueryRequestStatus) && (request.Status == QueryRequestStatus)) || (!string.IsNullOrEmpty(QueryRequestStatus))) && ((string.IsNullOrEmpty(QueryApprovalStatus) && (approvalStatus == QueryApprovalStatus)) || (!string.IsNullOrEmpty(QueryApprovalStatus)))); } }
/// <summary> /// BL method to add approval entity into azure table /// </summary> /// <param name="request">takes request as input</param> public void AddUpdateApproval(List <Approvers> approverslist, string requestid, string UserID, string backendId, int missingconfirmationlimit, string requestTitle) { //Get Caller Method name string callerMethodName = string.Empty; try { //Get Caller Method name from CallerInformation class callerMethodName = CallerInformation.TrackCallerMethodName(); RequestUpdateDAL requestupdatedal = new RequestUpdateDAL(); //get the user tasks from list of approvers got from backend List <Approvers> lstapprover = (from apr in approverslist where apr.User.UserID.Equals(UserID) && (!string.IsNullOrEmpty(apr.Status) && apr.Status != taskNotStartedStatus) select apr).ToList(); if (lstapprover != null && lstapprover.Count > 0) { foreach (Approvers approver in lstapprover) { string partitionkey = string.Concat(CoreConstants.AzureTables.ApprovalPK, UserID); string approverOrder = Convert.ToString(approver.Order); string serviceLayerTaskID = requestid + "_" + approverOrder; //get approval from service layer ApprovalEntity ServiceLayerApproval = requestupdatedal.GetApproval(partitionkey, serviceLayerTaskID); //get the current approver from list of approvers got from backend // Approvers approver = approverslist.Find(x => x.User.UserID == UserID); //check if approval exists or not if (ServiceLayerApproval != null) { if (!ServiceLayerApproval.BackendConfirmed) { //check for Status Confirmation and update approval flags if (ServiceLayerApproval.Status == approver.Status) { ServiceLayerApproval.Backendoverwritten = false; ServiceLayerApproval.BackendConfirmed = true; ServiceLayerApproval.Missingconfirmations = 0; } else { //increase Missingconfirmation limit as status is not matching ServiceLayerApproval.Missingconfirmations = ServiceLayerApproval.Missingconfirmations + 1; ServiceLayerApproval.Backendoverwritten = false; ServiceLayerApproval.BackendConfirmed = false; //Add message to update triggering VIP queue to trigger request update. RequestUpdateTrigger(requestid, UserID, backendId); //check for Missing confirmation limit if (ServiceLayerApproval.Missingconfirmations > missingconfirmationlimit) { ServiceLayerApproval.Backendoverwritten = true; ServiceLayerApproval.BackendConfirmed = true; ServiceLayerApproval.Missingconfirmations = 0; ServiceLayerApproval.Status = approver.Status; } } } else { ServiceLayerApproval.Status = approver.Status; } ServiceLayerApproval.DueDate = approver.DueDate; ServiceLayerApproval.DecisionDate = approver.DecisionDate; //calling DAL method to add request entity requestupdatedal.AddUpdateApproval(ServiceLayerApproval); } else { //generating approval entity from input approver,request obj by adding partitionkey and rowkey ApprovalEntity approvalentity = new ApprovalEntity(); approvalentity.PartitionKey = partitionkey; approvalentity.RowKey = serviceLayerTaskID; approvalentity.RequestId = requestid; string status = approver.Status; //if (string.IsNullOrEmpty(status)) //{ // status = CoreConstants.AzureTables.Waiting; //} approvalentity.Status = status; approvalentity.BackendID = backendId; approvalentity.ServiceLayerTaskID = serviceLayerTaskID; approvalentity.TaskTitle = requestTitle; approvalentity.DueDate = approver.DueDate; //calling DAL method to add request entity requestupdatedal.AddUpdateApproval(approvalentity); } } } } catch (DataAccessException DALexception) { throw DALexception; } catch (Exception exception) { //write exception into application insights InsightLogger.Exception(exception.Message + " - Error in BL while inserting Approval", exception, callerMethodName); throw new BusinessLogicException(); } }
public Task <ApprovalEntity?> UpdateApprovalAsync(ApprovalEntity approvalEntity) { return(_approvalsRepository.UpdateActivelyAsync(approvalEntity) !); }
public async Task <ApprovalEntity?> CreateApprovalAsync(ApprovalEntity approvalEntity) { return(await _approvalsRepository.AddAsync(approvalEntity) !); }