static void Main(string[] args) { var reg = new WorkflowService(); Session1(reg); Session2(reg); }
public APHelper() { api = createAPI(); if (api == null) throw new Exception("init - api is null"); sysEntry = (String)ConfigurationManager.AppSettings["ERSEntry"]; }
public void Given_simple_workflow_runned_twice() { _service = new WorkflowService(); var instance1 = _service.Get<FooWorkflow>(SimpleWorkflowKey); instance1.Ping(); var instance2 = _service.Get<FooWorkflow>(SimpleWorkflowKey); instance2.Ping(); }
public void Given_simple_workflow_runned_twice() { _service = new WorkflowService(); var instance1 = _service.Get<FooWorkflow>(SimpleWorkflowKey); try { instance1.Crash(); } catch (Exception ex) { _exception = ex; } }
public void Initialize() { _workflowRepositoryMock = new Mock <IWorkflowRepository>(); _workflowXmlValidatorMock = new Mock <IWorkflowXmlValidator>(); _userRepositoryMock = new Mock <IUserRepository>(); _usersRepositoryMock = new Mock <IUsersRepository>(); _workflowValidationErrorBuilder = new Mock <IWorkflowValidationErrorBuilder>(); _triggerConverter = new Mock <ITriggerConverter>(); _projectMetaRepository = new Mock <IProjectMetaRepository>(); _artifactRepository = new Mock <IArtifactRepository>(); _applicationSettingsRepositoryMock = new Mock <IApplicationSettingsRepository>(); _applicationSettingsRepositoryMock = new Mock <IApplicationSettingsRepository>(); _serviceLogRepositoryMock = new Mock <IServiceLogRepository>(); _sendMessageExecutorMock = new Mock <ISendMessageExecutor>(); _webhooksRepositoryMock = new Mock <IWebhooksRepository>(); _service = new WorkflowService(_workflowRepositoryMock.Object, _workflowXmlValidatorMock.Object, _usersRepositoryMock.Object, _workflowValidationErrorBuilder.Object, _projectMetaRepository.Object, _triggerConverter.Object, null, null, _artifactRepository.Object, _applicationSettingsRepositoryMock.Object, _serviceLogRepositoryMock.Object, _sendMessageExecutorMock.Object, _webhooksRepositoryMock.Object); _workflowDataValidatorMock = new Mock <IWorkflowDataValidator>(); _workflowDataValidatorMock .Setup(q => q.ValidateUpdateDataAsync(It.IsAny <IeWorkflow>(), It.IsAny <ProjectTypes>())) .ReturnsAsync(new WorkflowDataValidationResult()); typeof(WorkflowService) .GetField("_workflowDataValidator", BindingFlags.Instance | BindingFlags.NonPublic) ?.SetValue(_service, _workflowDataValidatorMock.Object); _workflow = new SqlWorkflow { Name = "Workflow1", Description = "Workflow1Description" }; _workflowArtifactTypes = new List <SqlWorkflowArtifactTypes> { new SqlWorkflowArtifactTypes { ProjectId = 1, ProjectPath = "Project1", ArtifactTypeName = "Artifact1", ArtifactTypeId = 204 }, new SqlWorkflowArtifactTypes { ProjectId = 2, ProjectPath = "Project2", ArtifactTypeName = "Artifact2", ArtifactTypeId = 205 }, new SqlWorkflowArtifactTypes { ProjectId = 3, ProjectPath = "Project3", ArtifactTypeName = "Artifact3", ArtifactTypeId = 206 } }; _workflowStates = new List <SqlState> { new SqlState { VersionId = 1, WorkflowStateId = 1, Name = "New", Default = true, CanvasSettings = I18NHelper.FormatInvariant("<S><LN>{0}</LN></S>", Location) }, new SqlState { VersionId = 2, WorkflowStateId = 2, Name = "Active", CanvasSettings = string.Empty } }; _workflowEvents = new List <SqlWorkflowEventData> { new SqlWorkflowEventData { WorkflowId = 10, Name = "Transition1", FromState = "New", ToState = "Active", FromStateId = 1, ToStateId = 2, Permissions = "<P S=\"0\"><G>1</G></P>", CanvasSettings = I18NHelper.FormatInvariant("<S><PRT><FR>{0}</FR><TO>{1}</TO></PRT></S>", (int)FromPort, (int)ToPort), Type = 0, Triggers = "<TSR><TS><T><AEN><ES><E>test.com</E></ES><M>4QOTT0IR7W</M></AEN></T></TS></TSR>" }, new SqlWorkflowEventData { WorkflowId = 10, Name = "PropertyChange1", Type = 1, Triggers = "<TSR><TS><T><AEN><ES><E>test.com</E></ES><M>4QOTT0IR7W</M></AEN></T></TS></TSR>", PropertyTypeId = 1 }, new SqlWorkflowEventData { WorkflowId = 10, Name = "PropertyChange2", Type = 1, Triggers = "<TSR><TS><T><AEN><ES><E>test.com</E></ES><M>4QOTT0IR7W</M></AEN></T></TS></TSR>", PropertyTypeId = 2 }, new SqlWorkflowEventData { WorkflowId = 10, Name = "NewArtifact1", Type = 2, Triggers = "<TSR><TS><T><AEN><ES><E>test.com</E></ES><M>4QOTT0IR7W</M></AEN></T></TS></TSR>", }, }; _userItems = new List <UserDto>(); _userQueryResult = new QueryResult <UserDto>(); _projectTypes = new ProjectTypes(); _projectTypes.PropertyTypes.Add(new PropertyType { Name = "Property1", Id = 1 }); _projectTypes.PropertyTypes.Add(new PropertyType { Name = "Property2", Id = 2 }); _triggers = new List <IeTrigger> { new IeTrigger() }; }
public HttpResponseMessage ProcessMobileCheckin(string param) { try { var session = HttpContext.Current.Session; var currentCheckInState = session["CheckInState"] as CheckInState; if (currentCheckInState.CheckIn.SearchType.Guid != Constants.CHECKIN_SEARCH_TYPE_USERLOGIN.AsGuid()) { throw new Exception(); //We'll catch this later and return a forbidden } var localDeviceConfigCookie = HttpContext.Current.Request.Cookies[CheckInCookieKey.LocalDeviceConfig].Value; var localDevice = localDeviceConfigCookie.FromJsonOrNull <LocalDeviceConfiguration>(); var rockContext = new Rock.Data.RockContext(); UserLoginService userLoginService = new UserLoginService(rockContext); var family = userLoginService.Queryable().AsNoTracking() .Where(u => u.UserName == currentCheckInState.CheckIn.SearchValue) .Select(u => u.Person.PrimaryFamily) .FirstOrDefault(); var checkinFamily = new CheckInFamily { Group = family.Clone(false), Caption = family.ToString(), Selected = true }; currentCheckInState.CheckIn.Families.Add(checkinFamily); SaveState(session, currentCheckInState); Guid blockGuid = ( Guid )session["BlockGuid"]; var block = BlockCache.Get(blockGuid); Guid? workflowGuid = block.GetAttributeValue("WorkflowType").AsGuidOrNull(); string workflowActivity = block.GetAttributeValue("WorkflowActivity"); List <string> errors; var workflowService = new WorkflowService(rockContext); var workflowType = WorkflowTypeCache.Get(workflowGuid.Value); var CurrentWorkflow = Rock.Model.Workflow.Activate(workflowType, currentCheckInState.Kiosk.Device.Name, rockContext); var activityType = workflowType.ActivityTypes.Where(a => a.Name == workflowActivity).FirstOrDefault(); if (activityType != null) { WorkflowActivity.Activate(activityType, CurrentWorkflow, rockContext); if (workflowService.Process(CurrentWorkflow, currentCheckInState, out errors)) { if (errors.Any()) { var innerException = new Exception(string.Join(" -- ", errors)); ExceptionLogService.LogException(new Exception("Process Mobile Checkin failed initial workflow. See inner exception for details.", innerException)); } // Keep workflow active for continued processing CurrentWorkflow.CompletedDateTime = null; SaveState(session, currentCheckInState); List <CheckInFamily> families = currentCheckInState.CheckIn.Families; families = families.OrderBy(f => f.Caption).ToList(); return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, param)); } else { if (errors.Any()) { var innerException = new Exception(string.Join(" -- ", errors)); ExceptionLogService.LogException(new Exception("Process Mobile Checkin failed initial workflow. See inner exception for details.", innerException)); } else { ExceptionLogService.LogException(new Exception("Process Mobile Checkin failed initial workflow. See inner exception for details.")); } } } else { return(ControllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, string.Format("Workflow type does not have a '{0}' activity type", workflowActivity))); } return(ControllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, String.Join("\n", errors))); } catch (Exception ex) { ExceptionLogService.LogException(ex, HttpContext.Current); return(ControllerContext.Request.CreateResponse(HttpStatusCode.Forbidden, "Forbidden")); } }
protected void lbProfileNext_Click(object sender, EventArgs e) { // setup merge fields var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); mergeFields.Add("PersonId", hfPersonId.Value); mergeFields.Add("FirstName", tbFirstName.Text); mergeFields.Add("LastName", tbLastName.Text); mergeFields.Add("StreetAddress", acAddress.Street1); mergeFields.Add("City", acAddress.City); mergeFields.Add("State", acAddress.State); mergeFields.Add("PostalCode", acAddress.PostalCode); mergeFields.Add("Country", acAddress.Country); mergeFields.Add("Email", tbEmail.Text); mergeFields.Add("HomePhone", pnbHomePhone.Text); mergeFields.Add("MobilePhone", pnbHomePhone.Text); mergeFields.Add("BirthDate", dpBirthdate.Text); mergeFields.Add("OtherUpdates", tbOtherUpdates.Text); // if an email was provided email results RockContext rockContext = new RockContext(); if (!string.IsNullOrWhiteSpace(GetAttributeValue("UpdateEmail"))) { var receiptEmail = new SystemEmailService(rockContext).Get(new Guid(GetAttributeValue("UpdateEmail"))); if (receiptEmail != null && receiptEmail.To.IsNotNullOrWhiteSpace()) { var errorMessages = new List <string>(); var message = new RockEmailMessage(receiptEmail); foreach (var recipient in message.GetRecipients()) { recipient.MergeFields = mergeFields; } message.Send(out errorMessages); } } // launch workflow if configured if (!string.IsNullOrWhiteSpace(GetAttributeValue("WorkflowType"))) { var workflowService = new WorkflowService(rockContext); var workflowType = WorkflowTypeCache.Get(new Guid(GetAttributeValue("WorkflowType"))); if (workflowType != null && (workflowType.IsActive ?? true)) { var workflow = Rock.Model.Workflow.Activate(workflowType, "Kiosk Update Info"); // set attributes workflow.SetAttributeValue("PersonId", hfPersonId.Value); workflow.SetAttributeValue("FirstName", tbFirstName.Text); workflow.SetAttributeValue("LastName", tbLastName.Text); workflow.SetAttributeValue("StreetAddress", acAddress.Street1); workflow.SetAttributeValue("City", acAddress.City); workflow.SetAttributeValue("State", acAddress.State); workflow.SetAttributeValue("PostalCode", acAddress.PostalCode); workflow.SetAttributeValue("Country", acAddress.Country); workflow.SetAttributeValue("Email", tbEmail.Text); workflow.SetAttributeValue("HomePhone", pnbHomePhone.Text); workflow.SetAttributeValue("MobilePhone", pnbHomePhone.Text); workflow.SetAttributeValue("BirthDate", dpBirthdate.Text); workflow.SetAttributeValue("OtherUpdates", tbOtherUpdates.Text); // launch workflow List <string> workflowErrors; workflowService.Process(workflow, out workflowErrors); } } HidePanels(); pnlComplete.Visible = true; lCompleteMessage.Text = GetAttributeValue("CompleteMessageLava").ResolveMergeFields(mergeFields); }
//送往下一步 protected void btnSendNext_Click(object sender, EventArgs e) { try { DateTime now = DateTime.Now; string CurrentActivityText = string.Empty; string currentOpinionRemark = string.Empty; string processGUID = this.txtProcessGUID.Value.ToString(); decimal days = Helper.ConverToDecimal(this.txtDays.Value); string instanceId = this.hiddenInstanceId.Value; string DepManagerRemark = this.txtDepmanagerRemark.Value; string DirectorRemark = this.txtDirectorRemark.Value; string DeputyGeneralRemark = this.txtDeputyGeneralRemark.Value; string GeneralManagerRemark = this.txtGeneralManagerRemark.Value; int activityInstanceID = Helper.ConverToInt32(hiddenActivityInstanceID.Value); string strNextActivityPerformers = hiddenNextActivityPerformers.Value.ToString().Trim(); IDictionary <string, PerformerList> nextActivityPerformers = NextActivityPerformers(strNextActivityPerformers); if (nextActivityPerformers == null) { base.RegisterStartupScript("", "<script>alert('请选择办理步骤或办理人员');</script>"); return; } switch (hiddenPerformField.Value.ToString()) { case "DepManager": //部门经理 currentOpinionRemark = this.txtDepmanagerRemark.Value; break; case "Director": //主管总监 currentOpinionRemark = this.txtDirectorRemark.Value; break; case "Deputy": //副总经理 currentOpinionRemark = this.txtDeputyGeneralRemark.Value; break; case "General": //总经理 currentOpinionRemark = this.txtGeneralManagerRemark.Value; break; } if (!string.IsNullOrEmpty(instanceId)) { //调用流程 IWorkflowService service = new WorkflowService(); WfAppRunner initiator = new WfAppRunner(); initiator.AppName = "请假流程"; initiator.AppInstanceID = instanceId; initiator.ProcessGUID = processGUID; initiator.UserID = LoginUserID.ToString(); initiator.UserName = LoginUserName; initiator.Conditions = GetCondition(string.Format("days-{0}", days)); initiator.NextActivityPerformers = nextActivityPerformers; WfExecutedResult runAppResult = service.RunProcessApp(initiator); if (runAppResult.Status != WfExecutedStatus.Success) { base.RegisterStartupScript("", "<script>alert('" + runAppResult.Message + "');</script>"); return; } ActivityInstanceEntity activityInstanceEntity = service.GetActivityInstance(activityInstanceID); if (activityInstanceEntity != null) { CurrentActivityText = activityInstanceEntity.ActivityName; } try { //保存业务数据 //BizAppFlowEntity AppFlowEntity = new Entity.BizAppFlowEntity(); //AppFlowEntity.AppName = "请假流程"; //AppFlowEntity.AppInstanceID = instanceId.ToString(); //AppFlowEntity.ActivityName = CurrentActivityText; //AppFlowEntity.Remark = string.Format("{0}(ID:{1}) {2}", LoginUserName, LoginUserID, currentOpinionRemark); //AppFlowEntity.ChangedTime = now; //AppFlowEntity.ChangedUserID = LoginUserID.ToString(); //AppFlowEntity.ChangedUserName = LoginUserName; HrsLeaveOpinionEntity hrsleaveOpinionEntity = new HrsLeaveOpinionEntity(); hrsleaveOpinionEntity.AppInstanceID = instanceId.ToString(); hrsleaveOpinionEntity.ActivityID = activityInstanceEntity.ActivityGUID.ToString(); hrsleaveOpinionEntity.ActivityName = CurrentActivityText; hrsleaveOpinionEntity.Remark = string.Format("{0}(ID:{1}) {2}", LoginUserName, LoginUserID, currentOpinionRemark); hrsleaveOpinionEntity.ChangedTime = now; hrsleaveOpinionEntity.ChangedUserID = LoginUserID.ToString(); hrsleaveOpinionEntity.ChangedUserName = LoginUserName; WorkFlows.AddHrsLeaveOpinion(hrsleaveOpinionEntity); } catch (Exception ex) { } try { HrsLeaveEntity hrsLeaveEntity = new Entity.HrsLeaveEntity(); hrsLeaveEntity.ID = Helper.ConverToInt32(instanceId); hrsLeaveEntity.DepManagerRemark = DepManagerRemark; hrsLeaveEntity.DirectorRemark = DirectorRemark; hrsLeaveEntity.DeputyGeneralRemark = DeputyGeneralRemark; hrsLeaveEntity.GeneralManagerRemark = GeneralManagerRemark; hrsLeaveEntity.CurrentActivityText = CurrentActivityText; WorkFlows.UpdateHrsLeave(hrsLeaveEntity); } catch (Exception ex) { } base.RegisterStartupScript("", "<script>alert('办理成功');window.location.href='FlowList.aspx';</script>"); } } catch (Exception ex) { base.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('流程发起出现异常 EXCEPTION:" + ex.ToString() + "');</script>"); } }
public void EnviarOportunidadeParaAprovacao(int id, string criadoPor) { var oportunidadeBusca = _oportunidadeRepositorio.ObterOportunidadePorId(id); if (oportunidadeBusca == null) { _logger.Info($"Oportunidade {oportunidadeBusca.Id} não encontrada"); } var token = Autenticador.Autenticar(); if (token == null) { _logger.Info("Não foi possível se autenticar no serviço de Workflow"); } var workflow = new WorkflowService(token); var oportunidadeDetalhes = _oportunidadeRepositorio.ObterDetalhesOportunidade(id); var usuario = _usuarioRepositorio.ObterUsuarioPorId(criadoPor.ToInt()); var campos = new { oportunidadeId = oportunidadeDetalhes.Id, oportunidadeDetalhes.Descricao, oportunidadeDetalhes.Identificacao, ContaId = oportunidadeDetalhes.Conta, ContatoId = oportunidadeDetalhes.Contato, MercadoriaId = oportunidadeDetalhes.Mercadoria, oportunidadeDetalhes.Aprovada, oportunidadeDetalhes.DataFechamento, oportunidadeDetalhes.TabelaId, oportunidadeDetalhes.Probabilidade, oportunidadeDetalhes.SucessoNegociacao, oportunidadeDetalhes.ClassificacaoCliente, oportunidadeDetalhes.Segmento, oportunidadeDetalhes.EstagioNegociacao, oportunidadeDetalhes.StatusOportunidade, oportunidadeDetalhes.MotivoPerda, oportunidadeDetalhes.TipoDeProposta, oportunidadeDetalhes.TipoServico, oportunidadeDetalhes.TipoNegocio, oportunidadeDetalhes.TipoOperacaoOportunidade, oportunidadeDetalhes.RevisaoId, oportunidadeDetalhes.Observacao, oportunidadeDetalhes.FaturamentoMensalLCL, oportunidadeDetalhes.FaturamentoMensalFCL, oportunidadeDetalhes.VolumeMensal, oportunidadeDetalhes.CIFMedio, oportunidadeDetalhes.PremioParceria, CriadoPor = usuario.Login, oportunidadeDetalhes.TipoOperacao, oportunidadeDetalhes.Vendedor, oportunidadeDetalhes.FormaPagamento, DataInicio = oportunidadeDetalhes.DataInicio.DataFormatada(), DataTermino = oportunidadeDetalhes.DataTermino.DataFormatada() }; var retorno = workflow.EnviarParaAprovacao( new CadastroWorkflow(Processo.OPORTUNIDADE, 1, oportunidadeBusca.Id, usuario.Login, usuario.Nome, usuario.Email, JsonConvert.SerializeObject(campos))); if (retorno == null) { throw new Exception("Nenhuma resposta do serviço de Workflow"); } if (retorno.sucesso == false) { _logger.Info(retorno.mensagem); } var oportunidadeWorkflow = new EnvioWorkflow(oportunidadeBusca.Id, Processo.OPORTUNIDADE, retorno.protocolo, retorno.mensagem, usuario.Id); _workflowRepositorio.IncluirEnvioAprovacao(oportunidadeWorkflow); if (oportunidadeBusca.StatusOportunidade != StatusOportunidade.CANCELADA) { oportunidadeBusca.StatusOportunidade = StatusOportunidade.ENVIADO_PARA_APROVACAO; } _oportunidadeRepositorio.AtualizarStatusOportunidade(oportunidadeBusca.StatusOportunidade, oportunidadeBusca.Id); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { if (_workflowType != null) { pnlWorkflowList.Visible = true; var idCol = gWorkflows.ColumnsOfType <BoundField>().Where(c => c.DataField == "WorkflowId").FirstOrDefault(); if (idCol != null) { idCol.Visible = !string.IsNullOrWhiteSpace(_workflowType.WorkflowIdPrefix); } var rockContext = new RockContext(); var workflowService = new WorkflowService(rockContext); var qry = workflowService .Queryable("Activities.ActivityType,InitiatorPersonAlias.Person").AsNoTracking() .Where(w => w.WorkflowTypeId.Equals(_workflowType.Id)); // Activated Date Range Filter if (drpActivated.LowerValue.HasValue) { qry = qry.Where(w => w.ActivatedDateTime >= drpActivated.LowerValue.Value); } if (drpActivated.UpperValue.HasValue) { DateTime upperDate = drpActivated.UpperValue.Value.Date.AddDays(1); qry = qry.Where(w => w.ActivatedDateTime.Value < upperDate); } // State Filter List <string> states = cblState.SelectedValues; if (states.Count == 1) // Don't filter if none or both options are selected { if (states[0] == "Active") { qry = qry.Where(w => !w.CompletedDateTime.HasValue); } else { qry = qry.Where(w => w.CompletedDateTime.HasValue); } } // Completed Date Range Filter if (drpCompleted.LowerValue.HasValue) { qry = qry.Where(w => w.CompletedDateTime.HasValue && w.CompletedDateTime.Value >= drpCompleted.LowerValue.Value); } if (drpCompleted.UpperValue.HasValue) { DateTime upperDate = drpCompleted.UpperValue.Value.Date.AddDays(1); qry = qry.Where(w => w.CompletedDateTime.HasValue && w.CompletedDateTime.Value < upperDate); } string name = tbName.Text; if (!string.IsNullOrWhiteSpace(name)) { qry = qry.Where(w => w.Name.StartsWith(name)); } int?personId = ppInitiator.SelectedValue; if (personId.HasValue) { qry = qry.Where(w => w.InitiatorPersonAlias.PersonId == personId.Value); } string status = tbStatus.Text; if (!string.IsNullOrWhiteSpace(status)) { qry = qry.Where(w => w.Status.StartsWith(status)); } // Filter query by any configured attribute filters if (AvailableAttributes != null && AvailableAttributes.Any()) { var attributeValueService = new AttributeValueService(rockContext); var parameterExpression = attributeValueService.ParameterExpression; foreach (var attribute in AvailableAttributes) { var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString()); qry = attribute.FieldType.Field.ApplyAttributeQueryFilter(qry, filterControl, attribute, workflowService, Rock.Reporting.FilterMode.SimpleFilter); } } IQueryable <Workflow> workflows = null; var sortProperty = gWorkflows.SortProperty; if (sortProperty != null) { if (sortProperty.Property == "Initiator") { if (sortProperty.Direction == SortDirection.Ascending) { workflows = qry .OrderBy(w => w.InitiatorPersonAlias.Person.LastName) .ThenBy(w => w.InitiatorPersonAlias.Person.NickName); } else { workflows = qry .OrderByDescending(w => w.InitiatorPersonAlias.Person.LastName) .ThenByDescending(w => w.InitiatorPersonAlias.Person.NickName); } } else { workflows = qry.Sort(sortProperty); } } else { workflows = qry.OrderByDescending(s => s.CreatedDateTime); } // Since we're not binding to actual workflow list, but are using AttributeField columns, // we need to save the workflows into the grid's object list var workflowObjectQry = workflows; if (gWorkflows.AllowPaging) { workflowObjectQry = workflowObjectQry.Skip(gWorkflows.PageIndex * gWorkflows.PageSize).Take(gWorkflows.PageSize); } gWorkflows.ObjectList = workflowObjectQry.ToList().ToDictionary(k => k.Id.ToString(), v => v as object); gWorkflows.EntityTypeId = EntityTypeCache.Get <Workflow>().Id; var qryGrid = workflows.Select(w => new { w.Id, w.WorkflowId, w.Name, Initiator = w.InitiatorPersonAlias != null ? w.InitiatorPersonAlias.Person : null, Activities = w.Activities.Where(a => a.ActivatedDateTime.HasValue && !a.CompletedDateTime.HasValue).OrderBy(a => a.ActivityType.Order).Select(a => a.ActivityType.Name), w.CreatedDateTime, Status = w.Status, IsCompleted = w.CompletedDateTime.HasValue }); gWorkflows.SetLinqDataSource(qryGrid); gWorkflows.DataBind(); } else { pnlWorkflowList.Visible = false; } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { if (_workflowType != null) { pnlWorkflowList.Visible = true; var rockContext = new RockContext(); var workflowService = new WorkflowService(rockContext); var qry = workflowService .Queryable("Activities.ActivityType,InitiatorPersonAlias.Person").AsNoTracking() .Where(w => w.WorkflowTypeId.Equals(_workflowType.Id)); // Activated Date Range Filter if (drpActivated.LowerValue.HasValue) { qry = qry.Where(w => w.ActivatedDateTime >= drpActivated.LowerValue.Value); } if (drpActivated.UpperValue.HasValue) { DateTime upperDate = drpActivated.UpperValue.Value.Date.AddDays(1); qry = qry.Where(w => w.ActivatedDateTime.Value < upperDate); } // State Filter List <string> states = cblState.SelectedValues; if (states.Count == 1) // Don't filter if none or both options are selected { if (states[0] == "Active") { qry = qry.Where(w => !w.CompletedDateTime.HasValue); } else { qry = qry.Where(w => w.CompletedDateTime.HasValue); } } // Completed Date Range Filter if (drpCompleted.LowerValue.HasValue) { qry = qry.Where(w => w.CompletedDateTime.HasValue && w.CompletedDateTime.Value >= drpCompleted.LowerValue.Value); } if (drpCompleted.UpperValue.HasValue) { DateTime upperDate = drpCompleted.UpperValue.Value.Date.AddDays(1); qry = qry.Where(w => w.CompletedDateTime.HasValue && w.CompletedDateTime.Value < upperDate); } string name = tbName.Text; if (!string.IsNullOrWhiteSpace(name)) { qry = qry.Where(w => w.Name.StartsWith(name)); } int?personId = ppInitiator.SelectedValue; if (personId.HasValue) { qry = qry.Where(w => w.InitiatorPersonAlias.PersonId == personId.Value); } string status = tbStatus.Text; if (!string.IsNullOrWhiteSpace(status)) { qry = qry.Where(w => w.Status.StartsWith(status)); } // Filter query by any configured attribute filters if (AvailableAttributes != null && AvailableAttributes.Any()) { var attributeValueService = new AttributeValueService(rockContext); var parameterExpression = attributeValueService.ParameterExpression; foreach (var attribute in AvailableAttributes) { var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString()); if (filterControl != null) { var filterValues = attribute.FieldType.Field.GetFilterValues(filterControl, attribute.QualifierValues); var expression = attribute.FieldType.Field.AttributeFilterExpression(attribute.QualifierValues, filterValues, parameterExpression); if (expression != null) { var attributeValues = attributeValueService .Queryable() .Where(v => v.Attribute.Id == attribute.Id); attributeValues = attributeValues.Where(parameterExpression, expression, null); qry = qry.Where(w => attributeValues.Select(v => v.EntityId).Contains(w.Id)); } } } } List <Workflow> workflows = null; var sortProperty = gWorkflows.SortProperty; if (sortProperty != null) { if (sortProperty.Property == "Initiator") { if (sortProperty.Direction == SortDirection.Ascending) { workflows = qry .OrderBy(w => w.InitiatorPersonAlias.Person.LastName) .ThenBy(w => w.InitiatorPersonAlias.Person.NickName) .ToList(); } else { workflows = qry .OrderByDescending(w => w.InitiatorPersonAlias.Person.LastName) .ThenByDescending(w => w.InitiatorPersonAlias.Person.NickName) .ToList(); } } else { workflows = qry.Sort(sortProperty).ToList(); } } else { workflows = qry.OrderByDescending(s => s.CreatedDateTime).ToList(); } // Since we're not binding to actual workflow list, but are using AttributeField columns, // we need to save the workflows into the grid's object list gWorkflows.ObjectList = new Dictionary <string, object>(); workflows.ForEach(w => gWorkflows.ObjectList.Add(w.Id.ToString(), w)); gWorkflows.DataSource = workflows.Select(w => new { w.Id, w.Name, Initiator = (w.InitiatorPersonAlias != null ? w.InitiatorPersonAlias.Person.FullName : ""), Activities = w.ActiveActivities.Select(a => a.ActivityType.Name).ToList().AsDelimited("<br/>"), w.CreatedDateTime, Status = string.Format("<span class='label label-info'>{0}</span>", w.Status), State = (w.CompletedDateTime.HasValue ? "<span class='label label-default'>Completed</span>" : "<span class='label label-success'>Active</span>") }).ToList(); gWorkflows.DataBind(); } else { pnlWorkflowList.Visible = false; } }
private static void Session2(WorkflowService reg) { var instance = reg.Get<PingForewerWorkflow>("PingForewer"); instance.Ping(); }
private String RenderActivityContent(WorkflowService api, WFBaseProcessInstance pi, string id, WFManualWorkItem[] mwks, WFAutomaticWorkItem[] awks) { string header = // "<DIV style=\"DISPLAY:none;OVERFLOW: auto\">\n" "<TABLE id='popupTable' align=center border=1 bordercolor=lightgrey>\n" + "<TR><td>\n" + "<TABLE style=\"background-color: #ffffcc;font-family: 宋体,Verdana,sans-serif;font-size: 12;Z-INDEX:106\" cellSpacing=\"0\" cellPadding=\"2\" border=\"0\">\n"; string footer = "</TABLE>\n" + "</TD></TR>\n" + "</TABLE>\n"; string content = ""; WFBaseActivityInstance ai = api.GetActivityInst(id); //Retreive process definition and Activity definition string xmlString = api.GetProcDefXml(pi.DefID); WFProcessDefinition processDef = new WFProcessDefinition(); ProcDefXmlParser xmlParser = new ProcDefXmlParser(processDef); xmlParser.Parse(xmlString); IWFActivityDefinition ad = processDef.FindActivityByName(ai.Name); WFManualActivityDefinition activityDef = null; if (ad != null && ad.GetType() == typeof(WFManualActivityDefinition)) { activityDef = (WFManualActivityDefinition)ad; } bool isSub = false; //zhouli ArrayList arrSub = new ArrayList(); ArrayList arrSubName = new ArrayList(); if (ai.Session > 0) { string status = ConvUtil.GetDisplayStatus(pi.Status, ai.Session, ai.TokenPos.Value, ai.Pending, ai.InStack); //zhouli string sql = string.Format(@"SELECT Proc_Inst_ID,Proc_Inst_Name FROM WF_PROC_INSTS WHERE SUPER_PROC_INST_ID='{0}'", pi.ProcInstID); DataTable dtSub = SQLHelper.GetDataTable2(sql); if (dtSub.Rows.Count > 0) { foreach (DataRow dr in dtSub.Rows) { arrSub.Add(dr["Proc_Inst_ID"].ToString()); arrSubName.Add(dr["Proc_Inst_Name"].ToString()); } } status = GetCNStatus(status); content += ConstructRow(status, ""); content += ConstructRow(null, null); if (mwks == null || mwks.Length == 0) { content += ConstructRow("开始日期:", DTFormat(ai.StartedDate)); if (ai.CompletedDate.Ticks > 0) { content += ConstructRow("完成日期:", DTFormat(ai.CompletedDate)); } if (awks != null) { Hashtable names = GetSubProcInstName(api, awks); string url = null; string procInstName = null; foreach (WFAutomaticWorkItem wk in awks) { procInstName = (string)names[wk.WorkItemID]; url = string.Format("<a href=# onclick=\"parent.showSubProcess('{0}')\">Sub Process '{1}'</a>", wk.WorkItemID, procInstName); content += ConstructRow(string.Format("#{0}", wk.Session), url); } } } //Show Mannual activity information else { ArrayList participantList = new ArrayList(); ArrayList participantStatus = new ArrayList(); //Create a list of participant involved in this activity for (int index = mwks.Length - 1; index >= 0; index--) { if (mwks[index].Status == WFManualWorkItem.ASSIGNED || mwks[index].Status == WFManualWorkItem.OVERDUE || mwks[index].Status == WFManualWorkItem.COMPLETED) { if (!String.IsNullOrEmpty(mwks[index].UserID)) { participantList.Add(mwks[index].UserID); participantStatus.Add(mwks[index].Status); } } } //Show type of activity and participant info if it AgileWork of type process adaptation if (activityDef != null && activityDef.CustomProperties.Contains("Ascentn.AgileWork.Premier.ProcessAdaptation")) { //Get type of the AgileWork string activityType = api.GetCustomAttr(pi.WorkObjectID, id + "_ApprovalType") as string; //Show type of the activity content += ConstructRow(null, null); content += ConstructRow("Activity Type:", activityType); //Add those participant who have not been assgined yet(in case of sequential type) to participantList if (activityType == "Sequential") { string activityProperties = api.GetCustomAttr(pi.WorkObjectID, id + "_ActivityProperties") as string; if (!String.IsNullOrEmpty(activityProperties)) { string[] approverInfoList = activityProperties.Split(';'); //If number of Approver is more than one, only first approver is get assigned //So add the rest approver(who have not been assigned)to the Participant List if (approverInfoList.Length > 1) { for (int i = 1; i < approverInfoList.Length; i++) { string[] userInfoList = approverInfoList[i].Split('|'); string user = userInfoList[0]; if (!String.IsNullOrEmpty(user)) { participantList.Add(user); participantStatus.Add("In Queue"); } } } } } } #region 显示人物列表 //Show participant list for the activity if (participantList.Count > 0) { content += ConstructRow("参与该任务的用户", null); for (int i = 0; i < participantList.Count; i++) { if (participantList[i].ToString().ToLower() != @"dev003\dummy")//zhouli content += ConstructRow(participantList[i] + ":", participantStatus[i]); } } foreach (WFManualWorkItem wk in mwks) { if (content.Length > 0) content += ConstructRow(null, null); if (wk.UserID.ToLower() == @"dev003\dummy") //zhouli { for (int sub = 0; sub < arrSub.Count; sub++) { //content += ConstructRow("子流程", arrSub[sub].ToString()); string url = string.Format("<a href=# onclick=\"parent.showSubProcess('{0}')\">{1}</a>", arrSub[sub].ToString(), arrSubName[sub].ToString()); content += ConstructRow("子流程", url); } } else { content += ConstructRow("会话:", wk.Session); content += ConstructRow("任务:", wk.Name); content += ConstructRow("任务处理人:", GetUserName(wk.UserID)); //zhouli content += ConstructRow("任务接收日期:", DTFormat(wk.AssignedDate)); //content += ConstructRow("过期日期:", DTFormat(wk.DueDate)); if (wk.CompletedDate.Ticks > 0) { content += ConstructRow("完成日期:", DTFormat(wk.CompletedDate)); } content += ConstructRow("状态:", wk.Status); } } #endregion } //Add custom attributes changes during this activity into content content += AddCustomAttribToContent(pi.ProcInstID, ai.StartedDate.ToString("M/d/yyyy H:mm:ss:fff tt"), ai.CompletedDate.ToString("M/d/yyyy H:mm:ss:fff tt")); //Show Process Adaptation Link only when AgileWork is of type Ascentn.AgileWork.Premier.ProcessAdaptation and not completed or cancled if (status != WFBaseActivityInstance.PASSED && status != WFBaseActivityInstance.CANCELLED && activityDef != null && activityDef.CustomProperties.Contains("Ascentn.AgileWork.Premier.ProcessAdaptation")) { // Get Process Adaptation Url from web.config string processAdaptationUrl = (String)ConfigurationManager.AppSettings["ProcessAdaptationUrl"]; string queryString = "?ProcessTemplate=" + pi.DefName + "&ProcessInstance=" + pi.ProcInstID + "&ActiveInstance=" + id; string processAdptationLink = string.Format("<a href=# onclick=\"parent.showProcessAdaptation('{0}')\">Open Process Adaptation</a>", processAdaptationUrl + queryString); //Add process adaptation link to the content content += ConstructRow(null, null); content += ConstructRow(processAdptationLink, null); } } else { content += ConstructRow("信息:", "此步骤还未流转到!"); } return header + content + footer; }
private Hashtable GetSubProcInstName(WorkflowService api, WFAutomaticWorkItem[] wks) { Hashtable h = new Hashtable(); if (wks == null || wks.Length == 0) return h; Hashtable hPIIDs = new Hashtable(); // ensure unique String piIDs = ""; foreach (WFAutomaticWorkItem w in wks) { if (hPIIDs[w.WorkItemID] == null) { if (piIDs.Length > 0) piIDs += ","; piIDs += String.Format("'{0}'", w.WorkItemID); hPIIDs[w.WorkItemID] = w.WorkItemID; } } WFQueryExpr expr = new WFQueryExpr("PROC_INST_ID", SQLExpr.IN, WFAny.Create(piIDs), true); WFBaseProcessInstance[] pis = api.QueryProcInsts(expr); if (pis == null) return h; foreach (WFBaseProcessInstance pi in pis) { h[pi.ProcInstID] = pi.ProcInstName; } return h; }
protected void btnUpdate_Click(object sender, EventArgs e) { var errors = new List <string>(); RockContext rockContext = new RockContext(); var workflows = GetWorkflows(rockContext); //Get the new attribute values from the repeater Dictionary <string, string> attributeUpdates = GetNewAttributeValues(); if (attributeUpdates.Any()) { var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); foreach (var workflow in workflows) { //Reuse the mergefields with new workflow mergeFields["Workflow"] = workflow; //We will store the attribute value changes and apply them all at once Dictionary <string, string> toUpdate = new Dictionary <string, string>(); foreach (var update in attributeUpdates) { toUpdate[update.Key] = update.Value.ResolveMergeFields(mergeFields); //if (toUpdate[update.Key]) //{ //} } foreach (var update in toUpdate) { workflow.SetAttributeValue(update.Key, update.Value); } workflow.SaveAttributeValues(); } } //Workflow settings //Activate the workflows if requested or if a new activity is activated if (ddlState.SelectedValue == "NotComplete" || ddlActivities.SelectedValue.IsNotNullOrWhiteSpace()) { foreach (var workflow in workflows) { workflow.CompletedDateTime = null; } } else if (ddlState.SelectedValue == "Complete") { foreach (var workflow in workflows) { workflow.MarkComplete(); } } //Update Status message if (tbStatus.Text.IsNotNullOrWhiteSpace()) { var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); foreach (var workflow in workflows) { mergeFields["Workflow"] = workflow; workflow.Status = tbStatus.Text.ResolveMergeFields(mergeFields); } } //Activate New Activity int?activityTypeId = ddlActivities.SelectedValueAsId(); if (activityTypeId.HasValue) { var activityType = WorkflowActivityTypeCache.Get(activityTypeId.Value); if (activityType != null) { foreach (var workflow in workflows) { var activity = WorkflowActivity.Activate(activityType, workflow, rockContext); activity.Guid = Guid.NewGuid(); foreach (var action in activity.Actions) { action.Guid = Guid.NewGuid(); } } } } rockContext.SaveChanges(); //Process workflows List <string> errorMessages = new List <string>(); if (workflows.Where(w => w.IsActive).Any()) { foreach (var workflow in workflows) { WorkflowService workflowService = new WorkflowService(new RockContext()); workflowService.Process(workflow, out errorMessages); } } pnlConfirmation.Visible = false; pnlDisplay.Visible = false; pnlDone.Visible = true; }
/// <summary> /// Completes the form action based on the action selected by the user. /// </summary> /// <param name="action">The action.</param> /// <param name="formAction">The form action.</param> /// <param name="currentPerson">The current person.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> private string CompleteFormAction(WorkflowAction action, string formAction, Person currentPerson, RockContext rockContext) { var workflowService = new WorkflowService(rockContext); var activity = action.Activity; var workflow = activity.Workflow; var mergeFields = RequestContext.GetCommonMergeFields(currentPerson); mergeFields.Add("Action", action); mergeFields.Add("Activity", activity); mergeFields.Add("Workflow", workflow); Guid activityTypeGuid = Guid.Empty; string responseText = "Your information has been submitted successfully."; // // Get the target activity type guid and response text from the // submitted form action. // foreach (var act in action.ActionTypeCache.WorkflowForm.Actions.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries)) { var actionDetails = act.Split(new char[] { '^' }); if (actionDetails.Length > 0 && actionDetails[0] == formAction) { if (actionDetails.Length > 2) { activityTypeGuid = actionDetails[2].AsGuid(); } if (actionDetails.Length > 3 && !string.IsNullOrWhiteSpace(actionDetails[3])) { responseText = actionDetails[3].ResolveMergeFields(mergeFields); } break; } } action.MarkComplete(); action.FormAction = formAction; action.AddLogEntry("Form Action Selected: " + action.FormAction); if (action.ActionTypeCache.IsActivityCompletedOnSuccess) { action.Activity.MarkComplete(); } // // Set the attribute that should contain the submitted form action. // if (action.ActionTypeCache.WorkflowForm.ActionAttributeGuid.HasValue) { var attribute = AttributeCache.Get(action.ActionTypeCache.WorkflowForm.ActionAttributeGuid.Value); if (attribute != null) { IHasAttributes item = null; if (attribute.EntityTypeId == workflow.TypeId) { item = workflow; } else if (attribute.EntityTypeId == activity.TypeId) { item = activity; } if (item != null) { item.SetAttributeValue(attribute.Key, formAction); } } } // // Activate the requested activity if there was one. // if (!activityTypeGuid.IsEmpty()) { var activityType = workflow.WorkflowTypeCache.ActivityTypes.Where(a => a.Guid.Equals(activityTypeGuid)).FirstOrDefault(); if (activityType != null) { WorkflowActivity.Activate(activityType, workflow); } } return(responseText); }
protected void lbProfileNext_Click(object sender, EventArgs e) { // setup merge fields var mergeFields = new Dictionary <string, object>(); mergeFields.Add("PersonId", hfPersonId.Value); mergeFields.Add("FirstName", tbFirstName.Text); mergeFields.Add("LastName", tbLastName.Text); mergeFields.Add("StreetAddress", acAddress.Street1); mergeFields.Add("City", acAddress.City); mergeFields.Add("State", acAddress.State); mergeFields.Add("PostalCode", acAddress.PostalCode); mergeFields.Add("Country", acAddress.Country); mergeFields.Add("Email", tbEmail.Text); mergeFields.Add("HomePhone", pnbHomePhone.Text); mergeFields.Add("MobilePhone", pnbHomePhone.Text); mergeFields.Add("BirthDate", dpBirthdate.Text); mergeFields.Add("OtherUpdates", tbOtherUpdates.Text); var globalAttributeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields(CurrentPerson); globalAttributeFields.ToList().ForEach(d => mergeFields.Add(d.Key, d.Value)); // if an email was provided email results RockContext rockContext = new RockContext(); if (!string.IsNullOrWhiteSpace(GetAttributeValue("UpdateEmail"))) { var receiptEmail = new SystemEmailService(rockContext).Get(new Guid(GetAttributeValue("UpdateEmail"))); if (receiptEmail != null) { var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read(rockContext).GetValue("ExternalApplicationRoot"); var recipients = new List <RecipientData>(); recipients.Add(new RecipientData(null, mergeFields)); Email.Send(receiptEmail.Guid, recipients, appRoot); } } // launch workflow if configured if (!string.IsNullOrWhiteSpace(GetAttributeValue("WorkflowType"))) { var workflowTypeService = new WorkflowTypeService(rockContext); var workflowService = new WorkflowService(rockContext); var workflowType = workflowTypeService.Get(new Guid(GetAttributeValue("WorkflowType"))); if (workflowType != null) { var workflow = Rock.Model.Workflow.Activate(workflowType, "Kiosk Update Info"); // set attributes workflow.SetAttributeValue("PersonId", hfPersonId.Value); workflow.SetAttributeValue("FirstName", tbFirstName.Text); workflow.SetAttributeValue("LastName", tbLastName.Text); workflow.SetAttributeValue("StreetAddress", acAddress.Street1); workflow.SetAttributeValue("City", acAddress.City); workflow.SetAttributeValue("State", acAddress.State); workflow.SetAttributeValue("PostalCode", acAddress.PostalCode); workflow.SetAttributeValue("Country", acAddress.Country); workflow.SetAttributeValue("Email", tbEmail.Text); workflow.SetAttributeValue("HomePhone", pnbHomePhone.Text); workflow.SetAttributeValue("MobilePhone", pnbHomePhone.Text); workflow.SetAttributeValue("BirthDate", dpBirthdate.Text); workflow.SetAttributeValue("OtherUpdates", tbOtherUpdates.Text); // lauch workflow List <string> workflowErrors; workflowService.Process(workflow, out workflowErrors); } } HidePanels(); pnlComplete.Visible = true; lCompleteMessage.Text = GetAttributeValue("CompleteMessageLava").ResolveMergeFields(mergeFields); bool enableDebug = GetAttributeValue("EnableDebug").AsBoolean(); if (enableDebug && IsUserAuthorized(Authorization.EDIT)) { lDebug.Visible = true; lDebug.Text = mergeFields.lavaDebugInfo(); } }
public WorkflowForm GetNextForm(int?workflowId = null, string formAction = null, List <MobileField> formFields = null) { var rockContext = new RockContext(); var workflowService = new WorkflowService(rockContext); var workflow = LoadWorkflow(workflowId, rockContext); var currentPerson = GetCurrentPerson(); var action = ProcessAndGetNextAction(workflow, currentPerson, rockContext, out var message); if (action == null) { return(new WorkflowForm { Message = message ?? GetCompletionMessage(workflow, string.Empty) }); } // // If this is a form submittal, then complete the form and re-process. // if (!string.IsNullOrEmpty(formAction) && formFields != null) { SetFormValues(action, formFields); var responseText = CompleteFormAction(action, formAction, currentPerson, rockContext); action = ProcessAndGetNextAction(workflow, currentPerson, rockContext, out message); if (action == null) { return(new WorkflowForm { Message = message ?? GetCompletionMessage(workflow, responseText) }); } } // // Begin building up the response with the form data. // var activity = action.Activity; var form = action.ActionTypeCache.WorkflowForm; var mobileForm = new WorkflowForm { WorkflowId = workflow.Id }; // // Populate all the form fields that should be visible on the workflow. // foreach (var formAttribute in form.FormAttributes.OrderBy(a => a.Order)) { if (formAttribute.IsVisible) { var attribute = AttributeCache.Get(formAttribute.AttributeId); string value = attribute.DefaultValue; // // Get the current value from either the workflow or the activity. // if (workflow.AttributeValues.ContainsKey(attribute.Key) && workflow.AttributeValues[attribute.Key] != null) { value = workflow.AttributeValues[attribute.Key].Value; } else if (activity.AttributeValues.ContainsKey(attribute.Key) && activity.AttributeValues[attribute.Key] != null) { value = activity.AttributeValues[attribute.Key].Value; } var mobileField = new MobileField { AttributeId = attribute.Id, Key = attribute.Key, Title = attribute.Name, IsRequired = formAttribute.IsRequired, ConfigurationValues = attribute.QualifierValues.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Value), RockFieldType = attribute.FieldType.Class, Value = value }; if (formAttribute.IsReadOnly) { var field = attribute.FieldType.Field; string formattedValue = null; // get formatted value if (attribute.FieldType.Class == typeof(Rock.Field.Types.ImageFieldType).FullName) { formattedValue = field.FormatValueAsHtml(null, attribute.EntityTypeId, activity.Id, value, attribute.QualifierValues, true); } else { formattedValue = field.FormatValueAsHtml(null, attribute.EntityTypeId, activity.Id, value, attribute.QualifierValues); } mobileField.Value = formattedValue; mobileField.RockFieldType = string.Empty; if (formAttribute.HideLabel) { mobileField.Title = string.Empty; } } mobileForm.Fields.Add(mobileField); } } // // Build the list of form actions (buttons) that should be presented // to the user. // foreach (var btn in form.Actions.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries)) { var actionDetails = btn.Split(new char[] { '^' }); if (actionDetails.Length > 0) { var btnType = DefinedValueCache.Get(actionDetails[1].AsGuid()); if (btnType != null) { mobileForm.Buttons.Add(new WorkflowFormButton { Text = actionDetails[0], Type = btnType.Value }); } } } return(mobileForm); }
public void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; var rockContext = new RockContext(); var hospitalWorkflow = dataMap.GetString("HospitalAdmissionWorkflow").AsGuidOrNull(); var nursingHomeAdmissionWorkflow = dataMap.GetString("NursingHomeResidentWorkflow").AsGuidOrNull(); var homeBoundPersonWorkflow = dataMap.GetString("HomeboundPersonWorkflow").AsGuidOrNull(); var workflowService = new WorkflowService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personAliasService = new PersonAliasService(rockContext); var personService = new PersonService(rockContext); var definedValueService = new DefinedValueService(rockContext); var workflowTypesIdAsStrings = new WorkflowTypeService(rockContext).Queryable() .Where(wt => wt.Guid == hospitalWorkflow || wt.Guid == nursingHomeAdmissionWorkflow || wt.Guid == homeBoundPersonWorkflow ) .ToList() .Select(wf => wf.Id.ToString()) .ToList(); var attributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && workflowTypesIdAsStrings.Contains(a.EntityTypeQualifierValue)) .Select(a => a.Id).ToList(); var wfTmpqry = workflowService.Queryable().AsNoTracking() .Where(w => ( w.WorkflowType.Guid == hospitalWorkflow || w.WorkflowType.Guid == nursingHomeAdmissionWorkflow || w.WorkflowType.Guid == homeBoundPersonWorkflow ) && (w.Status == "Active")); var tqry = wfTmpqry.Join(attributeValueService.Queryable(), obj => obj.Id, av => av.EntityId.Value, (obj, av) => new { Workflow = obj, AttributeValue = av }) .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(obj => obj.Workflow) .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }); var qry = tqry.ToList(); var newQry = qry.Select(w => new { Workflow = w.Workflow, Person = GetPerson(personAliasService, w.AttributeValues) }); var workflowsToClose = newQry .Where(cd => cd.Person.IsDeceased && cd.Workflow.CompletedDateTime == null) .Select(cd => cd.Workflow) .ToList(); foreach (var workflow in workflowsToClose) { workflow.MarkComplete(); } rockContext.SaveChanges(); context.Result = string.Format("Closed {0} workflows.", workflowsToClose.Count()); }
//提交请假信息 protected void btnSave_Click(object sender, EventArgs e) { try { string processGUID = this.txtProcessGUID.Value.ToString(); decimal days = Helper.ConverToDecimal(this.txtDays.Value); int leaveType = Helper.ConverToInt32(selectLeaveType.Value); string strNextActivityPerformers = hiddenNextActivityPerformers.Value.ToString().Trim(); IDictionary <string, PerformerList> nextActivityPerformers = NextActivityPerformers(strNextActivityPerformers); if (nextActivityPerformers == null) { base.RegisterStartupScript("", "<script>alert('请选择办理步骤或办理人员');</script>"); return; } DateTime now = DateTime.Now; //请假业务数据 HrsLeaveEntity hrsLeaveEntity = new HrsLeaveEntity(); hrsLeaveEntity.LeaveType = leaveType; hrsLeaveEntity.Days = days; try { hrsLeaveEntity.FromDate = Helper.ConvertToDateTime(this.txtFromDate.Value, now); } catch (Exception ex) { hrsLeaveEntity.FromDate = now; } try { hrsLeaveEntity.ToDate = Helper.ConvertToDateTime(this.txtToDate.Value, now); } catch (Exception ex) { hrsLeaveEntity.ToDate = now; } hrsLeaveEntity.CurrentActivityText = string.Empty; hrsLeaveEntity.Status = 0; hrsLeaveEntity.CreatedUserID = LoginUserID; hrsLeaveEntity.CreatedUserName = this.LoginUserName; hrsLeaveEntity.CreatedDate = now; int instanceId = WorkFlows.AddHrsLeave(hrsLeaveEntity); if (instanceId > 0) { //调用流程 IWorkflowService service = new WorkflowService(); WfAppRunner initiator = new WfAppRunner(); initiator.AppName = "请假流程"; initiator.AppInstanceID = instanceId.ToString(); initiator.ProcessGUID = processGUID; initiator.UserID = LoginUserID.ToString(); initiator.UserName = LoginUserName; initiator.Conditions = GetCondition(string.Format("days-{0}", days)); WfExecutedResult startedResult = service.StartProcess(initiator); if (startedResult.Status != WfExecutedStatus.Success) { base.RegisterStartupScript("", "<script>alert('" + startedResult.Message + "');</script>"); return; } //送往下一步 /* * PerformerList pList = new PerformerList(); * pList.Add(new Performer(nextUserID.ToString(), nextUserName)); * * initiator.NextActivityPerformers = new Dictionary<String, PerformerList>(); * initiator.NextActivityPerformers.Add(stepGuid, pList); */ initiator.NextActivityPerformers = nextActivityPerformers; WfExecutedResult runAppResult = service.RunProcessApp(initiator); if (runAppResult.Status != WfExecutedStatus.Success) { base.RegisterStartupScript("", "<script>alert('" + runAppResult.Message + "');</script>"); return; } //保存业务数据 //BizAppFlowEntity AppFlowEntity = new Entity.BizAppFlowEntity(); //AppFlowEntity.AppName = "流程发起"; //AppFlowEntity.AppInstanceID = instanceId.ToString(); //AppFlowEntity.ActivityName = "流程发起"; //AppFlowEntity.Remark = string.Format("申请人:{0}-{1}", LoginUserID, LoginUserName); //AppFlowEntity.ChangedTime = now; //AppFlowEntity.ChangedUserID = LoginUserID.ToString(); //AppFlowEntity.ChangedUserName = LoginUserName; //WorkFlows.AddBizAppFlow(AppFlowEntity); HrsLeaveOpinionEntity hrsleaveOpinionEntity = new HrsLeaveOpinionEntity(); hrsleaveOpinionEntity.AppInstanceID = instanceId.ToString(); hrsleaveOpinionEntity.ActivityID = System.Guid.Empty.ToString(); hrsleaveOpinionEntity.ActivityName = "流程发起"; hrsleaveOpinionEntity.Remark = string.Format("申请人:{0}-{1}", LoginUserID, LoginUserName); hrsleaveOpinionEntity.ChangedTime = now; hrsleaveOpinionEntity.ChangedUserID = LoginUserID.ToString(); hrsleaveOpinionEntity.ChangedUserName = LoginUserName; WorkFlows.AddHrsLeaveOpinion(hrsleaveOpinionEntity); base.RegisterStartupScript("", "<script>alert('流程发起成功');window.location.href='FlowList.aspx';</script>"); } } catch (Exception ex) { base.RegisterStartupScript("", "<script>alert('流程发起出现异常 EXCEPTION:" + ex.ToString() + "');</script>"); } }
bool TryGenerateSource(AssemblyBuilder assemblyBuilder, BuildProvider buildProvider, WorkflowService workflowService, bool isSupportedVersion, string filePath, out string activityName) { bool generatedSource; string codeFileName; this.GenerateSource(isSupportedVersion, filePath, assemblyBuilder, workflowService, out codeFileName, out generatedSource, out activityName); if (generatedSource) { this.WriteCodeFile(assemblyBuilder, buildProvider, codeFileName); this.GenerateExpressionRootFactory(assemblyBuilder, buildProvider, GeneratedNamespace, activityName); } return generatedSource; }
/// <summary> /// /// </summary> protected void InitStepMember() { WfAppRunner runner = new WfAppRunner(); string strNodes = string.Empty; //流程定义的GUID string flowGuid = Request.QueryString["ProcessGUID"] == null ? "" : Request.QueryString["ProcessGUID"].ToString(); string Step = Request.QueryString["Step"] == null ? "" : Request.QueryString["Step"].ToString(); if (string.IsNullOrEmpty(flowGuid) || string.IsNullOrEmpty(Step)) { base.RegisterStartupScript("", "<script>alert('流程GUID为空');</script>"); } else { List <ZTreeEntity> zTreeEntityList = new List <ZTreeEntity>(); String processGUID = flowGuid; IWorkflowService service = new WorkflowService(); switch (Step) { case "start": //流程第一步选择 ActivityEntity firstActivity = service.GetFirstActivity(processGUID, string.Empty); String firstActivityGUID = firstActivity.ActivityGUID; string conditions = Request.QueryString["condition"] == null ? "" : Request.QueryString["condition"].ToString(); runner = new WfAppRunner { ProcessGUID = flowGuid, Version = "1", UserID = this.LoginUserID.ToString() }; IList <NodeView> nextNodes = service.GetFirstActivityRoleUserTree(runner, GetCondition(conditions)); if (nextNodes != null) { if (nextNodes != null) { ZTreeEntity zTreeEntity = null; foreach (NodeView item in nextNodes) { zTreeEntity = new ZTreeEntity(); zTreeEntity.id = string.Format("step[{0}]", item.ActivityGUID); zTreeEntity.pId = "0"; zTreeEntity.name = item.ActivityName; zTreeEntity.nocheck = false; zTreeEntityList.Add(zTreeEntity); foreach (var user in item.Users) { zTreeEntity = new ZTreeEntity(); zTreeEntity.id = string.Format("step[{0}]member[{1}]", item.ActivityGUID, user.UserID); zTreeEntity.pId = string.Format("step[{0}]", item.ActivityGUID); zTreeEntity.name = user.UserName; zTreeEntity.nocheck = false; zTreeEntityList.Add(zTreeEntity); } } } } else { LiteralMSG.Text = "当前没有需要您办理的步骤"; } break; case "task": try { if (LoginUserID > 0) { string condition = Request.QueryString["condition"] == null ? "" : Request.QueryString["condition"].ToString(); string instanceId = Request.QueryString["instanceId"] == null ? string.Empty : Request.QueryString["instanceId"].ToString(); runner.AppInstanceID = instanceId; runner.ProcessGUID = processGUID; runner.UserID = this.LoginUserID.ToString(); hiddenIsSelectMember.Value = "true"; //IList<NodeView> NodeViewList = service.GetNextActivityTree(runner, GetCondition(condition)); IList <NodeView> NodeViewList = service.GetNextActivityRoleUserTree(runner, GetCondition(condition)); if (NodeViewList != null) { ZTreeEntity zTreeEntity = null; foreach (NodeView item in NodeViewList) { zTreeEntity = new ZTreeEntity(); zTreeEntity.id = string.Format("step[{0}]", item.ActivityGUID); zTreeEntity.pId = "0"; zTreeEntity.name = item.ActivityName; zTreeEntityList.Add(zTreeEntity); foreach (var user in item.Users) { zTreeEntity = new ZTreeEntity(); zTreeEntity.id = string.Format("step[{0}]member[{1}]", item.ActivityGUID, user.UserID); zTreeEntity.pId = string.Format("step[{0}]", item.ActivityGUID); zTreeEntity.name = user.UserName; zTreeEntity.nocheck = false; zTreeEntityList.Add(zTreeEntity); } } } else { LiteralMSG.Text = "当前没有需要您办理的步骤"; } } } catch (Exception ex) { } break; } strNodes = JsonHelper.ObjectToJson(zTreeEntityList); } Response.Write(strNodes); Response.End(); }
private WFManualWorkItem[] GetManualWorkItems(WorkflowService api, string aiID) { // manual work items WFAny any = WFAny.Create(aiID); WFQueryExpr expr = new WFQueryExpr("ACTIVITY_INST_ID", SQLExpr.EQ, any, true); WFManualWorkItem[] wks = api.QueryWorkList(expr); if (wks == null || wks.Length == 0) return null; SortedList sl = new SortedList(); foreach (WFManualWorkItem wk in wks) { string key = (DateTime.MaxValue - wk.AssignedDate).ToString(); sl.Add(key + UUID.GetID(), wk); } sl.Values.CopyTo(wks, 0); return wks; }
public SampleFormsController(UnitWork Unit, WorkflowService Service) { service = Service; unit = Unit; }
protected void InitFlowInfo() { string AppInstanceID = Request.QueryString["AppInstanceID"] == null ? string.Empty : Request.QueryString["AppInstanceID"].ToString(); string ProcessGUID = Request.QueryString["ProcessGUID"] == null ? string.Empty : Request.QueryString["ProcessGUID"].ToString(); int ActivityInstanceID = Request.QueryString["ActivityInstanceID"] == null ? 0 : Helper.ConverToInt32(Request.QueryString["ActivityInstanceID"].ToString()); if (!string.IsNullOrEmpty(AppInstanceID)) { int leaveID = int.Parse(AppInstanceID); HrsLeaveEntity hrsLeaveEntity = WorkFlows.GetHrsLeaveModel(leaveID); if (hrsLeaveEntity != null && hrsLeaveEntity.ID > 0) { selectLeaveType.Value = hrsLeaveEntity.LeaveType.ToString(); selectLeaveType.Disabled = true; txtDays.Value = hrsLeaveEntity.Days.ToString(); txtFromDate.Value = hrsLeaveEntity.FromDate.ToString("yyyy-MM-dd"); txtToDate.Value = hrsLeaveEntity.ToDate.ToString("yyyy-MM-dd"); hiddenInstanceId.Value = hrsLeaveEntity.ID.ToString(); hiddenActivityInstanceID.Value = ActivityInstanceID.ToString(); this.txtDepmanagerRemark.Value = hrsLeaveEntity.DepManagerRemark; this.txtDirectorRemark.Value = hrsLeaveEntity.DirectorRemark; //主管总监 this.txtDeputyGeneralRemark.Value = hrsLeaveEntity.DeputyGeneralRemark; //副总经理 this.txtGeneralManagerRemark.Value = hrsLeaveEntity.GeneralManagerRemark; //总经理 //权限设置 IWorkflowService service = new WorkflowService(); ActivityInstanceEntity activityInstanceEntity = service.GetActivityInstance(ActivityInstanceID); ProcessInstanceEntity processInstanceEntity = service.GetProcessInstance(activityInstanceEntity.ProcessInstanceID); this.txtProcessGUID.Value = activityInstanceEntity.ProcessGUID; if (activityInstanceEntity != null) { ActivityEntity activityEntity = service.GetActivityEntity(processInstanceEntity.ProcessGUID, processInstanceEntity.Version, activityInstanceEntity.ActivityGUID); var roles = service.GetActivityRoles(processInstanceEntity.ProcessGUID, processInstanceEntity.Version, activityInstanceEntity.ActivityGUID); if (activityEntity != null && roles != null && roles.Count > 0) { foreach (var role in roles) { if (role.ID == LoginRoleID.ToString()) { switch (role.ID) { case "2": //部门经理 this.txtDepmanagerRemark.Disabled = false; hiddenPerformField.Value = "DepManager"; break; case "4": //主管总监 this.txtDirectorRemark.Disabled = false; hiddenPerformField.Value = "Director"; break; case "7": //副总经理 this.txtDeputyGeneralRemark.Disabled = false; hiddenPerformField.Value = "Deputy"; break; case "8": //总经理 this.txtGeneralManagerRemark.Disabled = false; hiddenPerformField.Value = "General"; break; } } } } } } } }
void AddSupportedVersions(WorkflowServiceHost workflowServiceHost, WorkflowService baseService) { AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); IList<Tuple<string, Stream>> streams = null; string xamlFileName = Path.GetFileNameWithoutExtension(VirtualPathUtility.GetFileName(this.xamlVirtualFile)); GetSupportedVersionStreams(xamlFileName, out streams); if (streams != null) { try { foreach (Tuple<string, Stream> stream in streams) { try { WorkflowService service = CreatetWorkflowServiceAndSetCompiledExpressionRoot(stream.Item1, stream.Item2, baseService.Name); if (service != null) { workflowServiceHost.SupportedVersions.Add(service); } } catch (Exception e) { Exception newException; if (Fx.IsFatal(e) || !TryWrapSupportedVersionException(stream.Item1, e, out newException)) { throw; } throw FxTrace.Exception.AsError(newException); } } } finally { foreach (Tuple<string, Stream> stream in streams) { stream.Item2.Dispose(); } } } }
/// <summary> /// Updates the workflow. /// </summary> /// <param name="id">The identifier.</param> /// <param name="recommendation">The recommendation.</param> /// <param name="reportLink">The report link.</param> /// <param name="reportStatus">The report status.</param> /// <param name="rockContext">The rock context.</param> private static void UpdateWorkflow(int id, string recommendation, string documentId, string reportStatus, RockContext rockContext) { var workflowService = new WorkflowService(rockContext); var workflow = new WorkflowService(rockContext).Get(id); if (workflow != null && workflow.IsActive) { workflow.LoadAttributes(); if (workflow.Attributes.ContainsKey("ReportStatus")) { if (workflow.GetAttributeValue("ReportStatus").IsNotNullOrWhiteSpace() && reportStatus.IsNullOrWhiteSpace()) { // Don't override current values if Webhook is older than current values return; } } if (workflow.Attributes.ContainsKey("Report")) { if (workflow.GetAttributeValue("Report").IsNotNullOrWhiteSpace() && documentId.IsNullOrWhiteSpace()) { // Don't override current values if Webhook is older than current values return; } } // Save the recommendation if (!string.IsNullOrWhiteSpace(recommendation)) { if (SaveAttributeValue(workflow, "ReportRecommendation", recommendation, FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext, new Dictionary <string, string> { { "ispassword", "false" } })) { } } // Save the report link if (documentId.IsNotNullOrWhiteSpace()) { int entityTypeId = EntityTypeCache.Get(typeof(Checkr)).Id; if (SaveAttributeValue(workflow, "Report", $"{entityTypeId},{documentId}", FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext, new Dictionary <string, string> { { "ispassword", "false" } })) { } } if (!string.IsNullOrWhiteSpace(reportStatus)) { // Save the status if (SaveAttributeValue(workflow, "ReportStatus", reportStatus, FieldTypeCache.Get(Rock.SystemGuid.FieldType.SINGLE_SELECT.AsGuid()), rockContext, new Dictionary <string, string> { { "fieldtype", "ddl" }, { "values", "Pass,Fail,Review" } })) { } } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); workflow.SaveAttributeValues(rockContext); foreach (var activity in workflow.Activities) { activity.SaveAttributeValues(rockContext); } }); } rockContext.SaveChanges(); List <string> workflowErrors; workflowService.Process(workflow, out workflowErrors); }
internal static WorkflowService CreatetWorkflowService(Stream activityStream, XName defaultServiceName) { WorkflowService service = null; object serviceObject; serviceObject = LoadXaml(activityStream); if (serviceObject is Activity) { service = new WorkflowService { Body = (Activity)serviceObject }; } else if (serviceObject is WorkflowService) { service = (WorkflowService)serviceObject; } // If name of the service is not set // service name = xaml file name with extension // service namespace = IIS virtual path // service config name = Activity.DisplayName if (service != null) { if (service.Name == null) { service.Name = defaultServiceName; if (service.ConfigurationName == null && service.Body != null) { service.ConfigurationName = XmlConvert.EncodeLocalName(service.Body.DisplayName); } } } return service; }
public HttpResponseMessage Family(string param) { try { var session = HttpContext.Current.Session; var localDeviceConfigCookie = HttpContext.Current.Request.Cookies[CheckInCookieKey.LocalDeviceConfig].Value; var localDevice = localDeviceConfigCookie.FromJsonOrNull <LocalDeviceConfiguration>(); var currentKioskId = localDevice.CurrentKioskId.Value; Guid blockGuid = ( Guid )session["BlockGuid"]; var currentCheckInState = new CheckInState(currentKioskId, localDevice.CurrentCheckinTypeId, localDevice.CurrentGroupTypeIds); currentCheckInState.CheckIn.UserEnteredSearch = true; currentCheckInState.CheckIn.ConfirmSingleFamily = true; currentCheckInState.CheckIn.SearchType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER); currentCheckInState.CheckIn.SearchValue = param; var rockContext = new Rock.Data.RockContext(); var block = BlockCache.Get(blockGuid); string workflowActivity = block.GetAttributeValue("WorkflowActivity"); Guid? workflowGuid = block.GetAttributeValue("WorkflowType").AsGuidOrNull(); List <string> errors; var workflowService = new WorkflowService(rockContext); var workflowType = WorkflowTypeCache.Get(workflowGuid.Value); var CurrentWorkflow = Rock.Model.Workflow.Activate(workflowType, currentCheckInState.Kiosk.Device.Name, rockContext); var activityType = workflowType.ActivityTypes.Where(a => a.Name == workflowActivity).FirstOrDefault(); if (activityType != null) { WorkflowActivity.Activate(activityType, CurrentWorkflow, rockContext); if (workflowService.Process(CurrentWorkflow, currentCheckInState, out errors)) { if (errors.Any()) { var innerException = new Exception(string.Join(" -- ", errors)); ExceptionLogService.LogException(new Exception("Process Mobile Checkin failed initial workflow. See inner exception for details.", innerException)); } // Keep workflow active for continued processing CurrentWorkflow.CompletedDateTime = null; SaveState(session, currentCheckInState); List <CheckInFamily> families = currentCheckInState.CheckIn.Families; families = families.OrderBy(f => f.Caption).ToList(); return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, families)); } else { if (errors.Any()) { var innerException = new Exception(string.Join(" -- ", errors)); ExceptionLogService.LogException(new Exception("Process Mobile Checkin failed initial workflow. See inner exception for details.", innerException)); } else { ExceptionLogService.LogException(new Exception("Process Mobile Checkin failed initial workflow. See inner exception for details.")); } } } else { return(ControllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, string.Format("Workflow type does not have a '{0}' activity type", workflowActivity))); } return(ControllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, String.Join("\n", errors))); } catch (Exception ex) { ExceptionLogService.LogException(ex, HttpContext.Current); return(ControllerContext.Request.CreateResponse(HttpStatusCode.Forbidden, "Forbidden")); } }
protected virtual WorkflowServiceHost CreateWorkflowServiceHost(WorkflowService service, Uri[] baseAddresses) { WorkflowServiceHost workflowServiceHost = new WorkflowServiceHost(service, baseAddresses); if (service.DefinitionIdentity != null) { AddSupportedVersions(workflowServiceHost, service); } return workflowServiceHost; }
/// <summary> /// Renders the specified context. /// </summary> /// <param name="context">The context.</param> /// <param name="result">The result.</param> public override void Render(Context context, TextWriter result) { // first ensure that entity commands are allowed in the context if (!this.IsAuthorized(context)) { result.Write(string.Format(RockLavaBlockBase.NotAuthorizedMessage, this.Name)); base.Render(context, result); return; } var attributes = new Dictionary <string, string>(); string parmWorkflowType = null; string parmWorkflowName = null; string parmWorkflowId = null; string parmActivityType = null; /* Parse the markup text to pull out configuration parameters. */ var parms = ParseMarkup(_markup, context); foreach (var p in parms) { if (p.Key.ToLower() == "workflowtype") { parmWorkflowType = p.Value; } else if (p.Key.ToLower() == "workflowname") { parmWorkflowName = p.Value; } else if (p.Key.ToLower() == "workflowid") { parmWorkflowId = p.Value; } else if (p.Key.ToLower() == "activitytype") { parmActivityType = p.Value; } else { attributes.AddOrReplace(p.Key, p.Value); } } /* Process inside a new stack level so our own created variables do not * persist throughout the rest of the workflow. */ context.Stack(() => { using (var rockContext = new RockContext()) { WorkflowService workflowService = new WorkflowService(rockContext); Rock.Model.Workflow workflow = null; WorkflowActivity activity = null; /* They provided a WorkflowType, so we need to kick off a new workflow. */ if (parmWorkflowType != null) { string type = parmWorkflowType; string name = parmWorkflowName ?? string.Empty; WorkflowTypeCache workflowType = null; /* Get the type of workflow */ if (type.AsGuidOrNull() != null) { workflowType = WorkflowTypeCache.Read(type.AsGuid()); } else if (type.AsIntegerOrNull() != null) { workflowType = WorkflowTypeCache.Read(type.AsInteger()); } /* Try to activate the workflow */ if (workflowType != null) { workflow = Rock.Model.Workflow.Activate(workflowType, parmWorkflowName); /* Set any workflow attributes that were specified. */ foreach (var attr in attributes) { if (workflow.Attributes.ContainsKey(attr.Key)) { workflow.SetAttributeValue(attr.Key, attr.Value.ToString()); } } if (workflow != null) { List <string> errorMessages; workflowService.Process(workflow, out errorMessages); if (errorMessages.Any()) { context["Error"] = string.Join("; ", errorMessages.ToArray()); } context["Workflow"] = workflow; } else { context["Error"] = "Could not activate workflow."; } } else { context["Error"] = "Workflow type not found."; } } /* They instead provided a WorkflowId, so we are working with an existing Workflow. */ else if (parmWorkflowId != null) { string id = parmWorkflowId.ToString(); /* Get the workflow */ if (id.AsGuidOrNull() != null) { workflow = workflowService.Get(id.AsGuid()); } else if (id.AsIntegerOrNull() != null) { workflow = workflowService.Get(id.AsInteger()); } if (workflow != null) { if (workflow.CompletedDateTime == null) { /* Currently we cannot activate an activity in a workflow that is currently * being processed. The workflow is held in-memory so the activity we would * activate would not show up for the processor and probably never run. */ if (!workflow.IsProcessing) { bool hasError = false; /* If they provided an ActivityType parameter then we need to activate * a new activity in the workflow. */ if (parmActivityType != null) { string type = parmActivityType.ToString(); WorkflowActivityTypeCache activityType = null; /* Get the type of activity */ if (type.AsGuidOrNull() != null) { activityType = WorkflowActivityTypeCache.Read(type.AsGuid()); } else if (type.AsIntegerOrNull() != null) { activityType = WorkflowActivityTypeCache.Read(type.AsInteger()); } if (activityType != null) { activity = WorkflowActivity.Activate(activityType, workflow); /* Set any workflow attributes that were specified. */ foreach (var attr in attributes) { if (activity.Attributes.ContainsKey(attr.Key)) { activity.SetAttributeValue(attr.Key, attr.Value.ToString()); } } } else { context["Error"] = "Activity type was not found."; hasError = true; } } /* Process the existing Workflow. */ if (!hasError) { List <string> errorMessages; workflowService.Process(workflow, out errorMessages); if (errorMessages.Any()) { context["Error"] = string.Join("; ", errorMessages.ToArray()); } context["Workflow"] = workflow; context["Activity"] = activity; } } else { context["Error"] = "Cannot activate activity on workflow that is currently being processed."; } } else { context["Error"] = "Workflow has already been completed."; } } else { context["Error"] = "Workflow not found."; } } else { context["Error"] = "Must specify one of WorkflowType or WorkflowId."; } RenderAll(NodeList, context, result); } }); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { using (var rockContext = new RockContext()) { var contextEntity = this.ContextEntity(); var workflowService = new WorkflowService(rockContext); var workflowActivityService = new WorkflowActivityService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personAliasService = new PersonAliasService(rockContext); var entityTypeService = new EntityTypeService(rockContext); Guid homeBoundPersonWorkflow = GetAttributeValue("HomeboundPersonWorkflow").AsGuid(); int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id; string status = (contextEntity != null ? "Completed" : "Active"); var workflowType = new WorkflowTypeService(rockContext).Get(homeBoundPersonWorkflow); var workflowTypeIdAsString = workflowType.Id.ToString(); var attributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString) .Select(a => a.Id).ToList(); // Look up the activity type for "Visitation" var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault(); var activityAttributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString) .Select(a => a.Id).ToList(); var wfTmpqry = workflowService.Queryable().AsNoTracking() .Where(w => (w.WorkflowType.Guid == homeBoundPersonWorkflow) && (w.Status == "Active" || w.Status == status)); var visitQry = workflowActivityService.Queryable() .Join( attributeValueService.Queryable(), wa => wa.Id, av => av.EntityId.Value, (wa, av) => new { WorkflowActivity = wa, AttributeValue = av }) .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(wa => wa.WorkflowActivity) .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }); if (contextEntity != null) { var personGuid = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList(); var validWorkflowIds = new AttributeValueService(rockContext).Queryable() .Where(av => av.Attribute.Key == "HomeboundPerson" && personGuid.Contains(av.Value)).Select(av => av.EntityId); wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id)); visitQry = visitQry.Where(w => validWorkflowIds.Contains(w.WorkflowActivity.WorkflowId)); gReport.Columns[10].Visible = true; } var visits = visitQry.ToList(); var workflows = wfTmpqry.Join( attributeValueService.Queryable(), obj => obj.Id, av => av.EntityId.Value, (obj, av) => new { Workflow = obj, AttributeValue = av }) .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(obj => obj.Workflow) .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }) .ToList(); var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (wf, wa) => new { WorkflowObjects = wf, VisitationActivities = wa }) .Select(obj => new { Workflow = obj.WorkflowObjects.Workflow, AttributeValues = obj.WorkflowObjects.AttributeValues, VisitationActivities = obj.VisitationActivities }).ToList(); if (contextEntity == null) { // Make sure they aren't deceased qry = qry.AsQueryable().Where(w => ! (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ? personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased : false)).ToList(); } var newQry = qry.Select(w => new { Id = w.Workflow.Id, Workflow = w.Workflow, Name = w.Workflow.Name, Address = new Func <string>(() => { PersonAlias p = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid()); Location homeLocation = p.Person.GetHomeLocation(); if (homeLocation == null) { return(""); } return(homeLocation.Street1 + homeLocation.City + " " + homeLocation.State + ", " + homeLocation.PostalCode); })(), HomeboundPerson = new Func <Person>(() => { return(personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid()).Person); })(), Age = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "HomeboundPerson").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.Age, StartDate = w.AttributeValues.Where(av => av.AttributeKey == "StartDate").Select(av => av.ValueAsDateTime).FirstOrDefault(), Description = w.AttributeValues.Where(av => av.AttributeKey == "HomeboundResidentDescription").Select(av => av.ValueFormatted).FirstOrDefault(), Visits = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(), LastVisitor = new Func <string>(() => { var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault(); if (visitor != null) { return(visitor.ValueFormatted); } return("N/A"); })(), LastVisitDate = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), EndDate = w.AttributeValues.Where(av => av.AttributeKey == "EndDate").Select(av => av.ValueFormatted).FirstOrDefault(), Status = w.Workflow.Status, Communion = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(), Actions = "" }).OrderBy(w => w.Name).ToList().AsQueryable(); SortProperty sortProperty = gReport.SortProperty; if (sortProperty != null) { gReport.SetLinqDataSource(newQry.Sort(sortProperty)); } else { gReport.SetLinqDataSource(newQry.OrderBy(p => p.Name)); } gReport.DataBind(); } }
private List <Rock.Model.Workflow> GetWorkflows(RockContext rockContext) { EntitySetService entitySetService = new EntitySetService(rockContext); var entitySet = entitySetService.Get(PageParameter("EntitySetId").AsInteger()); var workflowEntityId = EntityTypeCache.GetId(typeof(Rock.Model.Workflow)); if (entitySet == null || entitySet.EntityTypeId != workflowEntityId) { return(null); } WorkflowService workflowService = new WorkflowService(rockContext); var workflowQueryable = workflowService.Queryable(); var qry = entitySet.Items .Join(workflowQueryable, i => i.EntityId, w => w.Id, (i, w) => w); var firstWorkflow = qry.FirstOrDefault(); if (firstWorkflow == null) { return(null); } var workflowTypeId = firstWorkflow.WorkflowTypeId; AttributeService attributeService = new AttributeService(rockContext); AttributeValueService attributeValueService = new AttributeValueService(rockContext); var attributeQueryable = attributeService.Queryable() .Where(a => a.EntityTypeId == workflowEntityId && a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeId.ToString()) .Select(a => a.Id); var attributeValueQueryable = attributeValueService.Queryable() .Where(av => attributeQueryable.Contains(av.AttributeId)); var mixedItems = qry.GroupJoin(attributeValueQueryable, w => w.Id, av => av.EntityId, (w, av) => new { Workflow = w, AttributeValues = av }) .ToList(); Dictionary <string, AttributeCache> attributes = new Dictionary <string, AttributeCache>(); foreach (var id in attributeQueryable.ToList()) { var attributeCache = AttributeCache.Get(id); if (attributeCache != null) { attributes[attributeCache.Key] = attributeCache; } } var workflows = new List <Rock.Model.Workflow>(); foreach (var item in mixedItems) { var workflow = item.Workflow; workflow.Attributes = attributes; workflow.AttributeValues = new Dictionary <string, AttributeValueCache>(); foreach (var attribute in attributes) { var attributeValue = item.AttributeValues.Where(av => av.AttributeKey == attribute.Key).FirstOrDefault(); workflow.AttributeValues[attribute.Key] = attributeValue != null ? new AttributeValueCache(attributeValue) : new AttributeValueCache(); } workflows.Add(workflow); } return(workflows); }
private IQueryable <HospitalRow> GetQuery(RockContext rockContext) { var contextEntity = this.ContextEntity(); var workflowService = new WorkflowService(rockContext); var workflowActivityService = new WorkflowActivityService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personAliasService = new PersonAliasService(rockContext); var definedValueService = new DefinedValueService(rockContext); var entityTypeService = new EntityTypeService(rockContext); int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id; string status = (contextEntity != null ? "Completed" : "Active"); Guid hospitalWorkflow = GetAttributeValue("HospitalAdmissionWorkflow").AsGuid(); var workflowType = new WorkflowTypeService(rockContext).Get(hospitalWorkflow); var workflowTypeIdAsString = workflowType.Id.ToString(); var attributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString) .Select(a => a.Id).ToList(); // Look up the activity type for "Visitation" var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault(); var activityAttributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString) .Select(a => a.Id).ToList(); var wfTmpqry = workflowService.Queryable().AsNoTracking() .Where(w => (w.WorkflowType.Guid == hospitalWorkflow) && (w.Status == "Active" || w.Status == status)); var visitQry = workflowActivityService.Queryable() .Join( attributeValueService.Queryable(), wa => wa.Id, av => av.EntityId.Value, (wa, av) => new { WorkflowActivity = wa, AttributeValue = av }) .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(wa => wa.WorkflowActivity) .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }); if (contextEntity != null) { var personGuid = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList(); var validWorkflowIds = new AttributeValueService(rockContext).Queryable() .Where(av => av.Attribute.Key == "PersonToVisit" && personGuid.Contains(av.Value)).Select(av => av.EntityId); wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id)); visitQry = visitQry.Where(w => validWorkflowIds.Contains(w.WorkflowActivity.WorkflowId)); gReport.Columns[10].Visible = true; } var visits = visitQry.ToList(); var workflows = wfTmpqry.Join( attributeValueService.Queryable(), obj => obj.Id, av => av.EntityId.Value, (obj, av) => new { Workflow = obj, AttributeValue = av }) .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(obj => obj.Workflow) .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }) .ToList(); var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (wf, wa) => new { Workflow = wf, WorkflowActivities = wa }) .Select(obj => new { Workflow = obj.Workflow.Workflow, AttributeValues = obj.Workflow.AttributeValues, VisitationActivities = obj.WorkflowActivities }).ToList(); if (contextEntity == null) { // Make sure they aren't deceased qry = qry.AsQueryable().Where(w => ! (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ? personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased : false)).ToList(); } var newQry = qry.Select(w => new HospitalRow { Id = w.Workflow.Id, Workflow = w.Workflow, Name = w.Workflow.Name, Hospital = w.AttributeValues.Where(av => av.AttributeKey == "Hospital").Select(av => av.ValueFormatted).FirstOrDefault(), HospitalAddress = new Func <string>(() => { DefinedValueCache dv = DefinedValueCache.Get(w.AttributeValues.Where(av => av.AttributeKey == "Hospital").Select(av => av.Value).FirstOrDefault().AsGuid()); return(dv.AttributeValues["Qualifier1"].ValueFormatted + " " + dv.AttributeValues["Qualifier2"].ValueFormatted + " " + dv.AttributeValues["Qualifier3"].ValueFormatted + ", " + dv.AttributeValues["Qualifier4"].ValueFormatted); })(), PersonToVisit = new Func <Person>(() => { PersonAlias pa = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()); if (pa != null) { return(pa.Person); } return(new Person()); })(), Campus = new Func <string>(() => { PersonAlias pa = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()); if (pa != null) { var campus = pa.Person.GetCampus(); return(campus != null ? campus.Name : "[Unknown]"); } return("[Unknown]"); })(), Age = new Func <int?>(() => { PersonAlias pa = personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()); if (pa != null) { return(pa.Person.Age); } return(null); })(), Room = w.AttributeValues.Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(), NotifiedBy = w.AttributeValues.Where(av => av.AttributeKey == "NotifiedBy").Select(av => av.ValueFormatted).FirstOrDefault(), AdmitDate = w.AttributeValues.Where(av => av.AttributeKey == "AdmitDate").Select(av => av.ValueAsDateTime).FirstOrDefault(), Description = w.AttributeValues.Where(av => av.AttributeKey == "VisitationRequestDescription").Select(av => av.ValueFormatted).FirstOrDefault(), Visits = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(), LastVisitor = new Func <string>(() => { var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault(); if (visitor != null) { return(visitor.ValueFormatted); } return("N/A"); })(), LastVisitDate = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), DischargeDate = w.AttributeValues.Where(av => av.AttributeKey == "DischargeDate").Select(av => av.ValueFormatted).FirstOrDefault(), Status = w.Workflow.Status, Communion = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(), Actions = "" }).ToList().AsQueryable().OrderBy(p => p.Hospital).ThenBy(p => p.PersonToVisit.LastName); return(newQry); }
/// <summary> /// Triggers all the workflows of the given triggerType for the given entity item. /// </summary> /// <param name="item">The item.</param> /// <param name="triggerType">Type of the trigger.</param> /// <param name="personAlias">The person alias.</param> /// <returns></returns> private bool TriggerWorkflows(ContextItem item, WorkflowTriggerType triggerType, PersonAlias personAlias) { IEntity entity = item.Entity; Dictionary <string, PropertyInfo> properties = null; // Look at each trigger for this entity and for the given trigger type // and see if it's a match. foreach (var trigger in WorkflowTriggersCache.Triggers(entity.TypeName, triggerType).Where(t => t.IsActive == true)) { bool match = true; // If a qualifier column was given, then we need to check the previous or current qualifier value // otherwise it's just an automatic match. if (!string.IsNullOrWhiteSpace(trigger.EntityTypeQualifierColumn)) { // Get and cache the properties https://lotsacode.wordpress.com/2010/04/13/reflection-type-getproperties-and-performance/ // (Note: its possible that none of the triggers need them, so future TODO could be to // bypass all this in that case. if (properties == null) { properties = new Dictionary <string, PropertyInfo>(); foreach (PropertyInfo propertyInfo in entity.GetType().GetProperties()) { properties.Add(propertyInfo.Name.ToLower(), propertyInfo); } } match = IsQualifierMatch(item, properties, trigger); } // If we found a matching trigger, then fire it; otherwise do nothing. if (match) { // If it's one of the pre or immediate triggers, fire it immediately; otherwise queue it. if (triggerType == WorkflowTriggerType.PreSave || triggerType == WorkflowTriggerType.PreDelete || triggerType == WorkflowTriggerType.ImmediatePostSave) { var workflowType = WorkflowTypeCache.Get(trigger.WorkflowTypeId); if (workflowType != null && (workflowType.IsActive ?? true)) { var workflow = Rock.Model.Workflow.Activate(workflowType, trigger.WorkflowName); List <string> workflowErrors; using (var rockContext = new RockContext()) { var workflowService = new WorkflowService(rockContext); if (!workflowService.Process(workflow, entity, out workflowErrors)) { SaveErrorMessages.AddRange(workflowErrors); return(false); } } } } else { var transaction = new Rock.Transactions.WorkflowTriggerTransaction(); transaction.Trigger = trigger; transaction.Entity = entity.Clone(); transaction.PersonAlias = personAlias; Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction); } } } return(true); }
/// <summary> /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" /> /// fires that is associated with the <see cref="IJob" />. /// </summary> /// <param name="context">The execution context.</param> /// <remarks> /// The implementation may wish to set a result object on the /// JobExecutionContext before this method exits. The result itself /// is meaningless to Quartz, but may be informative to /// <see cref="IJobListener" />s or /// <see cref="ITriggerListener" />s that are watching the job's /// execution. /// </remarks> public virtual void Execute(IJobExecutionContext context) { int workflowsProcessed = 0; int workflowErrors = 0; int workflowExceptions = 0; var processingErrors = new List <string>(); var exceptionMsgs = new List <string>(); foreach (var workflowId in new WorkflowService(new RockContext()) .GetActive() .Where(wf => (wf.WorkflowType.IsActive == true || !wf.WorkflowType.IsActive.HasValue)) .Select(w => w.Id) .ToList()) { try { // create a new rockContext and service for every workflow to prevent a build-up of Context.ChangeTracker.Entries() var rockContext = new RockContext(); var workflowService = new WorkflowService(rockContext); var workflow = workflowService.Queryable().FirstOrDefault(a => a.Id == workflowId); if (workflow != null) { var workflowType = workflow.WorkflowTypeCache; if (workflowType != null) { try { if (!workflow.LastProcessedDateTime.HasValue || RockDateTime.Now.Subtract(workflow.LastProcessedDateTime.Value).TotalSeconds >= (workflowType.ProcessingIntervalSeconds ?? 0)) { var errorMessages = new List <string>(); var processed = workflowService.Process(workflow, out errorMessages); if (processed) { workflowsProcessed++; } else { workflowErrors++; processingErrors.Add(string.Format("{0} [{1}] - {2} [{3}]: {4}", workflowType.Name, workflowType.Id, workflow.Name, workflow.Id, errorMessages.AsDelimited(", "))); } } } catch (Exception ex) { string workflowDetails = string.Format("{0} [{1}] - {2} [{3}]", workflowType.Name, workflowType.Id, workflow.Name, workflow.Id); exceptionMsgs.Add(workflowDetails + ": " + ex.Message); throw new Exception("Exception occurred processing workflow: " + workflowDetails, ex); } } } } catch (Exception ex) { ExceptionLogService.LogException(ex, null); workflowExceptions++; } } var resultMsg = new StringBuilder(); resultMsg.AppendFormat("{0} workflows processed", workflowsProcessed); if (workflowErrors > 0) { resultMsg.AppendFormat(", {0} workflows reported an error", workflowErrors); } if (workflowExceptions > 0) { resultMsg.AppendFormat(", {0} workflows caused an exception", workflowExceptions); } if (processingErrors.Any()) { resultMsg.Append(Environment.NewLine + processingErrors.AsDelimited(Environment.NewLine)); } if (exceptionMsgs.Any()) { throw new Exception("One or more exceptions occurred processing workflows..." + Environment.NewLine + exceptionMsgs.AsDelimited(Environment.NewLine)); } context.Result = resultMsg.ToString(); }
public IQueryable <NursingHomeRow> GetQuery(RockContext rockContext) { var contextEntity = this.ContextEntity(); var workflowService = new WorkflowService(rockContext); var workflowActivityService = new WorkflowActivityService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personAliasService = new PersonAliasService(rockContext); var definedValueService = new DefinedValueService(rockContext); var entityTypeService = new EntityTypeService(rockContext); var groupMemberService = new GroupMemberService(rockContext); var groupService = new GroupService(rockContext); Guid nursingHomeAdmissionWorkflow = GetAttributeValue("NursingHomeResidentWorkflow").AsGuid(); Guid nursingHomeList = GetAttributeValue("NursingHomeList").AsGuid(); Guid volunteerGroup = GetAttributeValue("VolunteerGroup").AsGuid(); Group groupId = new Group(); List <DefinedValueCache> facilities = DefinedTypeCache.Get(nursingHomeList).DefinedValues; Dictionary <Guid, string> volunteerList = new Dictionary <Guid, string>(); groupId = groupService.GetByGuid(volunteerGroup); var groupMemberEntityTypeId = EntityTypeCache.Get(typeof(GroupMember)).Id; var groupMemberAttributeQry = attributeService.Queryable() .Where(a => a.EntityTypeId == groupMemberEntityTypeId) .Select(a => a.Id); var groupMemberAttributeValueQry = attributeValueService.Queryable() .Where(av => groupMemberAttributeQry.Contains(av.AttributeId)); if (groupId.IsNotNull()) { var groupMemberList = groupMemberService.Queryable() .Where(a => a.GroupId == groupId.Id && a.GroupMemberStatus == GroupMemberStatus.Active) .GroupJoin(groupMemberAttributeValueQry, gm => gm.Id, av => av.EntityId, (gm, av) => new { GroupMember = gm, GroupMemberAttributeValues = av }) .ToList(); var groupMembers = new List <GroupMember>(); foreach (var set in groupMemberList) { var groupMember = set.GroupMember; groupMember.Attributes = set.GroupMemberAttributeValues .ToDictionary(av => av.AttributeKey, av => AttributeCache.Get(av.AttributeId)); groupMember.AttributeValues = set.GroupMemberAttributeValues .ToDictionary(av => av.AttributeKey, av => new AttributeValueCache(av)); groupMembers.Add(groupMember); } foreach (var nursingHome in facilities) { foreach (var groupMember in groupMembers) { if (groupMember.GetAttributeValue("NursingHomes").IsNotNullOrWhiteSpace()) { if (groupMember.GetAttributeValue("NursingHomes").ToLower().Contains(nursingHome.Guid.ToString().ToLower())) { if (volunteerList.ContainsKey(nursingHome.Guid)) { volunteerList[nursingHome.Guid] = volunteerList[nursingHome.Guid] + ", " + groupMember.EntityStringValue; } else { volunteerList.Add(nursingHome.Guid, groupMember.EntityStringValue); } } } } } } int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id; string status = (contextEntity != null ? "Completed" : "Active"); var workflowType = new WorkflowTypeService(rockContext).Get(nursingHomeAdmissionWorkflow); var workflowTypeIdAsString = workflowType.Id.ToString(); var attributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString) .Select(a => a.Id).ToList(); // Look up the activity type for "Visitation" var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault(); var activityAttributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString) .Select(a => a.Id).ToList(); var wfTmpqry = workflowService.Queryable().AsNoTracking() .Where(w => (w.WorkflowType.Guid == nursingHomeAdmissionWorkflow) && (w.Status == "Active" || w.Status == status)); var visitQry = workflowActivityService.Queryable() .Join( attributeValueService.Queryable(), wa => wa.Id, av => av.EntityId.Value, (wa, av) => new { WorkflowActivity = wa, AttributeValue = av }) .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(wa => wa.WorkflowActivity) .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }); if (contextEntity != null) { var personGuid = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList(); var validWorkflowIds = new AttributeValueService(rockContext).Queryable() .Where(av => av.Attribute.Key == "PersonToVisit" && personGuid.Contains(av.Value)).Select(av => av.EntityId); wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id)); visitQry = visitQry.Where(w => validWorkflowIds.Contains(w.WorkflowActivity.WorkflowId)); gReport.Columns[10].Visible = true; } var visits = visitQry.ToList(); var workflows = wfTmpqry.Join( attributeValueService.Queryable(), obj => obj.Id, av => av.EntityId.Value, (obj, av) => new { Workflow = obj, AttributeValue = av }) .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(obj => obj.Workflow) .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }) .ToList(); var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (Workflow, wa) => new { Workflow = Workflow, WorkflowActivities = wa }) .Select(obj => new { Workflow = obj.Workflow.Workflow, AttributeValues = obj.Workflow.AttributeValues, VisitationActivities = obj.WorkflowActivities }).ToList(); if (contextEntity == null) { // Make sure they aren't deceased qry = qry.AsQueryable().Where(w => ! (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ? personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased : false)).ToList(); } var newQry = qry.Select(w => new NursingHomeRow { Id = w.Workflow.Id, Workflow = w.Workflow, NursingHome = new Func <string>(() => { if (w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).Any()) { return(facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).Select(dv => dv.Value).FirstOrDefault()); } return("N/A"); })(), Person = new Func <Person>(() => { AttributeValue personAliasAV = w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").FirstOrDefault(); if (personAliasAV != null) { PersonAlias pa = personAliasService.Get(personAliasAV.Value.AsGuid()); return(pa != null ? pa.Person : new Person()); } return(new Person()); })(), Address = new Func <string>(() => { DefinedValueCache dv = facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).FirstOrDefault(); if (dv != null) { return(dv.AttributeValues["Qualifier1"].ValueFormatted + " " + dv.AttributeValues["Qualifier2"].ValueFormatted + " " + dv.AttributeValues["Qualifier3"].ValueFormatted + ", " + dv.AttributeValues["Qualifier4"].ValueFormatted); } return(""); })(), PastoralMinister = new Func <string>(() => { DefinedValueCache dv = facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).FirstOrDefault(); if (dv != null && (dv.AttributeValues.ContainsKey("PastoralMinister") || dv.AttributeValues.ContainsKey("Qualifier6"))) { return(dv.AttributeValues.ContainsKey("PastoralMinister") ? dv.AttributeValues["PastoralMinister"].ValueFormatted : dv.AttributeValues["Qualifier6"].ValueFormatted); } return(""); })(), Volunteers = new Func <string>(() => { String vList = ""; if (volunteerList.TryGetValue(w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid(), out vList)) { return(vList); } else { return(""); } })(), Room = w.AttributeValues.Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(), AdmitDate = w.AttributeValues.Where(av => av.AttributeKey == "AdmitDate").Select(av => av.ValueAsDateTime).FirstOrDefault(), Description = w.AttributeValues.Where(av => av.AttributeKey == "VisitationRequestDescription").Select(av => av.ValueFormatted).FirstOrDefault(), Visits = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(), LastVisitor = new Func <string>(() => { var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault(); if (visitor != null) { return(visitor.ValueFormatted); } return("N/A"); })(), LastVisitDate = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), DischargeDate = w.AttributeValues.Where(av => av.AttributeKey == "DischargeDate").Select(av => av.ValueFormatted).FirstOrDefault(), Status = w.Workflow.Status, Communion = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(), Actions = "" }).ToList().AsQueryable().OrderBy(p => p.NursingHome).ThenBy(p => p.Person.FullName); return(newQry); }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The workflow action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages) { errorMessages = new List <string>(); var actionType = action.ActionTypeCache; if (!action.LastProcessedDateTime.HasValue && actionType != null && actionType.WorkflowForm != null && actionType.WorkflowForm.NotificationSystemEmailId.HasValue) { if (action.Activity != null && (action.Activity.AssignedPersonAliasId.HasValue || action.Activity.AssignedGroupId.HasValue)) { var recipients = new List <RockMessageRecipient>(); var workflowMergeFields = GetMergeFields(action); if (action.Activity.AssignedPersonAliasId.HasValue) { var person = new PersonAliasService(rockContext).Queryable() .Where(a => a.Id == action.Activity.AssignedPersonAliasId.Value) .Select(a => a.Person) .FirstOrDefault(); if (person != null && !string.IsNullOrWhiteSpace(person.Email)) { recipients.Add(new RockEmailMessageRecipient(person, CombinePersonMergeFields(person, workflowMergeFields))); action.AddLogEntry(string.Format("Form notification sent to '{0}'", person.FullName)); } } if (action.Activity.AssignedGroupId.HasValue) { var personList = new GroupMemberService(rockContext).GetByGroupId(action.Activity.AssignedGroupId.Value) .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active && m.Person.Email != "") .Select(m => m.Person) .ToList(); foreach (var person in personList) { recipients.Add(new RockEmailMessageRecipient(person, CombinePersonMergeFields(person, workflowMergeFields))); action.AddLogEntry(string.Format("Form notification sent to '{0}'", person.FullName)); } } if (recipients.Count > 0) { // The email may need to reference activity Id, so we need to save here. WorkflowService workflowService = new WorkflowService(rockContext); workflowService.PersistImmediately(action); var systemEmail = new SystemEmailService(rockContext).Get(action.ActionTypeCache.WorkflowForm.NotificationSystemEmailId.Value); if (systemEmail != null) { var emailMessage = new RockEmailMessage(systemEmail); emailMessage.SetRecipients(recipients); emailMessage.CreateCommunicationRecord = false; emailMessage.AppRoot = GlobalAttributesCache.Get().GetValue("InternalApplicationRoot") ?? string.Empty; emailMessage.Send(); } else { action.AddLogEntry("Could not find the selected notification system email", true); } } else { action.AddLogEntry("Could not send form notification due to no assigned person or group member not having email address", true); } } else { action.AddLogEntry("Could not send form notification due to no assigned person or group", true); } } return(false); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); var service = new WorkflowService(rockContext); ParseControls(rockContext, true); Workflow dbWorkflow = null; if (Workflow != null) { dbWorkflow = service.Get(Workflow.Id); if (dbWorkflow != null) { if (!dbWorkflow.CompletedDateTime.HasValue && Workflow.CompletedDateTime.HasValue) { dbWorkflow.AddLogEntry("Workflow Manually Completed."); dbWorkflow.CompletedDateTime = Workflow.CompletedDateTime; } else if (dbWorkflow.CompletedDateTime.HasValue && !Workflow.CompletedDateTime.HasValue) { dbWorkflow.AddLogEntry("Workflow Manually Re-Activated."); dbWorkflow.CompletedDateTime = null; } if (dbWorkflow.Name.Trim() != Workflow.Name.Trim()) { dbWorkflow.AddLogEntry(string.Format("Workflow name manually changed from '{0}' to '{0}'.", dbWorkflow.Name, tbName.Text)); dbWorkflow.Name = Workflow.Name; } if (dbWorkflow.Status.Trim() != Workflow.Status.Trim()) { dbWorkflow.AddLogEntry(string.Format("Workflow status manually changed from '{0}' to '{0}'.", dbWorkflow.Status, tbStatus.Text)); dbWorkflow.Status = Workflow.Status; } if (!dbWorkflow.InitiatorPersonAliasId.Equals(Workflow.InitiatorPersonAliasId)) { dbWorkflow.AddLogEntry(string.Format("Workflow status manually changed from '{0}' to '{0}'.", dbWorkflow.InitiatorPersonAlias != null ? dbWorkflow.InitiatorPersonAlias.Person.FullName : "", Workflow.InitiatorPersonAlias != null ? Workflow.InitiatorPersonAlias.Person.FullName : "")); dbWorkflow.InitiatorPersonAlias = Workflow.InitiatorPersonAlias; dbWorkflow.InitiatorPersonAliasId = Workflow.InitiatorPersonAliasId; } if (!Page.IsValid || !dbWorkflow.IsValid) { return; } foreach (var activity in Workflow.Activities) { if (!activity.IsValid) { return; } foreach (var action in activity.Actions) { if (!action.IsValid) { return; } } } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); dbWorkflow.LoadAttributes(rockContext); foreach (var attributeValue in Workflow.AttributeValues) { dbWorkflow.SetAttributeValue(attributeValue.Key, Workflow.GetAttributeValue(attributeValue.Key)); } dbWorkflow.SaveAttributeValues(rockContext); WorkflowActivityService workflowActivityService = new WorkflowActivityService(rockContext); WorkflowActionService workflowActionService = new WorkflowActionService(rockContext); var activitiesInUi = new List <Guid>(); var actionsInUI = new List <Guid>(); foreach (var activity in Workflow.Activities) { activitiesInUi.Add(activity.Guid); foreach (var action in activity.Actions) { actionsInUI.Add(action.Guid); } } // delete WorkflowActions that were removed in the UI foreach (var action in workflowActionService.Queryable() .Where(a => a.Activity.WorkflowId.Equals(dbWorkflow.Id) && !actionsInUI.Contains(a.Guid))) { workflowActionService.Delete(action); } // delete WorkflowActivities that aren't assigned in the UI anymore foreach (var activity in workflowActivityService.Queryable() .Where(a => a.WorkflowId.Equals(dbWorkflow.Id) && !activitiesInUi.Contains(a.Guid))) { workflowActivityService.Delete(activity); } rockContext.SaveChanges(); // add or update WorkflowActivities(and Actions) that are assigned in the UI foreach (var editorWorkflowActivity in Workflow.Activities) { // Add or Update the activity type WorkflowActivity workflowActivity = dbWorkflow.Activities.FirstOrDefault(a => a.Guid.Equals(editorWorkflowActivity.Guid)); if (workflowActivity == null) { workflowActivity = new WorkflowActivity(); workflowActivity.ActivityTypeId = editorWorkflowActivity.ActivityTypeId; dbWorkflow.Activities.Add(workflowActivity); } workflowActivity.AssignedPersonAliasId = editorWorkflowActivity.AssignedPersonAliasId; workflowActivity.AssignedGroupId = editorWorkflowActivity.AssignedGroupId; workflowActivity.ActivatedDateTime = editorWorkflowActivity.ActivatedDateTime; workflowActivity.LastProcessedDateTime = editorWorkflowActivity.LastProcessedDateTime; if (!workflowActivity.CompletedDateTime.HasValue && editorWorkflowActivity.CompletedDateTime.HasValue) { workflowActivity.AddLogEntry("Activity Manually Completed."); workflowActivity.CompletedDateTime = RockDateTime.Now; } if (workflowActivity.CompletedDateTime.HasValue && !editorWorkflowActivity.CompletedDateTime.HasValue) { workflowActivity.AddLogEntry("Activity Manually Re-Activated."); workflowActivity.CompletedDateTime = null; } // Save Activity Type rockContext.SaveChanges(); // Save ActivityType Attributes workflowActivity.LoadAttributes(rockContext); foreach (var attributeValue in editorWorkflowActivity.AttributeValues) { workflowActivity.SetAttributeValue(attributeValue.Key, editorWorkflowActivity.GetAttributeValue(attributeValue.Key)); } workflowActivity.SaveAttributeValues(rockContext); foreach (var editorWorkflowAction in editorWorkflowActivity.Actions) { WorkflowAction workflowAction = workflowActivity.Actions.FirstOrDefault(a => a.Guid.Equals(editorWorkflowAction.Guid)); if (workflowAction == null) { // New action workflowAction = new WorkflowAction(); workflowAction.ActionTypeId = editorWorkflowAction.ActionTypeId; workflowActivity.Actions.Add(workflowAction); } workflowAction.LastProcessedDateTime = editorWorkflowAction.LastProcessedDateTime; workflowAction.FormAction = editorWorkflowAction.FormAction; if (!workflowAction.CompletedDateTime.HasValue && editorWorkflowAction.CompletedDateTime.HasValue) { workflowAction.AddLogEntry("Action Manually Completed."); workflowAction.CompletedDateTime = RockDateTime.Now; } if (workflowAction.CompletedDateTime.HasValue && !editorWorkflowAction.CompletedDateTime.HasValue) { workflowAction.AddLogEntry("Action Manually Re-Activated."); workflowAction.CompletedDateTime = null; } } // Save action updates rockContext.SaveChanges(); } }); } Workflow = service .Queryable("WorkflowType,Activities.ActivityType,Activities.Actions.ActionType") .FirstOrDefault(w => w.Id == Workflow.Id); var errorMessages = new List <string>(); service.Process(Workflow, out errorMessages); } ShowReadonlyDetails(); }
protected virtual WorkflowServiceHost CreateWorkflowServiceHost(WorkflowService service, Uri[] baseAddresses) { return(new WorkflowServiceHost(service, baseAddresses)); }
// if the 1st parameter "supportedVersionXamlxfilePath" is null, we fall back to the primary generated type internal static ICompiledExpressionRoot GetExpressionRoot(string supportedVersionXamlxfilePath, WorkflowService service, string virtualPath) { Assembly compiledAssembly = BuildManager.GetCompiledAssembly(virtualPath); if (compiledAssembly == null) { return null; } Type generatedType; if (supportedVersionXamlxfilePath != null) { string fullTypeNameToSearch = GeneratedNamespace + "." + WorkflowServiceHostFactory.GetSupportedVersionGeneratedTypeName(supportedVersionXamlxfilePath) + ExpressionRootFactorySuffix; generatedType = compiledAssembly.GetType(fullTypeNameToSearch); } else { generatedType = BuildManager.GetCompiledType(virtualPath); } Type workflowServiceType = typeof(WorkflowService); if (generatedType != workflowServiceType && workflowServiceType.IsAssignableFrom(generatedType)) { MethodInfo createExpressionRootMethod = generatedType.GetMethod(CreateExpressionRootMethodName, BindingFlags.Public | BindingFlags.Static); if (createExpressionRootMethod != null) { return (ICompiledExpressionRoot)createExpressionRootMethod.Invoke(null, new object[] { service.Body }); } } return null; }
public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses) { WorkflowServiceHost host = null; Stream stream; string str2; if (string.IsNullOrEmpty(constructorString)) { throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.WorkflowServiceHostFactoryConstructorStringNotProvided)); } if (baseAddresses == null) { throw System.ServiceModel.Activation.FxTrace.Exception.ArgumentNull("baseAddresses"); } if (baseAddresses.Length == 0) { throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.BaseAddressesNotProvided)); } if (!HostingEnvironment.IsHosted) { throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.Hosting_ProcessNotExecutingUnderHostedContext("WorkflowServiceHostFactory.CreateServiceHost"))); } string virtualPath = VirtualPathUtility.Combine(AspNetEnvironment.Current.XamlFileBaseLocation, constructorString); if (this.GetServiceFileStreamOrCompiledCustomString(virtualPath, baseAddresses, out stream, out str2)) { object obj2; using (stream) { BuildManager.GetReferencedAssemblies(); XamlXmlReaderSettings settings = new XamlXmlReaderSettings { ProvideLineInfo = true }; XamlReader xamlReader = ActivityXamlServices.CreateReader(new XamlXmlReader(XmlReader.Create(stream), settings)); if (System.ServiceModel.Activation.TD.XamlServicesLoadStartIsEnabled()) { System.ServiceModel.Activation.TD.XamlServicesLoadStart(); } obj2 = XamlServices.Load(xamlReader); if (System.ServiceModel.Activation.TD.XamlServicesLoadStopIsEnabled()) { System.ServiceModel.Activation.TD.XamlServicesLoadStop(); } } WorkflowService service = null; if (obj2 is Activity) { service = new WorkflowService { Body = (Activity)obj2 }; } else if (obj2 is WorkflowService) { service = (WorkflowService)obj2; } if (service != null) { if (service.Name == null) { string fileName = VirtualPathUtility.GetFileName(virtualPath); string namespaceName = string.Format(CultureInfo.InvariantCulture, "/{0}{1}", new object[] { ServiceHostingEnvironment.SiteName, VirtualPathUtility.GetDirectory(ServiceHostingEnvironment.FullVirtualPath) }); service.Name = XName.Get(XmlConvert.EncodeLocalName(fileName), namespaceName); if ((service.ConfigurationName == null) && (service.Body != null)) { service.ConfigurationName = XmlConvert.EncodeLocalName(service.Body.DisplayName); } } host = this.CreateWorkflowServiceHost(service, baseAddresses); } } else { Type typeFromAssembliesInCurrentDomain = this.GetTypeFromAssembliesInCurrentDomain(constructorString); if (null == typeFromAssembliesInCurrentDomain) { typeFromAssembliesInCurrentDomain = this.GetTypeFromCompileCustomString(str2, constructorString); } if (null == typeFromAssembliesInCurrentDomain) { BuildManager.GetReferencedAssemblies(); typeFromAssembliesInCurrentDomain = this.GetTypeFromAssembliesInCurrentDomain(constructorString); } if (null != typeFromAssembliesInCurrentDomain) { if (!TypeHelper.AreTypesCompatible(typeFromAssembliesInCurrentDomain, typeof(Activity))) { throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.TypeNotActivity(typeFromAssembliesInCurrentDomain.FullName))); } Activity activity = (Activity)Activator.CreateInstance(typeFromAssembliesInCurrentDomain); host = this.CreateWorkflowServiceHost(activity, baseAddresses); } } if (host == null) { throw System.ServiceModel.Activation.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activation.SR.CannotResolveConstructorStringToWorkflowType(constructorString))); } ((IDurableInstancingOptions)host.DurableInstancingOptions).SetScopeName(XName.Get(XmlConvert.EncodeLocalName(VirtualPathUtility.GetFileName(ServiceHostingEnvironment.FullVirtualPath)), string.Format(CultureInfo.InvariantCulture, "/{0}{1}", new object[] { ServiceHostingEnvironment.SiteName, VirtualPathUtility.GetDirectory(ServiceHostingEnvironment.FullVirtualPath) }))); return(host); }
void GenerateSource(bool isSupportedVersion, string filePath, AssemblyBuilder assemblyBuilder, WorkflowService workflowService, out string codeFileName, out bool generatedSource, out string activityName) { // Get unique file and type name for the workflowservice codeFileName = assemblyBuilder.GetTempFilePhysicalPath(assemblyBuilder.CodeDomProvider.FileExtension); if (isSupportedVersion) { activityName = WorkflowServiceHostFactory.GetSupportedVersionGeneratedTypeName(filePath); } else { activityName = workflowService.Name.LocalName + "_" + Guid.NewGuid().ToString().Replace("-", "_"); } TextExpressionCompilerSettings settings = new TextExpressionCompilerSettings { Activity = workflowService.Body, ActivityName = activityName, ActivityNamespace = GeneratedNamespace, Language = CodeDomProvider.GetLanguageFromExtension(assemblyBuilder.CodeDomProvider.FileExtension), GenerateAsPartialClass = false, AlwaysGenerateSource = false, ForImplementation = false }; TextExpressionCompiler compiler = new TextExpressionCompiler(settings); generatedSource = false; using (StreamWriter fileStream = new StreamWriter(codeFileName)) { try { generatedSource = compiler.GenerateSource(fileStream); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } throw FxTrace.Exception.AsError(new HttpCompileException(SR.XamlBuildProviderExtensionException(ex.Message))); } } }
static WorkflowService GetService() { Variable <Customer> customer = new Variable <Customer>(); Variable <Order> order = new Variable <Order>(); Variable <string> drug = new Variable <string>(); Variable <double> adjustedCost = new Variable <double>(); Variable <int> percentagePaidByInsurance = new Variable <int>(); Variable <CorrelationHandle> customerHandle = new Variable <CorrelationHandle>(); Variable <CorrelationHandle> orderHandle = new Variable <CorrelationHandle>(); XPathMessageContext pathContext = new XPathMessageContext(); pathContext.AddNamespace("psns", Constants.PharmacyServiceNamespace); MessageQuerySet GetOrderQuerySet = new MessageQuerySet { { "OrderID", new XPathMessageQuery("//psns:Order/psns:OrderID", pathContext) } }; MessageQuerySet GetOrderIDQuerySet = new MessageQuerySet { { "OrderID", new XPathMessageQuery("//ser:guid", pathContext) } }; MessageQuerySet customerQuerySet = new MessageQuerySet { { "CustomerID", new XPathMessageQuery("//psns:GetBaseCost/psns:Customer/psns:CustomerID", pathContext) } }; MessageQuerySet customerIDQuerySet = new MessageQuerySet { { "CustomerID", new XPathMessageQuery("//ser:guid", pathContext) } }; // This will use implicit correlation within the workflow using the WorkflowServiceHost's default CorrelationHandle Receive prescriptionRequest = new Receive { DisplayName = "Request Perscription", OperationName = "GetBaseCost", ServiceContractName = Constants.PharmacyServiceContractName, CanCreateInstance = true, //CorrelatesWith = customerHandle, -- add this line for explicit correlation CorrelatesOn = customerQuerySet, Content = new ReceiveParametersContent { Parameters = { { "Customer", new OutArgument <Customer>(customer) }, { "Drug", new OutArgument <string>(drug) }, } } }; // This will use implicit correlation within the workflow using the WorkflowServiceHost's default CorrelationHandle Receive GetInsurancePaymentPercentageRequest = new Receive { DisplayName = "Get Insurance Coverage", ServiceContractName = Constants.PharmacyServiceContractName, OperationName = "GetInsurancePaymentPercentage", CanCreateInstance = true, //CorrelatesWith = customerHandle, -- add this line for explicit correlation CorrelatesOn = customerIDQuerySet, Content = ReceiveContent.Create(new OutArgument <Guid>()) }; // This will explicitly correlate with the SendReply action after the prescriptionRequest using the OrderID (stored in the orderHandle) Receive GetAdjustedCostRequest = new Receive { DisplayName = "Get Adjusted Cost", OperationName = "GetAdjustedCost", ServiceContractName = Constants.PharmacyServiceContractName, CanCreateInstance = true, CorrelatesOn = GetOrderIDQuerySet, CorrelatesWith = orderHandle, Content = ReceiveContent.Create(new OutArgument <Guid>()) }; Activity PrescriptonWorkflow = new Sequence() { Variables = { customer, order, drug, percentagePaidByInsurance, adjustedCost, customerHandle, orderHandle }, Activities = { new WriteLine { Text = "Beginning Workflow" }, new Parallel { Branches = { new Sequence { Activities = { GetInsurancePaymentPercentageRequest, new Assign <int> { To = new OutArgument <int>((e) => percentagePaidByInsurance.Get(e)), Value = new InArgument <int>((e) => new Random().Next(0, 100)) }, new SendReply { DisplayName = "Return Percentage", Request = GetInsurancePaymentPercentageRequest, Content = SendContent.Create(new InArgument <int>((e) => percentagePaidByInsurance.Get(e))) } } }, new Sequence { Activities = { prescriptionRequest, new WriteLine { Text = new InArgument <string>(env => (string.Format("{0}, {1}\t{2}",customer.Get(env).LastName, customer.Get(env).FirstName, customer.Get(env).CustomerID.ToString()))) }, new Assign <Order> { To = new OutArgument <Order>(order), Value = new InArgument <Order>((e) => new Order() { CustomerID = customer.Get(e).CustomerID,Drug = drug.Get(e), OrderID = Guid.NewGuid() }) }, new WriteLine { Text = new InArgument <string>(env => (string.Format("OrderID: {0}",order.Get(env).OrderID.ToString()))) }, new Assign <int> { To = new OutArgument <int>((e) => order.Get(e).Cost), Value = new InArgument <int>((e) => new Random().Next(20, 50)) }, new SendReply { DisplayName = "Send Adjusted Cost", Request = prescriptionRequest, // Initialize the orderHandle using the MessageQuerySet to correlate with the final GetAdjustedCost request CorrelationInitializers = { new QueryCorrelationInitializer { CorrelationHandle = orderHandle, MessageQuerySet = GetOrderQuerySet } }, Content = SendContent.Create(new InArgument <Order>((e) => order.Get(e))) } } } } }, new Assign <double> { To = new OutArgument <double>((e) => adjustedCost.Get(e)), Value = new InArgument <double>((e) => order.Get(e).Cost *(100 - percentagePaidByInsurance.Get(e)) * .01) }, new WriteLine { Text = new InArgument <string>(env => (string.Format("Base Cost: ${0}", order.Get(env).Cost.ToString()))) }, new WriteLine { Text = new InArgument <string>(env => (string.Format("Insurance Coverage: {0}%", percentagePaidByInsurance.Get(env).ToString()))) }, new WriteLine { Text = new InArgument <string>(env => (string.Format("Adjusted Cost: ${0}", decimal.Round(Convert.ToDecimal(adjustedCost.Get(env)), 2)))) }, GetAdjustedCostRequest, new SendReply { Request = GetAdjustedCostRequest, Content = SendContent.Create(new InArgument <double>((e) => adjustedCost.Get(e))) }, new WriteLine { Text = "Workflow Completed" } } }; WorkflowService service = new WorkflowService { Name = "PharmacyService", Body = PrescriptonWorkflow, ConfigurationName = "PharmacyService" }; return(service); }
private static WorkflowService createAPI() { try { string url = (String)ConfigurationManager.AppSettings["ServerUrl"]; string admin = (String)ConfigurationManager.AppSettings["APAdmin"]; string pass = (String)ConfigurationManager.AppSettings["APPWD"]; string domain = (String)ConfigurationManager.AppSettings["APDomain"]; WorkflowService api = new WorkflowService(url); System.Net.ICredentials credentials = new System.Net.NetworkCredential(admin, pass, domain); api.Credentials = credentials; api.CheckAuthenticated(); api.SetClientAppName("ERS"); return api; } catch (Exception e) { throw new Exception(errorMSGPrefix + e.Message, e); } return null; }
private WFAutomaticWorkItem[] GetAutomaticWorkItems(WorkflowService api, string aiID) { // manual work items WFAny any = new WFAny(); any.Type = WFTypeCode._STRING; any.Value = aiID; WFQueryExpr expr = new WFQueryExpr(); expr.ColumnName = "ACTIVITY_INST_ID"; expr.Operator = SQLExpr.EQ; expr.Any = any; expr.IsValue = true; WFAutomaticWorkItem[] wks = api.QueryProcedureList(expr); if (wks == null || wks.Length == 0) return null; SortedList sl = new SortedList(); string procedure = null; string prefix = WFConstants.BUILT_IN_PROCEDURE; foreach (WFAutomaticWorkItem wk in wks) { procedure = wk.ProcedureInfo; if (!procedure.StartsWith(prefix)) continue; procedure = procedure.Remove(0, prefix.Length + 1); if (!procedure.StartsWith("SubProcess")) continue; sl.Add((int.MaxValue - wk.Session) + UUID.GetID(), wk); } wks = new WFAutomaticWorkItem[sl.Count]; if (sl.Count > 0) sl.Values.CopyTo(wks, 0); return wks; }