예제 #1
1
 protected override void Execute(CodeActivityContext executionContext)
 {
     Boolean Logging = EnableLogging.Get(executionContext);
     string LogFilePath = LogFile.Get(executionContext);
     EntityReference Email = EmailId.Get(executionContext);
     try
     {
         if (Logging)
             Log("Workflow Execution Start", LogFilePath);
         IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
         IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
         IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
         if (Logging)
             Log("Sending Email", LogFilePath);
         SendEmailRequest sendEmailreq = new SendEmailRequest();
         sendEmailreq.EmailId = Email.Id;
         sendEmailreq.TrackingToken = "";
         sendEmailreq.IssueSend = true;
         SendEmailResponse sendEmailresp = (SendEmailResponse)service.Execute(sendEmailreq);
         if (Logging)
             Log("Workflow Executed Successfully", LogFilePath);
     }
     catch (Exception ex)
     {
         Log(ex.Message, LogFilePath);
     }
 }
예제 #2
0
        protected override void Execute(CodeActivityContext context)
        {
            //initialization code
            try
            {
                // Get the tracing service
                ITracingService tracingService =
                context.GetExtension<ITracingService>();

                // Get the context service.
                IWorkflowContext mycontext =
                context.GetExtension<IWorkflowContext>();

                IOrganizationServiceFactory serviceFactory =
                context.GetExtension<IOrganizationServiceFactory>();

                // Use the context service to create an instance of CrmService.
                IOrganizationService crmService =
                serviceFactory.CreateOrganizationService(mycontext.UserId);

                //Split parameters by Pipe
                string[] parameters = inSPParams.Get(context).Split('|');

                //create object parameters for sqlhelper
                object[] sqlPars = new object[parameters.Length];

                for (int i = 0; i < parameters.Length; i++)
                {
                    sqlPars[i] = parameters[i];
                }

                //format connection string
                string conn = String.Format("Data Source={0};Initial Catalog={1};User Id={2};Password={3}",
                                            inSPDBInstance.Get(context),
                                            inSPDatabase.Get(context),
                                            inUsername.Get(context),
                                            inPassword.Get(context));

                //Execute DataSet
                DataSet ds = SqlHelper.ExecuteDataset(conn, inSPName.Get(context), sqlPars);

                if (ds != null)
                {
                    if (ds.Tables.Count > 0)
                    {
                        SPResult.Set(context, ds.Tables[0].Rows[0][0].ToString());
                    }
                    else
                        SPResult.Set(context, "0");
                }
                else
                {
                    SPResult.Set(context, "0");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #3
0
        /// <summary>
        /// The execute.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        protected override void Execute(CodeActivityContext context)
        {
            var token = context.GetExtension<ActivityCancellationToken>();
            var notify = context.GetExtension<SpinNotify>();
            for (int i = 0; i < this.Loops; i++)
            {
                WorkflowTrace.Verbose(
                    "SpinWaiter loop {0} of {1}, spinning {2} iterations", i, this.Loops, this.Iterations);

                // Don't do this from a Code or Native Activity
                // The activity will be faulted
                // token.ThrowIfCancellationRequested();
                if (token != null && token.IsCancellationRequested(context))
                {
                    return;
                }

                Thread.SpinWait(this.Iterations);
                if (notify != null)
                {
                    notify.LoopComplete(this.Loops, this.Iterations);
                }
            }

            WorkflowTrace.Verbose("SpinWaiter done with {0} iterations", this.Iterations * this.Loops);
        }
        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);
        }
예제 #5
0
 protected override void Execute(CodeActivityContext executionContext)
 {
     Boolean Logging = EnableLogging.Get(executionContext);
     string LogFilePath = LogFile.Get(executionContext);
     EntityReference Attachment = AttachmentId.Get(executionContext);
     string entityName = EntityName.Get(executionContext);
     string recordId = RecordId.Get(executionContext);
     try
     {
         if (Logging)
             Log("Workflow Execution Start", LogFilePath);
         if (ValidateParameters(executionContext))
         {
             IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
             IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
             IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
             if (Logging)
                 Log("Attaching Attachment", LogFilePath);
             Entity UpdatedAttachment = new Entity("annotation");
             UpdatedAttachment.Id = Attachment.Id;
             UpdatedAttachment.Attributes.Add("objectid", new EntityReference(entityName, new Guid(recordId)));
             service.Update(UpdatedAttachment);
             if (Logging)
                 Log("Attachment linked successfully", LogFilePath);
             if (Logging)
                 Log("Workflow Executed Successfully", LogFilePath);
         }
     }
     catch (Exception ex)
     {
         Log(ex.Message, LogFilePath);
     }
 }
예제 #6
0
        /// <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);
        }
예제 #7
0
파일: PostUrl.cs 프로젝트: cesugden/Scripts
        /// <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();
        }
        /// <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 " + _activityName + ".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(_activityName + ".Execute(), Correlation Id: {0}, Initiating User: {1}",
                context.CorrelationId,
                context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                EntityCollection recordsToProcess = service.RetrieveMultiple(new FetchExpression(FetchXMLQuery.Get(executionContext)));
                recordsToProcess.Entities.ToList().ForEach(a =>
                {
                    ExecuteWorkflowRequest request = new ExecuteWorkflowRequest
                    {
                        EntityId = a.Id,
                        WorkflowId = (Workflow.Get(executionContext)).Id
                    };

                    service.Execute(request); //run the workflow
                });

            }
            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 StartScheduledWorkflows.Execute(), Correlation Id: {0}", context.CorrelationId);
        }
예제 #9
0
        /// <summary>
        /// This method is called when the workflow executes.
        /// </summary>
        /// <param name="executionContext">The data for the event triggering
        /// the workflow.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

            IServiceEndpointNotificationService endpointService =
                     executionContext.GetExtension<IServiceEndpointNotificationService>();
            endpointService.Execute(ServiceEndpoint.Get(executionContext), context);
        }
예제 #10
0
        // 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

            bool doFlush = context.GetValue(this.DoFlush);
            List<string> text = context.GetValue(this.Text);
            if (doFlush)
                context.GetExtension<List<string>>().Clear();
            context.GetExtension<List<string>>().AddRange(text);
        }
예제 #11
0
        /// <summary>
        /// Checks if the "Est. Close Date" is greater than 10 days. If it is,
        /// send an email to the administrator so that s/he can verify close date
        /// with the owner of the opportunity.
        /// </summary>
        protected override void Execute(CodeActivityContext executionContext)
        {
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory =
                    executionContext.GetExtension<IOrganizationServiceFactory>();
                IOrganizationService service =
                    serviceFactory.CreateOrganizationService(context.UserId);

            // Get opportunity entity
            Entity opportunity = service.Retrieve("opportunity", 
                this.inputOpportunity.Get(executionContext).Id, new ColumnSet("estimatedclosedate"));

            // Calulate 10 days from today
            DateTime todayPlusTen = DateTime.UtcNow.AddDays(10.0);

            // Check "Est. Close Date"
            if (opportunity.Contains("estimatedclosedate"))
            {
                DateTime estCloseDate = (DateTime)opportunity["estimatedclosedate"];
                if (DateTime.Compare(estCloseDate, todayPlusTen) > 0)
                {
                    // Need system user id for activity party
                    WhoAmIRequest systemUserRequest = new WhoAmIRequest();
                    WhoAmIResponse systemUser = 
                        (WhoAmIResponse)service.Execute(systemUserRequest);

                    // Create an activity party for the email
                    Entity[] activityParty = new Entity[1];
                    activityParty[0] = new Entity("activityparty");
                    activityParty[0]["partyid"] = 
                        new EntityReference("systemuser", systemUser.UserId);

                    // Create an email message
                    Entity email = new Entity("email");
                    email.LogicalName = "email";
                    email["subject"] = 
                        "Warning: Close date has been extended more than 10 days.";
                    email["description"] = "Verify close date is correct.";
                    email["to"] = activityParty;
                    email["from"] = activityParty;
                    email["regardingobjectid"] = opportunity.ToEntityReference();
                    Guid emailId = service.Create(email);

                    // Send email
                    SendEmailRequest sendEmailRequest = new SendEmailRequest();
                    sendEmailRequest.EmailId = emailId;
                    sendEmailRequest.IssueSend = true;
                    sendEmailRequest.TrackingToken = "";
                    SendEmailResponse sendEmailResponse = 
                        (SendEmailResponse)service.Execute(sendEmailRequest);
                }
            }
        }
        /// <summary>
        /// Performs the addition of two summands
        /// </summary>
        protected override void Execute(CodeActivityContext executionContext)
        {
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory =
                executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service =
                serviceFactory.CreateOrganizationService(context.UserId);


            // Retrieve the summands and perform addition
            this.MessageName.Set(executionContext, context.MessageName);
        }
예제 #13
0
 protected override void Execute(CodeActivityContext executionContext)
 {
     Boolean Logging = EnableLogging.Get(executionContext);
     string LogFilePath = LogFile.Get(executionContext);
     EntityReference Email = EmailId.Get(executionContext);
     EntityReference Attachment = AttachmentId.Get(executionContext);
     try
     {
         if (Logging)
             Log("Workflow Execution Start", LogFilePath);
         // Create CRM Service in Workflow
         IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
         IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
         IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
         if (Logging)
             Log("Retrieving Attahment", LogFilePath);
         // Retrieve the Attachment from the given template
         Entity TempAttachment = service.Retrieve("annotation", Attachment.Id, new ColumnSet(true));
         if (TempAttachment != null)
         {
             if (Logging)
                 Log("Creating New Attachment", LogFilePath);
             // Create new Attachment under Email Activity
             Entity NewAttachment = new Entity("activitymimeattachment");
             if (TempAttachment.Contains("subject"))
                 NewAttachment.Attributes.Add("subject", TempAttachment["subject"]);
             if (TempAttachment.Contains("filename"))
                 NewAttachment.Attributes.Add("filename", TempAttachment["filename"]);
             if (TempAttachment.Contains("mimetype"))
                 NewAttachment.Attributes.Add("mimetype", TempAttachment["mimetype"]);
             if (TempAttachment.Contains("documentbody"))
                 NewAttachment.Attributes.Add("body", TempAttachment["documentbody"]);
             NewAttachment.Attributes.Add("objectid", new EntityReference(Email.LogicalName, Email.Id));
             NewAttachment.Attributes.Add("objecttypecode", "email");
             NewAttachment.Attributes.Add("attachmentnumber", 1);
             service.Create(NewAttachment);
             if (Logging)
                 Log("New Attachment Added To Email", LogFilePath);
         }
         else
         {
             if (Logging)
                 Log("Temp Attachment doesnot exist", LogFilePath);
         }
         if (Logging)
             Log("Workflow Executed Successfully", LogFilePath);
     }
     catch (Exception ex)
     {
         Log(ex.Message, LogFilePath);
     }
 }
예제 #14
0
        /// <summary>
        /// Performs the addition of two summands
        /// </summary>
        protected override void Execute(CodeActivityContext executionContext)
        {
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory =
                executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service =
                serviceFactory.CreateOrganizationService(context.UserId);


            // Retrieve the summands and perform addition
            this.result.Set(executionContext,
                this.firstSummand.Get(executionContext) +
                this.secondSummand.Get(executionContext));
        }
 protected override void Execute(CodeActivityContext executionContext)
 {
     Boolean Logging = EnableLogging.Get(executionContext);
     EntityReference Letter = LetterId.Get(executionContext);
     EntityReference Attachment = AttachmentId.Get(executionContext);
     IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
     IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
     IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
     try
     {
         if (Logging)
             Log("Workflow Execution Start",service);
         if (Logging)
             Log("Retrieving Attahment", service);
         Entity TempAttachment = service.Retrieve("annotation", Attachment.Id, new ColumnSet(true));
         if (TempAttachment != null)
         {
             if (Logging)
                 Log("Creating New Attachment", service);
             Entity NewAttachment = new Entity("annotation");
             if (TempAttachment.Contains("subject"))
                 NewAttachment.Attributes.Add("subject", TempAttachment["subject"]);
             if (TempAttachment.Contains("filename"))
                 NewAttachment.Attributes.Add("filename", TempAttachment["filename"]);
             if (TempAttachment.Contains("notetext"))
                 NewAttachment.Attributes.Add("notetext", TempAttachment["notetext"]);
             if (TempAttachment.Contains("mimetype"))
                 NewAttachment.Attributes.Add("mimetype", TempAttachment["mimetype"]);
             if (TempAttachment.Contains("documentbody"))
                 NewAttachment.Attributes.Add("documentbody", TempAttachment["documentbody"]);
             NewAttachment.Attributes.Add("objectid", new EntityReference(Letter.LogicalName, Letter.Id));
             service.Create(NewAttachment);
             if (Logging)
                 Log("New Attachment Added To Letter", service);
         }
         else
         {
             if (Logging)
                 Log("Temp Attachment doesnot exist", service);
         }
         if (Logging)
             Log("Workflow Executed Successfully", service);
     }
     catch (Exception ex)
     {
         Log(ex.Message, service);
         throw ex;
     }
 }
예제 #16
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

            //Create an Organization Service
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);

            //Retrieve the contact id
            Guid contactId = this.Contact.Get(executionContext).Id;

            //<snippetReleaseISVActivities1>
            //Create the request
            RetrieveRequest request = new RetrieveRequest();
            request.ColumnSet = new ColumnSet(new string[] { "birthdate" });
            request.Target = new EntityReference(EntityName.Contact, contactId);

            //Retrieve the entity to determine what the birthdate is set at
            Entity entity = (Entity)((RetrieveResponse)service.Execute(request)).Entity;
            //</snippetReleaseISVActivities1>

            //Extract the date out of the entity
            DateTime? birthdate;
            if (entity.Contains(ContactAttributes.Birthdate))
            {
                birthdate = (DateTime?)entity[ContactAttributes.Birthdate];
            }
            else
            {
                birthdate = null;
            }

            //Check to see if the current birthday is set. We don't want the activity to fail if the birthdate is not set
            if (birthdate == null)
            {
                return;
            }

            //Calculate the next birthdate. Encapsulated in a methdo so that the method can be used in the test case for verification purposes
            DateTime nextBirthdate = CalculateNextBirthday(birthdate.Value);

            //Update the next birthday field on the entity
            Entity updateEntity = new Entity(EntityName.Contact);
            updateEntity.Id = contactId;
            updateEntity["new_nextbirthday"] = nextBirthdate;

            service.Update(updateEntity);
        }
 protected override void Execute(CodeActivityContext executionContext)
 {
     Boolean Logging = EnableLogging.Get(executionContext);
     string LogFilePath = LogFile.Get(executionContext);
     EntityReference Attachment = AttachmentId.Get(executionContext);
     OutputAttachmentId.Set(executionContext, new EntityReference("annotation", Guid.Empty));
     try
     {
         if (Logging)
             Log("Workflow Execution Start", LogFilePath);
         IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
         IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
         IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
         if (Logging)
             Log("Reading Attachment", LogFilePath);
         Entity ExistingAttachment = service.Retrieve(Attachment.LogicalName, Attachment.Id, new ColumnSet(true));
         if (ExistingAttachment != null)
         {
             if (Logging)
                 Log("Creating New Attachment", LogFilePath);
             // Create new Attachment under Email Activity
             Entity NewAttachment = new Entity("annotation");
             if (ExistingAttachment.Contains("subject"))
                 NewAttachment.Attributes.Add("subject", ExistingAttachment["subject"]);
             if (ExistingAttachment.Contains("filename"))
                 NewAttachment.Attributes.Add("filename", ExistingAttachment["filename"]);
             if (ExistingAttachment.Contains("mimetype"))
                 NewAttachment.Attributes.Add("mimetype", ExistingAttachment["mimetype"]);
             if (ExistingAttachment.Contains("documentbody"))
                 NewAttachment.Attributes.Add("documentbody", ExistingAttachment["documentbody"]);
             Guid NewAttachmentId = service.Create(NewAttachment);
             OutputAttachmentId.Set(executionContext, new EntityReference("annotation", NewAttachmentId));
             if (Logging)
                 Log("New Attachment Created", LogFilePath);
         }
         else
         {
             if (Logging)
                 Log("Provided Attachment doesnot exist", LogFilePath);
         }
         if (Logging)
             Log("Workflow Executed Successfully", LogFilePath);
     }
     catch (Exception ex)
     {
         Log(ex.Message, LogFilePath);
     }
 }
        /// <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)
        {
            // Create a Lead class and populate it with the input arguments
            Lead l = new Lead();
            l.ContactName = ContactName.Get(context);
            l.ContactPhone = ContactPhone.Get(context);
            l.Interests = Interests.Get(context);
            l.Comments = Notes.Get(context);
            l.WorkflowID = context.WorkflowInstanceId;
            l.Status = "Open";

            // Add this to the work queue to be persisted later
            PersistLead persist = context.GetExtension<PersistLead>();
            persist.AddLead(l, "Insert");

            // Store the request in the OutArgument
            Lead.Set(context, l);

            // Add a custom track record
            CustomTrackingRecord userRecord = new CustomTrackingRecord("New Lead")
            {
                Data = 
                {
                    {"Name", l.ContactName},
                    {"Phone", l.ContactPhone}
                }
            };

            // Emit the custom tracking record
            context.Track(userRecord);
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            try
            {
                _tracingService = executionContext.GetExtension<ITracingService>();
                IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
                _service = serviceFactory.CreateOrganizationService(context.UserId);

                //Do stuff
            }
            catch (Exception ex)
            {
                _tracingService.Trace("Exception: {0}", ex.ToString());
            }
        }
예제 #21
0
 protected override void Execute(CodeActivityContext context)
 {
     ProgressExtension extension = context.GetExtension<ProgressExtension>();
     if(extension != null) {
         extension.SetProgress(Progress.Get(context));
     }
 }
        protected override void Execute(CodeActivityContext context)
        {
            var regParticipant = context.GetExtension<RegistrationPeristenceParticipant>();

            regParticipant.UserName = this.UserName.Get(context);
            regParticipant.Email = this.Email.Get(context);
        }
예제 #23
0
        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;
            }
        }
예제 #24
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            Boolean EnableLoggingValue = EnableLogging.Get(executionContext);
            string ProductUriValue = ProductUri.Get(executionContext);
            string AppSIDValue = AppSID.Get(executionContext);
            string AppKeyValue = AppKey.Get(executionContext);
            string LogFilePath = LogFile.Get(executionContext);
            EntityReference Attachment = AttachmentId.Get(executionContext);
            CloudAppConfig config = new CloudAppConfig();
            config.ProductUri = ProductUriValue;
            config.AppSID = AppSIDValue;
            config.AppKey = AppKeyValue;
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
            try
            {
                if (EnableLoggingValue)
                    Log("WorkFlow Started", LogFilePath);
                if (EnableLoggingValue)
                    Log("Retrieving Attachment From CRM", LogFilePath);
                Entity ThisAttachment = service.Retrieve("annotation", Attachment.Id, new ColumnSet(new string[] { "filename", "documentbody", "mimetype" }));
                if (ThisAttachment != null)
                {
                    if (EnableLoggingValue)
                        Log("Attachment Retrieved Successfully", LogFilePath);
                    if (ThisAttachment.Contains("mimetype") && ThisAttachment.Contains("documentbody"))
                    {
                        string FileName = "Aspose .NET AutoMerge Attachment (" + DateTime.Now.ToString() + ").docx";
                        if (ThisAttachment.Contains("filename"))
                            FileName = ThisAttachment["filename"].ToString();
                        config.FileName = FileName;
                        byte[] DocumentBody = Convert.FromBase64String(ThisAttachment["documentbody"].ToString());
                        MemoryStream fileStream = new MemoryStream(DocumentBody);

                        if (EnableLoggingValue)
                            Log("Upload Attachment on Storage", LogFilePath);
                        UploadFileOnStorage(config, fileStream);
                    }
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message, LogFilePath);
                throw ex;
            }
        }
예제 #25
0
 // 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
     var text = context.GetValue(Text);
     MessageBox.Show(text);
     var wce =  context.GetExtension<WorkflowCommunicationExtension>();
     wce.CommunicationContent = text;
 }
예제 #26
0
 // If your activity returns a value, derive from CodeActivity<TResult>
 // and return the value from the Execute method.
 protected override void Execute(CodeActivityContext context)
 {
    IApproval approveAction = context.GetExtension<IApproval>();
    if (approveAction != null)
    {
        approveAction.Approve();
    }
 }
예제 #27
0
 /// <summary>
 /// The execute.
 /// </summary>
 /// <param name="context">
 /// The context.
 /// </param>
 protected override void Execute(CodeActivityContext context)
 {
     var repository = context.GetExtension<IResourceRepository<int, Sample>>();
     var result = repository.Put(
         int.Parse(this.Key.Get(context)), this.Sample.Get(context), this.ExistingSample.Get(context));
     this.Sample.Set(context, result);
     Trace.WriteLine(string.Format("Existing tag {0}, New tag {1}", this.ExistingSample.Get(context).Tag, result.Tag));
 }
예제 #28
0
        /// <summary>
        /// Calculates the shortest distance between two points based on their zipcodes,
        /// and returns the value.
        /// </summary>
        protected override void Execute(CodeActivityContext executionContext)
        {
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory =
                executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service =
                serviceFactory.CreateOrganizationService(context.UserId);

            // Calculate the distance between those two points
            // based on the Zip Codes
            double distance = CalculateDistance(
                this.startingZipCode.Get(executionContext),
                this.endingZipCode.Get(executionContext));

            // Set the result in the output parameter
            this.totalDistance.Set(executionContext, distance);
        }
예제 #29
0
        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
            {
                //Entity entity = (Entity)context.InputParameters["Target"];

                //TODO: Do stuff

                string city = City.Get(executionContext);
                string country = Country.Get(executionContext);
                Weather.GlobalWeather Client = new Weather.GlobalWeather();
                string Get = Client.GetWeather(city,country);

                String xmlString = Get;

                // Create an XmlReader
                using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
                {
                    //reader.ReadStartElement("CurrentWeather");

                    while (reader.Read())
                    {
                        switch (reader.Name.ToString())
                        {
                            case "Temperature":
                                string Temp=reader.ReadString();
                                Temp_C.Set(executionContext, Temp);
                                break;

                        }

                    }

                }

            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException(e.Message);
            }
        }
예제 #30
0
 protected override void Execute(CodeActivityContext context)
 {
     var buildDetail = context.GetExtension<IBuildDetail>();
     var externalLink = InformationNodeConverters.AddExternalLink(buildDetail.Information,
         "ScorchWorkspace has been obsoleted. Click for more information.",
         new Uri("http://buildweb/help/scorchworkspace.html"));
     externalLink.Save();
 }
예제 #31
0
        /// <summary>
        /// The execute.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        protected override void Execute(CodeActivityContext context)
        {
            var atm = context.GetExtension <IAtmViewModel>();

            atm.ControlCamera(this.Record);
        }
예제 #32
0
        protected override void Execute(CodeActivityContext context)
        {
            // Get the connection string
            DBConnection ext = context.GetExtension <DBConnection>();

            if (ext == null)
            {
                throw new InvalidProgramException("No connection string available");
            }

            // Lookup the operator
            UserTasksDataContext dc = new UserTasksDataContext(ext.ConnectionString);
            OperatorConfig       oc = dc.OperatorConfigs.SingleOrDefault(x => x.OperatorKey == OperatorKey.Get(context));

            if (oc == null)
            {
                throw new InvalidProgramException("The specified operator (" + OperatorKey.Get(context).ToString() + ") was not found");
            }

            // Lookup the QueueInstance
            dc.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, dc.QueueInstances);
            QueueInstance qi = dc.QueueInstances.SingleOrDefault(x => x.QueueInstanceKey == QueueInstanceKey.Get(context));

            if (qi == null)
            {
                throw new InvalidProgramException("The specified request (" + QueueInstanceKey.Get(context) + ") was not found");
            }

            if (qi.AssignedOperatorID != null)
            {
                if (qi.AssignedOperatorID != oc.OperatorConfigID)
                {
                    Result.Set(context, -1);
                    return;
                }
            }

            qi.AssignedOperatorID = oc.OperatorConfigID;
            qi.AssignedDate       = DateTime.UtcNow;

            // Update the QueueInstance record
            PersistQueueInstance persist = context.GetExtension <PersistQueueInstance>();

            persist.AddQueueInstance(qi);

            Result.Set(context, 0);

            // Add a custom track record
            CustomTrackingRecord userRecord = new CustomTrackingRecord("Assign")
            {
                Data =
                {
                    { "QueueInstanceKey", qi.QueueInstanceKey      },
                    { "OperatorKey",      OperatorKey.Get(context) },
                    { "SubQueueID",       qi.CurrentSubQueueID     },
                    { "QC",               qi.QC                    }
                }
            };

            // Emit the custom tracking record
            context.Track(userRecord);
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Extract the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            try
            {
                //Create the context
                IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                DynamicUrlParser parser           = new DynamicUrlParser();
                EntityReference  primaryEntity    = parser.ConvertToEntityReference(service, RecordUrl.Get <string>(executionContext));
                string           relationshipName = RelationshipName.Get <string>(executionContext);

                Guid   ownerId   = Guid.Empty;
                string ownerType = string.Empty;

                EntityReference owner = SystemUser.Get <EntityReference>(executionContext);
                if (owner != null)
                {
                    ownerId   = owner.Id;
                    ownerType = owner.LogicalName;
                }
                else
                {
                    owner = Team.Get <EntityReference>(executionContext);
                    if (owner != null)
                    {
                        ownerId   = owner.Id;
                        ownerType = owner.LogicalName;
                    }
                }

                if (ownerId != Guid.Empty)
                {
                    string childEntityName = null, childEntityAttribute = null;
                    if (relationshipName.Contains(';'))
                    {
                        string[] relationshipNames = relationshipName.Split(';');
                        foreach (string rel in relationshipNames)
                        {
                            OneToManyRelationshipMetadata oneToNRelationship = RetrieveRelationshipInfo(service, primaryEntity, relationshipName);
                            if (oneToNRelationship != null)
                            {
                                childEntityName      = oneToNRelationship.ReferencingEntity;
                                childEntityAttribute = oneToNRelationship.ReferencingAttribute;
                                RetrieveAndUpdateRelatedRecords(service, primaryEntity, childEntityName, childEntityAttribute, ownerId, ownerType);
                            }
                        }
                    }
                    else
                    {
                        OneToManyRelationshipMetadata oneToNRelationship = RetrieveRelationshipInfo(service, primaryEntity, relationshipName);
                        if (oneToNRelationship != null)
                        {
                            childEntityName      = oneToNRelationship.ReferencingEntity;
                            childEntityAttribute = oneToNRelationship.ReferencingAttribute;
                            RetrieveAndUpdateRelatedRecords(service, primaryEntity, childEntityName, childEntityAttribute, ownerId, ownerType);
                        }
                    }
                }
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                throw new Exception("XrmWorkflowTools.AssignChildRecords: " + ex.Message);
            }
        }
예제 #34
0
        }                                                        //Se genera archivo

        #endregion

        // Si la actividad devuelve un valor, se debe derivar de CodeActivity<TResult>
        // y devolver el valor desde el método Execute.
        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);

            // GUID of target record (case)
            Guid gCaseId = context.PrimaryEntityId;

            //Create the statecode vars
            int iStatusCode = 0;
            int iStateCode  = 0;

            //Obtenemos los valores de los parámetros del caso.
            string strPhaseName         = PhaseName.Get <string>(executionContext);
            bool   isResponseDocument   = ResponseDocument.Get <bool>(executionContext);
            bool   isCourierLetterSent  = CourierLetterSent.Get <bool>(executionContext);
            bool   isCustomerEMailSent  = CustomerEMailSent.Get <bool>(executionContext);
            bool   isLetterWasReceived  = LetterWasReceived.Get <bool>(executionContext);
            bool   isEMailWasReceived   = EMailWasReceived.Get <bool>(executionContext);
            bool   isTrasuFileGenerated = TrasuFileGenerated.Get <bool>(executionContext);


            //4.2.3	Reclamos OSIPTEL – Estados:

            //1. BORRADOR, todos los casos inician con este statecode = 864340007

            //2. PENDIENTE, después de haber pasado por: Identificación, Documentación, Investigación = 864340008
            //Validamos que el caso haya pasado correctamente por los estados mencionados arriba.

            if (strPhaseName == "Identificacion" || strPhaseName == "Identity")
            {
                iStatusCode = (int)StatusCode.Pending;
                iStateCode  = (int)StateCode.Active;
            }
            else if (strPhaseName == "Documentacion" || strPhaseName == "Documents")
            {
                iStatusCode = (int)StatusCode.Pending;
                iStateCode  = (int)StateCode.Active;
            }
            else if (strPhaseName == "Investigacion" || strPhaseName == "Research")
            {
                iStatusCode = (int)StatusCode.Pending;
                iStateCode  = (int)StateCode.Active;
            }

            //3. CON RESOLUCIÓN,después de que el documento de respuesta es generado en la etapa "Notificar Cliente" = 864340001
            if (isResponseDocument)
            {
                if (strPhaseName == "Notificar Cliente" || strPhaseName == "Notify Customer")
                {
                    if (isResponseDocument == true)
                    {
                        iStatusCode = (int)StatusCode.WithResolution;
                        iStateCode  = (int)StateCode.Active;
                    }
                }
            }

            //4. EN NOTIFICACIÓN, Caso de Reclamo OSIPTEL con Estado actualizado a “En Notificación” después de recibir la confirmación del sistema
            //   externo de que la carta se envió al courier o el email se envió al cliente = 864340002
            else if (isCourierLetterSent || isCustomerEMailSent)
            {
                if (isCourierLetterSent == true)
                {
                    iStatusCode = (int)StatusCode.InNotification;
                    iStateCode  = (int)StateCode.Active;
                }

                else if (isCustomerEMailSent == true)
                {
                    iStatusCode = (int)StatusCode.InNotification;
                    iStateCode  = (int)StateCode.Active;
                }
            }

            //5. NOTIFICADO, Caso de Reclamo OSIPTEL con estado actualizado a “Notificado” después de la confirmación del sistema externo
            //   sobre el envío de la notificación vía email o en físico por el Courier.  = 864340003
            //To get this answer we need consume a web service to know if email or letter was received to their destiny.
            else if (isLetterWasReceived || isEMailWasReceived)
            {
                if (isLetterWasReceived == true)
                {
                    iStatusCode = (int)StatusCode.Notified;
                    iStateCode  = (int)StateCode.Active;
                }

                else if (isEMailWasReceived == true)
                {
                    iStatusCode = (int)StatusCode.Notified;
                    iStateCode  = (int)StateCode.Active;
                }
            }

            //6. POR ELEVAR, Caso de Reclamo OSIPTEL se actualiza con el estado “Por Elevar ” cuando el caso es avanzado a la etapa “Notificar TRASU”
            //   Esto significa que el cliente apeló y la oferta SARA fue rechazada / imposible  = 864340004
            else if (strPhaseName == "Notificar TRASU" || strPhaseName == "Notify TRASU")
            {
                iStatusCode = (int)StatusCode.ToElevate;
                iStateCode  = (int)StateCode.Active;
            }

            //7. ELEVADO, Caso de Reclamo OSIPTEL es actualizado con estado “Elevado” cuando se genera el archivo de informe a TRASU = 864340005
            else if (isTrasuFileGenerated)
            {
                if (isTrasuFileGenerated == true)
                {
                    iStatusCode = (int)StatusCode.Elevated;
                }
                iStateCode = (int)StateCode.Active;
            }

            //8. RESUELTO, Caso de Reclamo OSIPTEL es actualizado con estado “Resuelto” después de que es concluido automáticamente   = 864340009
            //Esto se guarda automáticamente.

            //Procedemos a actualizar el statuscode del caso.
            UpdateStatusCode(gCaseId, iStatusCode, iStateCode, service);
        }
예제 #35
0
        protected override void Execute(CodeActivityContext context)
        {
            try
            {
                IWorkflowContext            workflowContext = context.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory  = context.GetExtension <IOrganizationServiceFactory>();
                IOrganizationService        service         = serviceFactory.CreateOrganizationService(workflowContext.UserId);

                RepositoryService     RepositoryService = new RepositoryService(workflowContext.OrganizationName, workflowContext.IsExecutingOffline);
                HistoricoDistribuidor historico         = RepositoryService.HistoricoDistribuidor.Retrieve(workflowContext.PrimaryEntityId);
                string   datasExecucao    = SDKore.Configuration.ConfigurationManager.GetSettingValue("Intelbras.CRM2013.Application.Workflow.DataExecucaohistoricoDistribuidor", true);
                string[] datas            = datasExecucao.Split(';');
                bool     controleExecucao = false;
                foreach (string data in datas)
                {
                    if (Convert.ToDateTime(data + "/" + DateTime.Now.Year.ToString()) == DateTime.Now.Date)
                    {
                        //if (DateTime.Now.Day == 1 && (DateTime.Now.Month == 1 || DateTime.Now.Month == 4 || DateTime.Now.Month == 7 || DateTime.Now.Month == 10))
                        //if (DateTime.Now.Day == 24 && (DateTime.Now.Month == 1 || DateTime.Now.Month == 3 || DateTime.Now.Month == 7 || DateTime.Now.Month == 10))
                        //{
                        //1- Identificar os registros ativos na entidade "Histórico de Ditribuidores" cuja data de início seja maior ou igual a data de início do trimestre
                        if (historico.DataInicio.HasValue && historico.DataInicio.Value.Date <= DateTime.Now.Date && historico.DataFim.HasValue && historico.DataFim.Value.Date >= DateTime.Now.Date)
                        {
                            RepositoryService.HistoricoDistribuidor.AlterarStatus(historico.ID.Value, 993520000); //Fluxo Concluído 993.520.000

                            //2- Nas revendas relacionadas à esses registros, alterar o valor do atributo "Distribuidor Preferencial" para registrar o novo distribuidor.
                            Conta conta = RepositoryService.Conta.Retrieve(historico.Revenda.Id);
                            conta.ID = historico.Revenda.Id;
                            RepositoryService.Conta.Update(conta);

                            //Cada alteração deverá disparar uma mensagem "MSG0072 - REGISTRA_CONTA" para atualizar os sistemas envolvidos.
                            string nomeAbrevMatriEconom = String.Empty;
                            string nomeAbrevRet         = String.Empty;
                            string codigoClienteRet     = String.Empty;
                            var    mensagem             = new Domain.Integracao.MSG0072(workflowContext.OrganizationName, workflowContext.IsExecutingOffline);
                            mensagem.Enviar(conta, ref nomeAbrevRet, ref codigoClienteRet, ref nomeAbrevMatriEconom);
                            controleExecucao = true;
                        }
                        else if (historico.DataFim.HasValue && historico.DataFim.Value.Date < DateTime.Now.Date)
                        {
                            RepositoryService.HistoricoDistribuidor.AlterarStatus(historico.ID.Value, 993520000); //Fluxo Concluído 993.520.000
                        }
                        else
                        {
                            //Mantém o registro ativo
                            RepositoryService.HistoricoDistribuidor.AlterarStatus(historico.ID.Value, 0);
                        }
                    }
                }
                if (!controleExecucao)
                {
                    //Mantém o registro ativo
                    RepositoryService.HistoricoDistribuidor.AlterarStatus(historico.ID.Value, 0);
                }
            }
            catch (Exception e)
            {
                SDKore.Helper.Error.Create(e, System.Diagnostics.EventLogEntryType.Information);
                throw new InvalidWorkflowException(e.Message + " :: " + e.StackTrace, e);
            }
        }