本文整理汇总了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);
}
示例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);
}
}
示例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;
}
}
示例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;
}
示例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;
}
}
示例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;
}
示例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);
}
}
}
示例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);
}
示例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;
}
示例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;
}
}
示例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];
}
示例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"];
}
示例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();
}
示例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();
}
}
示例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);
}