当前位置: 首页>>代码示例>>C#>>正文


C# QueryExpression类代码示例

本文整理汇总了C#中QueryExpression的典型用法代码示例。如果您正苦于以下问题:C# QueryExpression类的具体用法?C# QueryExpression怎么用?C# QueryExpression使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


QueryExpression类属于命名空间,在下文中一共展示了QueryExpression类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: When_executing_a_query_expression_with_2_filters_combined_with_an_or_filter_right_result_is_returned

        public void When_executing_a_query_expression_with_2_filters_combined_with_an_or_filter_right_result_is_returned()
        {
            var context = new XrmFakedContext();
            var contact1 = new Entity("contact") { Id = Guid.NewGuid() }; contact1["fullname"] = "Contact 1"; contact1["firstname"] = "First 1";
            var contact2 = new Entity("contact") { Id = Guid.NewGuid() }; contact2["fullname"] = "Contact 2"; contact2["firstname"] = "First 2";

            context.Initialize(new List<Entity>() { contact1, contact2 });

            var qe = new QueryExpression() { EntityName = "contact" };
            qe.ColumnSet = new ColumnSet(true);
            

            var filter1 = new FilterExpression();
            filter1.AddCondition(new ConditionExpression("fullname", ConditionOperator.Equal, "Contact 1"));

            var filter2 = new FilterExpression();
            filter2.AddCondition(new ConditionExpression("fullname", ConditionOperator.Equal, "Contact 2"));

            qe.Criteria = new FilterExpression(LogicalOperator.Or);
            qe.Criteria.AddFilter(filter1);
            qe.Criteria.AddFilter(filter2);

            var result = XrmFakedContext.TranslateQueryExpressionToLinq(context, qe).ToList();

            Assert.True(result.Count == 2);
        }
开发者ID:ccellar,项目名称:fake-xrm-easy,代码行数:26,代码来源:FilterExpressionTests.cs

示例2: PreValidateContactCreate

        /// <summary>
        /// Pre-Validation method will default the values of contact preference fields
        /// </summary>
        private static void PreValidateContactCreate(IPluginExecutionContext context, IOrganizationService service)
        {
            Entity contactEntity = (Entity)context.InputParameters["Target"];
            OptionSetValue doNotAllow = new OptionSetValue(1);

            contactEntity.SetAttribute("donotemail", doNotAllow);
            contactEntity.SetAttribute("donotpostalmail", doNotAllow);
            contactEntity.SetAttribute("donotbulkemail", doNotAllow);
            contactEntity.SetAttribute("donotfax", doNotAllow);

            // Get a count of child phone call entities associated with this Contact
            QueryExpression query = new QueryExpression();
            query.EntityName = "phonecall";
            query.ColumnSet = new ColumnSet(allColumns: true);
            query.Criteria = new FilterExpression();
            query.Criteria.AddCondition(new ConditionExpression("regardingobjectid", ConditionOperator.Equal, context.PrimaryEntityId));

            RetrieveMultipleRequest request = new RetrieveMultipleRequest();
            request.Query = query;
            IEnumerable<Entity> results = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection.Entities;
            if (results.Any())
            {
                // Do not default contact preference for phone if there are already some associated phone calls
                // Why? Because! Testing!
                contactEntity.SetAttribute("donotphone", doNotAllow);
            }
        }
开发者ID:tswann,项目名称:CrmPluginTesting,代码行数:30,代码来源:ContactPlugin.cs

示例3: Run

        /// <summary>
        /// This method first connects to the Organization service. Afterwards, it
        /// retrieves roles.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user is prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetRetrieveRolesForOrg1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy is properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    QueryExpression query = new QueryExpression
                    {
                        EntityName = Role.EntityLogicalName,
                        ColumnSet = new ColumnSet("name", "roleid")

                    };

                    EntityCollection entities = _serviceProxy.RetrieveMultiple(query);
                    // Write the name and ID of each role to the console.
                    foreach (Entity item in entities.Entities)
                    {
                        Role role = item.ToEntity<Role>();
                        Console.WriteLine("Name: {0}. Id: {1}", role.Name, role.Id);
                    }
                    
                }
                //</snippetRetrieveRolesForOrg1>
            }
            // 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;
            }
        }
开发者ID:cesugden,项目名称:Scripts,代码行数:41,代码来源:RetrieveRolesForOrg.cs

示例4: FindPluginAssembly

        private static Guid FindPluginAssembly(OrganizationService service, string assemblyName)
        {
            var query = new QueryExpression
            {
                EntityName = "pluginassembly",
                ColumnSet = null,
                Criteria = new FilterExpression()
            };
            query.Criteria.AddCondition("name", ConditionOperator.Equal, assemblyName);

            var request = new RetrieveMultipleRequest
            {
                Query = query
            };

            var response = (RetrieveMultipleResponse)service.Execute(request);

            if (response.EntityCollection.Entities.Count == 1)
            {
                var id = response.EntityCollection[0].GetAttributeValue<Guid>("pluginassemblyid");
                _logger.Log(LogLevel.Debug, () => string.Format("Found id {0} for assembly", id));

                return id;
            }

            return Guid.Empty;
        }
开发者ID:skfd,项目名称:PluginAssemblyLoader,代码行数:27,代码来源:Program.cs

示例5: generateRiskFactorsForTemplate

        public Boolean generateRiskFactorsForTemplate(EntityReference riskTemplate, Guid fundingCaseRiskAssessmentId)
        {
            try
            {
                //
                QueryExpression qe = new QueryExpression("gcbase_risktemplateriskfactor");
                qe.Criteria.AddCondition("gcbase_risktemplate", ConditionOperator.Equal, riskTemplate.Id);
                qe.ColumnSet.AddColumns("gcbase_name", "gcbase_riskfactor", "gcbase_risktemplate");
                var riskFactors = _service.RetrieveMultiple(qe).Entities;

                foreach (var item in riskFactors)
                {
                    Entity riskFactorValue = new Entity("gcbase_riskfactorvalue");
                    riskFactorValue["gcbase_name"] = item.GetAttributeValue<EntityReference>("gcbase_riskfactor").Name;
                    riskFactorValue["gcbase_riskfactor"] = new EntityReference("gcbase_riskfactor", item.GetAttributeValue<EntityReference>("gcbase_riskfactor").Id);
                    riskFactorValue["gcbase_risktemplateriskfactor"] = new EntityReference("gcbase_risktemplateriskfactor", item.Id);
                    riskFactorValue["gcbase_fundingcaseriskassessment"] = new EntityReference("gcbase_fundingcaseriskassessment", fundingCaseRiskAssessmentId);
                    _service.Create(riskFactorValue);
                }

                return true;
            }
            catch
            {
                return false;
            }
        }
开发者ID:fredp613,项目名称:crmPluginsGnC,代码行数:27,代码来源:RiskTemplate.cs

示例6: GetSolutions

        /// <summary>
        /// Получаем набор неуправляемых решений для организации
        /// </summary>
        /// <param name="service">сервис</param>
        /// <returns></returns>
        public static EntityCollection GetSolutions(IOrganizationService service)
        {
            var solutions = new EntityCollection();

            QueryExpression q = new QueryExpression("solution");
            //Берем только неуправляемые решения
            q.Criteria.AddCondition(new ConditionExpression("ismanaged", ConditionOperator.Equal, false));
            //не берем специальные CRMные солюшены
            q.Criteria.AddCondition(new ConditionExpression("friendlyname", ConditionOperator.NotEqual, "Active Solution"));
            q.Criteria.AddCondition(new ConditionExpression("friendlyname", ConditionOperator.NotEqual, "Default Solution"));
            q.Criteria.AddCondition(new ConditionExpression("friendlyname", ConditionOperator.NotEqual, "Basic Solution"));
            q.Orders.Add(new OrderExpression("createdon", OrderType.Descending));
            q.ColumnSet = new ColumnSet("friendlyname", "uniquename", "version", "installedon");
            q.PageInfo = new PagingInfo()
            {
                Count = 200,
                PageNumber = 1
            };

            EntityCollection ec;
            do
            {
                ec = service.RetrieveMultiple(q);
                solutions.Entities.AddRange(ec.Entities);
                q.PageInfo.PageNumber++;
                q.PageInfo.PagingCookie = ec.PagingCookie;
            } while (ec.MoreRecords);

            return solutions;
        }
开发者ID:helekon,项目名称:MergeCustomization,代码行数:35,代码来源:DataHandler.cs

示例7: RetrieveSolutions

        private EntityCollection RetrieveSolutions()
        {
            try
            {
                QueryExpression qe = new QueryExpression("solution");
                qe.Distinct = true;
                qe.ColumnSet = new ColumnSet(true);
                qe.Criteria = new FilterExpression();
                qe.Criteria.AddCondition(new ConditionExpression("ismanaged", ConditionOperator.Equal, false));
                qe.Criteria.AddCondition(new ConditionExpression("isvisible", ConditionOperator.Equal, true));
                qe.Criteria.AddCondition(new ConditionExpression("uniquename", ConditionOperator.NotEqual, "Default"));

                return innerService.RetrieveMultiple(qe);
            }
            catch (Exception error)
            {
                if (error.InnerException != null && error.InnerException is FaultException)
                {
                    throw new Exception("Error while retrieving solutions: " + (error.InnerException).Message);
                }
                else
                {
                    throw new Exception("Error while retrieving solutions: " + error.Message);
                }
            }
        }
开发者ID:NORENBUCH,项目名称:XrmToolBox,代码行数:26,代码来源:SolutionPicker.cs

示例8: Verify

        /// <summary>
        /// Runs the given query against the OdataLib's uri translator and compares the results against an inmemorycontext
        /// </summary>
        /// <param name="expression">The query expression to run against the Uri parser</param>
        public void Verify(QueryExpression expression)
        {

            // 1. test : take the expression and construct the OData URI
            // /Customers?$top=1
            string queryFragment = null;
            queryFragment = this.UriQueryVisitor.ComputeUri(expression);

            Uri serviceBaseUri = new Uri("http://localhost:9000/");

            // http://localhost:9000/Customers?$top=1
            Uri queryUri = new Uri(serviceBaseUri, queryFragment);

            this.Logger.WriteLine(LogLevel.Info, "Running Uri :{0}", queryUri.OriginalString);

            EntityModelSchema schema = Workspace.ConceptualModel;

            // Generate an EDM model based on the EntityModelSchema to use in the UriParser
            IEdmModel model = this.DataServiceProviderFactory.CreateMetadataProvider(schema);

            // Generate an IDSQP based on the EntityModelSchema to use in the Expression Translator
            var queryResolver = this.DataServiceProviderFactory.CreateQueryProvider(schema);

            // 2. product : take the URI , run it through the parser and get the Linq expression
            ODataUriParser parser = new ODataUriParser(model, serviceBaseUri, queryUri);
            var query = parser.ParseUri();
            var result = query.Path;

            // Get the expected Results
            QueryValue expectedResults = null;
            expectedResults = this.Evaluator.Evaluate(expression);
        }
开发者ID:AlineGuan,项目名称:odata.net,代码行数:36,代码来源:ODataUriParserVerifier.cs

示例9: LoadSecureFields

        public List<SecureFieldInfo> LoadSecureFields()
        {
            var query = new QueryExpression("fieldpermission")
            {
                ColumnSet = new ColumnSet(true)
            };

            var fields = service.RetrieveMultiple(query).Entities.ToList();

            var fieldsInfos = new List<SecureFieldInfo>();

            foreach (var field in fields)
            {
                var fieldInfo =
                    fieldsInfos.FirstOrDefault(fi => fi.Entity == field.GetAttributeValue<string>("entityname")
                                                     && fi.Attribute ==
                                                     field.GetAttributeValue<string>("attributelogicalname"));

                if (fieldInfo == null)
                {
                    fieldInfo = new SecureFieldInfo
                    {
                        Attribute = field.GetAttributeValue<string>("attributelogicalname"),
                        Entity = field.GetAttributeValue<string>("entityname"),
                    };

                    fieldsInfos.Add(fieldInfo);
                }

                fieldInfo.Fields.Add(field);
            }

            return fieldsInfos;
        }
开发者ID:NielsMinnee,项目名称:XrmToolBox,代码行数:34,代码来源:FlsManager.cs

示例10: RetrieveEntityFormList

        /// <summary>
        /// Retrieves main forms for the specified entity
        /// </summary>
        /// <param name="logicalName">Entity logical name</param>
        /// <param name="oService">Crm organization service</param>
        /// <returns>Document containing all forms definition</returns>
        public static IEnumerable<Entity> RetrieveEntityFormList(string logicalName, IOrganizationService oService)
        {
            var qe = new QueryExpression("systemform")
            {
                ColumnSet = new ColumnSet(true),
                Criteria = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression("objecttypecode", ConditionOperator.Equal, logicalName),
                        new ConditionExpression("type", ConditionOperator.In, new[] {2,7}),
                    }
                }
            };

            try
            {
                return oService.RetrieveMultiple(qe).Entities;
            }
            catch
            {
                qe.Criteria.Conditions.RemoveAt(qe.Criteria.Conditions.Count - 1);
                return oService.RetrieveMultiple(qe).Entities;
            }
        }
开发者ID:NORENBUCH,项目名称:XrmToolBox,代码行数:31,代码来源:MetadataHelper.cs

示例11: FindGuidForObject

        public void FindGuidForObject(IOrganizationService myCRMWebservice)
        {
            var myQuery = new QueryExpression
            {
                EntityName = this.sCrmEntityName,
                ColumnSet = new ColumnSet(this.sCrmEntityGuidFieldName),
                Criteria = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression
                        {
                          AttributeName  =  this.sCrmFilterAttributeName,
                          Operator = ConditionOperator.Equal,
                          Values = {this.sCrmFilterAttributeValue}
                        }
                    }
                }

            };

            DataCollection<Entity> accountResult = myCRMWebservice.RetrieveMultiple(myQuery).Entities;
            if (accountResult.Count > 0)
                this.crmGuidId = (Guid)accountResult[0][this.sCrmEntityGuidFieldName];
        }
开发者ID:anthonied,项目名称:CRM,代码行数:25,代码来源:BaseContainer.cs

示例12: getSecurityRoleGuidBySecurityRoleName

        public void getSecurityRoleGuidBySecurityRoleName(IOrganizationService securityRoleCrmWebservice)
        {
            var myQuery = new QueryExpression
            {
                EntityName = "role",
                ColumnSet = new ColumnSet("roleid"),
                Criteria = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression
                        {
                          AttributeName  =  "name",
                          Operator = ConditionOperator.Equal,
                          Values = {"roleName"}
                        }
                    }
                }
            };

            //DataCollection<Entity> securityRoleResult = CrmWebservice.RetrieveMultiple(myQuery).Entities;
            DataCollection<Entity> securityRoleResult = securityRoleCrmWebservice.RetrieveMultiple(myQuery).Entities;
            if (securityRoleResult.Count > 0)
                this.guidSecurityRoleId = (Guid)securityRoleResult[0]["roleid"];
        }
开发者ID:anthonied,项目名称:CRM,代码行数:25,代码来源:SecurityRoleBase.cs

示例13: GetCompanyReferenceById

        public static EntityReference GetCompanyReferenceById(this IOrganizationService service, string companyName)
        {
            var compayNameCondition = ConditionExpressionHelper.CreateCompanyNameCondition(companyName);
            var filter = new FilterExpression();
            filter.Conditions.Add(compayNameCondition);

            var query = new QueryExpression(Account.EntityLogicalName)
            {
                ColumnSet = new ColumnSet(true)
            };

            query.Criteria.AddFilter(filter);

            var companies = service.RetrieveMultiple(query)
                .Entities.ToList();

            if (!companies.Any())
            {
                throw new CrmEntityNotFoundException(string.Format("Company '{0}' was not found.", companyName));
            }

            if (companies.Count > 1)
            {
                throw new CrmAmbiguousMatchException(string.Format("{0} companies found with name '{1}'.", companies.Count, companyName));
            }

            return companies.Single().ToEntityReference();
        }
开发者ID:hydr,项目名称:VcardCrmImporter,代码行数:28,代码来源:OrganizationServiceExtensions.cs

示例14: GetAllFormsByTypeCode

        public List<Entity> GetAllFormsByTypeCode(int objectTypeCode)
        {
            var qe = new QueryExpression("systemform")
            {
                ColumnSet = new ColumnSet(new[] { "name", "formxml" }),
                Criteria = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression("objecttypecode", ConditionOperator.Equal, objectTypeCode),
                        new ConditionExpression("type", ConditionOperator.In, new[] {2,7}),
                        new ConditionExpression("iscustomizable", ConditionOperator.Equal, true),
                        new ConditionExpression("formactivationstate", ConditionOperator.Equal, 1),
                    }
                }
            };

            try
            {
                return Service.RetrieveMultiple(qe).Entities.ToList();
            }
            catch
            {
                qe.Criteria.Conditions.RemoveAt(qe.Criteria.Conditions.Count - 1);
                return Service.RetrieveMultiple(qe).Entities.ToList();
            }
        }
开发者ID:rehanhsyed,项目名称:XrmToolBox,代码行数:27,代码来源:FormManager.cs

示例15: GetAccountReferenceByNameFuzzy

        public static EntityReference GetAccountReferenceByNameFuzzy(this IOrganizationService service, string companyName)
        {
            var name = CompanyNameHelper.RemoveCommonCompanySuffixes(companyName);
            var nameCondition = ConditionExpressionHelper.CreatePublisherNameBeginsWithCondition(name);

            var filter = new FilterExpression();
            filter.Conditions.Add(nameCondition);

            var query = new QueryExpression(Account.EntityLogicalName);
            query.Criteria.AddFilter(filter);

            var accounts = service.RetrieveMultiple(query).Entities;

            if (accounts.Count() > 1)
            {
                throw new CrmAmbiguousMatchException(
                    string.Format("Found multiple fuzzy matches when searching for {0}.  Fuzzy match search: {1}", companyName, name));
            }

            var account = accounts.FirstOrDefault();
            if (account == null)
            {
                throw new CrmEntityNotFoundException("Account not found with name: " + companyName);
            }

            return new EntityReference(Account.EntityLogicalName, account.Id);
        }
开发者ID:hydr,项目名称:VcardCrmImporter,代码行数:27,代码来源:OrganizationServiceExtensions.cs


注:本文中的QueryExpression类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。