//Post call for approval api public async Task <string> ApprovalAPIPostCall(string endpointUri, ApprovalQuery ObjApprovalQuery) { UserProfileController userProfileObj = new UserProfileController(); var result = string.Empty; try { //create object of client request using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose"); client.DefaultRequestHeaders.Add("ContentType", "application/json;odata=verbose"); client.DefaultRequestHeaders.Add("Authorization", "Bearer " + await userProfileObj.GetTokenForApplication()); //get API endpoint and format var request1 = new HttpRequestMessage(HttpMethod.Post, endpointUri); request1.Content = new StringContent(JsonConvert.SerializeObject(ObjApprovalQuery), Encoding.UTF8, "application/json"); var result1 = client.SendAsync(request1).Result; //if the api call returns successcode then return the result into string if (result1.IsSuccessStatusCode) { result = result1.Content.ReadAsStringAsync().GetAwaiter().GetResult(); } } } catch (Exception exception) { LoggerHelper.WriteToLog(exception, "Error While Connecting to an API." + exception.ToString()); throw new DataAccessException("Error While Connecting to an API"); } return(result); }
//Async task for save approval details public async Task <string> SendApprovalInfo(ApprovalQuery ObjApprovalQuer, string requestID) { string rspApprovaltasks = string.Empty; try { string WebApiRootURL = SettingsHelper.WebApiUrl; if (!string.IsNullOrEmpty(WebApiRootURL)) { //Creates the enpoint uri to be called StringBuilder EndPointUri = new StringBuilder(WebApiRootURL); string api = string.Format(SettingsHelper.ApprovalAPIReqID, requestID); //SettingsHelper.PersonalizationAPIUser + userid + "/"; Uri spotlightEndPointUri = new Uri(EndPointUri.Append(string.Format(api)).ToString()); Helper JsonHelperObj = new Helper(); //Gets the response returned by the Sync API rspApprovaltasks = await JsonHelperObj.ApprovalAPIPostCall(string.Format(spotlightEndPointUri.ToString()), ObjApprovalQuer); } else { //Write the trace in db that no url exists LoggerHelper.WriteToLog("WebApiRootURL URL is null", CoreConstants.Priority.High, CoreConstants.Category.Error); return(null); } } catch (Exception exception) { // logging an error if in case some exception occurs LoggerHelper.WriteToLog(exception, "Error while fetching the most popular videos" + exception.ToString()); throw new DataAccessException("Data Access Exception:-Error while saving user info"); } return(rspApprovaltasks); }
public QueryRange <IContent> ExecuteQueryInternal(ApprovalQuery query) { var itemsToBeApproved = _approvalRepository.ListAsync(query); var contentItemsToBeApproved = new List <IContent>(); var result = itemsToBeApproved.Result; foreach (ContentApproval approval in result) { contentItemsToBeApproved.Add(_contentRepository.Get <IContent>(approval.ContentLink)); } var items = new QueryRange <IContent>(contentItemsToBeApproved, new ItemRange()); return(items); }
public HttpResponseMessage PostApproval(ApprovalQuery ObjApprovalQuery) { string callerMethodName = string.Empty; try { //Get Caller Method name from CallerInformation class callerMethodName = CallerInformation.TrackCallerMethodName(); InsightLogger.TrackEvent("ApprovalAPIController :: Endpoint : api/approval/requests/{apprReqID} , Action :: POST: Updates the status of a user approval request :: Start(), Query From UI:" + JsonConvert.SerializeObject(ObjApprovalQuery)); //Checking ApprovalQuery object is valid or not(User and decision status are the mandatory input data required) if (!string.IsNullOrEmpty(ObjApprovalQuery.UserID) && !string.IsNullOrEmpty(ObjApprovalQuery.ApprovalDecision.Status)) { //Asynchronously Updates the status of the approval object , set the backend confirmed flag to false and invoke the backend request approval api //Fire And Forget Method implementaion InsightLogger.TrackEvent("ApprovalAPIController :: Endpoint : api/approval/requests/{apprReqID} , Action :: Get recevied Message, Response :: true, Message ::" + JsonConvert.SerializeObject(ObjApprovalQuery)); InsightLogger.TrackEvent("ApprovalAPIController :: Endpoint : api/approval/requests/{apprReqID} , Action :: return Acknowledgement message, Response :: true "); Task.Factory.StartNew(() => { ApprovalBL objappr = new ApprovalBL(); objappr.UpdateApprovalObject(ObjApprovalQuery); }); //return Response message success status code return(Request.CreateResponse(HttpStatusCode.OK)); } else { InsightLogger.TrackEvent("ApprovalAPIController :: Endpoint : api/approval/requests/{apprReqID} , Action :: Get Message has recevied, Response :: Approval Query is Invalid, Message ::" + JsonConvert.SerializeObject(ObjApprovalQuery)); //if model is not valid which means it doesn't contains mandatory fields return error message return(Request.CreateResponse(HttpStatusCode.OK, DataProvider.ApprovalResponseError <ApprovalResponse>("400", "Approval Query is Invalid", ""))); } } catch (DataAccessException dalexception) { return(Request.CreateResponse(HttpStatusCode.NotFound, DataProvider.ApprovalResponseError <ApprovalResponse>("400", dalexception.Message, dalexception.Message))); } catch (BusinessLogicException blexception) { return(Request.CreateResponse(HttpStatusCode.NotFound, DataProvider.ApprovalResponseError <ApprovalResponse>("400", blexception.Message, blexception.Message))); } catch (Exception exception) { InsightLogger.Exception(exception.Message, exception, callerMethodName); return(Request.CreateResponse(HttpStatusCode.NotFound, DataProvider.PersonalizationResponseError <UserBackendDTO>("400", exception.Message, exception.StackTrace))); } }
/// <summary> /// This method updates the approval object in azure layer /// </summary> /// <param name="objApprQry"></param> public void UpdateApprovalObject(ApprovalQuery objApprQry) { string callerMethodName = string.Empty; try { //Get Caller Method name from CallerInformation class callerMethodName = CallerInformation.TrackCallerMethodName(); //calling data access layer method for updating the approval status details objApprovalDAL.UpdateApprovalObjectStatus(objApprQry); } //catch (DataAccessException DALexception) //{ // throw DALexception; //} catch (Exception exception) { InsightLogger.Exception(exception.Message, exception, callerMethodName); //throw new BusinessLogicException("Error in BL while updating ApprovalEntity details in BL.Approval::UpdateApprovalObject()" + exception.Message, exception.InnerException); } }
public async Task <ActionResult> SendApprovalstatus(ApprovalQuery approvalInfo) { try { approvalInfo.UserID = userid; //Api Controller object initialization APIController apiControllerObj = new APIController(); //Send approval details to Approval API string stApprovalrequeststatus = await apiControllerObj.SendApprovalInfo(approvalInfo, approvalInfo.ApprovalRequestID); //creates list request details object List <ApprovalRequestDTO> requestsDetails = new List <ApprovalRequestDTO>(); // Return Json Formate object and pass to UI return(Json(requestsDetails, JsonRequestBehavior.AllowGet)); } catch (Exception exception) { LoggerHelper.WriteToLog(exception + " - Error while creating client context : " + exception.ToString(), CoreConstants.Priority.High, CoreConstants.Category.Error); return(View("Error")); } }
private async Task <List <ContentTask> > ProcessChangeData(int pageNumber, int pageSize, string sorting, AdvancedTaskIndexViewData model) { //List of All task for the user var query = new ApprovalQuery { Status = ApprovalStatus.InReview, Username = PrincipalInfo.CurrentPrincipal.Identity.Name, Reference = new Uri("changeapproval:") }; var list = await _approvalRepository.ListAsync(query, (pageNumber - 1) *pageSize, pageSize); model.TotalItemsCount = Convert.ToInt32(list.TotalCount); var taskList = new List <ContentTask>(); foreach (var task in list.PagedResult) { IContent content = null; var id = task.ID.ToString(); var customTask = new ContentTask { ApprovalId = task.ID, DateTime = task.ActiveStepStarted.ToString("dd MMMM HH:mm"), StartedBy = task.StartedBy, URL = PageEditing.GetEditUrl(new ContentReference(task.ID)).Replace(".contentdata:", ".changeapproval:") }; if (!(task is ContentApproval)) { var taskDetails = _changeTaskHelper.GetData(task.ID); if (taskDetails != null) { customTask.Type = taskDetails.Type; customTask.ContentName = taskDetails.Name; customTask.Details = taskDetails.Details; } if (task.Reference != null) { if (!string.IsNullOrEmpty(task.Reference.AbsolutePath)) { var pageId = task.Reference.AbsolutePath.Replace("/", ""); int.TryParse(pageId, out var contentId); if (contentId != 0) { _contentRepository.TryGet(new ContentReference(contentId), out content); } } } if (content != null) { customTask.ContentReference = content.ContentLink; customTask.ContentType = GetTypeContent(content); } customTask = await GetNotifications(id, customTask, false); taskList.Add(customTask); } } taskList = SortColumns(sorting, taskList); return(taskList); }
private async Task <List <ContentTask> > ProcessContentData(int pageNumber, int pageSize, string sorting, AdvancedTaskIndexViewData model, string taskValues, string approvalComment) { if (!string.IsNullOrEmpty(taskValues)) { await ApproveContent(taskValues, approvalComment); } //List of All task for the user var query = new ApprovalQuery { Status = ApprovalStatus.InReview, Username = PrincipalInfo.CurrentPrincipal.Identity.Name, Reference = new Uri("content:") }; var list = await _approvalRepository.ListAsync(query, (pageNumber - 1) *pageSize, pageSize); model.TotalItemsCount = Convert.ToInt32(list.TotalCount); var taskList = new List <ContentTask>(); foreach (var task in list.PagedResult) { var id = task.ID.ToString(); var customTask = new ContentTask { ApprovalId = task.ID, DateTime = task.ActiveStepStarted.ToString("dd MMMM HH:mm"), StartedBy = task.StartedBy }; if (task is ContentApproval approval) { _contentRepository.TryGet(approval.ContentLink, out IContent content); if (content != null) { customTask.URL = PageEditing.GetEditUrl(approval.ContentLink); id = content.ContentLink.ID.ToString(); var canUserPublish = await _helper.CanUserPublish(content); customTask.CanUserPublish = canUserPublish; customTask.ContentReference = content.ContentLink; customTask.ContentName = content.Name; customTask.ContentType = GetTypeContent(content); if (content is PageData) { customTask.Type = "Page"; } else if (content is BlockData) { customTask.Type = "Block"; if (!string.IsNullOrWhiteSpace(customTask.ContentType) && customTask.ContentType.Equals("Form container")) { customTask.Type = "Form"; } } else if (content is ImageData) { customTask.Type = "Image"; } else if (content is MediaData) { customTask.Type = "Media"; if (!string.IsNullOrWhiteSpace(customTask.ContentType) && customTask.ContentType.Equals("Video")) { customTask.Type = "Video"; } } var enableContentApprovalDeadline = bool.Parse(ConfigurationManager.AppSettings["ATM:EnableContentApprovalDeadline"] ?? "false"); var warningDays = int.Parse(ConfigurationManager.AppSettings["ATM:WarningDays"] ?? "4"); if (enableContentApprovalDeadline) { //Deadline Property of The Content var propertyData = content.Property.Get(ContentApprovalDeadlinePropertyName) ?? content.Property[ContentApprovalDeadlinePropertyName]; if (propertyData != null) { DateTime.TryParse(propertyData.ToString(), out DateTime dateValue); if (dateValue != DateTime.MinValue) { if (!string.IsNullOrEmpty(customTask.Type)) { customTask.Deadline = dateValue.ToString("dd MMMM HH:mm"); var days = DateTime.Now.CountDaysInRange(dateValue); if (days == 0) { customTask.WarningColor = "red"; } else if (days > 0 && days < warningDays) { customTask.WarningColor = "green"; } } else { customTask.Deadline = " - "; } } } } } //Get Notifications customTask = await GetNotifications(id, customTask, true); taskList.Add(customTask); } } taskList = SortColumns(sorting, taskList); return(taskList); }
/// <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> /// This method will update the status of backend request with the help of backend agent requestApproval API /// </summary> /// <param name="apprReqDetails"></param> /// <param name="backendID"></param> /// <param name="apprReqID"></param> /// <returns></returns> public async Task <string> UpdateApprovalRequest(ApprovalQuery apprReqDetails, string backendID, string apprReqID) { string result = string.Empty; string callerMethodName = string.Empty; try { //Get Caller Method name from CallerInformation class callerMethodName = CallerInformation.TrackCallerMethodName(); //get API endpoint and format it in agents/{backendID}/requestApproval/{reqID} string backendApiEndpoint = UrlSettings.GetBackendAgentRequestApprovalAPI(backendID, apprReqID); string apiURL = string.Format(ConfigurationManager.AppSettings["BackendAgentRequestApprovalAPIRouteMethod"].ToString(), backendID, apprReqID); string approvalquery = JsonConvert.SerializeObject(apprReqDetails); // InsightLogger.TrackEvent("ApprovalAPIController :: Endpoint : api/approval/requests/{ " + apprReqID + "} , Action : invoke the backend API for submit the approval or rejection for given request :: Baceknd API:" + backendApiEndpoint + " Approval Request Message:" + approvalquery); //Max Retry call from web.config int maxRetryCount = Convert.ToInt32(ConfigurationManager.AppSettings["MaxRetryCount"]); int maxThreadSleepInMilliSeconds = Convert.ToInt32(ConfigurationManager.AppSettings["MaxThreadSleepInMilliSeconds"]); int RetryAttemptCount = 0; bool IsSuccessful = false; //checking backend endpoint null or empty if (!string.IsNullOrEmpty(backendApiEndpoint)) { InsightLogger.TrackEvent("ApprovalAPIController :: Endpoint : api/approval/requests/{ " + apprReqID + "} , Action :: Notify Backend(invoking the backend agent API for approval), Response :: Success ,Details are Backend Agent API=" + apiURL + " Approval Query Message:" + approvalquery); using (HttpClient client = new HttpClient()) { //Implemented Use of retry / back-off logic do { try { //POST: Submits the approval or rejection for one specific request client.BaseAddress = new Uri(ConfigurationManager.AppSettings["BackendAPIURL"]); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); StringContent content = new StringContent(approvalquery, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(apiURL, content); //var request = new HttpRequestMessage(HttpMethod.Post, backendApiEndpoint); //StringContent content = new StringContent(approvalquery, Encoding.UTF8, "application/json"); //request.Content = new StringContent(approvalquery, Encoding.UTF8, "application/json"); //var resultset = client.PostAsync(request).Result; //if response message returns success code then return the successcode message //if (resultset.IsSuccessStatusCode) //{ // string resMessage = resultset.ReasonPhrase; // string response = resultset.Content.ReadAsStringAsync().GetAwaiter().GetResult(); // if (!string.IsNullOrEmpty(response)) // { // //request update acknowledgement // RequestsUpdateAck Objacknowledgement = JsonConvert.DeserializeObject<RequestsUpdateAck>(response); // //if request update acknowledgement error object is null means backend api successfully called // if (Objacknowledgement.Error == null) // { // result = resMessage; // } // } //} //else //{ // result = "Error occurred while invoking the backend Agent Request approval API."; //} IsSuccessful = true; } catch (Exception serviceException) { //Increasing RetryAttemptCount variable RetryAttemptCount = RetryAttemptCount + 1; //Checking retry call count is eual to max retry count or not if (RetryAttemptCount == maxRetryCount) { InsightLogger.TrackEvent(callerMethodName + " - exception while Call baceknd agent request approval API in ApprovalAPIController::Retry attempt count: [" + RetryAttemptCount + "]"); throw new ServiceLayerException(serviceException.Message, serviceException.InnerException); } else { InsightLogger.Exception(serviceException.Message, serviceException, callerMethodName); InsightLogger.TrackEvent(callerMethodName + " - exception while Call baceknd agent request approval API in ApprovalAPIController::Retry attempt count: [" + RetryAttemptCount + "]"); //Putting the thread into some milliseconds sleep and again call the same method call. Thread.Sleep(maxThreadSleepInMilliSeconds); } } } while (!IsSuccessful); } return(result); } else { //Write the trace in db that no url exists InsightLogger.TrackEvent(callerMethodName + " Error Details : baceknd agent request approval API is null"); return(null); } } catch (Exception exception) { // logging an error if in case some exception occurs InsightLogger.Exception(exception.Message, exception, callerMethodName); throw new ServiceLayerException(exception.Message, exception.InnerException); } }