Subject Records Imported to Custom Entity in CRM

In my project,there was a requirement for creating a custom entity which will have the same records as present in the subject entity.So I had to create a tool to import the subject records to the custom entity created in CRM(here named as : DecisionTreeNode)

Here in this article I will be demonstrating the steps for creating the tool which imports subject record to the custom entity.Below are the steps:

Step 1:

Create a new windows application with the following form design:

Step 2:

In the Program.cs ,it will have the following code :


static  class Program   {
///  <summary>
/// The main entry point for the application.
///  </summary>
[STAThread]
static  void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new  Utility());
}
}

Step 3 :

Add a new cs file and write the following code:

On click of the Retrieve button:

private  void ButtonSubjects_Click(object sender, EventArgs e)
{
try
{
Microsoft.Crm.Sdk.CrmAuthenticationToken token = new Microsoft.Crm.Sdk.CrmAuthenticationToken();
token.OrganizationName = ConfigurationManager.AppSettings["organizationName"];
string crmServerUrl = ConfigurationManager.AppSettings["crmServiceUrl"];
Microsoft.Crm.SdkTypeProxy.CrmService service = new Microsoft.Crm.SdkTypeProxy.CrmService();
if (crmServerUrl != null && crmServerUrl.Length > 0)
{
UriBuilder builder = new  UriBuilder(crmServerUrl);
builder.Path = "//MSCRMServices//2007//CrmService.asmx";
service.Url = builder.Uri.ToString();
}
service.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["username"], ConfigurationManager.AppSettings["password"], ConfigurationManager.AppSettings["Domain"]);
service.CrmAuthenticationTokenValue = token;
this.UpdateChildRecords(service);
labelMessage.Text = "Records imported to Decision TreeNode successfully.";
labelMessage.ForeColor = Color.Green;
labelMessage.Visible = true;
}
catch (Exception)
{
labelMessage.Text = "Records could not be imported!";
labelMessage.ForeColor = Color.Red;
labelMessage.Visible = true;
throw;
}
}

Which calls UpdateChild Records function

public  void UpdateChildRecords(CrmService crmService)
{
////string parentName = string.Empty;
QueryExpression query = new QueryExpression();
//// Setup the query for the new_decisiontreenode entity
query.EntityName = "subject";
//// Specify the columns to retrieve
ColumnSet columns = new ColumnSet();
columns.AddColumns(new  string[] { "subjectid", "parentsubject", "title", "description" });
query.ColumnSet = columns;
RetrieveMultipleRequest retrieveMultipleRequest = new RetrieveMultipleRequest();
retrieveMultipleRequest.ReturnDynamicEntities = true;
retrieveMultipleRequest.Query = query;
RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieveMultipleRequest);
BusinessEntityCollection businessUpdate = retrieved.BusinessEntityCollection;
//// Execute the query and return the result
foreach (BusinessEntity bechild in businessUpdate.BusinessEntities)
{
string parentId = string.Empty;
string currentTitle = string.Empty;
string fullName = string.Empty;
string formattedName = string.Empty;
DynamicEntity de = (DynamicEntity)bechild;
if (de.Properties.Contains("parentsubject"))
{
parentId = ((Microsoft.Crm.Sdk.CrmReference)de.Properties["parentsubject"]).Value.ToString();
currentTitle = de.Properties["title"].ToString();
fullName = this.GetParentName(crmService, ((Key)de.Properties["subjectid"]).Value.ToString()) + "." + currentTitle;
formattedName = fullName.Remove(0, 1);
}
string subjectId = ((Key)de.Properties["subjectid"]).Value.ToString();
string title = de.Properties["title"].ToString();
var lookupPropertySubject = new LookupProperty();
lookupPropertySubject.Name = "new_subject";
var lookupSubject = new Lookup();
lookupSubject.type = "subject";
lookupSubject.Value = new  Guid(subjectId);
if (string.IsNullOrEmpty(formattedName))
{
lookupSubject.name = title;
}
else
{
lookupSubject.name = formattedName;
}
lookupPropertySubject.Value = lookupSubject;
CreateNewRecord(subjectId, parentId, lookupPropertySubject, crmService);
}
public  string GetParentName(CrmService crmService, string subjectId)
{
////string parentName = string.Empty;
QueryExpression query = new QueryExpression();
//// Setup the query for the new_decisiontreenode entity
query.EntityName = "subject";
//// Specify the columns to retrieve
ColumnSet columns = new ColumnSet();
columns.AddColumns(new  string[] { "subjectid", "parentsubject", "title", "description" });
////ColumnSet columns= new AllColumns();
query.ColumnSet = columns;
//// Create the new_parentid condition
ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = "subjectid";
condition1.Operator = ConditionOperator.Equal;
condition1.Values = new  object[] { subjectId };
////Create the FilterExpression
FilterExpression filter = new FilterExpression();
filter.FilterOperator = LogicalOperator.And;
filter.Conditions.Add(condition1);
query.Criteria = filter;
RetrieveMultipleRequest retrieveMultipleRequest = new RetrieveMultipleRequest();
retrieveMultipleRequest.ReturnDynamicEntities = true;
retrieveMultipleRequest.Query = query;
RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieveMultipleRequest);
BusinessEntityCollection businessUpdate = retrieved.BusinessEntityCollection;
BusinessEntity businessEntity = businessUpdate.BusinessEntities[0];
//// Execute the query and return the result
DynamicEntity de = (DynamicEntity)businessEntity;
string fullName = string.Empty;
if (de.Properties.Contains("parentsubject"))
{
fullName = this.GetParentName(crmService, ((Microsoft.Crm.Sdk.CrmReference)de.Properties["parentsubject"]).Value.ToString()) + "." + ((Microsoft.Crm.Sdk.CrmReference)de.Properties["parentsubject"]).name.ToString();
}
return fullName;
}

Step 4 :
Creating new records in the custom entity:

</span>
public  static  void CreateNewRecord(string subjectId, string parentId, LookupProperty subject, CrmService crmService)
{
if (crmService != null && subject != null)
{
if (!IsIdExists(subjectId, crmService))
{
var entityDecisionTreeNode = new DynamicEntity();
entityDecisionTreeNode.Name = "new_decisiontreenode";
var boolToBeEscalated = new CrmBooleanProperty();
boolToBeEscalated.Name = "new_tobeescalatedflag";
boolToBeEscalated.Value = new CrmBoolean();
boolToBeEscalated.Value.Value = true;
var newSubjectId = new StringProperty("new_subjectid", subjectId);
var newParentId = new StringProperty("new_parentid", parentId);
var subjectName = new LookupProperty("new_subject", subject.Value);
var subjectTitle = new StringProperty("new_title", subject.Value.name);
entityDecisionTreeNode.Properties.Add(newSubjectId);
entityDecisionTreeNode.Properties.Add(newParentId);
entityDecisionTreeNode.Properties.Add(boolToBeEscalated);
entityDecisionTreeNode.Properties.Add(subjectName);
entityDecisionTreeNode.Properties.Add(subjectTitle);
var targetCreate = new TargetCreateDynamic();
targetCreate.Entity = entityDecisionTreeNode;
//// Create the request object.
var create = new CreateRequest();
create.Target = targetCreate;
//// Execute the request.
crmService.Execute(create);
}
}
}

 

The above function turn calls IsIdExists function,which checks duplicate records are not created:

public static bool IsIdExists(string subjectId, CrmService crmService)
{
QueryExpression query = new QueryExpression();
//// Setup the query for the new_decisiontreenode entity
query.EntityName = "new_decisiontreenode";
//// Specify the columns to retrieve
ColumnSet columns = new ColumnSet();
columns.AddColumns(new string[] { "new_subjectid" });
query.ColumnSet = columns;
//// Create the new_parentid condition
ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = "new_subjectid";
condition1.Operator = ConditionOperator.Equal;
condition1.Values = new object[] { subjectId };
////Create the FilterExpression
FilterExpression filter = new FilterExpression();
filter.FilterOperator = LogicalOperator.And;
filter.Conditions.Add(condition1);
query.Criteria = filter;
RetrieveMultipleRequest retrieveMultipleRequest = new RetrieveMultipleRequest();
retrieveMultipleRequest.ReturnDynamicEntities = true;
retrieveMultipleRequest.Query = query;
RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieveMultipleRequest);
BusinessEntityCollection businessUpdate = retrieved.BusinessEntityCollection;
if (businessUpdate.BusinessEntities.Count > 0)
{
return true;
}
else
{
return false;
}
}

Step 5:
On Button Close click the following code has to be added:

private void ButtonClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Utility_Load(object sender, EventArgs e)
{
labelMessage.Visible = false;
}

Now just build and run the exe,you will find the records created automatically to your custome entity.
Hope this helps and let me know if you face any issues.
Happy Coding 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s