コード例 #1
1
        private static EntityCollection WebresourceResult(OrganizationService orgService, string filename)
        {
            string fetchXml = string.Format(@"<fetch mapping='logical' version='1.0' >
                            <entity name='webresource' >
                                <attribute name='webresourceid' />
                                <attribute name='name' />
                                <attribute name='displayname' />
                                <filter type='and' >
                                    <condition attribute='name' operator='eq' value='{0}' />
                                </filter>
                            </entity>
                        </fetch>", filename);

            QueryBase query = new FetchExpression(fetchXml);

            var webresourceResult = orgService.RetrieveMultiple(query);
            return webresourceResult;
        }
        private static EntityCollection fetchAllRequests(IOrganizationService _service)
        {
            string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                  <entity name='ldv_launchrequest'>
                                    <attribute name='ldv_launchrequestid' />
                                    <attribute name='ldv_name' />
	                                <attribute name='ldv_customerid' />
                                    <attribute name='ldv_unitid' />
                                    <attribute name='ldv_prioritycode' />
                                    <attribute name='ldv_statuscode' />
                                    <order attribute='ldv_name' descending='false' />
                                    <filter type='and'>
                                      <condition attribute='ldv_statuscode' operator='eq' value='1' />
                                    </filter>
                                    <link-entity name='new_unit' from='new_unitid' to='ldv_unitid' link-type='inner' alias='aa'>
                                      <filter type='and'>
                                        <condition attribute='ohd_substatus' operator='eq' value='1' />
                                      </filter>
                                      <link-entity name='new_project' from='new_projectid' to='new_project' link-type='inner' alias='ab'>
                                        <filter type='and'>
                                          <condition attribute='ldv_launch' operator='eq' value='1' />
                                        </filter>
                                      </link-entity>
                                    </link-entity>
                                  </entity>
                                </fetch>";

            // Run the query with the FetchXML.
            var fetchExpression          = new FetchExpression(fetchXml);
            EntityCollection fetchResult =
                _service.RetrieveMultiple(fetchExpression);

            return(fetchResult);
        }
コード例 #3
0
ファイル: CrmService.cs プロジェクト: HansRoelants1979/Test
        public Collection <tcm.Gateway> GetGateways()
        {
            var             fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='tc_gateway'>
                                <attribute name='tc_iata' />
                                <attribute name='tc_gatewayid' />
                              </entity>
                            </fetch>";
            FetchExpression exp      = new FetchExpression(fetchXml);
            var             records  = orgService.RetrieveMultiple(exp);

            if (records == null || records.Entities.Count == 0)
            {
                return(null);
            }

            var gateways = new Collection <tcm.Gateway>();

            foreach (var item in records.Entities)
            {
                gateways.Add(new Models.Gateway {
                    Code = item["tc_iata"].ToString(), Id = item.Id.ToString()
                });
            }
            ;

            return(gateways);
        }
コード例 #4
0
ファイル: CrmService.cs プロジェクト: HansRoelants1979/Test
        public Collection <tcm.TourOperator> GetTourOperators()
        {
            var             fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='tc_touroperator'>
                                <attribute name='tc_touroperatorcode' />
                                <attribute name='tc_touroperatorid' />
                              </entity>
                            </fetch>";
            FetchExpression exp      = new FetchExpression(fetchXml);
            var             records  = orgService.RetrieveMultiple(exp);

            if (records == null || records.Entities.Count == 0)
            {
                return(null);
            }

            var tourOperators = new Collection <tcm.TourOperator>();

            foreach (var item in records.Entities)
            {
                tourOperators.Add(new Models.TourOperator {
                    Code = item["tc_touroperatorcode"].ToString(), Id = item.Id.ToString()
                });
            }
            ;

            return(tourOperators);
        }
コード例 #5
0
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                if (context.InputParameters.Contains("WebResource"))
                {
                    EntityReference webResourceRef = (EntityReference)context.InputParameters["WebResource"];
                    Entity          webResource    = service.Retrieve(webResourceRef.LogicalName, webResourceRef.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));

                    if (webResource.Contains("description") && webResource["description"] != null)
                    {
                        string description = (string)webResource["description"];
                        var    resource    = Common.ResourceFromString(description);

                        string content = Common.GetAttribute <string>(webResource, null, "content");
                        string fetchXml;
                        string data;
                        Common.ParseContent(content, out fetchXml, out data);
                        if (String.IsNullOrEmpty(fetchXml))
                        {
                            fetchXml = resource.fetchxml;
                        }

                        var fe              = new FetchExpression(fetchXml);
                        var result          = service.RetrieveMultiple(fe).Entities.ToList();
                        var updatedResource = new Entity(webResource.LogicalName);
                        updatedResource.Id             = webResource.Id;
                        updatedResource["content"]     = Common.PackContent(fetchXml, Common.SerializeEntityList(result));
                        resource.modifiedon            = Common.CurrentTime();
                        updatedResource["description"] = Common.ResourceToString(resource);
                        service.Update(updatedResource);
                    }

                    /*
                     * string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                     * <entity name='account'>
                     * <all-attributes/>
                     *
                     * <order attribute='name' descending='false' />
                     * <filter type='and'>
                     * <condition attribute='accountid' operator='in'>
                     * <value uiname='Client 1' uitype='account'>{0DE2A620-15F4-E711-93FE-00155D00C101}</value>
                     * <value uiname='Client 2' uitype='account'>{12E2A620-15F4-E711-93FE-00155D00C101}</value>
                     * </condition>
                     * </filter>
                     * </entity>
                     * </fetch>";
                     */
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
コード例 #6
0
ファイル: CrmService.cs プロジェクト: HansRoelants1979/Test
        public Collection <tcm.Currency> GetCurrencies()
        {
            var             fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='transactioncurrency'>
                                <attribute name='transactioncurrencyid' />
                                <attribute name='isocurrencycode' />
                              </entity>
                            </fetch>";
            FetchExpression exp      = new FetchExpression(fetchXml);
            var             records  = orgService.RetrieveMultiple(exp);

            if (records == null || records.Entities.Count == 0)
            {
                return(null);
            }

            var currencies = new Collection <tcm.Currency>();

            foreach (var item in records.Entities)
            {
                currencies.Add(new Models.Currency {
                    Code = item["isocurrencycode"].ToString(), Id = item.Id.ToString()
                });
            }
            ;

            return(currencies);
        }
コード例 #7
0
        public static EntityCollection RetrieveMultipleRecordsFetchXml(string query, IOrganizationService service)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                return(null);
            }
            if (service == null)
            {
                return(null);
            }
            EntityCollection entityCollection = new EntityCollection();

            int    fetchCount   = 10000;
            int    pageNumber   = 1;
            string pagingCookie = null;

            while (true)
            {
                string           xml              = CreateXml(query, pagingCookie, pageNumber, fetchCount);
                FetchExpression  fetch            = new FetchExpression(xml);
                EntityCollection returnCollection = service.RetrieveMultiple(fetch);
                entityCollection.Entities.AddRange(returnCollection.Entities);
                if (returnCollection.MoreRecords)
                {
                    pageNumber++;
                }
                else
                {
                    break;
                }
            }

            return(entityCollection);
        }
コード例 #8
0
 public static Guid GetLookupValue(object recordId, string entityName, string relatedAttribute, string matchValue, log4net.ILog log)
 {
     try
     {
         if (lookups.ContainsKey(matchValue))
         {
             return(lookups[matchValue]);
         }
         string           fetch      = string.Format(@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                   <entity name='{0}'>
                                     <attribute name='{1}' />
                                     <filter type='and'>
                                       <condition attribute='{2}' operator='eq' value='{3}' />
                                     </filter>
                                   </entity>
                                 </fetch>", entityName, entityName + "id", relatedAttribute, System.Security.SecurityElement.Escape(matchValue));
         FetchExpression  fetchQuery = new FetchExpression(fetch);
         EntityCollection results    = serviceProxy.RetrieveMultiple(fetchQuery);
         lookups.Add(matchValue, results.Entities[0].Id);
         return(results.Entities[0].Id);
     }
     catch (Exception ex)
     {
         log.Error("Record Id : " + recordId + " Related to  " + entityName + "  " + " Attribute " + relatedAttribute + " Value " + matchValue + " " + ex.Message.ToString());
         throw ex;
     }
 }
コード例 #9
0
        /// <summary>
        /// Adds dependent columns to a retrieval
        /// </summary>
        /// <param name="fetchExpression">The fetch expression</param>
        /// <param name="entityLogicalName">The entity logical name</param>
        /// <param name="dependentColumns">The dependent columns</param>
        private static void AddColumns(FetchExpression fetchExpression, string entityLogicalName, PluginManager.DependentColumn[] dependentColumns)
        {
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(fetchExpression.Query);
            foreach (XmlNode entity in xmlDocument.SelectNodes(string.Format("//entity[@name='{0}']", entityLogicalName)))
            {
                if (entity.SelectSingleNode("all-attributes") == null)
                {
                    HashSet <string> columns = new HashSet <string>();
                    foreach (DependentColumn dependentColumn in dependentColumns)
                    {
                        if (entity.SelectSingleNode(string.Format("attribute[@name='{0}']", dependentColumn.Column)) != null)
                        {
                            foreach (string column in dependentColumn.DependentColumns)
                            {
                                columns.Add(column);
                            }
                        }
                    }

                    foreach (string column in columns)
                    {
                        if (entity.SelectSingleNode(string.Format("attribute[@name='{0}']", column)) == null)
                        {
                            XmlNode attributeNode = xmlDocument.CreateNode(XmlNodeType.Element, "attribute", entity.NamespaceURI);
                            attributeNode.Attributes.Append(xmlDocument.CreateAttribute("name"));
                            attributeNode.Attributes["name"].Value = column;
                            entity.InsertAfter(attributeNode, entity.SelectSingleNode("attribute[last()]"));
                        }
                    }
                }
            }
            fetchExpression.Query = xmlDocument.OuterXml;
        }
コード例 #10
0
        public EntityCollection RetrieveMultipleWithPagination(FetchExpression fetchXml)
        {
            bool             moreRecords      = true;
            int              fetchCount       = 5000;
            int              pageNumber       = 1;
            string           pagingCookie     = null;
            EntityCollection entityCollection = new EntityCollection();

            while (moreRecords)
            {
                fetchXml = new FetchExpression(CreateXml(fetchXml.Query.ToString(), pagingCookie, pageNumber, fetchCount));

                var result = this.RetrieveMultiple(fetchXml);

                entityCollection.Entities.AddRange(result.Entities);

                moreRecords = result.MoreRecords;
                if (moreRecords)
                {
                    pageNumber++;
                    pagingCookie = result.PagingCookie;
                }
            }

            if (entityCollection.Entities.Count > 0)
            {
                return(entityCollection);
            }
            else
            {
                return(new EntityCollection());
            }
        }
コード例 #11
0
        internal void RetrieveProductInfo_FetchXML()
        {
            //建立JOIN查詢
            FetchExpression productsFetchQuery = new FetchExpression(@"
            <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                <entity name='product'>
                <attribute name='name'/>
                <attribute name='productnumber'/>
                <attribute name='statecode'/>
                <attribute name='productstructure'/>
                <order attribute='productnumber' descending='false'/>
                <link-entity name='product' from='productid' to='parentproductid' alias='ae'>
                    <attribute name='name'/>
                    <attribute name='productnumber'/>
                    <filter type='and'>
                    <condition attribute='name' operator='eq' value='觸控面板烤爐'/>
                    </filter>
                </link-entity>
                </entity>
            </fetch>
            ");

            var products = _orgService.RetrieveMultiple(productsFetchQuery).Entities;

            //取得查詢實體的欄位資料
            var categoryPN   = (AliasedValue)products[0].Attributes["ae.productnumber"];
            var categoryName = (AliasedValue)products[0].Attributes["ae.name"];

            onLog(string.Format("Product Family => ({0}) {1}", categoryPN.Value, categoryName.Value));

            foreach (Product prod in products)
            {
                onLog(string.Format("Product => ({0}) {1}", prod.ProductNumber, prod.Name));
            }
        }
        /// <summary>
        /// Execute FetchXMl query to retrieve related data
        /// </summary>
        /// <param name="relatedQuery">Related query</param>
        /// <param name="primaryEntity">primary entity</param>
        /// <param name="parameters">list of parameters attribute</param>
        /// <param name="filter">list of filter which need to apply</param>
        /// <param name="service">organization service</param>
        /// <returns>collection of related entities</returns>
        internal static EntityCollection RetrieveRelatedEntity(Entity relatedQuery, Entity primaryEntity, Dictionary <string, dynamic> parameters, List <QueryFilter> filter, IOrganizationService service)
        {
            if (relatedQuery.Contains("didd_query") && relatedQuery.Contains("didd_sequencenumber"))
            {
                // Query string in from of fetchXMl
                string queryString = Convert.ToString(relatedQuery.Attributes["didd_query"], CultureInfo.InvariantCulture);

                // Replace Placeholder in query string
                string query = NotificationTokenReplacer.ReplacePlaceHolders(null, primaryEntity, parameters, string.Empty, queryString);

                // get filter to apply for query string
                var queryFilter = filter.Where(x => x.SequenceNumber == (int)relatedQuery.Attributes["didd_sequencenumber"]).OrderBy(o => o.SubsequenceNumber).ToList <QueryFilter>();

                // add filter in query string
                List <string> param = new List <string>();
                foreach (var lst in queryFilter)
                {
                    param.Add(lst.Value);
                }

                // Execute query string
                FetchExpression fetchQuery = new FetchExpression(string.Format(CultureInfo.InvariantCulture, query, param.ToArray <string>()));
                return(service.RetrieveMultiple(fetchQuery));
            }
            else
            {
                throw new InvalidPluginExecutionException(string.Format(CultureInfo.InvariantCulture, "Notification Template Data Query is not configured properly. Please contact administrator."));
            }
        }
コード例 #13
0
        public void RetrieveAll_FetchExpression_Typed()
        {
            //Arrange
            int    totalRecords        = 5010;
            string distinctAccountName = Guid.NewGuid().ToString();

            List <Entity> accounts = new List <Entity>();

            for (int i = 0; i < totalRecords; i++)
            {
                accounts.Add(new Account()
                {
                    Id   = Guid.NewGuid(),
                    Name = distinctAccountName
                });
            }
            _context.Initialize(accounts);

            //Act
            var             fetchXml = $@"
                <fetch>
                  <entity name='account'>
                    <attribute name='name' />
                  </entity>
                </fetch>";
            FetchExpression fe       = new FetchExpression(fetchXml);

            IEnumerable <Account> results = _service.RetrieveAll <Account>(fe);

            //Assert
            Assert.Equal(totalRecords, results.Count());
        }
コード例 #14
0
        public int CountNNRelationship(string relationshipName, string countIdName)
        {
            string numberAlias = "numberofentities";

            XDocument xDocument = new XDocument(
                new XElement("fetch", new XAttribute("aggregate", true),
                             new XElement("entity", new XAttribute("name", entityName),
                                          new XElement("link-entity", new XAttribute("from", idName), new XAttribute("name", relationshipName), new XAttribute("to", idName),
                                                       new XElement("attribute", new XAttribute("name", countIdName), new XAttribute("aggregate", "count"), new XAttribute("alias", numberAlias))),
                                          new XElement("filter",
                                                       new XElement("condition", new XAttribute("attribute", idName), new XAttribute("operator", "eq"), new XAttribute("value", Id))))));

            FetchExpression fetchExpression = new FetchExpression(xDocument.ToString());

            EntityCollection entityCollection = Connection.Service.RetrieveMultiple(fetchExpression);

            int collectionCount = entityCollection.Entities.Count;

            if (collectionCount == 0)
            {
                return(0);
            }

            if (collectionCount != 1)
            {
                throw new Exception("wrong collection count");
            }

            Entity entity = entityCollection.Entities[0];

            AliasedValue aliasedValue = (AliasedValue)entity.Attributes[numberAlias];

            return((int)aliasedValue.Value);
        }
コード例 #15
0
ファイル: QualifyHelper.cs プロジェクト: hessejt/Samples
        //Optionsets aren't all global, so there's some mismatch between int values of the enums being mapped across entities
        public Int32 MapEnum(IOrganizationService service, string entityLogicalName, string fieldLogicalName, string sourceEnumLabel, OptionSetValue sourceEnumValue)
        {
            Int32  targetEnumValue = -1;
            string FetchXml        = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                     "<entity name ='stringmap' >" +
                                     "<attribute name ='attributevalue' />" +
                                     "<attribute name ='value' />" +
                                     "<filter type ='and' >" +
                                     "<condition attribute ='objecttypecodename' operator='eq' value = '" + entityLogicalName + "' />" +
                                     "<condition attribute ='attributename' operator='eq' value = '" + fieldLogicalName + "' />" +
                                     "</filter >" +
                                     "</entity >" +
                                     "</fetch >";
            FetchExpression FetchXmlQuery = new FetchExpression(FetchXml);

            EntityCollection FetchXmlResult = service.RetrieveMultiple(FetchXmlQuery);

            if (FetchXmlResult.Entities.Count > 0)
            {
                foreach (Entity Stringmap in FetchXmlResult.Entities)
                {
                    string OptionLabel = Stringmap.Attributes.Contains("value") ? (string)Stringmap.Attributes["value"] : string.Empty;
                    Int32  OptionValue = Stringmap.Attributes.Contains("attributevalue") ? (Int32)Stringmap.Attributes["attributevalue"] : 0;
                    if (OptionLabel.ToLower() == sourceEnumLabel.ToLower())
                    {
                        targetEnumValue = OptionValue;
                    }
                    else if (sourceEnumValue.Value == OptionValue)
                    {
                        targetEnumValue = OptionValue;
                    }
                }
            }
            return(targetEnumValue);
        }
コード例 #16
0
        protected override void ExecuteWorkflowLogic()
        {
            var additionalCondition = Conditions.Get(Context.ExecutionContext) ?? string.Empty;

            var sourceEntityFetchXml = $@"
                <fetch>
                  <entity name='{SourceEntity}' >
                    <attribute name='{SourceEntity}id' />
                    <filter type='and' >
                      <condition attribute='{SourceEntityLookupFieldName}' operator='eq' value='{SourceEntityParent.Id}' />
                      {additionalCondition}
                    </filter>
                  </entity>
                </fetch>";

            var sourceEntityQuery = new FetchExpression(sourceEntityFetchXml);

            var sourceEntities = QueryWithPaging(sourceEntityQuery);

            foreach (var sourceEntity in sourceEntities)
            {
                var initializeFromRequest = new InitializeFromRequest()
                {
                    EntityMoniker    = sourceEntity.ToEntityReference(),
                    TargetEntityName = TargetEntity,
                    TargetFieldType  = TargetFieldType.ValidForCreate
                };

                var initializeFromResponse = (InitializeFromResponse)Context.UserService.Execute(initializeFromRequest);

                var targetEntity = initializeFromResponse.Entity;
                targetEntity[TargetEntityLookupFieldName] = TargetEntityParent;
                Context.UserService.Create(targetEntity);
            }
        }
コード例 #17
0
        /// <summary>
        /// 根据Fetch查询字符串获取所有记录
        /// </summary>
        /// <param name="strFetch">Fetch查询字符串</param>
        /// <param name="callBack"></param>
        public static void RetriveAll(string strFetch, Action <Entity> callBack)
        {
            int page = 1, count = 500;
            var doc = XDocument.Parse(strFetch);

            var orgService = ContextContainer.GetValue <IOrganizationService>(ContextTypes.OrgService);


            while (true)
            {
                doc.Root.SetAttributeValue("page", page.ToString());
                doc.Root.SetAttributeValue("count", count.ToString());

                FetchExpression fetchExpression = new FetchExpression(doc.ToString());
                var             queryResponse   = orgService.RetrieveMultiple(fetchExpression);
                foreach (var entityItem in queryResponse.Entities.ToList())
                {
                    callBack(entityItem);
                }

                if (!queryResponse.MoreRecords)
                {
                    break;
                }

                page++;
            }
        }
コード例 #18
0
        private void buttonExecPredefinedCrmGridViewQuery_Click(object sender, EventArgs e)
        {
            var fex = new FetchExpression(@"<fetch>
  <entity name='account' >
    <attribute name='accountid' />
    <attribute name='name' />
    <attribute name='telephone1' />
    <attribute name='address1_city' />
    <attribute name='primarycontactid' />
    <attribute name='revenue' />
    <attribute name='address1_postofficebox' />
    <filter>
      <condition attribute='statecode' operator='eq' value='0' />
    </filter>
    <link-entity name='contact' from='contactid' to='primarycontactid' link-type='outer' alias='C' >
      <attribute name='emailaddress1' />
      <attribute name='address1_telephone3' />
    </link-entity>
    <attribute name='statecode' />
  </entity>
</fetch>");
            var res = Service.RetrieveMultiple(fex);

            CrmGridViewDesignedCols.DataSource = res;
        }
コード例 #19
0
        /// <summary>
        /// To get Security roles for different Business units using security role name Tc.Ids.Base and Tc.Ids.Rep
        /// </summary>
        /// <param name="businessUnits"></param>
        /// <returns></returns>
        private EntityReferenceCollection GetSecurityRolesByBusinessUnit(Guid businessUnitsId)
        {
            var query          = string.Format(@"<fetch distinct='false' output-format='xml-platform' version='1.0' mapping='logical'>
                                        <entity name='role'>
                                        <attribute name='businessunitid'/>
                                        <attribute name='roleid' />
                                        <filter type='and'>
                                         <filter type='or'>
                                          <condition attribute='name' operator='eq' value='{0}'/>
                                          <condition attribute='name' operator='eq' value='{1}'/>
                                         </filter >
                                         <condition attribute='businessunitid' operator='eq' value='{2}'>
                                          {2}
                                         </condition>
                                        </filter>
                                        </entity>
                                        </fetch> ", General.RoleTcIdBase, General.RoleTcIdRep, businessUnitsId);
            var fetch          = new FetchExpression(query);
            var roleCollection = service.RetrieveMultiple(fetch);

            if (roleCollection == null || roleCollection.Entities.Count != 2)
            {
                throw new InvalidPluginExecutionException("Security Role Tc.Ids.Base, Tc.Ids.Rep was not created for one or more Business Units.");
            }
            trace.Trace("Retrieved security roles for business unit");
            var roles = roleCollection.Entities.Select(r => new EntityReference {
                LogicalName = r.LogicalName, Id = r.Id
            }).ToList();

            return(new EntityReferenceCollection(roles));
        }
コード例 #20
0
        /// <summary>
        /// Processes the item set changes for custom relationship.
        /// </summary>
        /// <param name="itemSetConfig">The item set.</param>
        /// <param name="selectedIds">The selected ids.</param>
        ///
        private void ProcessItemSetChangesForCustomRelationship(pavelkh_advancedmultiselectitemsetconfiguration itemSetConfig, string selectedIds)
        {
            var relationshipName   = itemSetConfig.pavelkh_RelationshipName;
            var selectedIdList     = ParseIdList(selectedIds);
            var inputTarget        = this.PluginContext.InputTargetAsEntity;
            var entity1LogicalName = inputTarget.LogicalName;
            var entity2LogicalName =
                itemSetConfig.pavelkh_EntityName == entity1LogicalName ?
                itemSetConfig.pavelkh_ItemSetEntityName :
                itemSetConfig.pavelkh_EntityName;
            var fetchXmlQuery = itemSetConfig.pavelkh_FetchXmlForIntersect.Replace(
                ItemSetBuilder.FetchXmlEntityIdPlaceHolder,
                inputTarget.Id.ToString("D"));
            var fetchExpression  = new FetchExpression(fetchXmlQuery);
            var service          = this.PluginContext.Service;
            var entityCollection = service.RetrieveMultiple(fetchExpression);
            var existingSelected = entityCollection.Entities.Select(r => r.Id).ToList();
            var itemsToAssociate = selectedIdList
                                   .Except(existingSelected)
                                   .Select(r => new EntityReference(entity2LogicalName, r))
                                   .ToList();

            this.Associate(relationshipName, itemsToAssociate);

            var itemsToDisassociate = existingSelected
                                      .Except(selectedIdList)
                                      .Select(r => new EntityReference(entity2LogicalName, r))
                                      .ToList();

            this.Disassociate(relationshipName, itemsToDisassociate);
        }
コード例 #21
0
ファイル: MetadataLookupService.cs プロジェクト: kaitek/CRM
        public object GetValue(string entityName, string attributeLogicalName, Guid id)
        {
            if (id == Guid.Empty)
            {
                return(null);
            }

            string key = entityName + "|" + attributeLogicalName + "|" + id.ToString();

            if (!_stringObjectCache.ContainsKey(key))
            {
                string          fetch = string.Format(fetchPattern, entityName, entityName + "id", id, attributeLogicalName);
                FetchExpression query = new FetchExpression(fetch);
                List <Entity>   list  = _service.RetrieveMultiple(query).Entities.Select(con => con.ToEntity <Entity>()).ToList();

                if (list.Count > 0)
                {
                    if (list[0].Attributes.ContainsKey(attributeLogicalName))
                    {
                        object value = list[0][attributeLogicalName].ToString();
                        _stringObjectCache.Add(key, value);
                        return(value);
                    }
                }
                return(null);
            }
            return(_stringObjectCache[key]);
        }
コード例 #22
0
        private EntityReference GetWebsite()
        {
            var             fetchXml = $@"
<fetch>
  <entity name='adx_website'>
    <attribute name='adx_websiteid' />
    <attribute name='adx_name' />
  </entity>
</fetch>";
            FetchExpression query    = new FetchExpression(fetchXml);
            var             result   = Service.RetrieveMultiple(query);

            if (result.Entities.Count == 1)
            {
                var e = result.Entities[0];
                return(new EntityReference()
                {
                    Id = e.Id,
                    LogicalName = e.LogicalName,
                    Name = (string)e["adx_name"]
                });
            }
            else
            {
                throw new ApplicationException("Website is not unique.");
            }
        }
コード例 #23
0
        private void FindContacts(Guid guid)
        {
            Guid                        selectedUser   = (Guid)ddlUsers.SelectedValue;
            List <AuditItem>            data           = new List <Model.AuditItem>();
            FetchExpression             query          = null;
            Tuple <int, string, string> selectedEntity = (Tuple <int, string, string>)ddlEntities.SelectedItem;
            string                      auditFetchXml;

            if (selectedUser == Guid.Empty)
            {
                auditFetchXml = string.Format(ConnectionDetail.OrganizationMajorVersion < 8 ?
                                              FetchXml.DeletedAuditLogs.Replace("regardingobject", "object") :
                                              FetchXml.DeletedAuditLogs,
                                              dateFrom.Value.ToString("yyyy-MM-dd"),
                                              dateTo.Value.AddDays(1).ToString("yyyy-MM-dd"),
                                              2);
            }
            else
            {
                auditFetchXml = string.Format(ConnectionDetail.OrganizationMajorVersion < 8 ?
                                              FetchXml.DeleteAuditLogsByUser.Replace("regardingobject", "object") :
                                              FetchXml.DeleteAuditLogsByUser,
                                              dateFrom.Value.ToString("yyyy-MM-dd"),
                                              dateTo.Value.AddDays(1).ToString("yyyy-MM-dd"),
                                              2,
                                              selectedUser);
            }
            query = new FetchExpression(auditFetchXml);
            var queryResult = Service.RetrieveMultiple(query);

            foreach (Entity item in queryResult.Entities)
            {
                RetrieveAuditDetailsRequest auditDetailRequest = new RetrieveAuditDetailsRequest();
                auditDetailRequest.AuditId = item.Id;
                RetrieveAuditDetailsResponse response        = (RetrieveAuditDetailsResponse)Service.Execute(auditDetailRequest);
                AttributeAuditDetail         attributeDetail = (AttributeAuditDetail)response.AuditDetail;
                EntityMetadata metadata = entityMetadataList.FirstOrDefault(x => (x.ObjectTypeCode == 2));

                AuditItem auditItem = new Model.AuditItem()
                {
                    AuditId      = item.Id,
                    DeletedBy    = ((EntityReference)item["userid"]).Name,
                    DeletionDate = (DateTime)item["createdon"],
                    Entity       = ((EntityReference)item["objectid"]).LogicalName,
                    RecordId     = ((EntityReference)item["objectid"]).Id,
                    AuditDetail  = attributeDetail,
                    Metadata     = metadata
                };

                if (selectedEntity.Item3 != null && attributeDetail.OldValue.Contains(selectedEntity.Item3))
                {
                    auditItem.Name = attributeDetail.OldValue[selectedEntity.Item3].ToString();
                }

                data.Add(auditItem);
            }
            var contact = data.First(x => x.AuditDetail.OldValue.Id == guid);

            Service.Create(contact.AuditDetail.OldValue);
        }
コード例 #24
0
        /// <summary>
        /// Creates a FetchXML expression that supports paging from a baseline FetchXML query.
        /// </summary>
        /// <param name="fetchXml">The query.</param>
        /// <param name="pagingCookie">The paging cookie.</param>
        /// <param name="pageNumber">The page number to retrive.</param>
        /// <returns>The FetchExpression.</returns>
        private FetchExpression CreatePagedFetchExpression(string fetchXml, string pagingCookie, int pageNumber)
        {
            StringReader  stringReader = new StringReader(fetchXml);
            XmlTextReader textReader   = new XmlTextReader(stringReader);
            XmlDocument   document     = new XmlDocument();

            document.Load(textReader);

            XmlAttributeCollection attributes = document.DocumentElement.Attributes;

            if (pagingCookie != null)
            {
                XmlAttribute pagingAttribute = document.CreateAttribute("paging-cookie");
                pagingAttribute.Value = pagingCookie;
                attributes.Append(pagingAttribute);
            }

            XmlAttribute pageAttribute = document.CreateAttribute("page");

            pageAttribute.Value = pageNumber.ToString();
            attributes.Append(pageAttribute);

            StringBuilder sb           = new StringBuilder(1024);
            StringWriter  stringWriter = new StringWriter(sb);

            XmlTextWriter writer = new XmlTextWriter(stringWriter);

            document.WriteTo(writer);
            writer.Close();

            string          pagedFetchXml = sb.ToString();
            FetchExpression expression    = new FetchExpression(pagedFetchXml);

            return(expression);
        }
コード例 #25
0
        private List <Entity> GetUserQueues(Guid userId)
        {
            var fetch = $@"
                <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' no-lock='true'>
	              <entity name='queue'>
	                <attribute name='name' />
	                <attribute name='queueid' />    
	                <attribute name='ownerid' />    
                    <order attribute='name' descending='false' />
	                <link-entity name='queuemembership' from='queueid' to='queueid' visible='false' intersect='true'>
	                  <link-entity name='systemuser' from='systemuserid' to='systemuserid' alias='user'>
	                    <filter type='and'>
	                      <condition attribute='systemuserid' operator='eq' value='{userId}' />
	                    </filter>
	                  </link-entity>
	                </link-entity>
                    <link-entity name='team' from='queueid' to='queueid' link-type='outer' alias='team' >
                        <attribute name='name' />
                        <attribute name='isdefault' />
                    </link-entity>
	              </entity>
	            </fetch>"    ;

            var query    = new FetchExpression(fetch);
            var response = _client.RetrieveMultiple(query);

            return(response.Entities.ToList());
        }
コード例 #26
0
        /// <summary>
        /// Gets the entities count.
        /// </summary>
        /// <param name="logicalName">Name of the logical.</param>
        /// <param name="primaryKey">The primary key.</param>
        /// <param name="filteredFields">The filtered fields.</param>
        /// <param name="onlyActive">if set to <c>true</c> [only active].</param>
        /// <returns></returns>
        public override int GetEntitiesCount(string logicalName, string primaryKey, Dictionary <string, string> filteredFields, bool onlyActive)
        {
            int count            = 0;
            var filterExpression = this.GetFilterExpression(filteredFields, onlyActive);

            try
            {
                var request = "<fetch mapping='logical' aggregate='true'><entity name='{0}'><attribute name='{1}' aggregate='count' alias='count' />{2}</entity></fetch>".FormatWith(logicalName, primaryKey, filterExpression.ToFetchXml());

                var fetchExpression = new FetchExpression(request);

                var result = this.organizationServiceCache.GetOrganizationService().RetrieveMultiple(fetchExpression);
                if (result.Entities.Count == 0)
                {
                    return(0);
                }

                var entity = result.Entities[0];
                count = (int)((AliasedValue)entity["count"]).Value;
            }
            catch (Exception e)
            {
                if (e.Message.Contains("AggregateQueryRecordLimit"))
                {
                    count = this.GetImplicitEntitiesCount(logicalName, filterExpression);
                }
            }

            return(count);
        }
コード例 #27
0
        // For Returning Paged List of Entities
        public List <Entity> ReturnPagedListOfEntities(OrganizationServiceProxy service, string fetchXmlExpression)
        {
            bool   continueProcessing = true;
            int    fetchCount         = 5000;
            int    pageNumber         = 1;
            string pagingCookie       = null;

            List <Entity> pagedEntityList = new List <Entity>();

            while (continueProcessing == true)
            {
                string xmlRequest = CreateXml(fetchXmlExpression, pagingCookie, pageNumber, fetchCount);

                FetchExpression  getFetch = new FetchExpression(xmlRequest);
                EntityCollection entityCollectionRecords = service.RetrieveMultiple(getFetch);

                pagedEntityList.AddRange(entityCollectionRecords.Entities);

                if (entityCollectionRecords.MoreRecords == true)
                {
                    pageNumber++;
                }
                else
                {
                    continueProcessing = false;
                }
            }

            return(pagedEntityList);
        }
コード例 #28
0
        public static EntityCollection GetActiveCases(IOrganizationService _orgServ, string thread)
        {
            string           activeCaseFetch = @"<fetch version='1.0' count='500' output-format='xml-platform' mapping='logical' distinct='false'>
              <entity name='incident'>
                <attribute name='ticketnumber'/>    
                <attribute name='incidentid'/>
	            <attribute name='statecode'/>
	            <attribute name='statuscode'/>
                <attribute name='gcs_casetypes'/>
                <filter type='and'>
                <condition attribute = 'title' value = 'Anonymised Case:%' operator= 'not-like'/>   
                </filter>             
                <order attribute='createdon' descending='" + thread + @"'/>           
                <filter type='and'>        
                    <condition attribute='statecode' value='0' operator='eq'/>             
                    </filter>
              </entity>
            </fetch>";
            FetchExpression  f           = new FetchExpression(activeCaseFetch);
            EntityCollection activeCases = _orgServ.RetrieveMultiple(f);


            if (activeCases.Entities != null)
            {
                return(activeCases);
            }
            else
            {
                return(null);
            }
        }
コード例 #29
0
        public void TestDistinct()
        {
            XrmFakedContext      context = new XrmFakedContext();
            IOrganizationService service = context.GetOrganizationService();


            Entity e1 = new Entity("entity");

            e1.Id      = Guid.NewGuid();
            e1["name"] = "FakeXrmEasy";

            Entity e2 = new Entity("entity");

            e2.Id      = Guid.NewGuid();
            e2["name"] = "FakeXrmEasy";

            context.Initialize(new Entity[] { e1, e2 });

            var fetchXml            = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' returntotalrecordcount='true'>
                              <entity name='entity'>
                                    <attribute name='name' />                                    
                              </entity>
                            </fetch>";
            var query               = new FetchExpression(fetchXml);
            EntityCollection result = service.RetrieveMultiple(query);

            Assert.Equal(1, result.Entities.Count);
            Assert.False(result.MoreRecords);
        }
コード例 #30
0
        private EntityReference FetchQueueBy(int department, Guid sourceMarket, ITracingService trace, IOrganizationService service)
        {
            trace.Trace("FetchQueueBy - start");
            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='queue'>
                                <attribute name='queueid' />
                                <filter type='and'>
                                  <condition attribute='tc_department' operator='eq' value='{0}' />
                                  <condition attribute='tc_sourcemarket' operator='eq' value='{1}' />
                                </filter>
                              </entity>
                            </fetch>";

            fetchXml = string.Format(fetchXml, department, sourceMarket.ToString());
            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 or response.Entities is null or count is null.");
                return(null);
            }

            if (response.Entities.Count > 1)
            {
                throw new InvalidPluginExecutionException("Multiple queues exist with the same name.");
            }

            trace.Trace("FetchQueueBy - end");
            return(new EntityReference(EntityName.Queue, response.Entities[0].Id));
        }
コード例 #31
0
        /// <summary>
        /// Counts the number of records in the data source.
        /// </summary>
        /// <param name="cancel">The cancellation token.</param>
        /// <param name="progress">The progress.</param>
        /// <returns>The record count.</returns>
        public int GetRecordCount(string fetchXml, CancellationToken cancel, IProgress <ExecutionProgress> progress)
        {
            int    recordCount  = 0;
            int    pageNumber   = 1;
            string pagingCookie = null;

            progress?.Report(new ExecutionProgress(ExecutionStage.Extract, recordCount, recordCount));

            FetchExpression expression = CreatePagedFetchExpression(fetchXml, pagingCookie, pageNumber);

            using (OrganizationServiceProxy proxy = ((Dynamics365Connection)Parent).OrganizationServiceProxy)
            {
                EntityCollection entityRecords = proxy.RetrieveMultiple(expression);
                recordCount += entityRecords.Entities.Count;

                while (entityRecords.MoreRecords)
                {
                    pageNumber++;
                    pagingCookie  = entityRecords.PagingCookie;
                    expression    = CreatePagedFetchExpression(fetchXml, pagingCookie, pageNumber);
                    entityRecords = proxy.RetrieveMultiple(expression);
                    recordCount  += entityRecords.Entities.Count;
                    progress?.Report(new ExecutionProgress(ExecutionStage.Extract, recordCount, recordCount));
                    cancel.ThrowIfCancellationRequested();
                }
            }

            progress?.Report(new ExecutionProgress(ExecutionStage.Extract, recordCount, recordCount));

            return(recordCount);
        }
コード例 #32
0
ファイル: AccountTests.cs プロジェクト: BISmb/Projects
        public static Entity GetAccount(IOrganizationService service)
        {
            string fetch = @"
                <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                    <entity name='account'>
                    <attribute name='name' />
                    <attribute name='address1_city' />
                    <attribute name='primarycontactid' />
                    <attribute name='telephone1' />
                    <attribute name='accountid' />
                    <order attribute='name' descending='false' />
                    <link-entity name='contact' from='contactid' to='primarycontactid' visible='false' link-type='outer' alias='accountprimarycontactidcontactcontactid'>
                        <attribute name='emailaddress1' />
                    </link-entity>
                    </entity>
                </fetch>";

            FetchExpression ft = new FetchExpression(fetch);
            return service.RetrieveMultiple(ft)[0];
        }
コード例 #33
0
        public JsonResult<NewOppCount> Get(string userId)
        {
            OrganizationService orgService;

            CrmConnection connection = CrmConnection.Parse(
                ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString);

            using (orgService = new OrganizationService(connection))
            {
                //Query the CRM data based on the user id being passed in
                FetchExpression query = new FetchExpression(@"
                    <fetch distinct='true' aggregate='true' >
                        <entity name='opportunity' >
                        <attribute name='opportunityid' alias='NewOppCount' aggregate='count' />
                        <attribute name='ownerid' alias='ownerid' groupby='true' />
                        <filter type='and' >
                            <condition attribute='ownerid' operator='eq' value='" + userId + @"' />
                            <condition attribute='createdon' operator='today' />
                        </filter>
                        </entity>
                    </fetch>");

                //Get the result values for output
                EntityCollection results = orgService.RetrieveMultiple(query);
                string username =
                    (string)results.Entities[0].GetAttributeValue<AliasedValue>("ownerid_owneridname").Value;
                int count =
                    (int)results.Entities[0].GetAttributeValue<AliasedValue>("NewOppCount").Value;

                NewOppCount result = new NewOppCount
                {
                    Username = username,
                    Message = "New Opps Today:",
                    Count = count
                };

                //Return JSON or XML
                return Json(result);
            }
        }
コード例 #34
0
ファイル: RoleManager.cs プロジェクト: BISmb/Projects
 public EntityCollection RetrieveUserRoles(EntityReference user)
 {
     FetchExpression ft = new FetchExpression(
             @"  <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
                   <entity name='role'>
                     <attribute name='roleid' />
                     <attribute name='name' />
                     <attribute name='businessunitid' />
                     <order attribute='name' descending='false' />
                     <link-entity name='systemuserroles' from='roleid' to='roleid' visible='false' intersect='true'>
                       <link-entity name='systemuser' from='systemuserid' to='systemuserid' alias='team'>
                         <attribute name='systemuserid'/>
                         <attribute name='fullname'/>
                     <filter type='and'>
                       <condition attribute='systemuserid' operator='eq' value='"+user.Id+@"' />
                     </filter>
                       </link-entity>
                     </link-entity>
                   </entity>
                 </fetch>"
             );
     return service.RetrieveMultiple(ft);
 }
コード例 #35
0
        static void Main(string[] args)
        {
            CrmConnection connection = CrmConnection.Parse(
                ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString);

            using (_orgService = new OrganizationService(connection))
            {
                FetchExpression query1 = new FetchExpression(@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                                                <entity name='account'>
                                                                  <attribute name='name' />
                                                                  <attribute name='primarycontactid' />
                                                                  <attribute name='telephone1' />
                                                                  <attribute name='accountid' />
                                                                  <order attribute='name' descending='false' /></entity></fetch>");

                string query2 = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                <entity name='account'>
                                  <attribute name='name' />
                                  <attribute name='primarycontactid' />
                                  <attribute name='telephone1' />
                                  <attribute name='accountid' />
                                  <order attribute='name' descending='false' /></entity></fetch>";
            }
        }
コード例 #36
0
        /// <summary>
        /// Retrieves multiple records from CRM. Can retrieve more than 5,000 records through paging.
        /// </summary>
        /// <returns>CRM Records</returns>
        public EntityCollection GetRecordsFromCrm(FetchExpression fetchXml)
        {
            // Define the fetch attributes.
            // Set the number of records per page to retrieve.
            int fetchCount = 1000;
            // Initialize the page number.
            int pageNumber = 1;
            // Initialize the number of records.
            int recordCount = 0;
            // Specify the current paging cookie. For retrieving the first page,
            // pagingCookie should be null.
            string pagingCookie = null;
            EntityCollection results = new EntityCollection();
            EntityCollection returnRecords = new EntityCollection();
            do
            {
                // Build fetchXml string with the placeholders.
                string xml = CreateXml(fetchXml.Query, pagingCookie, pageNumber, fetchCount);

                results = Service.RetrieveMultiple(new FetchExpression(xml));
                returnRecords.Entities.AddRange(results.Entities);

                // Increment the page number to retrieve the next page.
                pageNumber++;

                // Set the paging cookie to the paging cookie returned from current results.
                pagingCookie = returnRecords.PagingCookie;
            } while (results.MoreRecords);
            return returnRecords;
        }
コード例 #37
0
        /// <summary>
        /// Evaluate the expressions and set their values based on the metadata response
        /// </summary>
        /// <param name="expressions"></param>
        /// <param name="metadataResponse"></param>
        /// <param name="service"></param>
        private static void SetValues(List<MetadataExpression> expressions, RetrieveMetadataChangesResponse metadataResponse, IOrganizationService service)
        {
            string formatString = "";
            foreach (var expr in expressions)
            {
                if (expr.ExpressionType == TokenExpressionType.EntityMetadata)
                {
                    var entityMetadata = metadataResponse.EntityMetadata.Where(m => m.LogicalName == expr.Entity).FirstOrDefault();
                    if (entityMetadata == null)
                        continue;

                    string propertyName = expr.PropertyName;
                    try
                    {
                        if (expr.Attribute == MetadataExpression.EntityProperties)
                        {
                            // Get properties from entity
                            object value = entityMetadata.GetType().GetProperty(expr.PropertyName).GetValue(entityMetadata);
                            expr.SerialiseValue(value);
                        }
                        else
                        {
                            // Get property from attribute
                            var attributeMetadata = entityMetadata.Attributes.Where(m => m.LogicalName == expr.Attribute).FirstOrDefault();
                            object value = attributeMetadata.GetType().GetProperty(expr.PropertyName).GetValue(attributeMetadata);
                            expr.SerialiseValue(value);

                        }
                        if (!string.IsNullOrWhiteSpace(formatString))
                            expr.Value = String.Format(formatString, expr.Value, expr.Entity, expr.Attribute, expr.PropertyName);
                    }
                    catch (Exception ex)
                    {
                        expr.SerialiseValue(ex.ToString());
                    }
                }
                else if (expr.ExpressionType==TokenExpressionType.Function)
                {
                    switch (expr.FunctionName.ToLower())
                    {
                        case "fetch":
                            try
                            {
                                // Execute the fetchxml
                                FetchExpression query = new FetchExpression(expr.Paramaters);
                                var response = service.RetrieveMultiple(query);
                                expr.SerialiseValue(response);
                            }
                            catch (Exception ex)
                            {
                                expr.SerialiseValue(ex.Message);
                            }
                            break;

                        case "format":
                            // Use a format string
                            formatString = expr.Paramaters;
                            break;

                    }

                }


            }
        }
コード例 #38
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory =
                executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service =
                serviceFactory.CreateOrganizationService(context.UserId);

            var settingName = SettingName.Get(executionContext);

            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' aggregate='true'>
                            <entity name='businessunit'>
                                <attribute name='businessunitid' groupby='true' alias='buid'/>
                                <attribute name='parentbusinessunitid' groupby='true' alias='pbuid'/>
                                <attribute name='name' groupby='true' alias='name'/>
                                    <link-entity name='salesorder' from='owningbusinessunit' to='businessunitid' alias='op'  link-type='outer'>
                                        <attribute name='new_datetime' groupby='true' dategrouping='month' alias='month' />
              	                                <attribute name='totalamount' alias='actualvalue_sum' aggregate='sum' />

              	                            </link-entity>
                            </entity>
                            </fetch>";

            //    <attribute name='opportunityratingcode' groupby='true' alias='oppratcode'  />

            //opportunityratingcode
            var fetch = new FetchExpression(fetchXml);
            var bus = service.RetrieveMultiple(fetch);
            var nonprocesedBu = bus.Entities.ToList();

            #region Aggregation Logic

            //              var processedNodesBu = new List<Node>();
            var finalNodeList = new List<Node>();

            var nonprocesedNodesBu = nonprocesedBu.Select(x =>
                new Node
                {
                    Buid = (Guid)x.GetAttributeValue<AliasedValue>("buid").Value,
                    PartialAmount = x.GetAttributeValue<AliasedValue>("actualvalue_sum").Value == null ? 0m : ((Money)x.GetAttributeValue<AliasedValue>("actualvalue_sum").Value).Value,
                    ParentBuid = x.Attributes.ContainsKey("pbuid") ? ((EntityReference)x.GetAttributeValue<AliasedValue>("pbuid").Value).Id : Guid.Empty,
                    Name = (string)x.GetAttributeValue<AliasedValue>("name").Value,
                    MonthNumber = x.Attributes.ContainsKey("month") ? ((int)x.GetAttributeValue<AliasedValue>("month").Value) : -1,
                    HasChilds = false
                }
                    )
               .ToList();

            var nonProcesedHelperNodesBu = new List<Node>(nonprocesedNodesBu);

            var distinctBu = nonProcesedHelperNodesBu.GroupBy(x => x.Name).Select(x => new BuMetadata(){Color = "#000000", Name = x.Key}).ToList();

            //Create tree structure of nodes

            //get BU where the data is completly empty
            var nodesFullYearAdd = nonProcesedHelperNodesBu.Where(x => x.MonthNumber == -1);

            //Fix the empty data   in real world, this should not be executed.
            foreach ( var item in nodesFullYearAdd )
            {
                for ( var i = 1; i <= 12; i++ )
                {
                    var nodeAdd = (Node)item.Clone();
                    nodeAdd.MonthNumber = i;
                    nodeAdd.PartialAmount = 0m;
                    finalNodeList.Add(nodeAdd);
                }
            }

            //check now
            var nodesAddMissingMonths = nonprocesedNodesBu.Where(x => x.MonthNumber != -1);
            var groupedNodesAddOtherMonths = (from node in nodesAddMissingMonths
                                              group node by node.Buid into nodeGroup
                                              select nodeGroup);

            //group data based on businessunit
            //foreach bussiness unit
            foreach ( var group in groupedNodesAddOtherMonths )
            {
                for ( var i = 1; i <= 12; i++ )
                {
                    //if group contains this month
                    if ( group.ToList().Any(x => x.MonthNumber == i) )
                    {
                        //get that month
                        var nodeFinal = group.ToList().FirstOrDefault(x => x.Buid == group.Key && x.MonthNumber == i);
                        //add to final list
                        finalNodeList.Add(nodeFinal);
                    }
                    else
                    {
                        //for given month record is not existing, just add empty record
                        var nodeFinal = group.ToList().FirstOrDefault(x => x.Buid == group.Key);
                        nodeFinal = nodeFinal ?? new Node();
                        var nodeAdd = (Node)nodeFinal.Clone();
                        nodeAdd.PartialAmount = 0m;
                        nodeAdd.MonthNumber = i;
                        finalNodeList.Add(nodeAdd);
                    }
                }
            }

            //foreach ( Node it in finalNodeList.OrderBy(x=>x.MonthNumber).ThenBy(x=>x.Name).ToList())
            //{
            //    Console.WriteLine("Month Number: "+it.MonthNumber);
            //    Console.WriteLine("Partial Amount: " + it.PartialAmount);
            //    Console.WriteLine("Name: " + it.Name);

            //}

            foreach ( var currentNode in finalNodeList )
            {
                var childs = finalNodeList.Where(x => x.ParentBuid == currentNode.Buid && x.MonthNumber == currentNode.MonthNumber).ToList();
                var amountOfChilds = childs.Count();
                if (amountOfChilds <= 0) continue;
                currentNode.HasChilds = true;
                currentNode.ChildNodes = new List<Node>(childs);
            }

            foreach ( var currentNode in finalNodeList )
            {
                currentNode.Amount = currentNode.GetNodeValue(currentNode);
            }

            //  af4df01e-2977-e511-80fa-3863bb345a68 kaporg 2
            var prefilteredList = finalNodeList.Where(x => x.ParentBuid == Guid.Empty);//new Guid("af4df01e-2977-e511-80fa-3863bb345a68"));

            var monthNames = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;

            var groupedListByMonth = (from node in prefilteredList
                                      group node by node.MonthNumber into nodeGroup
                                      select new MonthGraph()
                                      {
                                          MonthName = monthNames[nodeGroup.Key - 1],
                                          MonthNumber = nodeGroup.Key,
                                          Bu = nodeGroup.Select(o => new BuItem{ Amount = o.Amount, Name = o.Name, Id = o.Buid }).ToList()
                                      }
                                 ).ToList();

            var setting = new DataContractJsonSerializerSettings {UseSimpleDictionaryFormat = true};
            using ( var memoryStream = new MemoryStream() )
            {
                var serializer = new DataContractJsonSerializer(typeof(List<MonthGraph>), setting);
                serializer.WriteObject(memoryStream, groupedListByMonth);
                var json = Encoding.Default.GetString(memoryStream.ToArray());

                JsonObectString.Set(executionContext, json);
            }
             using ( var memoryStream = new MemoryStream() )
            {
                var serializer = new DataContractJsonSerializer(typeof(List<BuMetadata>), setting);
                serializer.WriteObject(memoryStream, distinctBu);
                var json = Encoding.Default.GetString(memoryStream.ToArray());

                JsonMetadata.Set(executionContext, json);
            }

            #endregion
        }
コード例 #39
0
        static void Main(string[] args)
        {
            try
            {
                logfilename = string.Format("{0}.log", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
                log("BEGIN");
                log("This code is supplied as is without guarantee. The latest code can be download from https://mscrmworkflowrunner.codeplex.com/");
                if (args.Count() != 1)
                {
                    throw new Exception("Invalid argument: config xml file.");
                }

                log(string.Format("Config file: {0}", args[0].ToString()));

                var configxml = new XmlDocument();
                configxml.Load(args[0].ToString());
                var connectionstring = configxml.SelectSingleNode("//config/connectionstring").InnerText;
                var workflownode = configxml.SelectSingleNode("//config/workflow");
                var workflowname = workflownode.Attributes["name"] != null ? workflownode.Attributes["name"].Value : null;
                Guid workflowid = workflownode.Attributes["id"] != null && !string.IsNullOrEmpty(workflownode.Attributes["id"].Value) ? new Guid(workflownode.Attributes["id"].Value) : Guid.Empty;
                var fetchxml = configxml.SelectSingleNode("//config/fetchxml").InnerText;

                var connection = CrmConnection.Parse(connectionstring);

                var service = new OrganizationService(connection);
                var context = new CrmOrganizationServiceContext(connection);

                if (workflowid == Guid.Empty)
                {
                    if (workflowname == null)
                    {
                        throw new Exception("Workflow name is required when no workflow id is specified!");
                    }
                    var query = new FetchExpression("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                        "  <entity name='workflow'>" +
                        "    <attribute name='workflowid' />" +
                        "    <attribute name='name' />" +
                        "    <filter type='and'>" +
                        "      <condition attribute='category' operator='eq' value='0' />" +
                        "      <condition attribute='type' operator='eq' value='1' />" +
                        "      <condition attribute='name' operator='eq' value='" + workflowname + "' />" +
                        "    </filter>" +
                        "  </entity>" +
                        "</fetch>");
                    var workflows = service.RetrieveMultiple(query);
                    if (workflows.Entities.Count < 1)
                    {
                        throw new Exception(string.Format("A workflow with the name {0} could not be found!", workflowname));
                    }
                    else if (workflows.Entities.Count > 1)
                    {
                        throw new Exception(string.Format("More than one workflow with the name {0} found!", workflowname));
                    }
                    workflowid = workflows.Entities[0].Id;
                }

                var results = service.RetrieveMultiple(new FetchExpression(fetchxml));

                foreach (var entity in results.Entities)
                {
                    var req = new ExecuteWorkflowRequest()
                    {
                        EntityId = entity.Id,
                        WorkflowId = workflowid
                    };
                    try
                    {
                        service.Execute(req);
                        logsuccess(string.Format("Workflow request complete for entity id {0}", entity.Id.ToString()));
                    }
                    catch (Exception ex)
                    {
                        logerror(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                logerror(ex.Message);
            }
            finally
            {
                log("END");
            }
        }
コード例 #40
0
        private void DoQueryExpressionToFetchXmlConversion()
        {
            //<snippetFetchXmlAndQueryExpressionQueryConversion2>
            // Build a query expression that we will turn into FetchXML.
            var queryExpression = new QueryExpression()
            {
                Distinct = false,
                EntityName = Contact.EntityLogicalName,
                ColumnSet = new ColumnSet("fullname", "address1_telephone1"),
                LinkEntities = 
                    {
                        new LinkEntity 
                        {
                            JoinOperator = JoinOperator.LeftOuter,
                            LinkFromAttributeName = "parentcustomerid",
                            LinkFromEntityName = Contact.EntityLogicalName,
                            LinkToAttributeName = "accountid",
                            LinkToEntityName = Account.EntityLogicalName,
                            LinkCriteria = 
                            {
                                Conditions = 
                                {
                                    new ConditionExpression("name", ConditionOperator.Equal, "Litware, Inc.")
                                }
                            }
                        }
                    },
                Criteria =
                {
                    Filters = 
                        {
                            new FilterExpression
                            {
                                FilterOperator = LogicalOperator.And,
                                Conditions = 
                                {
                                    new ConditionExpression("address1_stateorprovince", ConditionOperator.Equal, "WA"),
                                    new ConditionExpression("address1_city", ConditionOperator.In, new String[] {"Redmond", "Bellevue" , "Kirkland", "Seattle"}),
                                    new ConditionExpression("createdon", ConditionOperator.LastXDays, 30),
                                    new ConditionExpression("emailaddress1", ConditionOperator.NotNull)
                                },
                            },
                            new FilterExpression
                            {
                                FilterOperator = LogicalOperator.Or,
                                Conditions =
                                {
                                    new ConditionExpression("address1_telephone1", ConditionOperator.Like, "(206)%"),
                                    new ConditionExpression("address1_telephone1", ConditionOperator.Like, "(425)%")
                                }
                            }
                        }
                }
            };

            // Run the query as a query expression.
            EntityCollection queryExpressionResult =
                _serviceProxy.RetrieveMultiple(queryExpression);
            Console.WriteLine("Output for query as QueryExpression:");
            DisplayContactQueryResults(queryExpressionResult);

            // Convert the query expression to FetchXML.
            var conversionRequest = new QueryExpressionToFetchXmlRequest
            {
                Query = queryExpression
            };
            var conversionResponse =
                (QueryExpressionToFetchXmlResponse)_serviceProxy.Execute(conversionRequest);

            // Use the converted query to make a retrieve multiple request to Microsoft Dynamics CRM.
            String fetchXml = conversionResponse.FetchXml;
            var fetchQuery = new FetchExpression(fetchXml);
            EntityCollection result = _serviceProxy.RetrieveMultiple(fetchQuery);

            // Display the results.
            Console.WriteLine("\nOutput for query after conversion to FetchXML:");
            DisplayContactQueryResults(result);
            //</snippetFetchXmlAndQueryExpressionQueryConversion2>

        }
コード例 #41
0
        private void DoFetchXmlToQueryExpressionConversion()
        {
            //<snippetFetchXmlAndQueryExpressionQueryConversion1>
            // Create a Fetch query that we will convert into a query expression.
            var fetchXml =
                @"<fetch mapping='logical' version='1.0'>
	                <entity name='opportunity'>
		                <attribute name='name' />
		                <filter>
			                <condition attribute='estimatedclosedate' operator='next-x-fiscal-years' value='3' />
		                </filter>
		                <link-entity name='account' from='accountid' to='customerid'>
			                <link-entity name='contact' from='parentcustomerid' to='accountid'>
				                <attribute name='fullname' />
				                <filter>
					                <condition attribute='address1_city' operator='eq' value='Bellevue' />
					                <condition attribute='address1_stateorprovince' operator='eq' value='WA' />
				                </filter>
			                </link-entity>
		                </link-entity>
	                </entity>
                </fetch>";

            // Run the query with the FetchXML.
            var fetchExpression = new FetchExpression(fetchXml);
            EntityCollection fetchResult =
                _serviceProxy.RetrieveMultiple(fetchExpression);
            Console.WriteLine("\nOutput for query as FetchXML:");
            DisplayOpportunityQueryResults(fetchResult);

            // Convert the FetchXML into a query expression.
            var conversionRequest = new FetchXmlToQueryExpressionRequest
            {
                FetchXml = fetchXml
            };

            var conversionResponse =
                (FetchXmlToQueryExpressionResponse)_serviceProxy.Execute(conversionRequest);

            // Use the newly converted query expression to make a retrieve multiple
            // request to Microsoft Dynamics CRM.
            QueryExpression queryExpression = conversionResponse.Query;

            EntityCollection result = _serviceProxy.RetrieveMultiple(queryExpression);

            // Display the results.
            Console.WriteLine("\nOutput for query after conversion to QueryExpression:");
            DisplayOpportunityQueryResults(result);
            //</snippetFetchXmlAndQueryExpressionQueryConversion1>

        }
コード例 #42
0
ファイル: Form1.cs プロジェクト: OliverFlint/CRMinify
        private void listWebResources()
        {
            SolutionComboBoxItem selectedItem = (SolutionComboBoxItem)solutionComboBox.SelectedItem;
            //QueryExpression query = new QueryExpression("webresource")
            //{
            //    ColumnSet = new ColumnSet(true)
            //};
            //query.AddOrder("displayname", OrderType.Ascending);

            //if (selectedItem.Value != Guid.Empty)
            //{
            //    FilterExpression filter1 = new FilterExpression();
            //    filter1.AddCondition("solutionid", ConditionOperator.Equal, selectedItem.Value);
            //    query.Criteria.AddFilter(filter1);
            //}

            //FilterExpression filter2 = new FilterExpression();
            //filter2.AddCondition("webresourcetype", ConditionOperator.Equal, 2);
            //filter2.AddCondition("webresourcetype", ConditionOperator.Equal, 3);
            //filter2.FilterOperator = LogicalOperator.Or;
            //query.Criteria.AddFilter(filter2);

            var fetchXml = @"<fetch mapping='logical' count='500' version='1.0'>
                        <entity name='webresource'>
                            <attribute name='displayname' />
                            <attribute name='name' />
                            <attribute name='webresourcetype' />
                            <attribute name='ismanaged' />
                            <link-entity name='solutioncomponent' from='objectid' to='webresourceid'>
                                <filter>
                                    <condition attribute='solutionid' operator='eq' value='" + selectedItem.Value + @"' />
                                </filter>
                            </link-entity>
                            <filter type='or'>
                                <condition attribute='webresourcetype' operator='eq' value='2' />
                                <condition attribute='webresourcetype' operator='eq' value='3' />
                            </filter>
                        </entity>
                    </fetch>";
            FetchExpression fetchQuery = new FetchExpression(fetchXml);

            var results = this.service.RetrieveMultiple(fetchQuery);
            if (results.Entities.Count > 0)
            {
                webResourceListView.Items.Clear();
            }

            webResourceListView.View = View.Details;

            foreach (var item in results.Entities)
            {
                ListViewItem listViewItem = new ListViewItem(item.GetAttributeValue<string>("displayname"));
                listViewItem.SubItems.Add(item.GetAttributeValue<string>("name"));
                listViewItem.SubItems.Add(item.FormattedValues["webresourcetype"]);
                listViewItem.SubItems.Add(item.GetAttributeValue<bool>("ismanaged").ToString());
                listViewItem.Tag = item;
                webResourceListView.Items.Add(listViewItem);
            }
        }
コード例 #43
0
 private static int GetDefaultLCID(IOrganizationService service)
 {
     // Get the orgs default language
     FetchExpression languageQuery = new FetchExpression(@"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"" count=""1"" >
                                                                         <entity name=""organization"" >
                                                                             <attribute name=""languagecode"" />
                                                                         </entity>
                                                                     </fetch>");
     var orgSettings = service.RetrieveMultiple(languageQuery);
     var lcid = orgSettings.Entities[0].GetAttributeValue<int>("languagecode");
     return lcid;
 }
コード例 #44
0
 private void RetrieveMultiple(string fetch)
 {
     working = true;
     var outputtype = tsmiResultOption.SelectedIndex;
     var outputtypestring = tsmiResultOption.SelectedItem.ToString();
     WorkAsync("Executing FetchXML...",
         (eventargs) =>
         {
             EntityCollection resultCollection = null;
             QueryBase query;
             try
             {
                 query = GetQueryExpression();
             }
             catch (FetchIsAggregateException)
             {
                 query = new FetchExpression(fetch);
             }
             resultCollection = Service.RetrieveMultiple(query);
             if (outputtype == 2)
             {
                 var json = EntityCollectionSerializer.ToJSON(resultCollection, Formatting.Indented);
                 eventargs.Result = json;
             }
             else
             {
                 eventargs.Result = resultCollection;
             }
         },
         (completedargs) =>
         {
             working = false;
             if (completedargs.Error != null)
             {
                 if (MessageBox.Show(completedargs.Error.Message + "\n\nTry with result as ExecuteFetch?", "Execute", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.OK)
                 {
                     ExecuteFetch(fetch);
                 }
             }
             else if (outputtype == 0 && completedargs.Result is EntityCollection)
             {
                 var gridDialog = new ResultGrid((EntityCollection)completedargs.Result, this);
                 gridDialog.StartPosition = FormStartPosition.CenterParent;
                 gridDialog.ShowDialog();
             }
             else if (outputtype == 1 && completedargs.Result is EntityCollection)
             {
                 var serialized = EntityCollectionSerializer.Serialize((EntityCollection)completedargs.Result);
                 var xcdDialog = new XmlContentDisplayDialog(serialized.OuterXml, "XML Serialized RetrieveMultiple result", false, false, false, this);
                 xcdDialog.StartPosition = FormStartPosition.CenterParent;
                 xcdDialog.ShowDialog();
             }
             else if (outputtype == 2 && completedargs.Result is string)
             {
                 var result = completedargs.Result.ToString();
                 var xcdDialog = new XmlContentDisplayDialog(result, "JSON Serialized RetrieveMultiple result", false, false, false, this);
                 xcdDialog.btnFormat.Visible = false;
                 xcdDialog.StartPosition = FormStartPosition.CenterParent;
                 xcdDialog.ShowDialog();
             }
         });
     LogUse("RetrieveMultiple-" + outputtypestring);
 }
コード例 #45
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards a dynamic
        /// list is created and associated to the campaign and the campaign's activity.
        /// Then the dynamic list is copied to a static list and associated with the same
        /// campaign and campaign activity. Finally the sample distributes the campaign
        /// to both the dynamic and static lists.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetMarketingAutomation1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    #region Create Dynamic List

                    // Create FetchXml for marketing list's query which locates accounts
                    // in Seattle.
                    String fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                        <entity name='account'>
                                        <attribute name='name' />
                                        <attribute name='address1_city' />
                                        <attribute name='primarycontactid' />
                                        <attribute name='telephone1' />
                                        <attribute name='accountid' />
                                        <order attribute='name' descending='false' />
                                        <filter type='and'>
                                        <condition attribute='address1_city' operator='eq' value='seattle' />
                                        </filter>
                                        </entity>
                                        </fetch>";
                    //<snippetAddItemCampaign>
                    // Create dynamic list. Set the type to true to declare a dynamic
                    // list.
                    List dynamicList = new List()
                    {
                        Type = true,
                        ListName = "Dynamic List",
                        CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account),
                        Query = fetchXml
                    };
                    _dynamicListId = _serviceProxy.Create(dynamicList);
                    dynamicList.Id = _dynamicListId;

                    Console.WriteLine("Created dynamic list.");

                    #endregion

                    #region Associate dynamic list to campaign

                    // Create a campaign.
                    Campaign campaign = new Campaign()
                    {
                        Name = "Sample Campaign"
                    };
                    _campaignId = _serviceProxy.Create(campaign);
                    campaign.Id = _campaignId;

                    // Add the dynamic list to the campaign.
                    AddItemCampaignRequest addListToCampaignRequest =
                        new AddItemCampaignRequest()
                        {
                            CampaignId = _campaignId,
                            EntityId = _dynamicListId,
                            EntityName = List.EntityLogicalName,
                        };
                    _serviceProxy.Execute(addListToCampaignRequest);

                    Console.WriteLine("Added dynamic list to the campaign.");
                    //</snippetAddItemCampaign>

                    //<snippetAddItemCampaignActivity>
                    // Create a campaign activity to distribute fax to the list members.
                    CampaignActivity campaignActivity = new CampaignActivity()
                    {
                        Subject = "Sample Campaign Activity",
                        ChannelTypeCode = new OptionSetValue((int)CampaignActivityChannelTypeCode.Fax),
                        RegardingObjectId = campaign.ToEntityReference()
                    };
                    _campaignActivityId = _serviceProxy.Create(campaignActivity);

                    // Add dynamic list to campaign activity.
                    AddItemCampaignActivityRequest addListToCampaignActivityRequest = 
                        new AddItemCampaignActivityRequest()
                    {
                        CampaignActivityId = _campaignActivityId,
                        ItemId = _dynamicListId,
                        EntityName = List.EntityLogicalName
                    };
                    _serviceProxy.Execute(addListToCampaignActivityRequest);

                    Console.WriteLine("Added dynamic list to the campaign activity.");
                    //</snippetAddItemCampaignActivity>

                    #endregion

                    #region Associate static list to campaign
                    //<snippetCopyDynamicListToStatic>

                    // Copy the dynamic list to a static list.
                    CopyDynamicListToStaticRequest copyRequest = 
                        new CopyDynamicListToStaticRequest()
                        {
                            ListId = _dynamicListId
                        };
                    CopyDynamicListToStaticResponse copyResponse =
                        (CopyDynamicListToStaticResponse)_serviceProxy.Execute(copyRequest);
                    _staticListId = copyResponse.StaticListId;

                    Console.WriteLine("Copied dynamic list to a static list.");
                    //</snippetCopyDynamicListToStatic>

                    // Add the static list to the campaign.
                    AddItemCampaignRequest addStaticListToCampaignRequest =
                        new AddItemCampaignRequest()
                        {
                            CampaignId = _campaignId,
                            EntityId = _staticListId,
                            EntityName = List.EntityLogicalName
                        };
                    _serviceProxy.Execute(addStaticListToCampaignRequest);

                    Console.WriteLine("Added static list to the campaign.");

                    // Add the static list to the campaign activity.
                    AddItemCampaignActivityRequest addStaticListToCampaignActivityRequest = 
                        new AddItemCampaignActivityRequest()
                    {
                        CampaignActivityId = _campaignActivityId,
                        ItemId = _staticListId,
                        EntityName = List.EntityLogicalName
                    };
                    _serviceProxy.Execute(addStaticListToCampaignActivityRequest);

                    Console.WriteLine("Added static list to the campaign's activity.");

                    #endregion

                    #region Create fax for campaign's activity
                    // Create a fax.
                    Fax fax = new Fax()
                    {
                        Subject = "Example Fax"
                    };

                    Console.WriteLine("Created fax for campaign's activity.");
                    #endregion Create fax for campaign's activity

                    #region Distribute fax to the marketing list
                    //<snippetDistributeCampaignActivity>
                    // Distribute the campaign activity to the marketing lists.
                    DistributeCampaignActivityRequest distributeRequest = 
                        new DistributeCampaignActivityRequest() 
                        { 
                            CampaignActivityId = _campaignActivityId,
                            Activity = fax,
                            Owner = new EntityReference("systemuser", _salesManagerId),
                            Propagate = true,
                            SendEmail = false,
                            PostWorkflowEvent = true
                        };
                    _serviceProxy.Execute(distributeRequest);

                    Console.WriteLine("Distributed fax to the marketing lists.");
                    //</snippetDistributeCampaignActivity>
                    #endregion Distribute fax to the marketing list

                    #region Retrieve collection of entities from marketing list
                    // Retrieve a collection of entities that correspond 
                    // to all of the members in a marketing list
                    // This approach of retrieving list members allows you to dynamically
                    // retrieve the members of a list programmatically without requiring 
                    // knowledge of the member entity type.
                    OrganizationServiceContext orgContext = 
                        new OrganizationServiceContext(_serviceProxy);

                    var member = (from mb in orgContext.CreateQuery<List>()
                                  where mb.Id == _dynamicListId
                                  select mb).FirstOrDefault();

                    string fetchQuery = member.Query;

                    RetrieveMultipleRequest memberRequest = new RetrieveMultipleRequest();
                    FetchExpression fetch = new FetchExpression(fetchQuery);
                    memberRequest.Query = fetch;
                    RetrieveMultipleResponse memberResponse = 
                        (RetrieveMultipleResponse)_serviceProxy.Execute(memberRequest);

                    Console.WriteLine("Retrieved collection of entities from a marketing list.");
                    #endregion Retrieve collection of entities from marketing list

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetMarketingAutomation1>
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }