/// <inheritdoc /> protected override void Execute(Context context) { var query = FetchXml.Get(context); var result = context.Service.RetrieveMultiple(query); if (result.Entities.Count < 1) { return; } decimal resultAsDecimal = 0; foreach (var entity in result.Entities) { foreach (var attribute in entity.Attributes) { if (attribute.Value is decimal || attribute.Value is double || attribute.Value is int) { resultAsDecimal += Convert.ToDecimal(attribute.Value); } else if (attribute.Value is Money) { resultAsDecimal += ((Money)attribute.Value).Value; } } } ResultAsDecimal.Set(context, resultAsDecimal); ResultAsDouble.Set(context, Convert.ToDouble(resultAsDecimal)); ResultAsInteger.Set(context, Convert.ToInt32(resultAsDecimal)); ResultAsMoney.Set(context, new Money(resultAsDecimal)); }
protected void Execute(Context context, EntityReference ownerRef) { var fetchXml = FetchXml.Get(context); var entities = context.Service.RetrieveMultiple(fetchXml).Entities; var affectedEntities = 0; foreach (var entity in entities) { try { var request = new AssignRequest { Assignee = ownerRef, Target = entity.ToEntityReference() }; context.Service.Execute(request); affectedEntities++; } catch (Exception ex) { context.TracingService.Trace(ex); } } if (affectedEntities == 0) { SetError(context, "В процессе назначения записей произошли ошибки. Ни одна запись не назначена."); } else if (affectedEntities < entities.Count) { SetError(context, $"В процессе назначения записей произошли ошибки. Записей назначено: {affectedEntities}, записей не назначено: {entities.Count - affectedEntities}."); } AffectedEntities.Set(context, affectedEntities); }
protected override void Execute(Context context) { var query = FetchXml.Get(context); if (string.IsNullOrWhiteSpace(query)) { return; } var entities = context.Service.RetrieveMultiple(query).Entities; FindedCount.Set(context, entities.Count); if (entities.Count == 0) { DeletedCount.Set(context, 0); return; } var request = new ExecuteMultipleRequest { Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true }, Requests = new OrganizationRequestCollection() }; request.Requests.AddRange(entities.Select(entity => new DeleteRequest { Target = entity.ToEntityReference() })); var responses = (ExecuteMultipleResponse)context.Service.Execute(request); if (!responses.IsFaulted) { DeletedCount.Set(context, entities.Count); return; } var deletedCount = 0; var faults = new List <string>(); foreach (var response in responses.Responses) { if (response.Fault == null) { deletedCount++; } else { faults.Add(response.Fault.Message); } } DeletedCount.Set(context, deletedCount); throw new Exception(string.Join(" ", faults)); }
/// <inheritdoc /> protected override void Execute(Context context) { var query = FetchXml.Get(context); if (string.IsNullOrWhiteSpace(query)) { return; } var result = context.Service.RetrieveMultiple(query); ResultAsDecimal.Set(context, result.Entities.Count); ResultAsDouble.Set(context, Convert.ToDouble(result.Entities.Count)); ResultAsInteger.Set(context, Convert.ToInt32(result.Entities.Count)); }
/// <inheritdoc /> protected override void Execute(Context context) { var query = FetchXml.Get(context); if (string.IsNullOrWhiteSpace(query)) { return; } var result = context.Service.RetrieveMultiple(query); if (result.Entities.Count < 1) { return; } var values = new List <decimal>(); foreach (var entity in result.Entities) { foreach (var attribute in entity.Attributes) { if (attribute.Value is decimal || attribute.Value is double || attribute.Value is int) { values.Add(Convert.ToDecimal(attribute.Value)); } else if (attribute.Value is Money) { values.Add(((Money)attribute.Value).Value); } } } if (values.Count == 0) { return; } var sortedValues = values.OrderBy(number => number); var itemIndex = sortedValues.Count() / 2; var resultAsDecimal = sortedValues.Count() % 2 == 0 ? (sortedValues.ElementAt(itemIndex) + sortedValues.ElementAt(itemIndex - 1)) / 2 : sortedValues.ElementAt(itemIndex); ResultAsDecimal.Set(context, resultAsDecimal); ResultAsDouble.Set(context, Convert.ToDouble(resultAsDecimal)); ResultAsInteger.Set(context, Convert.ToInt32(resultAsDecimal)); ResultAsMoney.Set(context, new Money(resultAsDecimal)); }
private void PreviewLive(Entity view) { if (Live && Parent != null) { var service = ((IXrmToolBoxPluginControl)Parent).Service; if (service != null) { new Task(() => { var query = FetchXml; var queryAttributes = query.FirstChild.Attributes; XmlAttribute count; // Search for 'count' attribute, if any count = queryAttributes.Cast <XmlAttribute>().Where(x => x.Name == "count").FirstOrDefault(); if (count != null) { queryAttributes.Remove(count); } // Adding 'count' attribute to restrict output count = FetchXml.CreateAttribute("count"); count.Value = "50"; // Appending new attribute to query queryAttributes.Append(count); var result = service.RetrieveMultiple(new FetchExpression(query.InnerXml)); if (result != null) { Invoke(new Action(() => { Set(result.Entities); })); } }).Start(); } } }
/// <inheritdoc /> protected override void Execute(Context context) { Json.Set(context, null); var query = FetchXml.Get(context); var entity = context.SystemService.RetrieveMultiple(query).Entities.FirstOrDefault(); if (entity == null) { return; } Json.Set(context, JsonConvert.SerializeObject(new { entity.LogicalName, entity.Id, Attributes = entity.Attributes.ToDictionary(e => e.Key, e => e.Value), FormattedValues = entity.FormattedValues.ToDictionary(e => e.Key, e => e.Value) })); }
protected override void Execute(CodeActivityContext executionContext) { #region "Load CRM Service from context" Common objCommon = new Common(executionContext); objCommon.tracingService.Trace("ConcatenateFromQuery -- Start!"); #endregion #region "Read Parameters" var fetchXml = FetchXml.Get(executionContext); if (string.IsNullOrEmpty(fetchXml)) { return; } objCommon.tracingService.Trace($"FetchXML={fetchXml}"); var attributeFieldName = AttributeName.Get(executionContext); objCommon.tracingService.Trace($"AttributeName={attributeFieldName}"); var separator = Separator.Get(executionContext); objCommon.tracingService.Trace($"Separator={separator}"); var format = FormatString.Get(executionContext); objCommon.tracingService.Trace($"FormatString={format}"); IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); #endregion #region "Concatenation Execution" string pagingCookie = null; bool hasMoreRecords = false; bool canPerformPaging = fetchXml.IndexOf("top=", StringComparison.CurrentCultureIgnoreCase) < 0; int pageNumber = canPerformPaging ? 1 : 0; int fetchCount = canPerformPaging ? 250 : 0; List <string> stringValues = new List <string>(); do { objCommon.tracingService.Trace($"Fetch PageNumber={pageNumber}"); fetchXml = fetchXml.Replace("{PARENT_GUID}", context.PrimaryEntityId.ToString()); string xml = CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount); RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest { Query = new FetchExpression(xml) }; EntityCollection returnCollection = ((RetrieveMultipleResponse)objCommon.service.Execute(fetchRequest1)).EntityCollection; bool attributeNamesSentToTrace = false; foreach (var entity in returnCollection.Entities) { if (!entity.Attributes.Any()) { continue; } if (!attributeNamesSentToTrace) { var attributeNames = entity.Attributes.Select(a => a.Key).Aggregate((x, y) => x + "," + y); objCommon.tracingService.Trace($"List of attributes available: {attributeNames}"); attributeNamesSentToTrace = true; } object attribute = null; if (!string.IsNullOrEmpty(attributeFieldName)) { if (entity.Attributes.ContainsKey(attributeFieldName)) { attribute = entity.Attributes[attributeFieldName]; } } else { attribute = entity.Attributes.First().Value; } if (attribute == null) { continue; } if (attribute is AliasedValue) { attribute = ((AliasedValue)attribute).Value; } if (attribute is EntityReference) { attribute = ((EntityReference)attribute).Name; } else if (attribute is Money) { attribute = ((Money)attribute).Value; } else if (attribute is OptionSetValue) { attribute = ((OptionSetValue)attribute).Value; if (entity.FormattedValues.ContainsKey(attributeFieldName)) { attribute = entity.FormattedValues[attributeFieldName]; } } var attributeValueAsString = string.Format($"{{0:{format}}}", attribute); stringValues.Add(attributeValueAsString); } if (canPerformPaging && returnCollection.MoreRecords) { pageNumber++; pagingCookie = returnCollection.PagingCookie; hasMoreRecords = returnCollection.MoreRecords; } } while (hasMoreRecords); if (stringValues.Any()) { var concatenatedString = stringValues.Aggregate((x, y) => x + separator + y); objCommon.tracingService.Trace($"Concatenated string: {concatenatedString}"); ConcatenatedString.Set(executionContext, concatenatedString); } else { objCommon.tracingService.Trace("No data found to concatenate"); } objCommon.tracingService.Trace("ConcatenateFromQuery -- Done!"); #endregion }
/// <inheritdoc /> protected override void Execute(Context context) { var query = FetchXml.Get(context); if (string.IsNullOrWhiteSpace(query)) { return; } var result = context.Service.RetrieveMultiple(query); if (result.Entities.Count < 1) { return; } var entity = result.Entities.First(); var regex = new Regex(@"<attribute name=[""'](?<name>[^\s]+)[""']\s*/>", RegexOptions.IgnoreCase | RegexOptions.Multiline); var attributeName = regex.Matches(query).Cast <Match>().Select(match => match.Groups["name"].Value).FirstOrDefault(); if (attributeName == null) { ResultAsString.Set(context, entity.Id.ToString()); return; } if (entity.Attributes.Keys.All(a => a != attributeName)) { attributeName = entity.Attributes.Keys.FirstOrDefault(a => a.EndsWith($".{attributeName}")); } if (!entity.Contains(attributeName)) { return; } var attributeValue = entity.Attributes[attributeName]; if (attributeValue is AliasedValue) { attributeValue = ((AliasedValue)attributeValue).Value; } if (attributeValue is Money) { attributeValue = ((Money)attributeValue).Value; } if (attributeValue is EntityReference) { attributeValue = ((EntityReference)attributeValue).Id; } ResultAsString.Set(context, attributeValue.ToString()); if (attributeValue is DateTime) { ResultAsDateTime.Set(context, (DateTime)attributeValue); return; } if (attributeValue is OptionSetValue) { attributeValue = ((OptionSetValue)attributeValue).Value; // TODO: Получение метки элемента списка и отображение его в качестве текстового значения. ResultAsString.Set(context, attributeValue.ToString()); } if (attributeValue is bool || attributeValue is decimal || attributeValue is double || attributeValue is int) { var decimalValue = Convert.ToDecimal(attributeValue); ResultAsBoolean.Set(context, Convert.ToBoolean(attributeValue)); ResultAsDecimal.Set(context, decimalValue); ResultAsDouble.Set(context, Convert.ToDouble(attributeValue)); ResultAsInteger.Set(context, Convert.ToInt32(attributeValue)); ResultAsMoney.Set(context, new Money(decimalValue)); } }
/// <summary> /// SavedQueryView constructor /// </summary> /// <param name="serviceContext">OrganizationServiceContext</param> /// <param name="savedQuery">savedquery entity</param> /// <param name="fetchXmlString">Existing known FetchXML for this view</param> /// <param name="layoutXmlString">Existing known LayoutXML for this view</param> /// <param name="languageCode">Language code used to retrieve the localized attribute label</param> /// <param name="aliasColumnNameStringFormat">A format string used to compose an alias column label. Index 0 is the alias attribute display name, index 1 is the aliased entity's display name. Default is "{0} ({1})".</param> public SavedQueryView(OrganizationServiceContext serviceContext, Entity savedQuery, string fetchXmlString, string layoutXmlString, int?languageCode = 0, string aliasColumnNameStringFormat = DefaultAliasColumnNameStringFormat) { if (serviceContext == null) { throw new ArgumentNullException("serviceContext"); } if (savedQuery == null) { throw new ArgumentNullException("savedQuery"); } ServiceContext = serviceContext; SavedQuery = savedQuery; LanguageCode = languageCode ?? 0; AliasColumnNameStringFormat = aliasColumnNameStringFormat; if (string.IsNullOrEmpty(fetchXmlString)) { fetchXmlString = savedQuery.GetAttributeValue <string>("fetchxml"); } if (!string.IsNullOrEmpty(fetchXmlString)) { FetchXml = XElement.Parse(fetchXmlString); SortExpression = SetSortExpression(FetchXml); var entityElement = FetchXml.Element("entity"); if (entityElement != null) { var entityName = entityElement.Attribute("name").Value; EntityLogicalName = entityName; } var response = (RetrieveEntityResponse)ServiceContext.Execute(new RetrieveEntityRequest { LogicalName = EntityLogicalName, EntityFilters = EntityFilters.Attributes }); if (response == null || response.EntityMetadata == null) { ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Failed to get EntityMetadata for entity of type '{0}'.", EntityNamePrivacy.GetEntityName(EntityLogicalName))); return; } EntityMetadata = response.EntityMetadata; PrimaryKeyLogicalName = EntityMetadata.PrimaryIdAttribute; } if (string.IsNullOrEmpty(layoutXmlString)) { layoutXmlString = savedQuery.GetAttributeValue <string>("layoutxml"); } LayoutXml = XElement.Parse(layoutXmlString); var rowElement = LayoutXml.Element("row"); if (rowElement != null) { var cellNames = rowElement.Elements("cell") .Where(cell => cell.Attribute("ishidden") == null || cell.Attribute("ishidden").Value != "1") .Select(cell => cell.Attribute("name")).Where(name => name != null); CellNames = cellNames; var disabledSortCellNames = rowElement.Elements("cell") .Where(cell => cell.Attribute("disableSorting") != null && cell.Attribute("disableSorting").Value == "1") .Where(cell => cell.Attribute("name") != null) .Select(cell => cell.Attribute("name").Value); DisabledSortCellNames = disabledSortCellNames; var cellWidths = rowElement.Elements("cell") .Where(cell => cell.Attribute("ishidden") == null || cell.Attribute("ishidden").Value != "1") .Where(cell => cell.Attribute("name") != null) .ToDictionary(cell => cell.Attribute("name").Value, cell => Convert.ToInt32(cell.Attribute("width").Value)); CellWidths = cellWidths; } Name = ServiceContext.RetrieveLocalizedLabel(savedQuery.ToEntityReference(), "name", LanguageCode); Id = savedQuery.GetAttributeValue <Guid>("savedqueryid"); }
public override void DoAction(BaseSolution solution) { ActionStarted(); DynamicsSolution ds = (DynamicsSolution)solution; ds.Service.PublishAll(); if (!String.IsNullOrEmpty(FetchXml) && !String.IsNullOrEmpty(WorkflowId)) { // get all lines of fetch var fetchLines = FetchXml.Split('<'); //replace first line <fetch.... with <fetch {0}> for (int i = 0; i < fetchLines.Length; i++) { if (fetchLines[i].Contains("fetch")) { fetchLines[i] = "fetch {0}>"; break; } } FetchXml = String.Join("<", fetchLines); bool moreRecords; int page = 1; string cookie = string.Empty; int totalRecords = 0; int batch = 1000;//int.Parse(ConfigurationManager.AppSettings["batch"]); ExecuteMultipleRequest emr = new ExecuteMultipleRequest() { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings() { ContinueOnError = false, ReturnResponses = false } }; do { var xml = string.Format(FetchXml, cookie); var results = ds.Service.Service.RetrieveMultiple(new FetchExpression(xml)); totalRecords += results.Entities.Count; foreach (var r in results.Entities) { if (emr.Requests.Count == batch) { ds.Service.Service.Execute(emr); emr = new ExecuteMultipleRequest() { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings() { ContinueOnError = false, ReturnResponses = false } }; } emr.Requests.Add(new ExecuteWorkflowRequest { EntityId = r.Id, WorkflowId = Guid.Parse(WorkflowId) }); } if (emr.Requests.Any()) { ds.Service.Service.Execute(emr); emr = new ExecuteMultipleRequest() { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings() { ContinueOnError = false, ReturnResponses = false } }; } moreRecords = results.MoreRecords; if (moreRecords) { page++; cookie = string.Format("paging-cookie='{0}' page='{1}'", System.Security.SecurityElement.Escape(results.PagingCookie), page); } }while (moreRecords); LogInfo($"Processed {totalRecords} records"); } ActionCompleted(); }
protected override void Execute(CodeActivityContext context) { ITracingService trace = context.GetExtension <ITracingService>(); IWorkflowContext workflowContext = context.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = context.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId); var fetchXml = FetchXml.Get <string>(context); var returnType = FetchXml.Get <string>(context); var returnAttribute = FetchXml.Get <string>(context); if (string.IsNullOrWhiteSpace(fetchXml)) { trace.Trace("fetch xml is null"); return; } if (string.IsNullOrWhiteSpace(returnType)) { trace.Trace("return type is null"); return; } if (string.IsNullOrWhiteSpace(returnAttribute)) { trace.Trace("return attribute is null."); return; } var query = new FetchExpression(fetchXml); var response = service.RetrieveMultiple(query); if (response == null || response.Entities == null || response.Entities.Count == 0) { trace.Trace("response is null"); return; } if (!response.Entities[0].Contains(returnAttribute)) { trace.Trace("response doesnt have the requested attribute."); return; } if (response.Entities[0][returnAttribute] == null) { trace.Trace("returned object is null"); return; } if (returnType.Equals("bool", StringComparison.OrdinalIgnoreCase)) { trace.Trace("setting boolean value."); ReturnValueBool.Set(context, (bool)response.Entities[0][returnAttribute]); } if (returnType.Equals("int", StringComparison.OrdinalIgnoreCase)) { trace.Trace("setting integer value."); ReturnValueInt.Set(context, (int)response.Entities[0][returnAttribute]); } if (returnType.Equals("string", StringComparison.OrdinalIgnoreCase)) { trace.Trace("setting string value."); ReturnValueString.Set(context, response.Entities[0][returnAttribute].ToString()); } }