How to retrieve data from custom entity? - c#

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();

Related

Retrieve/fetch records from DYNAMICS 365 crm using C# code

Problem 1:
I am new to MICROSOFT DYNAMICS CRM 365. I have few tables with my CRM like(Account,Customer).I want to fetch all data from table account.
Below is my sample code for connection:(not sure this is correct or not but getting output message that i am connected to CRM)
public void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri)
{
try
{
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = UserName;
credentials.UserName.Password = Password;
Uri serviceUri = new Uri(SoapOrgServiceUri);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
proxy.EnableProxyTypes();
_services = (IOrganizationService)proxy;
Response.Write("Connected to CRM \n");
}
I need all data to be retrieved on button click event .
Output should be: result of "select * from ABC";
Problem 2:
if possible please suggest how to fetch records using given column name.
Output should be: result of "select * from ABC where ColumnName="test";
Fetching all entities list into List
var allEntities = **GetEntities(_service);**
foreach (var Entity in allEntities)
{
ddlEntityName.Items.Add(Entity.LogicalName);
}
//Function with single parameter (oganizationservice as a parameter)
//This will fetch Table/Entity Name Like ACCOUNT,CONTACT from Microsoft Dynamics CRM
public Microsoft.Xrm.Sdk.Metadata.EntityMetadata[] GetEntities(IOrganizationService organizationService)
{
Dictionary<string, string> attributesData = new Dictionary<string, string>();
RetrieveAllEntitiesRequest metaDataRequest = new RetrieveAllEntitiesRequest();
RetrieveAllEntitiesResponse metaDataResponse = new RetrieveAllEntitiesResponse();
metaDataRequest.EntityFilters = EntityFilters.Entity;
XmlDictionaryReaderQuotas myReaderQuotas = new XmlDictionaryReaderQuotas();
myReaderQuotas.MaxNameTableCharCount = 2147483647;
// Execute the request.
metaDataResponse = (RetrieveAllEntitiesResponse)organizationService.Execute(metaDataRequest);
var entities = metaDataResponse.EntityMetadata;
return entities.OrderBy(x => x.LogicalName).ToArray();//to arrange in ascending order
}
What about query expression?
This is your query :
Select * from ABC where ColumnName="test";
And this is the QueryExpression:
QueryExpression query = new QueryExpression()
{
EntityName = Contact.EntityLogicalName,
ColumnSet = new ColumnSet("address1_telephone1"),
};
to excute the query, this is how :
DataCollection<Entity> entityCollection = _services.RetrieveMultiple(query).Entities;
// Display the results.
foreach (Contact entity in entityCollection)
{
Console.WriteLine("my test: {0}", entity.address1_telephone1);
}
Regards

How to fetch entity records from CRM

I am very new to MS-CRM and I want to retreive all the details of the contact
var executeQuickFindRequest = new OrganizationRequest("ExecuteQuickFind");
executeQuickFindRequest.Parameters = new ParameterCollection();
var entities = new List<string> { "contact", "lead", "account" }; //specify search term
executeQuickFindRequest.Parameters.Add("SearchText", "maria");
//will cause serialisation exception if we don't convert to array
executeQuickFindRequest.Parameters.Add("EntityNames", entities.ToArray());
var executeQuickFindResponse = _orgService.Execute(executeQuickFindRequest);
var result = executeQuickFindResponse.Results;
The data here displayed contains display name's such as address_1_City,email_user
However I want to get there actual names like Address,Email etc etc.
Thanks
Just to extend what BlueSam has mentioned above.
EntityMetadata entityMetaData = retrieveEntityResponse.EntityMetadata;
for (int count = 0; count < entityMetaData.Attributes.ToList().Count; count++)
{
if (entityMetaData.Attributes.ToList()[count].DisplayName.LocalizedLabels.Count > 0)
{
string displayName = entityMetaData.Attributes.ToList()[count].DisplayName.LocalizedLabels[0].Label;
string logicalName = entityMetaData.Attributes.ToList()[count].LogicalName;
AttributeTypeCode dataType = (AttributeTypeCode)entityMetaData.Attributes.ToList()[count].AttributeType;
}
}
Above code will help you to get the display name, logical name and data type for each attribute in the entity. Similarly you can get other information as well from the entityMetaData object as per above code snippet.
As far as I know, you will need to pair it up with the attributes of the entities that are for that request. Here's a sample of how to retrieve an entity:
RetrieveEntityRequest retrieveBankAccountEntityRequest = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.Entity,
LogicalName = entityName
};
RetrieveEntityResponse retrieveEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveBankAccountEntityRequest);
You can do it easy as below
using (var service = new OrganizationService(CrmConnection.Parse("CRMConnectionString")))
{
var Res = service.Retrieve("sv_answer", new Guid("GUID Of Record"), new ColumnSet("ColumnName "));
}

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.

How to get result of rollup query for a custom entity

When trying to get the records I get this error
The 'Rollup' method does not support entities of type 'new_X'.
This is my code
RollupRequest req = new RollupRequest();
QueryExpression qe = new QueryExpression();
qe.EntityName = "new_x";
qe.ColumnSet = new ColumnSet(true);
req.Query = qe;
req.Target = new EntityReference("new_newpost", new Guid("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));
req.RollupType = RollupType.Related;
RollupResponse resp = (RollupResponse)xrm.Execute(req);
How can I get the results of rollup query
Thanks in advance
For custom entities you can do the fallowing
var rollupQuery = xrm.GoalRollupQuerySet.Where(c => c.Id == x.new_RecordstoRun.Id).First();
var result = xrm.RetrieveMultiple(new FetchExpression(rollupQuery.FetchXml));
But - How can I add a 'Skip' or 'Take' Linq to this?
You can only use the RollupRequest on a certain set of entities described on the MSDN.
So this will never work for "new_x" or "new_newpost".
This article has a correct demonstration of the RollupRequest using opportunity and account.
I would suggest just creating your own custom QueryExpression to retrieve all "new_x" and then link to "new_newpost" with LinkEntities.
Here is my code so get the results of RollupQuery
List<Guid> GetAllResultsFromRollupQuery(XrmServiceContext xrm, Guid rollupQueryId)
{
var rollupQuery = xrm.GoalRollupQuerySet.Where(v => v.Id == rollupQueryId).First();
var qa = GetQueryExpression(xrm, rollupQuery.FetchXml);
qa.PageInfo.Count = 1000;
qa.ColumnSet.AddColumn(rollupQuery.QueryEntityType + "id");
var result = new List<Guid>();
EntityCollection ec = null;
do
{
ec = xrm.RetrieveMultiple(qa);
ec.Entities.ToList().ForEach(v => result.Add((Guid)v.Attributes[rollupQuery.QueryEntityType + "id"]));
qa.PageInfo.PageNumber += 1;
} while (ec.MoreRecords == true);
return result;
}
QueryExpression GetQueryExpression(XrmServiceContext xrm, string fetchXml)
{
var req = new FetchXmlToQueryExpressionRequest { FetchXml = fetchXml };
var result = (FetchXmlToQueryExpressionResponse)xrm.Execute(req);
return result.Query;
}

Categories

Resources