示例#1
0
        protected override void Execute(System.Activities.CodeActivityContext context)
        {
            DataTable table = this.ExecuteQuery(context);

            if (table.Columns == null || table.Columns.Count == 0)
            {
                throw new ArgumentException("Query result must have at least one column");
            }


            List <decimal> inputValues = new List <decimal>();

            for (int rowNumber = 0; rowNumber < table.Rows.Count; rowNumber++)
            {
                decimal parsedValue = 0;
                if (decimal.TryParse(table.Rows[rowNumber][1].ToString(), out parsedValue))
                {
                    inputValues.Add(parsedValue);
                }
            }

            this.NumberOfItems.Set(context, inputValues.Count);
            if (inputValues.Any())
            {
                this.Mean.Set(context, this.RoundValue(context, inputValues.Average()));
                this.Median.Set(context, this.RoundValue(context, this.CalculateMedian(inputValues)));
                this.Highest.Set(context, this.RoundValue(context, inputValues.Max()));
                this.Lowest.Set(context, this.RoundValue(context, inputValues.Min()));
                this.StandardDeviation.Set(context, this.RoundValue(context, CalculateStandardDeviation(inputValues)));
            }
        }
        protected override void Execute(System.Activities.CodeActivityContext context)
        {
            var workflowContext = context.GetExtension <IWorkflowContext>();
            var service         = this.RetrieveOrganizationService(context);

            Entity email = service.Retrieve("email", this.Email.Get(context).Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("statuscode"));

            if (email["statuscode"] == null || email.GetAttributeValue <OptionSetValue>("statuscode").Value != 1)
            {
                throw new ArgumentException("Email must be in Draft status.");
            }

            SendEmailRequest sendEmailrequest = new SendEmailRequest
            {
                EmailId       = email.Id,
                TrackingToken = "",
                IssueSend     = true
            };

            try
            {
                SendEmailResponse sendEmailresponse = (SendEmailResponse)service.Execute(sendEmailrequest);
            }
            catch (Exception ex)
            {
                throw new Exception($"Exception on SendEmailResponse - {ex.Message}");
            }
        }
        protected override void Execute(System.Activities.CodeActivityContext context)
        {
            var workflowContext = context.GetExtension <IWorkflowContext>();
            var service         = this.RetrieveOrganizationService(context);

            QueryResult result   = ExecuteQueryForRecords(context);
            Entity      workflow = service.Retrieve("workflow", this.Workflow.Get(context).Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("primaryentity"));

            if (workflow.GetAttributeValue <string>("primaryentity").ToLower() != result.EntityName)
            {
                throw new ArgumentException($"Workflow entity ({workflow.GetAttributeValue<string>("primaryentity")} does not match query entity ({result.EntityName})");
            }

            int numberStarted = 0;

            foreach (Guid id in result.RecordIds)
            {
                try
                {
                    ExecuteWorkflowRequest request = new ExecuteWorkflowRequest()
                    {
                        EntityId = id, WorkflowId = workflow.Id
                    };
                    ExecuteWorkflowResponse response = service.Execute(request) as ExecuteWorkflowResponse;
                }
                catch (Exception ex)
                {
                    throw new Exception($"Error initiating workflow on record with ID = {id}; {ex.Message}");
                }
                numberStarted++;
            }
            this.NumberOfWorkflowsStarted.Set(context, numberStarted);
        }
示例#4
0
        protected override void Execute(System.Activities.CodeActivityContext context)
        {
            var workflowContext = context.GetExtension <IWorkflowContext>();
            var service         = this.RetrieveOrganizationService(context);

            QueryResult queryResult = ExecuteQueryForRecords(context);

            Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest metadataRequest = new Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest()
            {
                LogicalName = workflowContext.PrimaryEntityName, EntityFilters = EntityFilters.Relationships
            };
            var metadataResponse = service.Execute(metadataRequest) as Microsoft.Xrm.Sdk.Messages.RetrieveEntityResponse;
            var relationship     = metadataResponse.EntityMetadata.ManyToManyRelationships.FirstOrDefault(m =>
                                                                                                          m.SchemaName.Equals(RelationshipName.Get(context), StringComparison.InvariantCultureIgnoreCase) ||
                                                                                                          m.IntersectEntityName.Equals(RelationshipName.Get(context), StringComparison.InvariantCultureIgnoreCase));

            if (relationship == null)
            {
                throw new Exception($"Entity '{workflowContext.PrimaryEntityName}' does not have relationship with schema name or relationship entity name '{RelationshipName.Get(context)}'");
            }

            QueryExpression qe = new QueryExpression(relationship.IntersectEntityName);

            qe.Criteria.AddCondition(relationship.Entity1IntersectAttribute, ConditionOperator.Equal, workflowContext.PrimaryEntityId);
            qe.ColumnSet = new ColumnSet(relationship.Entity2IntersectAttribute);
            var alreadyAssociated = service.RetrieveMultiple(qe).Entities.Select(e => (Guid)e[relationship.Entity2IntersectAttribute]);

            var delta = queryResult.RecordIds.Except(alreadyAssociated).Select(id => new EntityReference(relationship.Entity2LogicalName, id)).ToList();

            service.Associate(workflowContext.PrimaryEntityName, workflowContext.PrimaryEntityId, new Relationship(relationship.SchemaName), new EntityReferenceCollection(delta));

            NumberOfRelationshipChanges.Set(context, delta.Count);
        }
        protected override void Execute(System.Activities.CodeActivityContext context)
        {
            var workflowContext = context.GetExtension <IWorkflowContext>();
            var service         = this.RetrieveOrganizationService(context);

            DateTime utcDateTime = this.DateToEvaluate.Get(context);

            if (utcDateTime.Kind != DateTimeKind.Utc)
            {
                utcDateTime = utcDateTime.ToUniversalTime();
            }

            TimeZoneSummary             timeZone = StaticMethods.CalculateTimeZoneToUse(this.TimeZoneOption.Get(context), workflowContext, service);
            LocalTimeFromUtcTimeRequest timeZoneChangeRequest = new LocalTimeFromUtcTimeRequest()
            {
                UtcTime = utcDateTime, TimeZoneCode = timeZone.MicrosoftIndex
            };
            LocalTimeFromUtcTimeResponse timeZoneResponse = service.Execute(timeZoneChangeRequest) as LocalTimeFromUtcTimeResponse;
            DateTime adjustedDateTime = timeZoneResponse.LocalTime;

            switch (adjustedDateTime.DayOfWeek)
            {
            case System.DayOfWeek.Sunday:
                this.DayOfWeekPick.Set(context, new OptionSetValue(222540000));
                break;

            case System.DayOfWeek.Monday:
                this.DayOfWeekPick.Set(context, new OptionSetValue(222540001));
                break;

            case System.DayOfWeek.Tuesday:
                this.DayOfWeekPick.Set(context, new OptionSetValue(222540002));
                break;

            case System.DayOfWeek.Wednesday:
                this.DayOfWeekPick.Set(context, new OptionSetValue(222540003));
                break;

            case System.DayOfWeek.Thursday:
                this.DayOfWeekPick.Set(context, new OptionSetValue(222540004));
                break;

            case System.DayOfWeek.Friday:
                this.DayOfWeekPick.Set(context, new OptionSetValue(222540005));
                break;

            case System.DayOfWeek.Saturday:
                this.DayOfWeekPick.Set(context, new OptionSetValue(222540006));
                break;
            }
            this.DayOfWeekName.Set(context, adjustedDateTime.DayOfWeek.ToString());
            this.DayOfMonth.Set(context, adjustedDateTime.Day);
            this.DayOfYear.Set(context, adjustedDateTime.DayOfYear);
            this.HourOfDay023.Set(context, adjustedDateTime.Hour);
            this.Minute.Set(context, adjustedDateTime.Minute);
            this.MonthOfYearInt.Set(context, adjustedDateTime.Month);
            this.MonthOfYearPick.Set(context, new OptionSetValue(222540000 + adjustedDateTime.Month - 1));
            this.MonthOfYearName.Set(context, System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(adjustedDateTime.Month));
            this.Year.Set(context, adjustedDateTime.Year);
        }
示例#6
0
        protected override void Execute(System.Activities.CodeActivityContext context)
        {
            var workflowContext = context.GetExtension <IWorkflowContext>();
            var service         = this.RetrieveOrganizationService(context);

            QueryResult result = ExecuteQueryForRecords(context);

            if (!result.EntityName.Equals("systemuser", StringComparison.InvariantCultureIgnoreCase) &&
                !result.EntityName.Equals("team", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Query must return a User or Team record");
            }

            // Ensure the record has an owner field
            RetrieveEntityRequest request = new Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest()
            {
                EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Entity,
                LogicalName   = workflowContext.PrimaryEntityName
            };
            RetrieveEntityResponse metadataResponse = service.Execute(request) as RetrieveEntityResponse;

            if (metadataResponse.EntityMetadata.OwnershipType == null || metadataResponse.EntityMetadata.OwnershipType.Value != OwnershipTypes.UserOwned)
            {
                throw new ArgumentException("This activity is only available for User owned records");
            }

            if (!result.RecordIds.Any())
            {
                return;
            }

            var           workflowRecord = new EntityReference(workflowContext.PrimaryEntityName, workflowContext.PrimaryEntityId);
            var           assignee       = new EntityReference(result.EntityName, result.RecordIds.FirstOrDefault());
            AssignRequest assignRequest  = new AssignRequest()
            {
                Assignee = assignee,
                Target   = workflowRecord
            };

            try
            {
                AssignResponse response = service.Execute(assignRequest) as AssignResponse;
                if (assignee.LogicalName.Equals("team"))
                {
                    this.NewOwner_Team.Set(context, assignee);
                }
                else
                {
                    this.NewOwner_User.Set(context, assignee);
                }
                this.RecordReassigned.Set(context, true);
            }
            catch (Exception ex)
            {
                throw new Exception($"There was an error reassigning the record: {ex.Message}");
            }
        }
        protected override void Execute(System.Activities.CodeActivityContext context)
        {
            var workflowContext = context.GetExtension <IWorkflowContext>();
            var service         = this.RetrieveOrganizationService(context);

            string emailField = "to";

            switch (this.EmailRecipientField.Get(context).Value)
            {
            case 222540001:
                emailField = "cc";
                break;

            case 222540002:
                emailField = "bcc";
                break;

            default:
                break;
            }

            Entity email = service.Retrieve("email", this.Email.Get(context).Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(emailField, "statuscode"));

            if (email["statuscode"] == null || email.GetAttributeValue <OptionSetValue>("statuscode").Value != 1)
            {
                throw new ArgumentException("Email must be in Draft status.");
            }

            QueryResult result          = ExecuteQueryForRecords(context);
            int         recipientsAdded = result.RecordIds.Count();


            if (result.RecordIds.Any())
            {
                List <Entity> recipients = new List <Entity>();
                if (email[emailField] != null && ((Microsoft.Xrm.Sdk.EntityCollection)email[emailField]).Entities != null && ((Microsoft.Xrm.Sdk.EntityCollection)email[emailField]).Entities.Any())
                {
                    recipients.AddRange(((EntityCollection)email[emailField]).Entities.ToList());
                }

                foreach (Guid id in result.RecordIds)
                {
                    if (!recipients.Any(r => ((EntityReference)(r["partyid"])).Id == id && ((EntityReference)(r["partyid"])).LogicalName == result.EntityName))
                    {
                        Entity party = new Entity("activityparty");
                        party["partyid"] = new EntityReference(result.EntityName, id);
                        recipients.Add(party);
                        recipientsAdded++;
                    }
                }

                email[emailField] = recipients.ToArray();
            }
            service.Update(email);
            NumberOfRecipientsAdded.Set(context, recipientsAdded);
        }
        protected override void DoExecute(System.Activities.CodeActivityContext context)
        {
            devlog.Debug(string.Format("Called on '{0}'and  '{1}'", CalDAVEvent, AdapterId));
            var myExchangeAppointment = CalDAVEvent.Get(context);
            var myAdapterId           = AdapterId.Get(context);

            devlog.Debug(string.Format("Got '{0}' and  '{1}'", myExchangeAppointment, myAdapterId));
            var dto = Repository.ConvertToDTO(myExchangeAppointment, myAdapterId);

            AdapterAppointment.Set(context, dto);
        }
示例#9
0
        protected override void DoExecute(System.Activities.CodeActivityContext context)
        {
            devlog.Debug(string.Format("Called on '{0}'and  '{1}'", AdapterAppointment, ServiceAccountId));
            var myAdapterAppointment  = AdapterAppointment.Get(context);
            var myServiceAccountId    = ServiceAccountId.Get(context);
            var myOriginalAppointment = OriginalCalDAVEvent.Get(context);

            devlog.Debug(string.Format("Got '{0}' and  '{1}' and '{2}'", myAdapterAppointment, myServiceAccountId, myOriginalAppointment));
            var Appointment = Repository.ConvertFromDTO(myAdapterAppointment, myServiceAccountId, myOriginalAppointment);

            CalDAVEvent.Set(context, Appointment);
        }
        protected override void DoExecute(System.Activities.CodeActivityContext context)
        {
            var internalId = InternalId.Get(context);

            devlog.DebugFormat("Entered for '{0}'", internalId);
            var found = Repository.EventByInternalId(internalId);

            try
            {
                CalDAVEvent.Set(context, found.Value);
                devlog.DebugFormat("found '{0}'", found.Value);
            }
            catch (NullReferenceException)
            {
                CalDAVEvent.Set(context, null);
                devlog.DebugFormat("found nothing");
            }
        }
        protected override void Execute(System.Activities.CodeActivityContext context)
        {
            var workflowContext = context.GetExtension <IWorkflowContext>();
            var service         = this.RetrieveOrganizationService(context);

            int day = this.Day.Get(context);

            if (day <= 0 || day > 31)
            {
                throw new ArgumentOutOfRangeException("Day outside of valid range (1 - 31)");
            }
            int month = this.MonthOfYearInt.Get(context);

            if (month < 1 || month > 12)
            {
                month = this.MonthOfYearPick.Get(context).Value - 222540000 + 1;
            }

            int year   = this.Year.Get(context);
            int hour   = this.HourOfDay023.Get(context);
            int minute = this.Minute.Get(context);

            DateTime parsedDate = DateTime.MinValue;

            try
            {
                parsedDate = new DateTime(year, month, day, hour, minute, 0, DateTimeKind.Unspecified);
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Error parsing date: " + ex.Message);
            }

            TimeZoneSummary             timeZone = StaticMethods.CalculateTimeZoneToUse(this.TimeZoneOption.Get(context), workflowContext, service);
            UtcTimeFromLocalTimeRequest timeZoneChangeRequest = new UtcTimeFromLocalTimeRequest()
            {
                LocalTime = parsedDate, TimeZoneCode = timeZone.MicrosoftIndex
            };
            UtcTimeFromLocalTimeResponse timeZoneResponse = service.Execute(timeZoneChangeRequest) as UtcTimeFromLocalTimeResponse;
            DateTime adjustedDateTime = timeZoneResponse.UtcTime;

            this.ModifiedDate.Set(context, adjustedDateTime);
        }
        protected override void Execute(System.Activities.CodeActivityContext context)
        {
            var workflowContext = context.GetExtension <IWorkflowContext>();
            var service         = this.RetrieveOrganizationService(context);

            this.ValidateColorCode(this.Table_BorderColor.Get(context), "Table - Border Color");
            this.ValidateColorCode(this.Header_BackgroundColor.Get(context), "Header - Background Color");
            this.ValidateColorCode(this.Header_FontColor.Get(context), "Header - Font Color");
            this.ValidateColorCode(this.Row_BackgroundColor.Get(context), "Row - Background Color");
            this.ValidateColorCode(this.Row_FontColor.Get(context), "Row - Font Color");
            this.ValidateColorCode(this.AlternatingRow_BackgroundColor.Get(context), "Alternating Row - Background Color");
            this.ValidateColorCode(this.AlternatingRow_FontColor.Get(context), "Alternating Row - Font Color");

            DataTable table = this.BuildDataTable(context, workflowContext, service);

            this.NumberOfFields.Set(context, table.Rows.Count);
            this.BuildResultsAsHtml(table, context, service);
            this.BuildResultsAsCsv(table, context);
        }
 /// <summary>
 /// Execute method manages process of destroying a given Deployment based on the ID specified
 /// </summary>
 /// <param name="context">Windows Workflow Foundation CodeActivity runtime context</param>
 protected override void Execute(System.Activities.CodeActivityContext context)
 {
 }
        protected override bool Execute(System.Activities.CodeActivityContext context)
        {
            Error.Set(context, null);

            if (string.IsNullOrEmpty(Args))
            {
                Error.Set(context, "Не определены объекты для которых будет сформирован отчет");
                return(false);
            }

            MultiPsSelectedArgs args;

            try
            {
                args = Args.DeserializeFromString <MultiPsSelectedArgs>();
            }
            catch (Exception ex)
            {
                Error.Set(context, "Ошибка преобразования параметров " + ex.Message);
                return(false);
            }

            args.DtStart = StartDateTime.Get(context); //Начальная дата
            args.DtEnd   = EndDateTime.Get(context);   //Конечная дата
            var reportUn = Report_id.Get(context);

            var businessObjectName = string.Empty; //Определяем какой бизнес объект используется в отчете

            try
            {
                try
                {
                    if (!string.IsNullOrEmpty(reportUn))
                    {
                        businessObjectName = ServiceFactory.StimulReportInvokeSync <string>("GetUsedBusinessObjectsNames", reportUn);
                    }
                }
                catch (Exception ex)
                {
                    Error.Set(context, "Ошибка запроса бизнес модели отчета " + ex.Message);
                    return(false);
                }

                BusinessObjectHelper.BuildBusinessObjectsParams(businessObjectName, args);

                var errs       = new StringBuilder();
                var compressed = StimulReportsProcedures.LoadDocument(Report_id.Get(context), errs, args, ReportFormat, args.TimeZoneId);
                if (errs.Length > 0)
                {
                    Error.Set(context, errs.ToString());
                }


                if (compressed == null)
                {
                    Error.Set(context, "Ошибка загрузки документа");
                    return(false);
                }

                SendEmail(context, CompressUtility.DecompressGZip(compressed));
            }
            catch (Exception ex)
            {
                Error.Set(context, ex.Message);
                if (!HideException.Get(context))
                {
                    throw ex;
                }
            }

            return(string.IsNullOrEmpty(Error.Get(context)));
        }
示例#15
0
 internal abstract object InternalExecuteInResolutionContextUntyped(CodeActivityContext resolutionContext);
 public CodeActivityContext(System.Activities.CodeActivityContext context, OutArgument<string[]> buildErrors)
 {
     _context = context;
     _buildErrors = buildErrors;
 }
 protected abstract TResult Execute(CodeActivityContext context);
 public Transaction GetCurrentTransaction(CodeActivityContext context)
 {
     return(GetCurrentTransactionCore(context));
 }
示例#19
0
 protected abstract void Execute(CodeActivityContext context);