// If your activity returns a value, derive from CodeActivity<TResult> // and return the value from the Execute method. protected override void Execute(CodeActivityContext context) { // Obtain the runtime value of the Text input argument string text = context.GetValue(Text); context.SetValue(Output, $"{text} workflow"); }
/// <summary> /// When implemented in a derived class, performs the execution of the activity. /// </summary> /// <param name="context">The execution context under which the activity executes.</param> protected override void Execute(CodeActivityContext context) { var data = this.Data.Get(context); ValidateData(data); var index = this.EmailTemplateIndex.Get(context); ValidateIndex(data, index); // Get the template cache extension var templateCache = context.GetExtension<ITemplateCache>(); var encoding = this.Encoding.Get(context); var emailTemplate = encoding != null ? templateCache.Get(data.EmailTemplates.ElementAt(index), encoding) : templateCache.Get(data.EmailTemplates.ElementAt(index)); ValidateEmailTemplate(emailTemplate); var args = new object[5]; args[InstanceIdIndex] = context.WorkflowInstanceId.ToString(); args[VerificationUrlIndex] = data.VerificationUrl; args[CancelUrlIndex] = data.CancelUrl; args[StylesUrlIndex] = data.StylesUrl; args[TemplateIndex] = this.EmailTemplateIndex.Get(context).ToString(CultureInfo.InvariantCulture); var body = data.BodyArguments != null ? string.Format(emailTemplate, (object[])data.BodyArguments) : string.Format(emailTemplate, new object[1]); this.MessageBody.Set(context, ReplaceTokens(body, args)); }
protected override void Execute(CodeActivityContext context) { object[] inObjects; if (this.parameters == null || this.parameters.Count == 0) { inObjects = Constants.EmptyArray; } else { inObjects = new object[this.parameters.Count]; for (int i = 0; i < this.parameters.Count; i++) { Fx.Assert(this.parameters[i] != null, "Parameter should not be null"); inObjects[i] = this.parameters[i].Get(context); } } // Formatter is cached since it is fixed for each definition of Send if (this.Formatter == null) { OperationDescription operation = ContractInferenceHelper.CreateOneWayOperationDescription(this.Send); this.Formatter = ClientOperationFormatterProvider.GetFormatterFromRuntime(operation); this.Send.OperationDescription = operation; } // Send.ChannelCacheEnabled must be set before we call this.MessageVersion // because this.MessageVersion will cache description and description resolution depends on the value of ChannelCacheEnabled this.Send.InitializeChannelCacheEnabledSetting(context); // MessageVersion is cached for perf reasons since it is fixed for each definition of Send Message outMessage = this.Formatter.SerializeRequest(this.MessageVersion, inObjects); this.Message.Set(context, outMessage); }
/// <summary> /// Processes the conversion of the version number /// </summary> /// <param name="context"></param> protected override void Execute(CodeActivityContext context) { // Get the values passed in var versionPattern = context.GetValue(VersionPattern); var buildNumber = context.GetValue(BuildNumber); var buildNumberPrefix = context.GetValue(BuildNumberPrefix); var version = new StringBuilder(); var addDot = false; // Validate the version pattern if (string.IsNullOrEmpty(versionPattern)) { throw new ArgumentException("VersionPattern must contain the versioning pattern."); } var versionPatternArray = versionPattern.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries); // Go through each pattern and convert it foreach (var conversionItem in versionPatternArray) { if (addDot) { version.Append("."); } version.Append(VersioningHelper.ReplacePatternWithValue(conversionItem, buildNumber, buildNumberPrefix, DateTime.Now)); addDot = true; } // Return the value back to the workflow context.SetValue(ConvertedVersionNumber, version.ToString()); }
protected override void Execute(CodeActivityContext context) { try { Guid FlowInstranceID = context.WorkflowInstanceId; DebugStatus debug = new DebugStatus(); if (debug.status == 0) { string result = s.Get(context); if (result == "true") { //TODO Change the step. //BLL.Document.DocumentEndStep(FlowInstranceID, "1"); } else { //BLL.Document.DocumentEndStep(FlowInstranceID, "2"); } } } catch//(Exception e) { //执行出错 } }
protected override void Execute(CodeActivityContext context) { usecarapplyform Applyinfo = new usecarapplyform(); Applyinfo.ApplyUserName = request.Get(context).ApplyUserName; Applyinfo.usecartype = new YunShanOA.BusinessLogic.UseCar.UseTypeManager().GetUsecarType(request.Get(context).usecartypeID); Applyinfo.WFID = context.WorkflowInstanceId; List<YunShanOA.Model.UseCarModel.usecaranduser> results = new List<usecaranduser>(); foreach (usecaranduser user in request.Get(context).Usecaranduser) { usecaranduser usecaranduser = new usecaranduser(); usecaranduser.Name = user.Name; usecaranduser.Email = user.Email; results.Add(usecaranduser); } Applyinfo.Usecaranduser = results; Applyinfo.BeginTime = request.Get(context).BeginTime; Applyinfo.EndTime = request.Get(context).EndTime; Applyinfo.StartDestination = request.Get(context).StartDestination; Applyinfo.EndDestination = request.Get(context).EndDestination; Applyinfo.ApplyStatus = 2; Applyinfo.ApplyReason = request.Get(context).ApplyReason; Applyinfo.Comment = request.Get(context).Comment; BusinessLogic.UseCar.UsecarApplyformManager ApplyformManager = new UsecarApplyformManager(); int i = ApplyformManager.Sava(Applyinfo); List<usecaranduser> s = new List<usecaranduser>(); s = new YunShanOA.BusinessLogic.UseCar.UsecarAndUserManager().GetCarAndUserlistByFormID(Applyinfo.UseCarApplyFormID); Applyinfo.Usecaranduser = s; Applyinfo.UseCarApplyFormID = i; Apply.Set(context, Applyinfo); // 获取 Text 输入参数的运行时值 }
// 如果活动返回值,则从 CodeActivity<TResult> // 派生并从 Execute 方法返回该值。 protected override void Execute(CodeActivityContext context) { // 获取 Text 输入参数的运行时值 ReviewCheck ReviewCheck = ReviewChecks.Get(context); DocumentApply documentApply = inApply.Get(context); if (ReviewCheck.Agree == 1) { if (inApply.Get(context).IsNeed) { documentApply.Status = 4; } else { documentApply.Status = 5; } } else { documentApply.Status = 6; } new YunShanOA.BusinessLogic.DocumentManager.DocumentManager().Save(documentApply); outApply.Set(context, documentApply); }
protected override void Execute(CodeActivityContext context) { var regParticipant = context.GetExtension<RegistrationPeristenceParticipant>(); regParticipant.UserName = this.UserName.Get(context); regParticipant.Email = this.Email.Get(context); }
protected override void Execute(CodeActivityContext executionContext) { //Create the tracing service ITracingService tracingService = executionContext.GetExtension<ITracingService>(); //Create the context IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); Entity entity = null; var inputs = context.InputParameters; if (context.InputParameters.Contains("target")) entity = (Entity)context.InputParameters["target"]; if (entity == null) return; DocLogic logic = new DocLogic(service); LoadDocParametersFactory loadDocParametersFactory = null; var subject = Subject.Get(executionContext); switch (entity.LogicalName) { case "opportunity": loadDocParametersFactory = new OpportunityParametersFactory(service, entity, subject); break; case "new_order": loadDocParametersFactory = new OrderParametersFactory(service, entity, subject); break; default: loadDocParametersFactory = null; break; } logic.Excute(loadDocParametersFactory); }
// If your activity returns a value, derive from CodeActivity<TResult> // and return the value from the Execute method. protected override void Execute(CodeActivityContext context) { PropertyDescriptorCollection propertyDescriptorCol = context.DataContext.GetProperties(); foreach (PropertyDescriptor pd in propertyDescriptorCol) { if (string.Equals(pd.Name, Singleton<Constants>.UniqueInstance.FileVariableName)) { try { NetworkCredential networkCredential = new NetworkCredential(Singleton<Constants>.UniqueInstance.UserName, Singleton<Constants>.UniqueInstance.PassWord, Singleton<Constants>.UniqueInstance.Domain); string sharePath = string.Format(@"\\{0}\c$", Singleton<Constants>.UniqueInstance.MachineName); //Singleton<Constants>.UniqueInstance.GacEssentialsPath.Substring(0, Singleton<Constants>.UniqueInstance.GacEssentialsPath.IndexOf(@"c$\Windows") + @"c$\Windows".Length); using (NetworkConnection nc = new NetworkConnection(sharePath, networkCredential)) { FileItem[] fileItems = (FileItem[])pd.GetValue(context.DataContext); foreach (FileItem fileItem in fileItems) { ReplaceFileHelper.ReplaceFile(fileItem); } } } catch (Exception e) { string msg = string.Format("exception encounterred: {0} when executing replacefilesactivity", e); Singleton<ReportMediator>.UniqueInstance.ReportStatus(msg, LogLevel.Warning); } } } // Obtain the runtime value of the Text input argument string text = context.GetValue(this.Text); }
protected override void Execute(CodeActivityContext context) { bool hire = Hire.Get(context); ApplicantResume resume = Resume.Get(context); string baseURI = WebConfigurationManager.AppSettings["BaseURI"]; if (string.IsNullOrEmpty(baseURI)) throw new InvalidOperationException("No baseURI appSetting found in web.config"); string htmlMailText; if (hire) { htmlMailText = string.Format(ServiceResources.GenericMailTemplate, ServiceResources.HireHeading, string.Format(ServiceResources.OfferText, resume.Name),baseURI); } else { htmlMailText = string.Format(ServiceResources.GenericMailTemplate, ServiceResources.NoHireHeading, string.Format(ServiceResources.NoHireText, resume.Name), baseURI); } SmtpClient smtpClient = new SmtpClient(); MailMessage msg = new MailMessage("*****@*****.**", resume.Email, string.Format(ServiceResources.ApplicationMailSubject), htmlMailText); msg.IsBodyHtml = true; smtpClient.Send(msg); }
protected override void Execute(CodeActivityContext context) { // Open the config file and get the Request Address Configuration config = ConfigurationManager .OpenExeConfiguration(ConfigurationUserLevel.None); AppSettingsSection app = (AppSettingsSection)config.GetSection("appSettings"); // Create a ReservationRequest class and populate // it with the input arguments ReservationRequest r = new ReservationRequest ( Title.Get(context), Author.Get(context), ISBN.Get(context), new Branch { BranchName = app.Settings["Branch Name"].Value, BranchID = new Guid(app.Settings["ID"].Value), Address = app.Settings["Address"].Value }, context.WorkflowInstanceId ); // Store the request in the OutArgument Request.Set(context, r); // Store the address in the OutArgument RequestAddress.Set(context, app.Settings["Request Address"].Value); }
/// <summary> /// The execute. /// </summary> /// <param name="context"> /// The context. /// </param> /// <exception cref="HttpResponseException"> /// There is a matching ETag /// </exception> protected override void Execute(CodeActivityContext context) { if (this.Request.Get(context).Headers.IfMatch.Any(etag => EntityTag.IsMatchingTag(this.ETag.Get(context), etag.Tag))) { throw new HttpResponseException(HttpStatusCode.PreconditionFailed); } }
protected override void DoExecute(CodeActivityContext context) { devlog.Debug(string.Format("Called on '{0}'", ExchangeAppointment)); var myExchangeAppointment = ExchangeAppointment.Get(context); devlog.Debug(string.Format("myExchangeAppointment:'{0}'", myExchangeAppointment)); ExchangeRepository.insertOrUpdate(myExchangeAppointment); }
/// <summary> /// You need to put this activity in a different agent that write the diagnostics log that you want to change. /// </summary> /// <param name="context"></param> protected override void Execute(CodeActivityContext context) { Thread.Sleep(30000); var findAndReplace = context.GetValue(FindAndReplaceStrings); _teamProjectUri = context.GetValue(TeamProjectUri); _buildUri = context.GetValue(BuildUri); var vssCredential = new VssCredentials(true); _fcClient = new FileContainerHttpClient(_teamProjectUri, vssCredential); var containers = _fcClient.QueryContainersAsync(new List<Uri>() { _buildUri }).Result; if (!containers.Any()) return; var agentLogs = GetAgentLogs(containers); if (agentLogs == null) return; using (var handler = new HttpClientHandler() { UseDefaultCredentials = true }) { var reader = DownloadAgentLog(agentLogs, handler); using (var ms = new MemoryStream()) { ReplaceStrings(findAndReplace, reader, ms); var response = UploadDocument(containers, agentLogs, ms); } } }
protected override void Execute(CodeActivityContext context) { Dictionary<string,string> getUserEmail = context.GetValue(UserEmail); //在这里获取下getUserEmail,看看有没有传进来数据 //如果有数据,在这里就可以根据WFID来获取MeetingApplyFormID //如果没有的话,应该是数据在存储的时候丢失了,要另外想办法 }
// If your activity returns a value, derive from CodeActivity<TResult> // and return the value from the Execute method. protected override void Execute(CodeActivityContext context) { // Obtain the runtime value of the Text input argument ItemInfo i = new ItemInfo(); i.ItemCode = context.GetValue<string>(this.ItemCode); switch (i.ItemCode) { case "12345": i.Description = "Widget"; i.Price = (decimal)10.0; break; case "12346": i.Description = "Gadget"; i.Price = (decimal)15.0; break; case "12347": i.Description = "Super Gadget"; i.Price = (decimal)25.0; break; } context.SetValue(this.Item, i); }
protected override void Execute(CodeActivityContext context) { // string text = context.GetValue(this.参与人员.姓名); //System.Console.WriteLine(text); }
internal void ExecuteBase(CodeActivityContext executionContext, XrmWorkflowActivityRegistration xrmWorkflowActivityRegistration) { try { Activity = xrmWorkflowActivityRegistration; ExecutionContext = executionContext; TracingService.Trace( "Entered Workflow {0}\nActivity Instance Id: {1}\nWorkflow Instance Id: {2}\nCorrelation Id: {3}\nInitiating User: {4}", GetType().Name, ExecutionContext.ActivityInstanceId, ExecutionContext.WorkflowInstanceId, Context.CorrelationId, Context.InitiatingUserId); Execute(); } catch (InvalidPluginExecutionException ex) { LogController.LogLiteral(ex.XrmDisplayString()); throw; } catch (Exception ex) { LogController.LogLiteral(ex.XrmDisplayString()); throw new InvalidPluginExecutionException(ex.Message, ex); } }
/// <summary> /// NOTE: When you add this activity to a workflow, you must set the following properties: /// /// URL - manually add the URL to which you will be posting data. For example: http://myserver.com/ReceivePostURL.aspx /// See this sample's companion file 'ReceivePostURL.aspx' for an example of how the receiving page might look. /// /// AccountName - populate this property with the Account's 'name' attribute. /// /// AccountNum - populate this property with the Account's 'account number' attribute. /// </summary> protected override void Execute(CodeActivityContext executionContext) { IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); // Build data that will be posted to a URL string postData = "Name=" + this.AccountName.Get(executionContext) + "&AccountNum=" + this.AccountNum.Get(executionContext); // Encode the data ASCIIEncoding encoding = new ASCIIEncoding(); byte[] encodedPostData = encoding.GetBytes(postData); // Create a request object for posting our data to a URL Uri uri = new Uri(this.URL.Get(executionContext)); HttpWebRequest urlRequest = (HttpWebRequest)WebRequest.Create(uri); urlRequest.Method = "POST"; urlRequest.ContentLength = encodedPostData.Length; urlRequest.ContentType = "application/x-www-form-urlencoded"; // Add the encoded data to the request using (Stream formWriter = urlRequest.GetRequestStream()) { formWriter.Write(encodedPostData, 0, encodedPostData.Length); } // Post the data to the URL HttpWebResponse urlResponse = (HttpWebResponse)urlRequest.GetResponse(); }
protected override void Execute(CodeActivityContext context) { Claim claim = Entity.Get<Claim>(context); IsValid.Set(context, true); if (String.IsNullOrEmpty(claim.DateCreated.ToString())) IsValid.Set(context, false); DateTime date = new DateTime(); if (!DateTime.TryParse(claim.DateCreated.ToString(), out date)) IsValid.Set(context, false); if (String.IsNullOrEmpty(claim.Description)) IsValid.Set(context, false); if (String.IsNullOrEmpty(claim.Accidents.ContactPhone)) IsValid.Set(context, false); if (!IsValidNumber(claim.Accidents.ContactPhone)) IsValid.Set(context, false); if (!IsValidCoordinate(claim.Accidents.Latitude.ToString())) IsValid.Set(context, false); if (!IsValidCoordinate(claim.Accidents.Longitude.ToString())) IsValid.Set(context, false); }
protected override void Execute(CodeActivityContext context) { string scriptPath = ScriptPath.Get(context); string scriptContents = null; if (!(Path.IsPathRooted(scriptPath))) scriptPath = Path.Combine(Directory.GetCurrentDirectory(), scriptPath); if (File.Exists(scriptPath)) scriptContents = File.ReadAllText(scriptPath); else throw new FileNotFoundException(String.Format("Powershell script file {0} does not exist.", scriptPath)); Runspace runSpace = RunspaceFactory.CreateRunspace(); runSpace.Open(); RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runSpace); Pipeline pipeLine = runSpace.CreatePipeline(); pipeLine.Commands.AddScript(scriptContents); pipeLine.Commands.Add("Out-String"); Collection<PSObject> returnObjects = pipeLine.Invoke(); runSpace.Close(); }
protected override void Execute(CodeActivityContext context) { TrackMessage(context, "Starting SVN action"); string destinationPath = context.GetValue(this.DestinationPath); string svnPath = context.GetValue(this.SvnPath); string svnToolPath = context.GetValue(this.SvnToolPath); string svnCommandArgs = context.GetValue(this.SvnCommandArgs); SvnCredentials svnCredentials = context.GetValue(this.SvnCredentials); string svnCommand = Regex.Replace(svnCommandArgs, "{uri}", svnPath); svnCommand = Regex.Replace(svnCommand, "{destination}", destinationPath); svnCommand = Regex.Replace(svnCommand, "{username}", svnCredentials.Username); TrackMessage(context, "svn command: " + svnCommand); // Never reveal the password! svnCommand = Regex.Replace(svnCommand, "{password}", svnCredentials.Password); if (File.Exists(svnToolPath)) { var process = Process.Start(svnToolPath, svnCommand); if (process != null) { process.WaitForExit(); process.Close(); } } TrackMessage(context, "End SVN action"); }
/// <summary> /// Executes the workflow activity. /// </summary> /// <param name="executionContext">The execution context.</param> protected override void Execute(CodeActivityContext executionContext) { // Create the tracing service ITracingService tracingService = executionContext.GetExtension<ITracingService>(); if (tracingService == null) { throw new InvalidPluginExecutionException("Failed to retrieve tracing service."); } tracingService.Trace("Entered " + _processName + ".Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}", executionContext.ActivityInstanceId, executionContext.WorkflowInstanceId); // Create the context IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>(); if (context == null) { throw new InvalidPluginExecutionException("Failed to retrieve workflow context."); } tracingService.Trace(_processName + ".Execute(), Correlation Id: {0}, Initiating User: {1}", context.CorrelationId, context.InitiatingUserId); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); try { //do the regex match Match match = Regex.Match(StringToValidate.Get(executionContext), MatchPattern.Get(executionContext), RegexOptions.IgnoreCase); //did we match anything? if (match.Success) { Valid.Set(executionContext, 1); } else { Valid.Set(executionContext, 0); } } catch (FaultException<OrganizationServiceFault> e) { tracingService.Trace("Exception: {0}", e.ToString()); // Handle the exception. throw; } catch (Exception e) { tracingService.Trace("Exception: {0}", e.ToString()); throw; } tracingService.Trace("Exiting " + _processName + ".Execute(), Correlation Id: {0}", context.CorrelationId); }
internal Context(IGraywulfActivity activity, CodeActivityContext activityContext) { InitializeMembers(); // Get job info from the scheduler var scheduler = activityContext.GetExtension<IScheduler>(); if (scheduler != null) { Guid jobguid, userguid; string jobid, username; scheduler.GetContextInfo( activityContext.WorkflowInstanceId, out userguid, out username, out jobguid, out jobid); this.userGuid = userguid; this.userName = username; this.jobGuid = jobguid; this.jobID = jobid; this.contextGuid = activityContext.WorkflowInstanceId; this.activityContext = activityContext; this.activity = activity; } }
protected override void Execute(CodeActivityContext context) { var isValid = new bool?(); var loan = context.GetValue(this.Loan); if (!(loan.CreditRating > 0)) { isValid = false; } if (!(loan.DownPaymentAmount > 0)) { isValid = false; } if (!(loan.LoanAmount > 0)) { isValid = false; } //If we didn't get set to false then we're valid. if(!isValid.HasValue) { isValid = true; } context.SetValue(Valid, isValid); }
protected override void DoExecute(CodeActivityContext context) { devlog.Debug(string.Format("Entered for '{0}'", adapterAppointment)); var myAdapterAppointment = adapterAppointment.Get(context); devlog.Debug(string.Format("would call for '{0}'", myAdapterAppointment)); AdapterAppointmentRepository.InsertOrUpdate(myAdapterAppointment); }
/// <summary> /// The execute. /// </summary> /// <param name="context"> /// The context. /// </param> protected override void Execute(CodeActivityContext context) { var args = this.Args ?? new object[0]; Console.WriteLine( "[{0,2:00}] {1}", Thread.CurrentThread.ManagedThreadId, string.Format(this.Message, args)); }
protected override string ExecuteOperation(CodeActivityContext context) { var hostedServiceName = context.GetValue<string>(HostedServiceName); var slot = context.GetValue(Slot).Description(); var storageServiceName = context.GetValue<string>(StorageServiceName); var deploymentName = context.GetValue<string>(DeploymentName); var label = context.GetValue<string>(Label); var package = context.GetValue<string>(Package); var configuration = context.GetValue<string>(Configuration); if (string.IsNullOrEmpty(deploymentName)) { deploymentName = Guid.NewGuid().ToString(); } Uri packageUrl; if (package.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) || package.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { packageUrl = new Uri(package); } else { //upload package to blob var storageName = string.IsNullOrEmpty(storageServiceName) ? hostedServiceName : storageServiceName; packageUrl = this.RetryCall(s => AzureBlob.UploadPackageToBlob( channel, storageName, s, package)); } //create new deployment package var deploymentInput = new CreateDeploymentInput { PackageUrl = packageUrl, Configuration = Utility.GetConfiguration(configuration), Label = ServiceManagementHelper.EncodeToBase64String(label), Name = deploymentName }; using (new OperationContextScope((IContextChannel)channel)) { try { this.RetryCall(s => this.channel.CreateOrUpdateDeployment( s, hostedServiceName, slot, deploymentInput)); } catch (CommunicationException ex) { throw new CommunicationExceptionEx(ex); } return RetrieveOperationId(); } }
// 如果活动返回值,则从 CodeActivity<TResult> // 并从 Execute 方法返回该值。 protected override void Execute(CodeActivityContext context) { // 获取 Text 输入参数的运行时值 string text = context.GetValue(this.Text); //1 }
protected override void Execute(CodeActivityContext context) { Stop(FFmpegProcess.Get <Process>(context)); }
protected override void Execute(CodeActivityContext executionContext) { ITracingService tracer = executionContext.GetExtension <ITracingService>(); IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); try { var targetName = context.PrimaryEntityName; tracer.Trace("ProcessingOnCreation:Execute retrieve triggering entity to process Artifacts for " + targetName); // retrieve all attributes from triggering entities because any field can be configured as a Question Identifier var targetEntity = service.Retrieve(targetName, context.PrimaryEntityId, new ColumnSet(true)); var accountId = Guid.Empty; var contactId = Guid.Empty; var incidentId = Guid.Empty; var artifactLookupName = ""; switch (targetName) { // Assuming that the Parent Account and Contact will be created in advance of any incident. case "account": artifactLookupName = "mcs_accountid"; accountId = targetEntity.Id; contactId = targetEntity.Contains("primarycontactid") ? ((EntityReference)targetEntity["primarycontactid"]).Id : Guid.Empty; break; case "contact": artifactLookupName = "mcs_contactid"; accountId = targetEntity.Contains("parentcustomerid") ? ((EntityReference)targetEntity["parentcustomerid"]).Id : Guid.Empty; var account = service.Retrieve("account", ((EntityReference)targetEntity["parentcustomerid"]).Id, new ColumnSet(new[] { "primarycontactid" })); contactId = account.Contains("primarycontactid") ? ((EntityReference)account["primarycontactid"]).Id : Guid.Empty; break; case "incident": incidentId = targetEntity.Id; artifactLookupName = "mcs_caseid"; accountId = targetEntity.Contains("customerid") ? ((EntityReference)targetEntity["customerid"]).Id : Guid.Empty; contactId = targetEntity.Contains("primarycontactid") ? ((EntityReference)targetEntity["primarycontactid"]).Id : Guid.Empty; break; // Below handles custom related records based on workflow input parameters default: // Retrieve WF arguments artifactLookupName = ArtifactLookupSchemaName.Get(executionContext); var caseLookup = CaseLookupSchemaName.Get(executionContext); if (caseLookup == null || artifactLookupName == null) { return; } // if we have the proper workflow arguments retrieve and set the incidentid, accountid, and contactid associated // with this related record incidentId = ((EntityReference)targetEntity[caseLookup]).Id; using (var xrm = new CrmServiceContext(service)) { var e = (from c in xrm.IncidentSet where c.Id == incidentId select new Incident() { PrimaryContactId = c.PrimaryContactId, CustomerId = c.CustomerId }).FirstOrDefault(); accountId = e.CustomerId != null ? e.CustomerId.Id : Guid.Empty; contactId = e.PrimaryContactId != null ? e.PrimaryContactId.Id : Guid.Empty; } break; } // Instantiate helper object var artifactService = new ArtifactService(service, targetEntity, artifactLookupName, accountId, contactId, incidentId); // Create Artifact based on target Entity and Artifact Rule foreach (var rule in artifactService.ArtifactRules) { // if the question identifier is null then in the context of a create this is a what is called a static rule // which means that the artifact gets created regardless of any criteria on create of the targetEntity if (rule.mcs_QuestionIdentifier == null) { tracer.Trace("ProcessingOnCreation:CreateRequiredDocs create new artifact with no Question Identifier"); artifactService.CreateArtifact(rule); } else if (targetEntity.Contains(rule.mcs_QuestionIdentifier)) { tracer.Trace(targetEntity.LogicalName + "Check This Question Identifier " + rule.mcs_QuestionIdentifier + " against " + rule.mcs_SuccessIndicator); string attr; string attrLabel = ""; // get the appropriate attribute values based on what type of field the question identifier is if (targetEntity[rule.mcs_QuestionIdentifier] is OptionSetValue) { attr = ((OptionSetValue)targetEntity[rule.mcs_QuestionIdentifier]).Value.ToString(); attrLabel = ArtifactService.GetOptionSetText(targetEntity.LogicalName, rule.mcs_QuestionIdentifier, Convert.ToInt32(attr), service); } else if (targetEntity[rule.mcs_QuestionIdentifier] is bool) { attr = ((bool)targetEntity[rule.mcs_QuestionIdentifier]).ToString(); } else { attr = (string)targetEntity[rule.mcs_QuestionIdentifier]; } tracer.Trace("attr = " + attr); // if the attribute value is equal to the success indicator add the required doc to the context for creation if (attr == rule.mcs_SuccessIndicator || attrLabel == rule.mcs_SuccessIndicator) { artifactService.CreateArtifact(rule); } } } } catch (Exception e) { throw new InvalidPluginExecutionException(e.Message); } }
protected override Location <TResult> Execute(CodeActivityContext context) { Fx.Assert(this.fieldInfo != null, "fieldInfo must not be null."); return(new FieldLocation(this.fieldInfo, this.Operand.Get(context))); }
protected override void Execute(CodeActivityContext context) { string text = context.GetValue(this.MyArgument); }
protected override void Execute(CodeActivityContext context) { IWorkflowContext workflowContext = context.GetExtension <IWorkflowContext>(); this.TextFormatted.Set(context, this.BookingDate.Get <DateTime>(context).ToLongDateString()); }
protected override void Execute(CodeActivityContext executionContext) { ITracingService tracer = executionContext.GetExtension <ITracingService>(); try { DateTime startingDate = StartingDate.Get(executionContext); DateTime endingDate = EndingDate.Get(executionContext); DateTime fromDate; DateTime toDate; int increment = 0; int[] monthDay = { 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int month; int day; if (startingDate > endingDate) { fromDate = endingDate; toDate = startingDate; } else { fromDate = startingDate; toDate = endingDate; } if (fromDate.Day > toDate.Day) { increment = monthDay[fromDate.Month - 1]; } if (increment == -1) { increment = DateTime.IsLeapYear(fromDate.Year) ? 29 : 28; } if (increment != 0) { day = (toDate.Day + increment) - fromDate.Day; increment = 1; } else { day = toDate.Day - fromDate.Day; } if ((fromDate.Month + increment) > toDate.Month) { month = (toDate.Month + 12) - (fromDate.Month + increment); increment = 1; } else { month = (toDate.Month) - (fromDate.Month + increment); increment = 0; } int year = toDate.Year - (fromDate.Year + increment); int yearsDifference = year; YearsDifference.Set(executionContext, yearsDifference); } catch (Exception ex) { tracer.Trace("Exception: {0}", ex.ToString()); } }
protected override void Execute(CodeActivityContext executionContext) { //*** Create the tracing service ITracingService tracingService = executionContext.GetExtension <ITracingService>(); if (tracingService == null) { throw new InvalidPluginExecutionException("Failed to retrieve the tracing service."); } //*** Create the context IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); if (context == null) { throw new InvalidPluginExecutionException("Failed to retrieve the workflow context."); } tracingService.Trace("{0}.Execute(): ActivityInstanceId: {1}; WorkflowInstanceId: {2}; CorrelationId: {3}; InitiatingUserId: {4} -- Entering", CHILD_CLASS_NAME, executionContext.ActivityInstanceId, executionContext.WorkflowInstanceId, context.CorrelationId, context.InitiatingUserId); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService serviceProxy = serviceFactory.CreateOrganizationService(context.UserId); if (context.InputParameters.Contains(Common.Target) && context.InputParameters[Common.Target] is Entity) { try { //*** Grab the Target Entity var theEntity = (Entity)context.InputParameters[Common.Target]; tracingService.Trace("Active Stage Name: {0}", theEntity.EntityState); //------------------------------------------------------------------------------------------------------------- var processInstancesRequest = new RetrieveProcessInstancesRequest { EntityId = theEntity.Id, EntityLogicalName = theEntity.LogicalName }; var processInstancesResponse = (RetrieveProcessInstancesResponse)serviceProxy.Execute(processInstancesRequest); var processCount = processInstancesResponse.Processes.Entities.Count; if (processCount > 0) { tracingService.Trace("{0}: Count of Process Instances concurrently associated with the Entity record: {1}", CHILD_CLASS_NAME, processCount); tracingService.Trace("{0}: BPF Definition Name currently set for the Entity record: {1}, Id: {2}", CHILD_CLASS_NAME, processInstancesResponse.Processes.Entities[0].Attributes[CrmEarlyBound.Workflow.Fields.Name], processInstancesResponse.Processes.Entities[0].Id.ToString()); var bpfEntityRef = this.BpfEntityReference.Get <EntityReference>(executionContext); var colSet = new ColumnSet(); colSet.AddColumn(CrmEarlyBound.Workflow.Fields.UniqueName); var bpfEntity = serviceProxy.Retrieve(bpfEntityRef.LogicalName, bpfEntityRef.Id, colSet); tracingService.Trace("{0}: Switching to BPF Unique Name: {1}, Id: {2}", CHILD_CLASS_NAME, bpfEntity.Attributes[CrmEarlyBound.Workflow.Fields.UniqueName].ToString(), bpfEntity.Id.ToString()); var bpfStageName = this.BpfStageName.Get <string>(executionContext).Trim(); var qe = new QueryExpression { EntityName = CrmEarlyBound.Workflow.EntityLogicalName, ColumnSet = new ColumnSet(new string[] { CrmEarlyBound.Workflow.Fields.Name }), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = CrmEarlyBound.Workflow.Fields.UniqueName, Operator = ConditionOperator.Equal, Values ={ bpfEntity.Attributes[CrmEarlyBound.Workflow.Fields.UniqueName] } //new_bpf_472aceaabf7c4f1db4d13ac3c7076c65 } } }, NoLock = true, Distinct = false }; #region Convert Query Expression to FetchXML var conversionRequest = new QueryExpressionToFetchXmlRequest { Query = qe }; var conversionResponse = (QueryExpressionToFetchXmlResponse)serviceProxy.Execute(conversionRequest); var fetchXml = conversionResponse.FetchXml; tracingService.Trace("{0}: [{1}], Message: {2}", CHILD_CLASS_NAME, fetchXml, context.MessageName); #endregion Convert the query expression to FetchXML. tracingService.Trace("{0}: Built BPF Query, Now Executing...", CHILD_CLASS_NAME); var entColByQuery = serviceProxy.RetrieveMultiple(qe).Entities; //// Execute Query with Filter Expressions //------------------------------------------------------------------------------------------------------------- if (entColByQuery != null && entColByQuery.Count > 0) //// Search and handle related entities { tracingService.Trace("{0}: Found matching Business Process Flows...", CHILD_CLASS_NAME); var bpfId = new Guid(); var bpfEntityName = String.Empty; foreach (var entity in entColByQuery) //// Loop related entities and retrieve Workflow Names { bpfId = entity.Id; bpfEntityName = entity.GetAttributeValue <string>(CrmEarlyBound.Workflow.Fields.Name); break; } if (bpfId != Guid.Empty) { tracingService.Trace("{0}: Successfully retrieved the Business Process Flow that we'll be switching to: {1}, Id: {2}", CHILD_CLASS_NAME, bpfEntityName, bpfId.ToString()); System.Threading.Thread.Sleep(2000); // Wait for 2 seconds before switching the process //*** Set to the new or same Business BpfEntityName Flow var setProcReq = new SetProcessRequest { Target = new EntityReference(theEntity.LogicalName, theEntity.Id), NewProcess = new EntityReference(CrmEarlyBound.Workflow.EntityLogicalName, bpfId) }; tracingService.Trace("{0}: ***Ready To Update - Business Process Flow", CHILD_CLASS_NAME); var setProcResp = (SetProcessResponse)serviceProxy.Execute(setProcReq); tracingService.Trace("{0}: ***Updated", CHILD_CLASS_NAME); } } else { tracingService.Trace("{0}: No Business Process Flows were found with Unique Name: {1}", CHILD_CLASS_NAME, bpfEntity.Attributes[CrmEarlyBound.Workflow.Fields.UniqueName].ToString()); } //------------------------------------------------------------------------------------------------------------- //*** Verify if the Process Instance was switched successfully for the Entity record processInstancesRequest = new RetrieveProcessInstancesRequest { EntityId = theEntity.Id, EntityLogicalName = theEntity.LogicalName }; processInstancesResponse = (RetrieveProcessInstancesResponse)serviceProxy.Execute(processInstancesRequest); processCount = processInstancesResponse.Processes.Entities.Count; if (processCount > 0) { var activeProcessInstance = processInstancesResponse.Processes.Entities[0]; //*** First Entity record is the Active Process Instance var activeProcessInstanceId = activeProcessInstance.Id; //*** Active Process Instance Id to be used later for retrieval of the active path of the process instance tracingService.Trace("{0}: Successfully Switched to '{1}' BPF for the Entity Record.", CHILD_CLASS_NAME, activeProcessInstance.Attributes[CrmEarlyBound.Workflow.Fields.Name]); tracingService.Trace("{0}: Count of process instances concurrently associated with the entity record: {1}.", CHILD_CLASS_NAME, processCount); var message = "All process instances associated with the entity record:"; for (var i = 0; i < processCount; i++) { message = message + " " + processInstancesResponse.Processes.Entities[i].Attributes[CrmEarlyBound.Workflow.Fields.Name] + ","; } tracingService.Trace("{0}: {1}", CHILD_CLASS_NAME, message.TrimEnd(message[message.Length - 1])); //*** Retrieve the Active Stage ID of the Active Process Instance var activeStageId = new Guid(activeProcessInstance.Attributes[CrmEarlyBound.ProcessStage.Fields.ProcessStageId].ToString()); var activeStagePosition = 0; var newStageId = new Guid(); var newStagePosition = 0; //*** Retrieve the BPF Stages in the active path of the Active Process Instance var activePathRequest = new RetrieveActivePathRequest { ProcessInstanceId = activeProcessInstanceId }; var activePathResponse = (RetrieveActivePathResponse)serviceProxy.Execute(activePathRequest); tracingService.Trace("{0}: Retrieved the BPF Stages in the Active Path of the Process Instance:", CHILD_CLASS_NAME); for (var i = 0; i < activePathResponse.ProcessStages.Entities.Count; i++) { var curStageName = activePathResponse.ProcessStages.Entities[i].Attributes[CrmEarlyBound.ProcessStage.Fields.StageName].ToString(); tracingService.Trace("{0}: Looping Through Stage #{1}: {2} (StageId: {3}, IndexId: {4})", CHILD_CLASS_NAME, i + 1, curStageName, activePathResponse.ProcessStages.Entities[i].Attributes[CrmEarlyBound.ProcessStage.Fields.ProcessStageId], i); //*** Retrieve the Active Stage Name and Stage Position based on a successful match of the activeStageId if (activePathResponse.ProcessStages.Entities[i].Attributes[CrmEarlyBound.ProcessStage.Fields.ProcessStageId].Equals(activeStageId)) { activeStagePosition = i; tracingService.Trace("{0}: Concerning the Process Instance -- Initial Active Stage Name: {1} (StageId: {2})", CHILD_CLASS_NAME, curStageName, activeStageId); } //*** Retrieve the New Stage Id, Stage Name, and Stage Position based on a successful match of the stagename if (curStageName.Equals(bpfStageName, StringComparison.InvariantCultureIgnoreCase)) { newStageId = new Guid(activePathResponse.ProcessStages.Entities[i].Attributes[CrmEarlyBound.ProcessStage.Fields.ProcessStageId].ToString()); newStagePosition = i; tracingService.Trace("{0}: Concerning the Process Instance -- Desired New Stage Name: {1} (StageId: {2})", CHILD_CLASS_NAME, curStageName, newStageId); } } //------------------------------------------------------------------------------------------------------------- //***Update the Business Process Flow Instance record to the desired Active Stage Entity retrievedProcessInstance; ColumnSet columnSet; var stageShift = newStagePosition - activeStagePosition; if (stageShift > 0) { tracingService.Trace("{0}: Number of Stages Shifting Forward: {1}", CHILD_CLASS_NAME, stageShift); //*** Stages only move in 1 direction --> Forward for (var i = activeStagePosition; i <= newStagePosition; i++) { System.Threading.Thread.Sleep(1000); //*** Retrieve the Stage Id of the next stage that you want to set as active var newStageName = activePathResponse.ProcessStages.Entities[i].Attributes[CrmEarlyBound.ProcessStage.Fields.StageName].ToString(); newStageId = new Guid(activePathResponse.ProcessStages.Entities[i].Attributes[CrmEarlyBound.ProcessStage.Fields.ProcessStageId].ToString()); tracingService.Trace("{0}: Setting To Stage #{1}: {2} (StageId: {3}, IndexId: {4})", CHILD_CLASS_NAME, i + 1, newStageName, newStageId, i); //*** Retrieve the BpfEntityName Instance record to update its Active Stage columnSet = new ColumnSet(); columnSet.AddColumn(ACTIVE_STAGE_ID); retrievedProcessInstance = serviceProxy.Retrieve(bpfEntity.Attributes[CrmEarlyBound.Workflow.Fields.UniqueName].ToString(), activeProcessInstanceId, columnSet); //*** Set the next Stage as the Active Stage retrievedProcessInstance[ACTIVE_STAGE_ID] = new EntityReference(CrmEarlyBound.ProcessStage.EntityLogicalName, newStageId); //(ProcessStage.EntityLogicalName, activeStageId); try { tracingService.Trace("{0}: ***Ready To Update -- BPF Stage", CHILD_CLASS_NAME); serviceProxy.Update(retrievedProcessInstance); tracingService.Trace("{0}: ***Updated", CHILD_CLASS_NAME); } catch (FaultException <OrganizationServiceFault> ex) { //*** Determine BPF Stage Requirements foreach (var stageAttribute in activePathResponse.ProcessStages.Entities[i].Attributes) { if (stageAttribute.Key.Equals("clientdata")) { tracingService.Trace("{0}: Attribute Key: {1}, Value: {2}", CHILD_CLASS_NAME, stageAttribute.Key, stageAttribute.Value.ToString()); break; } } tracingService.Trace(FullStackTraceException.Create(ex).ToString()); throw; } } } else { tracingService.Trace("{0}: Number of Stages Shifting Backwards: {1}", CHILD_CLASS_NAME, stageShift); } //------------------------------------------------------------------------------------------------------------- //***Retrieve the Business Process Flow Instance record again to verify its Active Stage information columnSet = new ColumnSet(); columnSet.AddColumn(ACTIVE_STAGE_ID); retrievedProcessInstance = serviceProxy.Retrieve(bpfEntity.Attributes[CrmEarlyBound.Workflow.Fields.UniqueName].ToString(), activeProcessInstanceId, columnSet); var activeStageEntityRef = retrievedProcessInstance[ACTIVE_STAGE_ID] as EntityReference; if (activeStageEntityRef != null) { if (activeStageEntityRef.Id.Equals(newStageId)) { tracingService.Trace("{0}: Concerning the Process Instance -- Modified -- Active Stage Name: {1} (StageId: {2})", CHILD_CLASS_NAME, activeStageEntityRef.Name, activeStageEntityRef.Id); } } } else { tracingService.Trace("{0}:The RetrieveProcessInstancesRequest object returned 0", CHILD_CLASS_NAME); } } } catch (FaultException <OrganizationServiceFault> ex) { tracingService.Trace("{0}: Fault Exception: An Error Occurred During Workflow Activity Execution", CHILD_CLASS_NAME); tracingService.Trace("{0}: Fault Timestamp: {1}", CHILD_CLASS_NAME, ex.Detail.Timestamp); tracingService.Trace("{0}: Fault Code: {1}", CHILD_CLASS_NAME, ex.Detail.ErrorCode); tracingService.Trace("{0}: Fault Message: {1}", CHILD_CLASS_NAME, ex.Detail.Message); ////localContext.Trace("{0}: Fault Trace: {1}", this.ChildClassName, ex.Detail.TraceText); tracingService.Trace("{0}: Fault Inner Exception: {1}", CHILD_CLASS_NAME, null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"); //*** Display the details of the inner exception. if (ex.InnerException != null) { Exception innerEx = ex; var i = 0; while (innerEx.InnerException != null) { innerEx = innerEx.InnerException; tracingService.Trace("{0}: Inner Exception: {1}, Message: {2};", CHILD_CLASS_NAME, i++, innerEx.Message); } } throw new InvalidPluginExecutionException(OperationStatus.Failed, ex.Detail.ErrorCode, ex.Message); } catch (Exception ex) { tracingService.Trace("{0}: Exception: An Error Occurred During Workflow Activity Execution", CHILD_CLASS_NAME); tracingService.Trace("{0}: Exception Message: {1}", CHILD_CLASS_NAME, ex.Message); //*** Display the details of the inner exception. if (ex.InnerException != null) { Exception innerEx = ex; var i = 0; while (innerEx.InnerException != null) { innerEx = innerEx.InnerException; tracingService.Trace("{0}: Inner Exception: {1}, Message: {2};", CHILD_CLASS_NAME, i++, innerEx.Message); } } throw new InvalidPluginExecutionException(OperationStatus.Failed, ex.HResult, ex.Message); } finally { tracingService.Trace("{0}.Execute(): ActivityInstanceId: {1}; WorkflowInstanceId: {2}; CorrelationId: {3} -- Exiting", CHILD_CLASS_NAME, executionContext.ActivityInstanceId, executionContext.WorkflowInstanceId, context.CorrelationId); // Uncomment to force plugin failure for Debugging //--> throw new InvalidPluginExecutionException(String.Format("{0}.Execute(): Plug-in Warning: Manually forcing exception for logging purposes.", CHILD_CLASS_NAME)); } } }
protected override bool Execute(CodeActivityContext context) { // If(env => (elements.Get(env).ElementAt(index.Get(env))).GetType() == typeof(CompensationParticipant)) return(this.Elements.Get(context).ElementAt(this.Index.Get(context)).GetType() == typeof(CompensationParticipant)); }
protected abstract void ExecuteActivity(CodeActivityContext executionContext);
protected override void Execute(CodeActivityContext context) { // This is an empty method because this activity is meant to "comment" other activities out, // so it intentionally does nothing at execution time. }
protected override bool Execute(CodeActivityContext context) { int ti_id = TiId.Get(context); Value.Set(context, 0); Status.Set(context, (int)VALUES_FLAG_DB.DataNotFull); StatusStr.Set(context, TVALUES_DB.FLAG_to_String(VALUES_FLAG_DB.DataNotFull, ";")); ValueDateTime.Set(context, DateTime.MinValue); List <TINTEGRALVALUES_DB> _valueList = new List <TINTEGRALVALUES_DB>(); ValueList.Set(context, _valueList); if (RequestType == enumEnrgyQualityRequestType.Archive) { if (StartDateTime.Get(context) == null || EndDateTime.Get(context) == null) { Error.Set(context, "Для архивных значений начальная и конечная дата должна быть определена"); return(false); } } try { List <TI_ChanelType> tiList = new List <TI_ChanelType>() { new TI_ChanelType() { TI_ID = ti_id, ChannelType = Channel.Get(context), DataSourceType = DataSourceType, } }; if (RequestType == enumEnrgyQualityRequestType.Archive) { //TODO часовой пояс var values = ARM_Service.DS_GetIntegralsValues_List(tiList, StartDateTime.Get(context), EndDateTime.Get(context), IsCoeffEnabled, false, false, true, false, false, enumTimeDiscreteType.DBHalfHours, EnumUnitDigit.None, null, false, false); if (values != null && values.IntegralsValue30orHour != null && values.IntegralsValue30orHour.Count > 0) { var integralTiValue = values.IntegralsValue30orHour[0]; double diff = 0; var flag = VALUES_FLAG_DB.None; if (integralTiValue.Val_List != null) { foreach (var iVal in integralTiValue.Val_List) { diff += iVal.F_VALUE_DIFF; flag = flag.CompareAndReturnMostBadStatus(iVal.F_FLAG); _valueList.Add(iVal); } } Value.Set(context, diff); var stat = flag; Status.Set(context, (int)stat); StatusStr.Set(context, TVALUES_DB.FLAG_to_String(stat, ";")); if (integralTiValue.Val_List != null && integralTiValue.Val_List.Count > 0) { ValueDateTime.Set(context, integralTiValue.Val_List.Last().EventDateTime); } } } else { var Val = ARM_Service.DS_ReadLastIntegralArchives(tiList); if (Val != null && Val.Count > 0) { var ValDict = Val.ToDictionary(k => k.Key, v => v.Value, new TI_ChanelComparer()); foreach (var r in tiList) { TINTEGRALVALUES_DB i_val; if (ValDict.TryGetValue(r, out i_val) && i_val != null) { Value.Set(context, i_val.F_VALUE); Status.Set(context, (int)i_val.F_FLAG); StatusStr.Set(context, TVALUES_DB.FLAG_to_String(i_val.F_FLAG, ";")); ValueDateTime.Set(context, i_val.EventDateTime); _valueList.Add(i_val); break; } } } } } catch (Exception ex) { Error.Set(context, ex.Message); if (!HideException.Get(context)) { throw ex; } } ValueList.Set(context, _valueList); return(string.IsNullOrEmpty(Error.Get(context))); }
protected override bool Execute(CodeActivityContext context) { // While(env => (assertFlag.Get(env) != false) && index.Get(env) < elements.Get(env).Count()) return((this.AssertFlag.Get(context) != false) && (this.Index.Get(context) < this.Elements.Get(context).Count())); }
protected override void Execute(CodeActivityContext context) { Job job = Job.Get(context); }
protected override T Execute(CodeActivityContext context) { return(Expression.Get(context)); }
protected override TResult Execute(CodeActivityContext context) { throw new NotImplementedException(); }
protected override void Execute(CodeActivityContext context) { Value.Set(context, ConfigurationManager.AppSettings[AppSettingName.Get(context)]); }
private void ExecuteWorkflow(CodeActivityContext executionContext, IWorkflowContext workflowContext, IOrganizationServiceFactory serviceFactory, IOrganizationService service, ITracingService tracing) { //YOUR WORKFLOW-CODE GO HERE }
// If your activity returns a value, derive from CodeActivity<TResult> // and return the value from the Execute method. protected override void Execute(CodeActivityContext context) { // Obtain the runtime value of the Text input argument string text = context.GetValue(this.Text); }
protected override void ValidateFilename(CodeActivityContext context, bool lookForFilesInPATH) { base.ValidateFilename(context, false); // For scripts we don't look in directories from PATH }
protected override bool Execute(CodeActivityContext context) { List <BalanceInfo> Bps = new List <BalanceInfo>(); List <HierLev3BalanceInfo> Bhl3 = new List <HierLev3BalanceInfo>(); List <FormulaInfo> Frmls = new List <FormulaInfo>(); try { var res = ARM_Service.BL_Get_Balance_List(ID.Get(context), HierarchyType, WithNested); if (res == null) { Error.Set(context, "Ошибка получения информации о балансах (null)"); } else { if (res.Balance_PS_List_2 != null) { foreach (var item in res.Balance_PS_List_2) { Bps.Add(new BalanceInfo { UserName = item.UserName, BalancePS_UN = item.BalancePS_UN, BalancePSName = item.BalancePSName, User_ID = item.User_ID, HierLev1_ID = item.HierLev1_ID, HierLev2_ID = item.HierLev2_ID, HierLev3_ID = item.HierLev3_ID, PS_ID = item.PS_ID, TI_ID = item.TI_ID, BalancePSType_ID = item.BalancePSType_ID, ForAutoUse = item.ForAutoUse, HighLimit = item.HighLimit, LowerLimit = item.LowerLimit, DispatchDateTime = item.DispatchDateTime }); } } if (res.Balance_HierLev3_List != null) { foreach (var item in res.Balance_HierLev3_List) { Bhl3.Add(new HierLev3BalanceInfo { UserName = item.UserName, Balance_HierLev3_UN = item.Balance_HierLev3_UN, BalanceHierLev3Name = item.BalanceHierLev3Name, User_ID = item.User_ID, HierLev1_ID = item.HierLev1_ID, HierLev2_ID = item.HierLev2_ID, HierLev3_ID = item.HierLev3_ID, BalanceHierLev3Type_ID = item.BalanceHierLev3Type_ID, ForAutoUse = item.ForAutoUse, HighLimit = item.HighLimit, LowerLimit = item.LowerLimit }); } } if (res.Formula_List != null) { foreach (var item in res.Formula_List) { Frmls.Add(new FormulaInfo() { UserName = item.UserName, Formula_UN = item.Formula_UN, FormulaName = item.FormulaName, User_ID = item.User_ID, HierLev1_ID = item.HierLev1_ID, HierLev2_ID = item.HierLev2_ID, HierLev3_ID = item.HierLev3_ID, PS_ID = item.PS_ID, TI_ID = item.TI_ID, FormulaType_ID = item.FormulaType_ID, HighLimit = item.HighLimit, LowerLimit = item.LowerLimit, FormulaClassification_ID = item.FormulaClassification_ID, Voltage = item.Voltage }); } } } } catch (Exception ex) { Error.Set(context, ex.Message); if (!HideException.Get(context)) { throw ex; } } PSBalanceList.Set(context, Bps); HierLev3BalanceList.Set(context, Bhl3); FormulsList.Set(context, Frmls); return(string.IsNullOrEmpty(Error.Get(context))); }
protected override bool Execute(CodeActivityContext context) { Error.Set(context, null); KeyValuePair <Guid, TReportResult> RepF = new KeyValuePair <Guid, TReportResult>(); MemoryStream doc = null; try { /* * string User_ID = ""; * List<UserInfo> UInfos = ARM_Service.EXPL_Get_All_Users(); * foreach (UserInfo u in UInfos) * if (u.UserName == UserName) * { * User_ID = u.User_ID; * break; * } * if (string.IsNullOrEmpty(User_ID)) * { * Error.Set(context, "Пользователь '" + UserName+"' не найден в системе"); * return false; * } */ string userId = null; if (!string.IsNullOrEmpty(UserName)) { try { userId = UserHelper.GetIdByUserName(UserName); } catch (Exception ex) { Error.Set(context, ex.Message); if (!HideException.Get(context)) { throw ex; } } } if (string.IsNullOrEmpty(userId)) { Error.Set(context, "Пользователь '" + UserName + "' не найден в системе"); return(false); } RepF = ARM_Service.REP_Export_Report(userId, ReportFormat, Report_id.Get(context), StartDateTime.Get(context), EndDateTime.Get(context), null, WcfTimeOut.Get(context)); doc = LargeData.DownloadData(RepF.Key); if (!string.IsNullOrEmpty(RepF.Value.Error)) { Error.Set(context, RepF.Value.Error); } } catch (Exception ex) { Error.Set(context, ex.Message); if (!HideException.Get(context)) { throw ex; } } return(string.IsNullOrEmpty(Error.Get(context))); }
public virtual void ExecuteCRMWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext crmWorkflowContext) { // Do nothing. }
protected override void Execute(CodeActivityContext context) { var status = context.GetValue(ApplicationStatus); //Custom logic for creating a new employee }
//Share function private void ShareRecord(Guid teamId, Entity workOrder, IOrganizationService service, CodeActivityContext activityContext) { GrantAccessRequest grantRequest = new GrantAccessRequest() { Target = new EntityReference(workOrder.LogicalName, workOrder.Id), PrincipalAccess = new PrincipalAccess() { Principal = new EntityReference("team", teamId), AccessMask = (AccessRights)getMask(activityContext) } }; // Execute the request. GrantAccessResponse grantResponse = (GrantAccessResponse)service.Execute(grantRequest); }
protected override void Execute(CodeActivityContext executionContext) { // Create the tracing service ITracingService tracingService = executionContext.GetExtension <ITracingService>(); if (tracingService == null) { throw new InvalidPluginExecutionException("Failed to retrieve tracing service."); } tracingService.Trace("Entered AddTabelArrangementProductToBooking.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}", executionContext.ActivityInstanceId, executionContext.WorkflowInstanceId); // Create the context IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); if (context == null) { throw new InvalidPluginExecutionException("Failed to retrieve workflow context."); } tracingService.Trace("AddTabelArrangementProductToBooking.Execute(), Correlation Id: {0}, Initiating User: {1}", context.CorrelationId, context.InitiatingUserId); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); Xrm xrm = new Xrm(service); tracingService.Trace("Creating AddTabelArrangementProductToBooking..."); try { var bookingResRef = BookableResourceRef.Get <EntityReference>(executionContext); var br = xrm.BookableResourceSet.FirstOrDefault(b => b.BookableResourceId.Value == bookingResRef.Id); EntityReferenceCollection enColl = new EntityReferenceCollection(); var udstyr = (from u in xrm.dyna_udstyrSet join ur in xrm.dyna_dyna_udstyr_bookableresourceSet on u.dyna_udstyrId equals ur.dyna_udstyrid where ur.bookableresourceid.Value == bookingResRef.Id select u).ToList(); foreach (var item in udstyr) { var be = new dyna_bookingequipment() { dyna_name = item.dyna_name, dyna_Amount = 1, dyna_UseEquipmentAs = false, dyna_EquipmentId = item.ToEntityReference(), dyna_BookableResourceBookingId = new EntityReference(BookableResourceBooking.EntityLogicalName, context.PrimaryEntityId) }; service.Create(be); } tracingService.Trace("Done."); } catch (FaultException <OrganizationServiceFault> e) { tracingService.Trace("Exception: {0} - {1}", e.ToString(), e.StackTrace); // Handle the exception. throw; } tracingService.Trace("Exiting AddTabelArrangementProductToBooking.Execute(), Correlation Id: {0}", context.CorrelationId); }
protected override void Execute(CodeActivityContext context) { List <POS> snake = new List <POS>(); POS rat = new POS(); Random r = new Random(); int k = 0; int size = SizeOfPlayArea.Get(context); int delay = Delay.Get(context); if (size < 300) { size = 300; } //Create boundry of PlayArea CreateBoundry(size, delay); //Draw Rat rat.x = (uint)r.Next(200, 200 + size); rat.y = (uint)r.Next(200, 200 + size); System.Windows.Forms.Cursor.Position = new Point((int)rat.x, (int)rat.y); mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, rat.x, rat.y, 0, 0); Thread.Sleep(1000); //Draw Snake for (uint i = 0; i < 100; i++) { var tmp = new POS(); tmp.x = 200 + i; tmp.y = 200; snake.Add(tmp); System.Windows.Forms.Cursor.Position = new Point((int)snake[snake.Count - 1].x, (int)snake[snake.Count - 1].y); uint mousex = (uint)System.Windows.Forms.Cursor.Position.X; uint mousey = (uint)System.Windows.Forms.Cursor.Position.X; mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, mousex, mousey, 0, 0); Thread.Sleep(delay); } int kk = 0; while (true) { kk += 1; if (kk > 100) { System.Windows.Forms.MessageBox.Show("You Can Stop Here!!!"); kk = 0; } //If Rat Found if ((snake[snake.Count - 1].x == rat.x) && (snake[snake.Count - 1].y == rat.y)) { rat.x = (uint)r.Next(200, 200 + size); rat.y = (uint)r.Next(200, 200 + size); Thread.Sleep(500); System.Windows.Forms.MessageBox.Show("You Can Stop Here!!!"); System.Windows.Forms.Cursor.Position = new Point((int)rat.x, (int)rat.y); mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, rat.x, rat.y, 0, 0); Thread.Sleep(500); } //Move Snake System.Windows.Forms.Cursor.Position = new Point((int)snake[0].x, (int)snake[0].y); mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, snake[0].x, snake[0].y, 0, 0); if (rat.x > snake[snake.Count - 1].x) { var tmp = new POS(); tmp.x = snake[snake.Count - 1].x + 1; tmp.y = snake[snake.Count - 1].y; snake.Add(tmp); } else if (rat.y > snake[snake.Count - 1].y) { var tmp = new POS(); tmp.x = snake[snake.Count - 1].x; tmp.y = snake[snake.Count - 1].y + 1; snake.Add(tmp); } else if (rat.x < snake[snake.Count - 1].x) { var tmp = new POS(); tmp.x = snake[snake.Count - 1].x - 1; tmp.y = snake[snake.Count - 1].y; snake.Add(tmp); } else if (rat.y < snake[snake.Count - 1].y) { var tmp = new POS(); tmp.x = snake[snake.Count - 1].x; tmp.y = snake[snake.Count - 1].y - 1; snake.Add(tmp); } snake.RemoveAt(0); Thread.Sleep(delay); System.Windows.Forms.Cursor.Position = new Point((int)snake[snake.Count - 1].x, (int)snake[snake.Count - 1].y); mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, snake[snake.Count - 1].x, snake[snake.Count - 1].y, 0, 0); Thread.Sleep(delay); k = (k + 1) % 100; } }
protected override TResult Execute(CodeActivityContext context) { return((TResult)this.invoker.InvokeExpression(context)); }
protected override void Execute(CodeActivityContext context) { MessageBox.Show(Text.Get(context)); }
public ActivityContextProxy(CodeMetricsHistory activity, CodeActivityContext context) { this.activity = activity; this.context = context; }
protected override void Execute(CodeActivityContext executionContext) { #region "Load CRM Service from context" Common objCommon = new Common(executionContext); objCommon.tracingService.Trace("Load CRM Service from context --- OK"); #endregion #region "Read Parameters" EntityReference roleReference = this.Role.Get(executionContext); EntityReference userReference = this.User.Get(executionContext); objCommon.tracingService.Trace(String.Format("RoleId: {0} - UserID: {1} ", roleReference.Id.ToString(), userReference.Id.ToString())); #endregion Entity systemUser = (Entity)objCommon.service.Retrieve( "systemuser", userReference.Id, new ColumnSet("businessunitid")); EntityReference businessUnit = (EntityReference)systemUser.Attributes["businessunitid"]; QueryExpression query = new QueryExpression { EntityName = "role", ColumnSet = new ColumnSet("parentrootroleid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "roleid", Operator = ConditionOperator.Equal, Values = { roleReference.Id } } } } }; EntityCollection givenRoles = objCommon.service.RetrieveMultiple(query); if (givenRoles.Entities.Count > 0) { Entity givenRole = givenRoles.Entities[0].ToEntity <Entity>(); EntityReference entRootRole = (EntityReference)givenRole.Attributes["parentrootroleid"]; Console.WriteLine("Role {0} is retrieved.", givenRole); QueryExpression query2 = new QueryExpression { EntityName = "role", ColumnSet = new ColumnSet("roleid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "parentrootroleid", Operator = ConditionOperator.Equal, Values = { entRootRole.Id } }, new ConditionExpression { AttributeName = "businessunitid", Operator = ConditionOperator.Equal, Values = { businessUnit.Id } } } } }; EntityCollection givenRoles2 = objCommon.service.RetrieveMultiple(query2); Entity givenRole2 = givenRoles2.Entities[0].ToEntity <Entity>(); Guid entRoleId = (Guid)givenRole2.Attributes["roleid"]; objCommon.service.Disassociate( "systemuser", userReference.Id, new Relationship("systemuserroles_association"), new EntityReferenceCollection() { new EntityReference("role", entRoleId) }); } }