/// <summary> /// Changes the state of a service request to the state provided if the action is possible. /// </summary> /// <param name="userId">ID of user performing the state change</param> /// <param name="requestId">ID of Service Request to change the state of</param> /// <param name="state">State to change the Service Request to</param> /// <param name="comments">Optional: Comments tied to the state change if applicable</param> /// <returns>Service Request after state change is attempted</returns> public IServiceRequestDto <IServiceRequestOptionDto, IServiceRequestUserInputDto> ChangeRequestState(int userId, int requestId, ServiceRequestState state, string comments = null) { IServiceRequestDto <IServiceRequestOptionDto, IServiceRequestUserInputDto> request = RequestFromId(requestId); switch (state) { case ServiceRequestState.Incomplete: throw new ServiceRequestStateException("Cannot change the state of a Service Request to Incomplete."); case ServiceRequestState.Submitted: return(SubmitRequest(userId, requestId)); case ServiceRequestState.Approved: case ServiceRequestState.Denied: ApprovalResult approval = state == ServiceRequestState.Approved ? ApprovalResult.Approved : ApprovalResult.Denied; return(ApproveRequest(userId, requestId, approval, comments)); case ServiceRequestState.Cancelled: return(CancelRequest(userId, requestId, comments)); case ServiceRequestState.Fulfilled: return(FulfillRequest(userId, requestId, comments)); } return(request); }
public static void StartFlow(string quoteId, string url, List <WorkFlowApproval> waitingApprovals, string region) { relatedQuoteId = quoteId; if (waitingApprovals != null) { //AutoResetEvent allows threads that need access to a resource to communicate with each other by signaling. //A thread waits for a signal by calling WaitOne on the AutoResetEvent. //If the AutoResetEvent is the non-signaled state (a thread becomes in signaled state by calling Set on AutoResetEvent), //the thread blocks waiting for the thread that currently controls the resource to signal that the resource is available by calling Set. AutoResetEvent syncEvent = new AutoResetEvent(false); Dictionary <string, object> inputs = new Dictionary <string, object>(); inputs.Add("Region", region); inputs.Add("QuoteId", quoteId); inputs.Add("Url", url); //inputs.Add("WaitingApprovalList", waitingApprovals); WorkflowApplication wfApp = GetWorkFlowApplication(inputs, syncEvent); wfApp.Extensions.Add(waitingApprovals); wfApp.Run(); syncEvent.WaitOne(); } else { SendErrorMail("There are no waiting approvals, start flow fail!"); ApprovalResult = ApprovalResult.WaitingApproverNotFound; } }
private static string MapResult(ApprovalResult result) { switch (result) { case ApprovalResult.Approved: { return("Approved"); } case ApprovalResult.Rejected: { return("Rejected"); } case ApprovalResult.Unknown: { return("Unknown"); } default: { return("Unknown"); } } }
public async Task CompleteRepairApprovalTask(int incidentId, ApprovalResult result) { var taskId = await GetTaskId(incidentId); var value = new { Status = "Completed", PercentComplete = 1, TaskOutcome = result.ToString() }; await UpdateTask(taskId, value); }
//EndDocSection:Unsubscribe //DocSection:ConfirmSubscription /// <summary> /// Handles confirmation requests for newsletter subscriptions (when using double opt-in). /// </summary> public ActionResult ConfirmSubscription(NewsletterConfirmSubscriptionViewModel model) { // Verifies that the confirmation request contains the required hash parameter if (!ModelState.IsValid) { // If the hash is missing, returns a view informing the user that the subscription confirmation was not successful ModelState.AddModelError(String.Empty, "The confirmation link is invalid."); return(View(model)); } // Attempts to parse the date and time parameter from the request query string // Uses the date and time formats required by the Kentico API DateTime parsedDateTime = DateTimeHelper.ZERO_TIME; if (!string.IsNullOrEmpty(model.DateTime) && !DateTime.TryParseExact(model.DateTime, SecurityHelper.EMAIL_CONFIRMATION_DATETIME_FORMAT, null, System.Globalization.DateTimeStyles.None, out parsedDateTime)) { // Returns a view informing the user that the subscription confirmation was not successful ModelState.AddModelError(String.Empty, "The confirmation link is invalid."); return(View(model)); } // Attempts to confirm the subscription specified by the request's parameters ApprovalResult result = SubscriptionService.ConfirmSubscription(model.SubscriptionHash, false, parsedDateTime); switch (result) { // The confirmation was successful or the recipient was already approved // Displays a view informing the user that the subscription is active case ApprovalResult.Success: case ApprovalResult.AlreadyApproved: return(View(model)); // The confirmation link has expired // Expiration occurs after a certain number of hours from the time of the original subscription // You can set the expiration interval in Kentico (Settings -> On‑line marketing -> Email marketing -> Double opt-in interval) case ApprovalResult.TimeExceeded: ModelState.AddModelError(String.Empty, "Your confirmation link has expired. Please subscribe to the newsletter again."); break; // The subscription specified in the request's parameters does not exist case ApprovalResult.NotFound: ModelState.AddModelError(String.Empty, "The subscription that you are attempting to confirm does not exist."); break; // The confirmation failed default: ModelState.AddModelError(String.Empty, "The confirmation of your newsletter subscription did not succeed."); break; } // If the subscription confirmation was not successful, displays a view informing the user return(View(model)); }
public async Task CompleteRepairApprovalTask(int incidentId, ApprovalResult result) { var taskId = await GetTaskId(incidentId); var value = new { Status = "Completed", PercentComplete = 1, TaskOutcome = result.ToString() }; await UpdateTask(taskId, value); }
public async Task <IActionResult> ConfirmAndSubmit(CertificateCheckViewModel vm) { if (vm.CanRequestDuplicate) { return(RedirectToAction("Index", "DuplicateRequest", new { certificateId = vm.Id, redirectToCheck = vm.RedirectToCheck, Uln = vm.Uln, StdCode = vm.StandardCode, Page = vm.Page, SearchString = vm.SearchString })); } if (vm.Status == CertificateStatus.Draft & vm.PrivatelyFundedStatus == CertificateStatus.Rejected & vm.FromApproval) { var certificate = await ApiClient.GetCertificate(vm.Id); var approvalResults = new ApprovalResult[1]; approvalResults[0] = new ApprovalResult { IsApproved = CertificateStatus.Submitted, CertificateReference = certificate.CertificateReference, PrivatelyFundedStatus = CertificateStatus.Approved }; await ApiClient.ApproveCertificates(new CertificatePostApprovalViewModel { UserName = ContextAccessor.HttpContext.User .FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn")?.Value, ApprovalResults = approvalResults }); return(RedirectToAction("Approved", "CertificateApprovals")); } else { return(RedirectToAction("Index", "Comment", new { certificateId = vm.Id, redirectToCheck = vm.RedirectToCheck, Uln = vm.Uln, StdCode = vm.StandardCode, Page = vm.Page, SearchString = vm.SearchString })); } }
public static ApprovalResult GetJumpResult(Aim.WorkFlow.WinService.Task task, string taskId, string winstanceId, string nextName, params string[] UserIdsNames) { ApprovalResult result = new ApprovalResult() { Task = task, TaskId = task.ID, ApprovalDateTime = DateTime.Now, Opinion = ApprovalOpinion.意, ExtendedProperties = new List <KeyValuePair_V2>().ToArray(), ApprovalNodeSkipInfoList = new List <ApprovalNodeSkipInfo>().ToArray(), //Comment = "" }; /// 设定选中的流转节点 if (nextName != "") { result.SwitchRules = new KeyValuePair_V2[] { new KeyValuePair_V2() { Key = task.ApprovalNodeName, Value = nextName } }; string nextNodeName = nextName; /// 设定指定流转节点的审批人员的信息. List <ApprovalNodeContext> approvalNodeContexts = new List <ApprovalNodeContext>(); ApprovalNodeContext specifiedApprovalNodeContext = new ApprovalNodeContext(); specifiedApprovalNodeContext.Name = nextNodeName; if (UserIdsNames != null && UserIdsNames.Length == 2) { LoadFromConfigString(specifiedApprovalNodeContext, UserIdsNames[0].TrimEnd(','), UserIdsNames[1].TrimEnd(',')); approvalNodeContexts.Add(specifiedApprovalNodeContext); result.SpecifiedApprovalNodeContexts = approvalNodeContexts.ToArray(); } } return(result); }
static void Main(string[] args) { ApprovalHandler you = new BasicApproval(new Approver("you", 10)); //Start chaining the handler you.RegisterNext(new ManagerApproval(new Approver("Manager", 200))) .RegisterNext(new VicePresidentApproval(new Approver("Vice President", 500))) .RegisterNext(new PresidentApproval(new Approver("President", 9000))); //try to approve $300 ApprovalResult result = you.Approve(300); Console.WriteLine("Trying to get $300 approved, The result is " + result); //try to approve $10000 result = you.Approve(10000); Console.WriteLine("Trying to get $10000 approved, The result is " + result); Console.ReadKey(); }
public static async Task <object> RunOrchestrator( [OrchestrationTrigger] DurableOrchestrationContext context) { var item = context.GetInput <QueueItem>(); var email = await context.CallActivityAsync <string>(Activity.GetEmailName, item.Id); await context.CallActivityAsync(Activity.SendEmailName, new Item { Email = email, Id = context.InstanceId }); var response = new ApprovalResult() { Email = email }; using (var timeoutCts = new CancellationTokenSource()) { var expiration = context.CurrentUtcDateTime.AddSeconds(120); var timeoutTask = context.CreateTimer(expiration, timeoutCts.Token); var responseTask = context.WaitForExternalEvent <string>(ApprovalResultName); var winner = await Task.WhenAny(responseTask, timeoutTask); if (winner == responseTask) { response.Result = "Success"; timeoutCts.Cancel(); } else { response.Result = "Failed"; timeoutCts.Cancel(); } } await context.CallActivityAsync(Activity.PostResultName, response);; return(item); }
public static void ResumeFlow(string quoteId, List <WorkFlowApproval> addtionlApprovals) { relatedQuoteId = quoteId; WorkFlowApproval approval = eQuotationContext.Current.WorkFlowApproval.OrderByDescending(q => q.LevelNum).FirstOrDefault(q => q.TypeID == quoteId && q.WorkFlowID != ""); if (approval != null) { string strSqlCmd = String.Format( "select top 1 Id,BlockingBookmarks from [System.Activities.DurableInstancing].[InstancesTable] where id='{0}'", approval.WorkFlowID); DataTable dt = dbGetDataTable("WFDB", strSqlCmd); if (dt.Rows.Count == 1) { string bookmark = dt.Rows[0]["BlockingBookmarks"].ToString(); string bookmarkName = bookmark.Substring(1, bookmark.IndexOf(":") - 1); AutoResetEvent syncEvent = new AutoResetEvent(false); WorkflowApplication wfApp = GetWorkFlowApplication(null, syncEvent); Guid instanceId = new Guid(approval.WorkFlowID); wfApp.Load(instanceId); wfApp.ResumeBookmark(bookmarkName, addtionlApprovals); wfApp.Run(); syncEvent.WaitOne(); } else { SendErrorMail("Bookmark is not found in InstancesTable, resume flow fail!"); ApprovalResult = ApprovalResult.ApprovalBookmarkNotFound; } } else { SendErrorMail("Approval is not found in WorkFlowApproval Table, resume flow fail!"); ApprovalResult = ApprovalResult.WaitingApproverNotFound; } }
/// <summary> /// Changes the state of a service request to the result of the Approval if the action is possible. /// </summary> /// <param name="userId">ID of user Approving the request</param> /// <param name="requestId">ID of Service Request to Approve</param> /// <param name="approvalResult">Result of the approval transaction (approved or denied)</param> /// <param name="comments">Optional: Comments tied to the Approval if applicable</param> /// <returns>Service Request after Approval is attempted</returns> public IServiceRequestDto <IServiceRequestOptionDto, IServiceRequestUserInputDto> ApproveRequest(int userId, int requestId, ApprovalResult approvalResult, string comments) { IServiceRequestDto <IServiceRequestOptionDto, IServiceRequestUserInputDto> request = RequestFromId(requestId); if (request.State != ServiceRequestState.Submitted) { throw new ServiceRequestStateException( string.Format("Cannot change the state of a Service Request to \"{0}\". " + "Service Request is in the \"{1}\" state and must be in the " + "\"{2}\" state to perform this action.", approvalResult, request.State, ServiceRequestState.Submitted)); } if (UserCanApproveRequest(userId, requestId)) { using (var context = new PrometheusContext()) { //Build and save approval transaction Approval approval = new Approval() { ApproverId = userId, Comments = comments, RequestorId = request.RequestedByUserId, ServiceRequestId = request.Id, Result = approvalResult }; context.Approvals.Add(approval); context.SaveChanges(userId); //Change state of the entity var requestEntity = context.ServiceRequests.Find(requestId); ClearTemporaryFields(requestEntity); //Approve or deny if (approvalResult == ApprovalResult.Approved) { requestEntity.State = ServiceRequestState.Approved; requestEntity.ApprovedDate = DateTime.UtcNow; } else { requestEntity.State = ServiceRequestState.Denied; requestEntity.DeniedDate = DateTime.UtcNow; } requestEntity.FinalUpfrontPrice = requestEntity.UpfrontPrice; requestEntity.FinalMonthlyPrice = requestEntity.MonthlyPrice; context.Entry(requestEntity).State = EntityState.Modified; context.SaveChanges(userId); request = ManualMapper.MapServiceRequestToDto(requestEntity); } } return(request); }
public ApprovalResult GetApprovalResult(Aim.WorkFlow.WFService.Task task) { ApprovalResult result = new ApprovalResult() { Task = task, TaskId = this.RequestData["TaskId"].ToString(), ApprovalDateTime = DateTime.Now, Opinion = ApprovalOpinion.意, //Comment = "" }; /// 设定跳过后续哪些节点. /*List<ApprovalNodeSkipInfo> approvalNodeSkipInfos = new List<ApprovalNodeSkipInfo>(); * * if (checkBox1.IsChecked.HasValue && checkBox1.IsChecked.Value) * approvalNodeSkipInfos.Add(new ApprovalNodeSkipInfo() { ApprovalNodeContextName = "经理审批", CanBeSkipped = true }); * * if (checkBox2.IsChecked.HasValue && checkBox2.IsChecked.Value) * approvalNodeSkipInfos.Add(new ApprovalNodeSkipInfo() { ApprovalNodeContextName = "主管审批", CanBeSkipped = true }); * * result.ApprovalNodeSkipInfoList = approvalNodeSkipInfos.ToArray(); */ /// 设定选中的流转节点 if (this.RequestData["Route"] != null && this.RequestData["Route"].ToString() != "") { result.SwitchRules = new KeyValuePair_V2[] { new KeyValuePair_V2() { Key = task.ApprovalNodeName, Value = this.RequestData["Route"].ToString() } }; /// 设定指定流转节点的审批人员的信息. List <ApprovalNodeContext> approvalNodeContexts = new List <ApprovalNodeContext>(); ApprovalNodeContext specifiedApprovalNodeContext = new ApprovalNodeContext(); specifiedApprovalNodeContext.Name = this.RequestData["NextNodeName"] == null ? "" : this.RequestData["NextNodeName"].ToString(); if (this.RequestData["UserType"] != null) { if (this.RequestData["UserType"].ToString() != "ADAccount" && this.RequestData["UserIds"].ToString() != "")//如果是组或者角色 { string[] grpIds = this.RequestData["UserIds"].ToString().Split(','); List <ApprovalUnitContext> approvalUnitContexts = new List <ApprovalUnitContext>(); foreach (string groupId in grpIds) { string cou = @"select count(*) from (select distinct ParentDeptName from View_SysUserGroup where ChildDeptName=(Select Name from SysRole where RoleID='{0}')) a"; string sql = ""; int count = DataHelper.QueryValue <int>(string.Format(cou, groupId)); IList <EasyDictionary> lists = null; //判断角色的唯一性,多部门角色需要对应到部门 if (count > 1) { sql = @"select distinct UserID,UserName Name from View_SysUserGroup where ChildDeptName in (Select Name from SysRole where RoleID='{0}') and (select top 1 Path+'.'+DeptId from View_SysUserGroup where UserID='{1}') like '%'+Path+'%'"; if (this.RequestData.Get("StartUserId") != null && this.RequestData.Get <string>("StartUserId") != "") { sql = string.Format(sql, groupId, this.RequestData.Get("StartUserId")); } else { sql = string.Format(sql, groupId, this.UserInfo.UserID); } lists = DataHelper.QueryDictList(sql); } else if (count == 1) { sql = "select UserId,UserName Name from View_SysUserGroup where ChildDeptName=(Select Name from SysRole where RoleID='{0}')"; sql = string.Format(sql, groupId); lists = DataHelper.QueryDictList(sql); } if (lists.Count == 0) { throw new Exception("缺少角色" + this.RequestData["UserNames"] + "的人员!"); } foreach (EasyDictionary ed in lists) { approvalUnitContexts.Add(new ApprovalUnitContext() { Approver = new Approver() { Value = ed["UserID"].ToString(), Name = ed["Name"].ToString() } }); } } specifiedApprovalNodeContext.ApprovalUnitContexts = approvalUnitContexts.ToArray(); approvalNodeContexts.Add(specifiedApprovalNodeContext); result.SpecifiedApprovalNodeContexts = approvalNodeContexts.ToArray(); } } else if (this.RequestData["UserIds"] != null && this.RequestData["UserIds"].ToString().Trim() != "") { string userIds = this.RequestData["UserIds"].ToString().TrimEnd(','); string userNames = this.RequestData["UserNames"].ToString().TrimEnd(','); LoadFromConfigString(specifiedApprovalNodeContext, userIds, userNames); approvalNodeContexts.Add(specifiedApprovalNodeContext); result.SpecifiedApprovalNodeContexts = approvalNodeContexts.ToArray(); } /*List<ApprovalNodeContext> approvalNodeContexts = new List<ApprovalNodeContext>(); * * ApprovalNodeContext specifiedApprovalNodeContext = new ApprovalNodeContext(); * specifiedApprovalNodeContext.Name = this.RequestData["RouteName"].ToString(); * * string userIds = this.RequestData["UserIds"].ToString().TrimEnd(','); * string userNames = this.RequestData["UserNames"].ToString().TrimEnd(','); * LoadFromConfigString(specifiedApprovalNodeContext, userIds,userNames); * approvalNodeContexts.Add(specifiedApprovalNodeContext); * result.SpecifiedApprovalNodeContexts = approvalNodeContexts.ToArray();*/ } return(result); }
private ApprovalResult GetApprovalResult(InstanceData data, WorkItem wi) { try { var result = new ApprovalResult(); if (wi.ActivityCode == "Activity14")//信审初审 { #region if (wi.ActionEventType == ActionEventType.Backward)//驳回 { result.uuid = data["uuid"].Value + string.Empty; result.type = "01"; result.status = "005"; result.messages = GetAllMsg(wi.InstanceId); return(result); } else//其它情况不需要推送 { return(null); } #endregion } else if (wi.ActivityCode == "Activity13")//信审终审 { #region if (wi.ActionEventType == ActionEventType.Backward)//驳回 有问题(驳回到初审还是FI?到FI需要通知) { //返回null,不处理,在待办任务中判断; return(null); } else { string zsshzt = data["zsshzt"].Value + string.Empty; result.uuid = data["uuid"].Value + string.Empty; result.type = "01"; if (zsshzt == "核准") { result.status = "001"; } else if (zsshzt == "拒绝") { result.status = "002"; } else { result.status = "004"; } result.messages = GetAllMsg(wi.InstanceId); return(result); } #endregion } else if (wi.ActivityCode == "Activity17")//运营初审 { #region if (wi.ActionEventType == ActionEventType.Backward)//驳回 { result.uuid = data["uuid"].Value + string.Empty; result.type = "02"; result.status = "005"; result.messages = GetAllMsg(wi.InstanceId); return(result); } else { //运营初审审核状态:拒绝需要回调; string yycsshzt = data["yycsshzt"].Value + string.Empty; if (yycsshzt == "拒绝") { result.uuid = data["uuid"].Value + string.Empty; result.type = "02"; result.status = "002"; result.messages = GetAllMsg(wi.InstanceId); return(result); } //其它情况不需要推送 return(null); } #endregion } else if (wi.ActivityCode == "Activity18")//运营终审 { #region if (wi.ActionEventType == ActionEventType.Backward)//驳回(只能驳回到初审,不需要消息推送) { return(null); } else if (wi.ActionEventType == ActionEventType.Forward)//提交 { //运营终审的状态:只有核准与拒绝 string yyzsshzt = data["yyzsshzt"].Value + string.Empty; result.uuid = data["uuid"].Value + string.Empty; result.type = "02"; if (yyzsshzt == "核准") { result.status = "001"; } else { result.status = "002"; } result.messages = GetAllMsg(wi.InstanceId); return(result); } #endregion } else if (wi.ActivityCode == "Activity12")//风控评估 { #region string fkresult = data["FK_RESULT"].Value + string.Empty; if (fkresult == "拒绝") { result.uuid = data["uuid"].Value + string.Empty; result.type = "01"; result.status = "002"; result.messages = GetAllMsg(wi.InstanceId); return(result); } #endregion } else { return(null); } return(null); } catch (Exception e) { return(null); } }
public JsonResult OnCreated(string id) { AppUtility.Engine.LogWriter.Write("WebApi OnCreated...workitemID-->" + id); WorkItem WorkItem = AppUtility.Engine.WorkItemManager.GetWorkItem(id); if (WorkItem == null) { return(Json(new { Success = false, Message = "workitemID错误" }, JsonRequestBehavior.AllowGet)); } if (WorkItem.ItemType == WorkItemType.Approve) { string conditions = ""; if (WorkItem.WorkflowCode == "RetailApp" || WorkItem.WorkflowCode == "CompanyApp" || WorkItem.WorkflowCode == "APPLICATION") { //#region 待办任务推送CRM ////if (WorkItem.ActivityCode != "Activity2") ////{ ////} //AppUtility.Engine.LogWriter.Write("待办任务推送开始:WorkItemID:" + id); //Dictionary<string, object> dic = new Dictionary<string, object>(); //dic.Add("SchemaCode", WorkItem.WorkflowCode + string.Empty); //dic.Add("workitemID", id + string.Empty); //try //{ // BizService.ExecuteBizNonQuery("CRMService", "postUnFinishedWorkItemInfo", dic); //} //catch (Exception ex) //{ // AppUtility.Engine.LogWriter.Write("待办任务推送异常:WorkItemID:" + id+",message:"+ex.Message); //} //AppUtility.Engine.LogWriter.Write("待办任务推送结束:WorkItemID:" + id); //#endregion //运营二个节点 if (WorkItem.ActivityCode == "Activity17" || WorkItem.ActivityCode == "Activity18") { conditions += " and (activitycode='Activity17' or activitycode='Activity18')"; } //信审二个节点 else if (WorkItem.ActivityCode == "Activity14" || WorkItem.ActivityCode == "Activity13") { conditions += " and (activitycode='Activity14' or activitycode='Activity13')"; } } #region 判断当前任务是否是有驳回过 if (WorkItem.DisplayName.Contains("信审") || WorkItem.DisplayName.Contains("运营人员")) { string sql = "select count(1) from Ot_Workitemfinished where instanceid='{0}' {1} and actioneventtype=3"; sql = string.Format(sql, WorkItem.InstanceId, conditions); AppUtility.Engine.LogWriter.Write("判断是否有驳回,SQL-->" + sql); int num = Convert.ToInt32(AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteScalar(sql)); AppUtility.Engine.LogWriter.Write("当前任务-->" + WorkItem.WorkItemID + "对应的单据之前有驳回过" + num + "次"); if (num > 0) { long ret = AppUtility.Engine.WorkItemManager.UpdatePriority(WorkItem.WorkItemID, PriorityType.High); AppUtility.Engine.LogWriter.Write("已驳回的单据,设置任务优先级为最高:WorkItemID-->" + WorkItem.WorkItemID + ",Result-->" + ret); } } #endregion #region 推送接口中心,回调信息 if (WorkItem.WorkflowCode == "APPLICATION") { #region FI进件节点 if (WorkItem.ItemType == WorkItemType.Fill) { if (WorkItem.PreActionEventType == ActionEventType.Backward) { var context = AppUtility.Engine.InstanceManager.GetInstanceContext(WorkItem.InstanceId); var activity = context.GetToken(WorkItem.TokenId - 1); if (activity.Activity == "Activity13")//信审终审驳回; { InstanceData data = new InstanceData(AppUtility.Engine, WorkItem.InstanceId, ""); string uuid = data["uuid"].Value + string.Empty; if (!string.IsNullOrEmpty(uuid)) { ApprovalResult para = new ApprovalResult(); para.uuid = uuid; para.type = "01"; para.status = "005"; para.messages = GetAllMsg(WorkItem.InstanceId); NameValueCollection nvBody = new NameValueCollection(); nvBody.Add("Uuid", para.uuid); nvBody.Add("CallbackType", "2"); nvBody.Add("CallbackParameters", JsonConvert.SerializeObject(para)); AppUtility.Engine.LogWriter.Write("推送消息给接口中心结果[Created FI Formdata]:" + HttpHelper.postFormData(ConfigurationManager.AppSettings["apiAddMQMsg"] + string.Empty, new NameValueCollection(), nvBody)); } } } } #endregion #region FI输入放款信息 else if (WorkItem.ActivityCode == "Activity48") { InstanceData data = new InstanceData(AppUtility.Engine, WorkItem.InstanceId, ""); //FI输入放款信息且是自动审批的,需要回调; if (data["Automatic_approval"].Value + string.Empty == "1") { string uuid = data["uuid"].Value + string.Empty; if (!string.IsNullOrEmpty(uuid)) { ApprovalResult para = new ApprovalResult(); para.uuid = uuid; para.type = "01"; para.status = "001"; para.messages = GetAllMsg(WorkItem.InstanceId); NameValueCollection nvBody = new NameValueCollection(); nvBody.Add("Uuid", para.uuid); nvBody.Add("CallbackType", "2"); nvBody.Add("CallbackParameters", JsonConvert.SerializeObject(para)); AppUtility.Engine.LogWriter.Write("推送消息给接口中心结果[Created 放款 Formdata]:" + HttpHelper.postFormData(ConfigurationManager.AppSettings["apiAddMQMsg"] + string.Empty, new NameValueCollection(), nvBody)); } } } #endregion } #endregion } return(Json(new { Success = true, Message = "" }, JsonRequestBehavior.AllowGet)); }
private static WorkflowApplication GetWorkFlowApplication(Dictionary <string, object> inputs, AutoResetEvent syncEvent) { AutoResetEvent InstanceUnloaded = new AutoResetEvent(false); InstanceStore store = new SqlWorkflowInstanceStore(ConfigurationManager.ConnectionStrings["WFDB"].ConnectionString); var accountFlowIdentity = new WorkflowIdentity { Name = "test", Version = new Version(1, 0, 0, 1) }; WorkflowApplication.DeleteDefaultInstanceOwner(store); WorkflowApplication.CreateDefaultInstanceOwner(store, null, WorkflowIdentityFilter.Any, new TimeSpan(0, 0, 0, 10)); WorkflowApplication wfApp = null; if (inputs == null) { wfApp = new WorkflowApplication(new QuoteApprovalFlow(), accountFlowIdentity); } else { wfApp = new WorkflowApplication(new QuoteApprovalFlow(), inputs, accountFlowIdentity); } wfApp.InstanceStore = store; wfApp.PersistableIdle = (e) => { ApprovalResult = ApprovalResult.WaitingForApproval; return(PersistableIdleAction.Unload); }; wfApp.Unloaded = (workflowApplicationEventArgs) => { syncEvent.Set(); /*InstanceUnloaded.Set();*/ //a thread becomes in signaled state by calling Set on AutoResetEvent }; //wfApp.OnUnhandledException = (e) => //{ // var test = e.ToString(); // return UnhandledExceptionAction.Terminate; //}; wfApp.Completed = (e) => { if (e.CompletionState == ActivityInstanceState.Faulted) { ApprovalResult = ApprovalResult.Exception; } else if (e.CompletionState == ActivityInstanceState.Canceled) { } else { ApprovalResult = (ApprovalResult)e.Outputs["Result"]; } syncEvent.Set(); }; wfApp.Aborted = (e) => { syncEvent.Set(); }; wfApp.OnUnhandledException = (e) => { ApprovalResult = ApprovalResult.Exception; //string subject = String.Format("eQ3.0 Workflow exception, quote Id: {0}", relatedQuoteId); //string strContent = String.Format("<p> eQ3.0 Workflow exception in {0}</p>", DateTime.Now.ToString()); //strContent += String.Format("<p>Quote Id: {0}</p>", relatedQuoteId); //strContent += String.Format("<p>Workflow Id: {0}</p>", e.InstanceId); //strContent += String.Format("<p>Error message: {0}</p>", e.UnhandledException.Message); //MailHelper.SendMail("*****@*****.**", subject, strContent); var message = String.Format("<p>Workflow ID: {0}</p>", e.InstanceId); message += String.Format("<p>Error message: {0}</p>", e.UnhandledException.Message); SendErrorMail(message); return(UnhandledExceptionAction.Terminate); }; return(wfApp); }
public static ApprovalResult GetApprovalResult(Aim.WorkFlow.WinService.Task task, string taskId, string winstanceId, string route, params string[] UserIdsNames) { ApprovalResult result = new ApprovalResult() { Task = task, TaskId = task.ID, ApprovalDateTime = DateTime.Now, Opinion = ApprovalOpinion.意, ExtendedProperties = new List <KeyValuePair_V2>().ToArray(), ApprovalNodeSkipInfoList = new List <ApprovalNodeSkipInfo>().ToArray(), //Comment = "" }; /// 设定跳过后续哪些节点. /*List<ApprovalNodeSkipInfo> approvalNodeSkipInfos = new List<ApprovalNodeSkipInfo>(); * * if (checkBox1.IsChecked.HasValue && checkBox1.IsChecked.Value) * approvalNodeSkipInfos.Add(new ApprovalNodeSkipInfo() { ApprovalNodeContextName = "经理审批", CanBeSkipped = true }); * * if (checkBox2.IsChecked.HasValue && checkBox2.IsChecked.Value) * approvalNodeSkipInfos.Add(new ApprovalNodeSkipInfo() { ApprovalNodeContextName = "主管审批", CanBeSkipped = true }); * * result.ApprovalNodeSkipInfoList = approvalNodeSkipInfos.ToArray(); */ /// 设定选中的流转节点 if (route != "") { result.SwitchRules = new KeyValuePair_V2[] { new KeyValuePair_V2() { Key = task.ApprovalNodeName, Value = route } }; WorkflowInstance ins = WorkflowInstance.Find(winstanceId); //Aim.WorkFlow.WorkflowTemplate temp = Aim.WorkFlow.WorkflowTemplate.Find(ins.WorkflowTemplateID); XmlDocument doc = new XmlDocument(); doc.LoadXml(ins.XAML); XmlElement root = doc.DocumentElement; string nameSpace = root.NamespaceURI; XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("ns", nameSpace); nsmgr.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml"); nsmgr.AddNamespace("bwa", "clr-namespace:BPM.WF.Activities;assembly=BPM.WF"); string current = "ApprovalNode Name=\"" + task.ApprovalNodeName + "\""; XmlNode currentNode = root.SelectSingleNode("//*[contains(@ApprovalNodeConfig,'" + current + "')]", nsmgr); //XmlNode node = root.SelectSingleNode("//*[@x:Key='" + nextName + "']", nsmgr); XmlNode node = currentNode.NextSibling.SelectSingleNode("ns:FlowSwitch/ns:FlowStep[@x:Key='" + route + "']", nsmgr); string nextUserIds = ""; string nextUserNames = ""; string nextUserAccountType = ""; string nextNodeName = ""; string content = "ApprovalNode Name=\"" + route + "\""; if (root.SelectSingleNode("//*[contains(@ApprovalNodeConfig,'" + content + "')]", nsmgr) != null)//直接路由 { string config = System.Web.HttpUtility.HtmlDecode(root.SelectSingleNode("//*[contains(@ApprovalNodeConfig,'" + content + "')]", nsmgr).Attributes["ApprovalNodeConfig"].InnerXml); XmlDocument docC = new XmlDocument(); docC.LoadXml(config); nextNodeName = docC.DocumentElement.Attributes["Name"].InnerText.ToString(); if (docC.DocumentElement.SelectSingleNode("ApprovalUnits") != null && docC.DocumentElement.SelectSingleNode("ApprovalUnits").ChildNodes.Count > 0) { XmlNodeList list = docC.DocumentElement.SelectSingleNode("ApprovalUnits").ChildNodes; foreach (XmlNode chd in list) { nextUserIds += chd.ChildNodes[0].Attributes["Value"].InnerText + ","; nextUserNames += chd.ChildNodes[0].Attributes["Name"].InnerText + ","; nextUserAccountType = chd.ChildNodes[0].Attributes["Type"].InnerText; } } } nextUserIds = nextUserIds.TrimEnd(','); nextUserNames = nextUserNames.TrimEnd(','); /// 设定指定流转节点的审批人员的信息. List <ApprovalNodeContext> approvalNodeContexts = new List <ApprovalNodeContext>(); ApprovalNodeContext specifiedApprovalNodeContext = new ApprovalNodeContext(); specifiedApprovalNodeContext.Name = nextNodeName; if (nextUserAccountType != "ADAccount" && nextUserIds != "" && UserIdsNames != null && UserIdsNames.Length == 0)//如果是组或者角色 { string[] grpIds = nextUserIds.Split(','); string[] grpNames = nextUserNames.Split(','); List <ApprovalUnitContext> approvalUnitContexts = new List <ApprovalUnitContext>(); foreach (string groupId in grpIds) { string cou = @"select count(*) from (select distinct ParentDeptName from View_SysUserGroup where ChildDeptName=(Select Name from SysRole where RoleID='{0}')) a"; string sql = ""; int count = DataHelper.QueryValue <int>(string.Format(cou, groupId)); IList <EasyDictionary> lists = null; //判断角色的唯一性,多部门角色需要对应到部门 if (count > 1) { sql = @"select distinct UserID,UserName Name from View_SysUserGroup where ChildDeptName in (Select Name from SysRole where RoleID='{0}') and (select top 1 Path+'.'+DeptId from View_SysUserGroup where UserID='{1}') like '%'+Path+'%'"; sql = string.Format(sql, groupId, task.OwnerId); lists = DataHelper.QueryDictList(sql); } else if (count == 1) { sql = "select UserId,UserName Name from View_SysUserGroup where ChildDeptName=(Select Name from SysRole where RoleID='{0}')"; sql = string.Format(sql, groupId); lists = DataHelper.QueryDictList(sql); } if (lists == null || lists.Count == 0) { throw new Exception("缺少角色" + nextUserNames + "的人员!"); } foreach (EasyDictionary ed in lists) { approvalUnitContexts.Add(new ApprovalUnitContext() { Approver = new Approver() { Value = ed["UserID"].ToString(), Name = ed["Name"].ToString() } }); } } specifiedApprovalNodeContext.ApprovalUnitContexts = approvalUnitContexts.ToArray(); approvalNodeContexts.Add(specifiedApprovalNodeContext); result.SpecifiedApprovalNodeContexts = approvalNodeContexts.ToArray(); } else if (UserIdsNames != null && UserIdsNames.Length == 2) { LoadFromConfigString(specifiedApprovalNodeContext, UserIdsNames[0].TrimEnd(','), UserIdsNames[1].TrimEnd(',')); approvalNodeContexts.Add(specifiedApprovalNodeContext); result.SpecifiedApprovalNodeContexts = approvalNodeContexts.ToArray(); } else if (nextUserIds.Trim() != "") { LoadFromConfigString(specifiedApprovalNodeContext, nextUserIds, nextUserNames); approvalNodeContexts.Add(specifiedApprovalNodeContext); result.SpecifiedApprovalNodeContexts = approvalNodeContexts.ToArray(); } /*List<ApprovalNodeContext> approvalNodeContexts = new List<ApprovalNodeContext>(); * * ApprovalNodeContext specifiedApprovalNodeContext = new ApprovalNodeContext(); * specifiedApprovalNodeContext.Name = this.RequestData["RouteName"].ToString(); * * string userIds = this.RequestData["UserIds"].ToString().TrimEnd(','); * string userNames = this.RequestData["UserNames"].ToString().TrimEnd(','); * LoadFromConfigString(specifiedApprovalNodeContext, userIds,userNames); * approvalNodeContexts.Add(specifiedApprovalNodeContext); * result.SpecifiedApprovalNodeContexts = approvalNodeContexts.ToArray();*/ } return(result); }
public static async Task PostResultOnQueue([ActivityTrigger] ApprovalResult result, [Queue("result", Connection = "AzureWebJobsStorage")] CloudQueue queue) { await queue.AddMessageAsync(new CloudQueueMessage(JsonConvert.SerializeObject(result))); }