Example #1
0
        public Guid?CreateTaskToCRMIncident(string ticketnumber, TimeItem timeItem)
        {
            try
            {
                Microsoft.Xrm.Sdk.Query.QueryExpression GetCasesByTicketNumber = new Microsoft.Xrm.Sdk.Query.QueryExpression {
                    EntityName = "incident", ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(true)
                };
                GetCasesByTicketNumber.Criteria.AddCondition("ticketnumber", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, ticketnumber);
                Microsoft.Xrm.Sdk.EntityCollection CaseResults = _service.RetrieveMultiple(GetCasesByTicketNumber);

                if (CaseResults.Entities.Count < 1)
                {
                    return(null);
                }

                Microsoft.Xrm.Sdk.Entity followup = new Microsoft.Xrm.Sdk.Entity("task");

                if (timeItem.title != null)
                {
                    followup["subject"] = timeItem.title.Replace(ticketnumber, "");
                }

                if (timeItem.description != null)
                {
                    followup["description"] = timeItem.description;
                }

                if (timeItem.isBillable == true && timeItem.isBillable != null)
                {
                    followup["actualdurationminutes"]    = (int)TimeSpan.Parse(timeItem.time).TotalMinutes;
                    followup["hsal_nonbillableduration"] = 0;
                }
                else
                {
                    followup["actualdurationminutes"]    = 0;
                    followup["hsal_nonbillableduration"] = (int)TimeSpan.Parse(timeItem.time).TotalMinutes;
                }

                followup["actualstart"] = DateTime.UtcNow;

                followup["regardingobjectid"] = CaseResults.Entities[0].ToEntityReference();

                Guid taskId = _service.Create(followup);

                Microsoft.Crm.Sdk.Messages.SetStateRequest req = new Microsoft.Crm.Sdk.Messages.SetStateRequest();
                req.EntityMoniker = new Microsoft.Xrm.Sdk.EntityReference("task", taskId);
                req.State         = new Microsoft.Xrm.Sdk.OptionSetValue(1);
                req.Status        = new Microsoft.Xrm.Sdk.OptionSetValue((5));
                _service.Execute(req);

                return(taskId);
            }
            catch (Exception ex)
            {
                //log error
                throw ex;
            }
        }
        private Entity[] GetSystemUsers(IOrganizationService service)
        {
            var qry = new Microsoft.Xrm.Sdk.Query.QueryExpression("systemuser");

            qry.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("domainname");
            var results = service.RetrieveMultiple(qry);

            return(results.Entities.ToArray <Entity>());
        }
            protected override void Test(IOrganizationService service)
            {
                //Test framework does not support the FetchXmlToQueryExpression so we fake the expected API result for the specified fetchXml.
                var fakedFetchQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression()
                {
                    EntityName = "new_transactiondatarecord",
                    ColumnSet  = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "new_transactiondatarecordid" }),
                    Criteria   = new Microsoft.Xrm.Sdk.Query.FilterExpression
                    {
                        FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And,
                        Conditions     =
                        {
                            new Microsoft.Xrm.Sdk.Query.ConditionExpression("new_datafield1", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, "TestValue")
                        }
                    }
                };

                service = new OrganizationServiceBuilder()
                          .WithFakeExecute((s, r) => {
                    if (r.RequestName == "FetchXmlToQueryExpression")
                    {
                        FetchXmlToQueryExpressionResponse resp = new FetchXmlToQueryExpressionResponse();
                        resp.Results.Add("Query", fakedFetchQuery);
                        return(resp);
                    }
                    return(s.Execute(r));
                })
                          .Build();

                var executionContext   = GetExecutionContext(service);
                var serializer         = new DefaultSerializer();
                var transactionPointer = new RecordPointer <Guid>(Ids.ExistingTransaction.LogicalName, Ids.ExistingTransaction.EntityId);

                var transactionServiceFactory = Container.Resolve <ITransactionServiceFactory>();
                var transactionService        = transactionServiceFactory.CreateTransactionService(executionContext, false);

                var transaction = transactionService.LoadTransaction(executionContext, transactionPointer);

                var evaluatorType = new EvaluatorType.DataReccordQueryMatchEvaluator(
                    Ids.DataRecordQueryEvaluator.ToRecordPointer(), "TestEvaluator",
                    "S3.D365.Transactions",
                    "CCLLC.BTF.Process.CDS.EvaluatorType.DataReccordQueryMatchEvaluator");



                string parameterJson = "{\"FetchXml\":\"<fetch><entity name='new_transactiondatarecord'><filter type='and'><condition value='TestValue' attribute='new_datafield1' operator='eq'/></filter></entity></fetch>\"}";

                var parameters = serializer.CreateParamters(parameterJson);

                var result = evaluatorType.Evaluate(executionContext, parameters, transaction);

                Assert.AreEqual(true, result.Passed);
            }
        private EntityReference GetDefaultTransactionCurrency(IOrganizationService service)
        {
            var qry     = new Microsoft.Xrm.Sdk.Query.QueryExpression("transactioncurrency");
            var results = service.RetrieveMultiple(qry);

            if (results != null && results.Entities.Count > 0)
            {
                return(results.Entities[0].ToEntityReference());
            }

            return(null);
        }
 public static Guid?GetIdFilter(this Microsoft.Xrm.Sdk.Query.QueryExpression query, string logicalName)
 {
     if (!string.IsNullOrEmpty(logicalName) && query != null && query.Criteria != null && query.Criteria.Filters != null && query.Criteria.Filters.Count > 0)
     {
         var idFilter = query.Criteria.Conditions.Where(r => r.AttributeName == $"{logicalName}id").FirstOrDefault();
         if (idFilter != null && idFilter.Values != null && idFilter.Values.Count == 1)
         {
             return(idFilter.Values.First().ConvertValueTo <Guid>(out bool resolved));
         }
     }
     return(null);
 }
Example #6
0
        private Entity[] GetTransactionCurrency(IOrganizationService service)
        {
            var qry = new Microsoft.Xrm.Sdk.Query.QueryExpression("transactioncurrency");

            qry.ColumnSet.AddColumns("isocurrencycode");
            var results = service.RetrieveMultiple(qry);

            if (results != null && results.Entities.Count > 0)
            {
                return(results.Entities.ToArray <Entity>());
            }

            return(new Entity[0]);
        }
        private EntityReference GetRootBusinessUnit(IOrganizationService service)
        {
            var qry = new Microsoft.Xrm.Sdk.Query.QueryExpression("businessunit");

            qry.Criteria.AddCondition("parentbusinessunitid", Microsoft.Xrm.Sdk.Query.ConditionOperator.Null);
            var results = service.RetrieveMultiple(qry);

            if (results != null && results.Entities.Count > 0)
            {
                return(results.Entities[0].ToEntityReference());
            }

            return(null);
        }
 public static string QuickFindFilter(this Microsoft.Xrm.Sdk.Query.QueryExpression query)
 {
     if (query.Criteria != null && query.Criteria.Filters != null && query.Criteria.Filters.Count > 0)
     {
         var qf = query.Criteria.Filters.Where(r => r.IsQuickFindFilter).SingleOrDefault();
         if (qf != null && qf.Conditions != null && qf.Conditions.Count > 0)
         {
             var value = qf.Conditions[0].Values.Where(v => v is string).FirstOrDefault() as string;
             if (!string.IsNullOrEmpty(value))
             {
                 return(value);
             }
         }
     }
     return(null);
 }
        public static T[] GetAttributeFilter <T>(this Microsoft.Xrm.Sdk.Query.QueryExpression query, string attributeLogicalName)
        {
            var results = new List <T>();

            void Resolve(Microsoft.Xrm.Sdk.Query.FilterExpression filter)
            {
                if (filter.Conditions != null && filter.Conditions.Count > 0)
                {
                    var condition = filter.Conditions.Where(r => r.AttributeName == attributeLogicalName).FirstOrDefault();
                    if (condition != null)
                    {
                        foreach (var v in condition.Values)
                        {
                            var resolved = false;
                            var t        = v.ConvertValueTo <T>(out resolved);
                            if (resolved && t != null)
                            {
                                results.Add(t);
                            }
                        }
                    }
                }
            }

            if (query != null && query.Criteria != null && query.Criteria.Conditions != null && query.Criteria.Conditions.Count > 0)
            {
                Resolve(query.Criteria);
                if (results.Count > 0)
                {
                    return(results.ToArray());
                }
            }

            if (query.Criteria != null && query.Criteria.Filters != null && query.Criteria.Filters.Count > 0)
            {
                foreach (var filter in query.Criteria.Filters.Where(r => r.Conditions != null && r.Conditions.Count > 0))
                {
                    Resolve(filter);
                    if (results.Count > 0)
                    {
                        return(results.ToArray());
                    }
                }
            }
            return(null);
        }
Example #10
0
        public Guid?CreateExternalComment(string ticketnumber, TimeItem timeItem)
        {
            try
            {
                Microsoft.Xrm.Sdk.Query.QueryExpression GetCasesByTicketNumber = new Microsoft.Xrm.Sdk.Query.QueryExpression {
                    EntityName = "incident", ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(true)
                };
                GetCasesByTicketNumber.Criteria.AddCondition("ticketnumber", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, ticketnumber);
                Microsoft.Xrm.Sdk.EntityCollection CaseResults = _service.RetrieveMultiple(GetCasesByTicketNumber);

                if (CaseResults.Entities.Count < 1)
                {
                    return(null);
                }

                Microsoft.Xrm.Sdk.Entity comment = new Microsoft.Xrm.Sdk.Entity("hsal_externalcomments");

                if (timeItem.title != null)
                {
                    comment["subject"] = timeItem.title.Replace(ticketnumber, "");
                }

                if (timeItem.description != null)
                {
                    comment["description"] = timeItem.description;
                }

                comment["regardingobjectid"] = CaseResults.Entities[0].ToEntityReference();

                Guid externalCommentId = _service.Create(comment);

                Microsoft.Crm.Sdk.Messages.SetStateRequest req = new Microsoft.Crm.Sdk.Messages.SetStateRequest();
                req.EntityMoniker = new Microsoft.Xrm.Sdk.EntityReference("hsal_externalcomments", externalCommentId);
                req.State         = new Microsoft.Xrm.Sdk.OptionSetValue(1);
                req.Status        = new Microsoft.Xrm.Sdk.OptionSetValue((2));
                _service.Execute(req);

                return(externalCommentId);
            }
            catch (Exception ex)
            {
                //log error
                throw ex;
            }
        }
Example #11
0
        public static Entity getUserAccessEntity(IOrganizationService service, ITracingService tracer, Entity srcEntity, Boolean update)
        {
            Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression
            {
                EntityName = "mp_useraccess",
                ColumnSet  = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "mp_createdby", "mp_createdon", "mp_modifiedby", "mp_modifiedon" }),
                Criteria   = new Microsoft.Xrm.Sdk.Query.FilterExpression
                {
                    Conditions =
                    {
                        new Microsoft.Xrm.Sdk.Query.ConditionExpression {
                            AttributeName = "mp_useraccessid",
                            Operator      = Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal,
                            Values        =                             { srcEntity.Id}
                        }
                    }
                }
            };

            DataCollection <Entity> list = service.RetrieveMultiple(query).Entities;

            if (list.Count >= 1)
            {
                tracer.Trace($"Found in mp_useraccess:{list[0].Id}");
                return(list[0]);
            }
            else
            {
                /*
                 * if update then get modified attributes from datenbase
                 */
                if (update)
                {
                    tracer.Trace($"Not found in mp_useraccess return load the original entity from database!");
                    Entity entity = service.Retrieve(srcEntity.LogicalName, srcEntity.Id,
                                                     new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "mp_createdby", "mp_createdon", "mp_modifiedby", "mp_modifiedon" }));
                    return(entity);
                }
                else
                {
                    tracer.Trace($"Not found in mp_useraccess return the original entity!");
                    return(srcEntity);
                }
            }
        }
Example #12
0
        public static DataCollection <Entity> getOpportunityProducts(IOrganizationService service, Guid opportunityGuid)
        {
            Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression
            {
                EntityName = "opportunityproduct",
                ColumnSet  = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "opportunityproductid", "volumediscountamount", "productname" }),
                Criteria   = new Microsoft.Xrm.Sdk.Query.FilterExpression
                {
                    Conditions =
                    {
                        new Microsoft.Xrm.Sdk.Query.ConditionExpression {
                            AttributeName = "opportunityid",
                            Operator      = Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal,
                            Values        =                             { opportunityGuid}
                        }
                    }
                }
            };

            return(service.RetrieveMultiple(query).Entities);
        }
Example #13
0
        private Microsoft.Xrm.Sdk.EntityCollection Execute(Microsoft.Xrm.Sdk.Query.QueryExpression qe, EntityShadow[] allEntities)
        {
            var baseEntities = (from a in allEntities where a.LogicalName == qe.EntityName select a).ToArray();

            var resultContainer = new QueryResultContainer(qe.ColumnSet, baseEntities, qe.EntityName);

            if (qe.LinkEntities != null && qe.LinkEntities.Count > 0)
            {
                foreach (var le in qe.LinkEntities)
                {
                    resultContainer.LinkEntity(string.Empty, le, allEntities);
                }
            }

            if (qe.Criteria != null)
            {
                resultContainer.ApplyFilter(string.Empty, qe.Criteria);
            }

            return(resultContainer.ToEntities(qe.Distinct, qe.Orders));
        }
        private void FillMigrationQueues(bool external, bool migrateAnnotations, bool migrateEmailAttachments)
        {
            OrganizationServiceProxy localProxy = null;

            if (IfdSelected)
            {
                localProxy = new OrganizationServiceProxy(serviceManagement, authCredentials.SecurityTokenResponse);
            }
            else
            {
                localProxy = new OrganizationServiceProxy(serviceManagement, authCredentials.ClientCredentials);
            }

            annotationsToMigrate = new ConcurrentQueue <Guid>();
            attachmentsToMigrate = new ConcurrentQueue <Guid>();
            string pagingCookie = null;

            Microsoft.Xrm.Sdk.Query.QueryExpression queryExpression;
            int pageSize = 1000;

            try
            {
                if (external)
                {
                    bool             moreRecords = false;
                    int              pageNum     = 1;
                    EntityCollection results;
                    if (migrateAnnotations)
                    {
                        Notify(string.Format("Getting list of '{0}' to migrate...", BinaryStorageOptions.AnnotationDetails.EntityName));

                        queryExpression          = new Microsoft.Xrm.Sdk.Query.QueryExpression(BinaryStorageOptions.AnnotationDetails.EntityName);
                        queryExpression.Criteria = new Microsoft.Xrm.Sdk.Query.FilterExpression(Microsoft.Xrm.Sdk.Query.LogicalOperator.And);
                        queryExpression.Criteria.AddCondition(BinaryStorageOptions.AnnotationDetails.FileNameAttributeKey, Microsoft.Xrm.Sdk.Query.ConditionOperator.DoesNotBeginWith, BinaryStorageOptions.Constants.ExternalFilePrefix);
                        queryExpression.Criteria.AddCondition(BinaryStorageOptions.AnnotationDetails.FileNameAttributeKey, Microsoft.Xrm.Sdk.Query.ConditionOperator.NotNull);
                        queryExpression.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(false);
                        queryExpression.PageInfo  = new Microsoft.Xrm.Sdk.Query.PagingInfo
                        {
                            Count        = pageSize,
                            PageNumber   = pageNum,
                            PagingCookie = pagingCookie,
                        };
                        results      = localProxy.RetrieveMultiple(queryExpression);
                        pagingCookie = results.PagingCookie;
                        moreRecords  = results.MoreRecords;
                        while (moreRecords || results.Entities.Count > 0)
                        {
                            results.Entities.Select(e => e.Id).ToList().ForEach(id => annotationsToMigrate.Enqueue(id));
                            Notify(string.Format("{0} found : {1}", BinaryStorageOptions.AnnotationDetails.EntityName, annotationsToMigrate.Count));
                            queryExpression.PageInfo.PageNumber   = ++pageNum;
                            queryExpression.PageInfo.PagingCookie = pagingCookie;
                            results      = localProxy.RetrieveMultiple(queryExpression);
                            pagingCookie = results.PagingCookie;
                            moreRecords  = results.MoreRecords;
                        }
                    }

                    if (migrateEmailAttachments)
                    {
                        Notify(string.Format("Getting list of '{0}' to migrate...", BinaryStorageOptions.AttachmentDetails.EntityName));

                        moreRecords              = false;
                        pageNum                  = 1;
                        pagingCookie             = null;
                        queryExpression          = new Microsoft.Xrm.Sdk.Query.QueryExpression(BinaryStorageOptions.AttachmentDetails.EntityName);
                        queryExpression.Criteria = new Microsoft.Xrm.Sdk.Query.FilterExpression(Microsoft.Xrm.Sdk.Query.LogicalOperator.And);
                        queryExpression.Criteria.AddCondition(BinaryStorageOptions.AttachmentDetails.FileNameAttributeKey, Microsoft.Xrm.Sdk.Query.ConditionOperator.DoesNotBeginWith, BinaryStorageOptions.Constants.ExternalFilePrefix);
                        queryExpression.Criteria.AddCondition(BinaryStorageOptions.AttachmentDetails.FileNameAttributeKey, Microsoft.Xrm.Sdk.Query.ConditionOperator.NotNull);
                        queryExpression.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(false);
                        queryExpression.PageInfo  = new Microsoft.Xrm.Sdk.Query.PagingInfo
                        {
                            Count        = pageSize,
                            PageNumber   = pageNum,
                            PagingCookie = pagingCookie,
                        };
                        results      = localProxy.RetrieveMultiple(queryExpression);
                        pagingCookie = results.PagingCookie;
                        moreRecords  = results.MoreRecords;
                        while (moreRecords || results.Entities.Count > 0)
                        {
                            results.Entities.Select(e => e.Id).ToList().ForEach(id => attachmentsToMigrate.Enqueue(id));
                            Notify(string.Format("{0} found : {1}", BinaryStorageOptions.AttachmentDetails.EntityName, attachmentsToMigrate.Count));
                            queryExpression.PageInfo.PageNumber   = ++pageNum;
                            queryExpression.PageInfo.PagingCookie = pagingCookie;
                            results      = localProxy.RetrieveMultiple(queryExpression);
                            pagingCookie = results.PagingCookie;
                            moreRecords  = results.MoreRecords;
                        }
                    }
                }
                else
                {
                    BinaryStorageOptions.Configuration.IConfigurationProvider configProvider;
                    BinaryStorageOptions.Providers.IBinaryStorageProvider     storageProvider;
                    allExternalFileNames = new ConcurrentDictionary <string, ConcurrentDictionary <Guid, string> >();
                    if (migrateAnnotations)
                    {
                        Notify(string.Format("Getting list of '{0}' to migrate...", BinaryStorageOptions.AnnotationDetails.EntityName));
                        configProvider  = BinaryStorageOptions.Configuration.Factory.GetConfigurationProvider(proxy, BinaryStorageOptions.AnnotationDetails.EntityName);
                        storageProvider = BinaryStorageOptions.Providers.Factory.GetStorageProvider(configProvider);
                        var externalAnnotations = new ConcurrentDictionary <Guid, string>(storageProvider.GetFileNames().ToDictionary(fn => new Guid(fn.Substring(0, 36))));
                        annotationsToMigrate = new ConcurrentQueue <Guid>(externalAnnotations.Keys);
                        if (!allExternalFileNames.TryAdd(BinaryStorageOptions.AnnotationDetails.EntityName, externalAnnotations))
                        {
                            throw new InvalidOperationException("Could not load list of annotations.");
                        }
                    }
                    if (migrateEmailAttachments)
                    {
                        Notify(string.Format("Getting list of '{0}' to migrate...", BinaryStorageOptions.AttachmentDetails.EntityName));
                        configProvider  = BinaryStorageOptions.Configuration.Factory.GetConfigurationProvider(proxy, BinaryStorageOptions.AttachmentDetails.EntityName);
                        storageProvider = BinaryStorageOptions.Providers.Factory.GetStorageProvider(configProvider);
                        var externalAttachments = new ConcurrentDictionary <Guid, string>(storageProvider.GetFileNames().ToDictionary(fn => new Guid(fn.Substring(0, 36))));
                        attachmentsToMigrate = new ConcurrentQueue <Guid>(externalAttachments.Keys);
                        if (!allExternalFileNames.TryAdd(BinaryStorageOptions.AttachmentDetails.EntityName, externalAttachments))
                        {
                            throw new InvalidOperationException("Could not load list of attachments.");
                        }
                    }
                }
            }
            finally
            {
                if (localProxy != null)
                {
                    localProxy.Dispose();
                    localProxy = null;
                }
            }
        }
Example #15
0
        static async Task Main(string[] args)
        {
            try
            {
                var _crmUrl           = "https://crm.test.ru/";
                var _organizationName = "Org";
                var config            = Microsoft.Xrm.Sdk.Client.ServiceConfigurationFactory
                                        .CreateConfiguration <Microsoft.Xrm.Sdk.IOrganizationService>(
                    new Uri($"{_crmUrl}{_organizationName}/XRMServices/2011/Organization.svc"));


                var clientCredentials = new System.ServiceModel.Description.ClientCredentials();
                clientCredentials.Windows.ClientCredential.UserName = "******";
                clientCredentials.Windows.ClientCredential.Password = "******";

                var client = new Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy(config, clientCredentials);
                //client.CallerId = new Guid("5c073647-da06-e611-80f9-005056971789");

                var q = new Microsoft.Xrm.Sdk.Query.QueryExpression("role")
                {
                    ColumnSet = { Columns = { "name", "businessunitid", "roleid" } },
                    Orders    =
                    {
                        new Microsoft.Xrm.Sdk.Query.OrderExpression("name", Microsoft.Xrm.Sdk.Query.OrderType.Ascending)
                    },
                    LinkEntities =
                    {
                        new Microsoft.Xrm.Sdk.Query.LinkEntity("role",                                              "systemuserroles", "roleid",       "roleid",
                                                               Microsoft.Xrm.Sdk.Query.JoinOperator.Inner)
                        {
                            LinkEntities =
                            {
                                new Microsoft.Xrm.Sdk.Query.LinkEntity("systemuserroles",                           "systemuser",                           "systemuserid",
                                                                       "systemuserid",                              Microsoft.Xrm.Sdk.Query.JoinOperator.Inner)
                                {
                                    LinkCriteria =
                                    {
                                        Filters            =
                                        {
                                            new Microsoft.Xrm.Sdk.Query.FilterExpression(Microsoft.Xrm.Sdk.Query
                                                                                         .LogicalOperator.And)
                                            {
                                                Conditions =
                                                {
                                                    new Microsoft.Xrm.Sdk.Query.ConditionExpression("systemuserid",
                                                                                                    Microsoft.Xrm.Sdk.Query.ConditionOperator.EqualUserId)
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                };

                var rq = new Microsoft.Xrm.Sdk.Messages.RetrieveMultipleRequest()
                {
                    Query = q
                };

                /*var n = new Microsoft.Crm.Sdk.Messages.SetStateRequest
                 * {
                 *  EntityMoniker =
                 *      new Microsoft.Xrm.Sdk.EntityReference("lead", new Guid("c5dc1b6f-1712-e811-8229-005056977311")),
                 *  State = new Microsoft.Xrm.Sdk.OptionSetValue(0),
                 *  Status = new Microsoft.Xrm.Sdk.OptionSetValue(100000003)
                 * };
                 *
                 * var r = client.Execute(n);*/

                var result = await client.RetrieveMultiple(q);

                //return result.Entities.Select(i => i.GetAttributeValue<string>("name"));
                foreach (var role in result.Entities)
                {
                    Console.WriteLine(role.GetAttributeValue <string>("name"));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.WriteLine();
            Console.WriteLine("Press key");
            Console.ReadKey();
        }
Example #16
0
 public override DataCollection <Entity> Execute()
 {
     Microsoft.Xrm.Sdk.Query.QueryExpression query = QueryHelper.CreateQueryExpressionFromTable(_entityName, _criteria, _crmContext);
     return(GlobalTestingContext.ConnectionManager.CurrentConnection.RetrieveMultiple(query).Entities);
 }
        public Microsoft.Xrm.Sdk.EntityCollection OnRetrieveMultiple(string primaryentityname, Microsoft.Xrm.Sdk.Query.QueryExpression query)
        {
            var result = new Microsoft.Xrm.Sdk.EntityCollection();

            for (var i = 0; i < 10; i++)
            {
                result.Entities.Add(new Microsoft.Xrm.Sdk.Entity {
                    LogicalName = primaryentityname, Id = Guid.NewGuid()
                });
            }
            return(result);
        }
Example #18
0
 public Microsoft.Xrm.Sdk.EntityCollection GetRecordsUsingQuery(Microsoft.Xrm.Sdk.Query.QueryExpression queryExpression)
 {
     throw new NotImplementedException();
 }
        //    public static Dictionary<string, Microsoft.Xrm.Sdk.EntityCollection> EntityCollectionCached = new Dictionary<string, Microsoft.Xrm.Sdk.EntityCollection>();



        //https://msdn.microsoft.com/en-us/library/mt269606.aspx
        public static Microsoft.Xrm.Sdk.EntityCollection RetrieveAll(Microsoft.Xrm.Sdk.IOrganizationService serviceOrgnization, string entityName
                                                                     , string columnSet = "", string filter = "", int retrievedNumberOfRecords = 50, string orderBy = "", int pageNumber = 1, string pagingCookie = null)
        {
            Microsoft.Xrm.Sdk.EntityCollection retVal = null;

            string uniqueRecordString = $"{entityName} '{columnSet}' '{filter}' {retrievedNumberOfRecords} '{orderBy}' {pageNumber}  ";

            /*
             * if (EntityCollectionCached.ContainsKey(uniqueRecordString))
             * {
             *  return EntityCollectionCached[uniqueRecordString];
             * }*/
            // Query using the paging cookie.
            // Define the paging attributes.
            // The number of records per page to retrieve.
            int queryCount = retrievedNumberOfRecords;

            // Create the query expression and add condition.
            Microsoft.Xrm.Sdk.Query.QueryExpression pagequery = new Microsoft.Xrm.Sdk.Query.QueryExpression();
            pagequery.EntityName = entityName;

            filter = filter.ToLower();
            if (!string.IsNullOrEmpty(filter) && !string.IsNullOrWhiteSpace(filter) && filter != "null")
            {
                string[] conditionsStr = filter.Split(new string[] { "&" }, StringSplitOptions.None);

                foreach (string conditionStr in conditionsStr)
                {
                    string[] conditionStrs          = conditionStr.Split('=');
                    string   conditionAttributeName = conditionStrs[0];

                    bool isNot = false;

                    if (conditionAttributeName.EndsWith("!"))
                    {
                        isNot = true;
                        conditionAttributeName = conditionAttributeName.Replace("!", "");
                    }

                    string conditionAttributeValue = conditionStrs[1];

                    // Define the condition expression for retrieving records.
                    Microsoft.Xrm.Sdk.Query.ConditionExpression pagecondition = new Microsoft.Xrm.Sdk.Query.ConditionExpression();
                    pagecondition.AttributeName = conditionAttributeName;



                    if (conditionAttributeValue.StartsWith("(") && conditionAttributeValue.EndsWith(")"))
                    {
                        conditionAttributeValue = conditionAttributeValue.Replace("(", "").Replace(")", "");

                        pagecondition.Operator = isNot ? Microsoft.Xrm.Sdk.Query.ConditionOperator.NotIn : Microsoft.Xrm.Sdk.Query.ConditionOperator.In;

                        foreach (var val in conditionAttributeValue.Split(','))
                        {
                            pagecondition.Values.Add(val);
                        }
                    }
                    else if (conditionAttributeValue.StartsWith("%") && conditionAttributeValue.EndsWith("%"))
                    {
                        pagecondition.Operator = isNot ? Microsoft.Xrm.Sdk.Query.ConditionOperator.NotLike : Microsoft.Xrm.Sdk.Query.ConditionOperator.Like;
                        pagecondition.Values.Add(conditionAttributeValue);
                    }
                    else if (conditionAttributeValue.StartsWith(">"))
                    {
                        object objConditionAttributeValue = AttributeManager.GetAttributeValueFromString(serviceOrgnization, entityName, conditionAttributeName, conditionAttributeValue.Replace("<", "").Replace(">", ""));
                        pagecondition.Operator = Microsoft.Xrm.Sdk.Query.ConditionOperator.GreaterEqual;
                        pagecondition.Values.Add(objConditionAttributeValue);
                    }
                    else if (conditionAttributeValue.StartsWith("<"))
                    {
                        object objConditionAttributeValue = AttributeManager.GetAttributeValueFromString(serviceOrgnization, entityName, conditionAttributeName, conditionAttributeValue.Replace("<", "").Replace(">", ""));
                        pagecondition.Operator = Microsoft.Xrm.Sdk.Query.ConditionOperator.LessEqual;
                        pagecondition.Values.Add(objConditionAttributeValue);
                    }
                    else
                    {
                        object objConditionAttributeValue = AttributeManager.GetAttributeValueFromString(serviceOrgnization, entityName, conditionAttributeName, conditionAttributeValue);
                        pagecondition.Operator = isNot ? Microsoft.Xrm.Sdk.Query.ConditionOperator.NotEqual : Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal;
                        pagecondition.Values.Add(objConditionAttributeValue);
                    }

                    pagequery.Criteria.AddCondition(pagecondition);
                }
            }

            // Define the order expression to retrieve the records.
            if (!string.IsNullOrEmpty(orderBy))
            {
                orderBy = orderBy.ToLower();
                string[] orderByStrs = orderBy.Split(' ');

                string orderAttributeName = orderByStrs[0];


                string orderType = "desc";

                if (orderByStrs.Length > 1)
                {
                    orderType = (string.IsNullOrEmpty(orderByStrs[1]) || orderByStrs[1] != "asc") ? "desc" : "asc";
                }

                Microsoft.Xrm.Sdk.Query.OrderExpression order = new Microsoft.Xrm.Sdk.Query.OrderExpression();
                order.AttributeName = orderAttributeName;

                order.OrderType = (orderType == "desc") ? Microsoft.Xrm.Sdk.Query.OrderType.Ascending : Microsoft.Xrm.Sdk.Query.OrderType.Descending;

                pagequery.Orders.Add(order);
            }

            // pagequery.ColumnSet.AddColumns("name", "emailaddress1");
            //By Rasheed
            string[] columns = GetColumnSet(entityName, columnSet);
            pagequery.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(columns);
            // end by rasheed

            // Assign the pageinfo properties to the query expression.
            pagequery.PageInfo            = new Microsoft.Xrm.Sdk.Query.PagingInfo();
            pagequery.PageInfo.Count      = queryCount;
            pagequery.PageInfo.PageNumber = pageNumber;

            // The current paging cookie. When retrieving the first page,
            // pagingCookie should be null.
            pagequery.PageInfo.PagingCookie = pagingCookie;


            // Retrieve the page.
            retVal = serviceOrgnization.RetrieveMultiple(pagequery);


            //EntityCollectionCached.Add(uniqueRecordString, retVal);
            return(retVal);
        }
Example #20
0
        /// <summary>
        /// Method to get users in given Role. in CRM Marketing list.
        /// This method has been customized to support dynamic lists.
        /// </summary>
        /// <param name="roleName"></param>
        /// <returns></returns>
        public override string[] GetUsersInRole(string roleName)
        {
            //setting that disabled the dynamic list functionality.
            if (SitecoreUtility.GetSitecoreSetting <bool>("AlphaSolutions.ExtendedCRMProvider.Disable.DynamicLists",
                                                          false))
            {
                return(base.GetUsersInRole(roleName));
            }

            Assert.ArgumentNotNull(roleName, "roleName");
            ConditionalLog.Info(string.Format("GetUsersInRole({0}). Started.", roleName), this, TimerAction.Start, "getUsersInRole");
            string text = base.CacheService.MembersCache.Get(roleName);

            if (text != null)
            {
                ConditionalLog.Info(string.Format("GetUsersInRole({0}). Finished (users have been retrieved from cache).", roleName), this, TimerAction.Stop, "getUsersInRole");
                return(text.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries));
            }

            // set up a query for the list to check type
            Microsoft.Xrm.Sdk.Query.ColumnSet columnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "listname", "query", "type" });

            Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression();
            query.ColumnSet = columnSet;

            Microsoft.Xrm.Sdk.Query.ConditionExpression listnameCondition = new Microsoft.Xrm.Sdk.Query.ConditionExpression();
            listnameCondition.AttributeName = "listname";
            listnameCondition.Operator      = Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal;
            listnameCondition.Values.Add(roleName);

            Microsoft.Xrm.Sdk.Query.FilterExpression filterList = new Microsoft.Xrm.Sdk.Query.FilterExpression();
            filterList.Conditions.Add(listnameCondition);
            filterList.FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And;
            query.EntityName          = "list";
            query.Criteria            = filterList;

            // Execute the query
            Microsoft.Xrm.Sdk.Messages.RetrieveMultipleRequest req = new Microsoft.Xrm.Sdk.Messages.RetrieveMultipleRequest();
            req.Query = query;

            Microsoft.Xrm.Sdk.Messages.RetrieveMultipleResponse res
                = (Microsoft.Xrm.Sdk.Messages.RetrieveMultipleResponse) this.OrganizationService.Execute(req);

            if (res != null && res.EntityCollection != null && res.EntityCollection.Entities.Count > 0)
            {
                Entity myList = res.EntityCollection.Entities[0];
                if (myList.Attributes.Keys.Contains("query"))
                {
                    // Define the fetch attributes.
                    // Set the number of records per page to retrieve.
                    int fetchCount = Settings.FetchThrottlingPageSize;
                    // 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;

                    //Convert fetchXML to Query Expression
                    var xml = myList["query"].ToString();

                    HashSet <string> hashSet = new HashSet <string>();


                    try
                    {
                        while (true)
                        {
                            string xmlpaging = CreateXml(xml, pagingCookie, pageNumber, fetchCount, Settings.UniqueKeyProperty);
                            Microsoft.Xrm.Sdk.Query.FetchExpression f       = new Microsoft.Xrm.Sdk.Query.FetchExpression(xmlpaging);
                            RetrieveMultipleRequest retrieveMultipleRequest = new RetrieveMultipleRequest();
                            retrieveMultipleRequest.Query = f;
                            RetrieveMultipleResponse retrieveMultipleResponse = (RetrieveMultipleResponse)this.OrganizationService.Execute(retrieveMultipleRequest);
                            if (retrieveMultipleResponse != null && retrieveMultipleResponse.EntityCollection != null)
                            {
                                ConditionalLog.Info(string.Format("GetUsersInRole({0}). Retrieved {1} users from CRM.", roleName, retrieveMultipleResponse.EntityCollection.Entities.Count), this, TimerAction.Tick, "getUsersInRole");
                                foreach (Entity current in retrieveMultipleResponse.EntityCollection.Entities)
                                {
                                    try
                                    {
                                        base.CacheService.UserCache.Add(this.ContactToUserConverter.Convert(current));
                                        hashSet.Add((string)current[Settings.UniqueKeyProperty]);
                                    }
                                    catch (Exception e)
                                    {
                                        ConditionalLog.Error(string.Format("GetUsersInRole({0}). Error in converting contact to user. Number of attributes gotten: {1}", current.LogicalName, current.Attributes.Count), e, this);
                                    }
                                }
                                // Check for morerecords, if it returns 1.
                                if (retrieveMultipleResponse.EntityCollection.MoreRecords)
                                {
                                    // Increment the page number to retrieve the next page.
                                    pageNumber++;
                                }
                                else
                                {
                                    // If no more records in the result nodes, exit the loop.
                                    break;
                                }
                                pagingCookie = retrieveMultipleResponse.EntityCollection.PagingCookie;
                            }
                        }
                        var ret = hashSet.ToArray <string>();
                        base.CacheService.MembersCache.Add(roleName, string.Join("|", ret));
                        return(ret);
                    }
                    catch (System.Exception sourceException)
                    {
                        ConditionalLog.Error(string.Format("Couldn't get contacts of {0} marketing list from CRM.", roleName), sourceException, this);
                    }
                }
                else
                {
                    return(base.GetUsersInRole(roleName));
                }
            }
            return(new string[0]);
        }