Dynamics CRM 2015 Online: cannot retrive custom fields - c#

The following code throws a KeyNotFoundException at WriteLine():
CrmConnection crmConnection = CrmConnection.Parse(_connectionString);
using (OrganizationService service = new OrganizationService(crmConnection))
{
QueryExpression query = new QueryExpression
{
EntityName = "contact",
ColumnSet = new ColumnSet("fullname", "new_customer_num", "new_is_customer"),
};
EntityCollection contacts = service.RetrieveMultiple(query);
if (contacts.Entities.Count > 0)
{
foreach (var e in contacts.Entities)
{
System.Diagnostics.Debug.WriteLine(
e.Attributes["fullname"].ToString() + "; " +
e.Attributes["new_is_customer"].ToString());
}
}
}
I've already added new_customer_num and new_is_customer (required) fields to Contact entity. If I deliberately misspell them, then FaultException is thrown at service.RetrieveMultiple(query); so I guess CRM "knows" my custom fields. Then why doesn't query result include them?

Well, to make it work, I had to add a condition:
QueryExpression query = new QueryExpression
{
EntityName = "contact",
ColumnSet = new ColumnSet("fullname", "ht_customer_num", "ht_is_customer"),
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = "new_is_customer",
Operator = ConditionOperator.Equal,
Values = { true }
},
},
}
};
SDK Doc for ColumnSet says that query returns only non-null values.

Related

How to build a query to get a security role where user X does not exists in Dynamics CRM 2016 C#

I need to update the list of users for a security role. How can I avoid re-associating an user that already has the role assigned?
I'm trying to build a query to get the role where user x is not in the role's list of users and then use it for the association if the user was not found. Here is what I have so far:
LinkEntity userRoles = new LinkEntity
{
LinkFromEntityName = "role",
LinkToEntityName = "systemuserroles",
LinkFromAttributeName = "roleid",
LinkToAttributeName = "roleid",
JoinOperator = JoinOperator.LeftOuter,
Columns = new ColumnSet(true),
EntityAlias = "userroles",
LinkCriteria =
{
Conditions =
{
new ConditionExpression{
//not sure how to build the "where user x does not exists"
}
}
}
};
QueryExpression roleQuery = new QueryExpression
{
EntityName = "role",
ColumnSet = new ColumnSet(true),
Criteria =
{
Conditions = {
new ConditionExpression {
AttributeName = "name",
Operator = ConditionOperator.Equal,
Values = { "RoleName"}
}
}
},
LinkEntities = { userRoles }
};
I need to build something like this query:
select * from role
where role.name = "RoleName"
and not exists
(select 1 from userRoles
where userRoles.roleid = role.roleid
and userRoles.user = "xyz")
Based on this post that explained it using Fetch XML, I was able to build this query that gets the role as long as the user I specify is not there:
LinkEntity userRoles = new LinkEntity
{
LinkFromEntityName = "role",
LinkToEntityName = "systemuserroles",
LinkFromAttributeName = "roleid",
LinkToAttributeName = "roleid",
JoinOperator = JoinOperator.LeftOuter,
Columns = new ColumnSet(true),
EntityAlias = "userroles",
LinkCriteria =
{
Conditions =
{
new ConditionExpression {
AttributeName = "systemuserid",
Operator = ConditionOperator.Equal,
Values = { "xyz" }
}
}
}
};
QueryExpression roleQuery = new QueryExpression
{
EntityName = "role",
ColumnSet = new ColumnSet(true),
Criteria =
{
Filters = {
new FilterExpression{
FilterOperator = LogicalOperator.And,
Conditions = {
new ConditionExpression{
EntityName = "systemuserroles",
AttributeName = "roleid",
Operator = ConditionOperator.Null
}
}
}
},
Conditions = {
new ConditionExpression {
AttributeName = "name",
Operator = ConditionOperator.Equal,
Values = { "RoleName"}
}
}
},
LinkEntities = { userRoles }
};

Microsoft CRM QueryExpression in C#

i have code like below:
QueryExpression query = new QueryExpression();
query.EntityName = "new_callistyorder";
ColumnSet col = new ColumnSet("new_nomororder","new_customer");
query.ColumnSet = col;
EntityCollection colect = service.RetrieveMultiple(query);
string str = string.Empty;
foreach (Entity e in colect.Entities)
{
if(e.Contains("new_nomororder")){
str = str + e.Attributes["new_nomororder"].ToString();
}
}
throw new InvalidPluginExecutionException(str);
Trough this code. I am able to get data from microsoft dynamic entity.
Now, i want to get the data which have biggest id.
If in SQL Query, it would be looks something like this : "Select top 1 my_id from Account order by my_id desc".
How can i do that on queryexpression ?
Thanks
You can add the order by using this:
query.AddOrder("my_id", OrderType.Descending);
and then getting the first element retrieved.
var entityCollection = service.RetrieveMultiple(query);
if(entityCollection.Entities.Count<1)
{
//perform some logic
}

How to retrieve data from custom entity?

This code helps to retrieve the contact records based on the relation 1:N from the account entity
I want to retrieve the records of another custom entity called company from the account entity however I don't know how to call custom data entities to use it in the RetrieveContact method
- contact is a standard entity and company is a custom entity
PS: the account lookup of the company entity is called cs_accountid
BusinessEntityCollection bec = RetrieveContact(Service, context, ((Key)(Account.Properties["accountid"])).Value.ToString(), "contact", "parentcustomerid");
if (bec.BusinessEntities.Count > 0)
{
foreach (contact c in bec.BusinessEntities)
{
c.parentcustomerid = new Customer();
c.parentcustomerid.type = "account";
c.parentcustomerid.Value = k.Value;
Service.Update(c);
}
}
private BusinessEntityCollection RetrieveContact(ICrmService service, IPluginExecutionContext context, string AccountID, string FromEntityName, string FromAttributeName)
{
// Create the ConditionExpression.
ConditionExpression condition = new ConditionExpression();
condition.AttributeName = "accountid";
condition.Operator = ConditionOperator.Equal;
condition.Values = new string[] { AccountID };
// Create the Link entities
LinkEntity le = new LinkEntity();
le.LinkFromEntityName = FromEntityName;
le.LinkFromAttributeName = FromAttributeName;
le.LinkToEntityName = "account";
le.LinkToAttributeName = "accountid";
// Create the FilterExpression.
FilterExpression filter = new FilterExpression();
// Set the properties of the filter.
filter.FilterOperator = LogicalOperator.And;
filter.AddCondition(condition);
le.LinkCriteria = filter;
// Create the QueryExpression object.
QueryExpression query = new QueryExpression();
// Set the properties of the QueryExpression object.
query.EntityName = FromEntityName;// EntityName.contact.ToString();
query.ColumnSet = new AllColumns();// cols;
query.LinkEntities.Add(le);
//query.AddOrder("lastname", OrderType.Ascending);
BusinessEntityCollection bec = service.RetrieveMultiple(query);
return bec;
}
private DynamicEntity RetournRecord(string entityname, Guid recordid, TargetRetrieveDynamic target, ICrmService Service)
{
target.EntityId = recordid;
target.EntityName = entityname;
RetrieveRequest retrieve = new RetrieveRequest();
retrieve.Target = target;
retrieve.ColumnSet = new AllColumns();
retrieve.ReturnDynamicEntities = true;
// Create a response reference and execute the retrieve request.
RetrieveResponse response1 = (RetrieveResponse)Service.Execute(retrieve);
return (DynamicEntity)response1.BusinessEntity;
}
Thank you for your help and your time!
I know this is old, but the problem with the createquery is due to a typo-> ["cs_accountid") It should end with a square bracket not a round one.
UPDATE:
this solution is for CRM 2011/2013 and not for CRM 4.0:
i never used earlybinding so this is my example for the latebinding (will work for you, too).
using Microsoft.Xrm.Sdk.Client;
...
var service = OrganizationServiceFactory.CreateOrganizationService(PluginExecutionContext.UserId);
using (var context = new OrganizationServiceContext(service))
{
List<Entity> myCompanyRecords = context.CreateQuery("cs_company").Where(o => ((EntityReference)o["cs_accountid").Id.Equals(id)).ToList();
}
the "id" is the Guid of your account-entity-record.
in your method you already have the parameter "service" and "context" so you can just use this:
List<Entity> myCompanyRecords = context.CreateQuery("cs_company").Where(o => ((EntityReference)o["cs_accountid").Id.Equals(id)).ToList();

How do I search for lead or account using Dynamics CRM SDK?

Can someone please provide a sample code for retrieving leads by email in CRM SDK? Is there any built in function that works like this?
Guid leadID = someLeadManager.GetByEmail(email);
Assuming that you've obtained the service, you can execute the following query.
private Guid GetGuidByEmail(String email)
{
QueryExpression query = new QueryExpression
{
EntityName = "lead",
ColumnSet = new ColumnSet("emailaddress1"),
Criteria = new FilterExpression
{
Filters =
{
new FilterExpression
{
Conditions =
{
new ConditionExpression(
"emailaddress1", ConditionOperator.Equals, email)
}
}
}
}
};
Entity entity = service.RetrieveMultiple(query).Entities.FirstOrDefault();
if(entity != null)
return entity.Id;
return Guid.Empty;
}
Now, if you need filtration for a match of part of the email, the query gets shorter, and instead, you can do the selection using LINQ like this.
private IEnumerable<Guid> GetGuidsByEmail(String email)
{
QueryExpression query = new QueryExpression
{
EntityName = "lead",
ColumnSet = new ColumnSet("emailaddress1")
};
IEnumerable<Entity> entities = service.RetrieveMultiple(query).Entities;
return entities
.Where(element => element.Contains("emailaddress1"))
.Where(element => Regex.IsMatch(element["emailaddress1"], email))
.Select(element => element.Id);
}
Do you want to retrieve leads that have a specific mail? Something like this can be done in that case.
private EntityCollection GetLeadsWithEmail(
IOrganizationService service, String wantedEmailAddress)
{
QueryExpression query = new QueryExpression();
query.EntityName = "lead";
// the columns you want
query.ColumnSet = new ColumnSet() { AllColumns = true };
query.Criteria = new FilterExpression();
query.Criteria.FilterOperator = LogicalOperator.And;
query.Criteria.Conditions.Add(new ConditionExpression(
"emailaddress1", ConditionOperator.Equal, wantedEmailAddress));
return service.RetrieveMultiple(query);
}
This will retrieve all the leads that have wantedEmailAddress in their emailaddress1 field.
You can then check if there were any matches from where you called it;
EntityCollection leadCollection = GetLeadsWithEmail(
service, "someone#example.com");
Entity entity = leadCollection[0];
You probably should first check the number of entities in the collection with leadCollection.Entities.Count and continue from there.
Here's a sample from MSDN.

CRM 4.0 - extracting contact data from email address

I'm trying to use an email address to retrieve contact data. I'm already using this but i'm wondering how to extend it so that custom fields can also be returned:
public ContactInfo GetContactByEmail(string email, CrmService service)
{
QueryExpression query = new QueryExpression();
query.EntityName = "contact";
ColumnSet columns = new ColumnSet();
columns.Attributes.Add("contactid");
query.ColumnSet = columns;
query.Criteria = new FilterExpression();
query.Criteria.FilterOperator = LogicalOperator.And;
ConditionExpression condition = new ConditionExpression();
condition.AttributeName = "emailaddress1";
condition.Operator = ConditionOperator.Equal;
condition.Values = new object[] { email.Trim() };
query.Criteria.Conditions.Add(condition);
RetrieveMultipleRequest request = new RetrieveMultipleRequest();
request.Query = query;
ContactInfo contactInfo = new ContactInfo();
RetrieveMultipleResponse response = null;
response = (RetrieveMultipleResponse)service.Execute(request);
foreach (contact cont in response.BusinessEntityCollection.BusinessEntities)
{
contactInfo.contactid = cont.contactid.Value;
//Would also like to retrieve a custom attribute called ContactType (type int)
}
return contactInfo;
}
Any help or examples would be really appreciated. Thank you.
You just need to add additional values to the ColumnSet, e.g.
ColumnSet columns = new ColumnSet();
columns.Attributes.Add("new_contacttype");
Note: The name here should be the schema and not the display.
Examples:
Using Dynamic Entities.
Using the ColumnSet Class.
CrmService.RetrieveMultiple Method.

Categories

Resources