Basic use of C# code in Plugin’s for MS CRM Dynamics 365
Tips and trics related Dynamics 365 crm Plugin, D365 Plugin tips, Dynamics CRM
Basic Structure to start writing a plugin for Beginners
using Microsoft.Xrm.Sdk; //References to be added
using Microsoft.Xrm.Sdk.Query; //References to be added
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BasicPlugin
{
public class BasicPlugin: IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
ITracingService tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity target= (Entity)context.InputParameters["Target"];
if(target.LogicalName=="EntityName")
{
//Write your line of code here
}
}
}
}
}
How to retrieve multiple Entity records using QueryExpression
QueryExpression query = new QueryExpression { EntityName = "new_otpmaster", ColumnSet = new ColumnSet("new_name") };
query.Criteria = new FilterExpression();
query.Criteria.AddCondition("new_oppurtunityid", ConditionOperator.Equal, leadGuid);
query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
query.AddOrder("createdon", OrderType.Ascending);
EntityCollection fetchedOTP = service.RetrieveMultiple(query);
Query expression with the filter on the linked entity
QueryExpression query = new QueryExpression { EntityName = "gap_additionaldata", ColumnSet = new ColumnSet(false) };
query.Criteria = new FilterExpression();
query.Criteria.AddCondition("gap_clientid", ConditionOperator.Equal, client.Id);
LinkEntity linkSetup = query.AddLink("gap_additionaldatatemplate", "gap_additionaldatatemplateid", "gap_additionaldatatemplateid", JoinOperator.Inner);
linkSetup.EntityAlias = "additionaldata"; // you should use lowercase here to keep consistent with the other names
linkSetup.LinkCriteria.FilterOperator = LogicalOperator.And; // And is the default, so you can comment this line if you want
linkSetup.LinkCriteria.AddCondition("gap_type", ConditionOperator.Equal, "810340001");
EntityCollection retrievedRecords = service.RetrieveMultiple(query);
QueryExpression to filter on N:N related entities
QueryExpression query = new QueryExpression("ihc_penaltydetail");
query.ColumnSet = new ColumnSet(true);
LinkEntity linkEntity1 = new LinkEntity("ihc_penaltydetail", "ihc_ihc_requestforappeal_ihc_penaltydetail", "ihc_penaltydetailid", "ihc_penaltydetailid", JoinOperator.Inner);
LinkEntity linkEntity2 = new LinkEntity("ihc_ihc_requestforappeal_ihc_penaltydetail", "ihc_requestforappeal", "ihc_requestforappealid", "ihc_requestforappealid", JoinOperator.Inner);
linkEntity1.LinkEntities.Add(linkEntity2);
query.LinkEntities.Add(linkEntity1);
linkEntity2.LinkCriteria = new FilterExpression();
linkEntity2.LinkCriteria.AddCondition(new ConditionExpression("ihc_requestforappealid", ConditionOperator.Equal, targetID));
EntityCollection collRecords = service.RetrieveMultiple(query);
How to retrieve entity records using service.retrieve in Plugin
Entity entity = service.Retrieve(target.LogicalName, target.Id, new ColumnSet("regardingobjectid"));
How to create a new Entity reference for Plugin using C#
EntityReference contactreference = new EntityReference(target.LogicalName, target.Id));
//or pass it as
new EntityReference("logicalName","ID"));
//How to get Name and Guid from an EntityReference or say a lookup field in MSCRM.
Guid contactlookup = (Guid)((EntityReference)(resultsys.Entities[0].Attributes["ccs_contact"])).Id;
string name = ((EntityReference)(resultsys.Entities[0].Attributes["ccs_contact"])).LogicalName;
How to add entity record to marketing list dynamically using C# in Plugin
AddMemberListRequest req = new AddMemberListRequest();
req.EntityId = contact.Id; //Add ContactId here (Or record Id here)
req.ListId = listId; // Add marketing List Id here
AddMemberListResponse resp = (AddMemberListResponse)service.Execute(req);
[/sourcecode]
How to change Status of Entity using Entity Moniker
SetStateRequest setStateRequest = new SetStateRequest()
{
EntityMoniker = new EntityReference
{
Id = OTP.Id, //Id of record
LogicalName = OTP.LogicalName,//Logical Name of record
},
State = new OptionSetValue(1),//value of status field
Status = new OptionSetValue(2) //value of status Reason field
};
service.Execute(setStateRequest);
How to Call a workflow from a Plugin in MSCRM
string esclateWorkflowName = "Send Acknowledgement Email for new case"; //The name of the workflow</span>
Guid workflowId = Guid.Empty;
QueryExpression query = new QueryExpression("workflow");
query.ColumnSet = new ColumnSet("workflowid");
query.Criteria.AddCondition(new ConditionExpression("name", ConditionOperator.Equal, esclateWorkflowName));
query.Criteria.AddCondition(new ConditionExpression("type", ConditionOperator.Equal, 1));
EntityCollection collWorkflow = service.RetrieveMultiple(query);
if (collWorkflow.Entities.Count > 0)
{
workflowId = collWorkflow.Entities[0].Id;
}
if ( workflowId != Guid.Empty)
{
ExecuteWorkflowRequest request = new ExecuteWorkflowRequest();
request.WorkflowId = workflowId;
request.EntityId = newCaseId; //Pass the guid of the entity record for which workflow has to trigger or you can also pass a random record in it;
ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)service.Execute(request);
}
How to resolve a Case Entity using Plugin
Since case resolution is different from state change of other entity here an intermediate entity is created by the system while closing a case. So EntityMoniker doesn’t work here.
Entity caseResolution = new Entity("incidentresolution");
caseResolution.Attributes.Add("incidentid", new EntityReference("incident", targetEntity.Id));
CloseIncidentRequest req = new CloseIncidentRequest();
req.IncidentResolution = caseResolution;
req.RequestName = "CloseIncident";
OptionSetValue o = new OptionSetValue();
o.Value = 5;//Option Value for the Resolved Status;
req.Status = o;
CloseIncidentResponse resp = (CloseIncidentResponse)service.Execute(req);
How to Assign a record to a user using a plugin in MSCRM
AssignRequest Assing = new AssignRequest()
{
Assignee = new EntityReference
{
LogicalName = "systemuser",
Id = result.Entities[0].Id, //Id of the user
},
Target = new EntityReference("incident", entity.Id) //record reference
};
service.Execute(Assing);
How to call an Action using C# code
Create an action in MSCRM with input fields and then with the name of the action call it using C# code.
private static void CallAction(OrganizationServiceProxy service1)
{
OrganizationRequest req = new OrganizationRequest("ccs_TestPleaseignore");
req["CusLastName"] = "Sinha";//Input fields for Action
req["CUSFirstname"] = new EntityReference("new_enquiry", enquiryObj.Id);//Input fields for Action
req["CUSFirstname"] = "Sanket1241";//Input fields for Action
req["Target"] = new EntityReference("contact", new Guid("FD348189-C674-E611-80C3-02215E94456F")); //setting target which is required
//execute the request
var response = service1.Execute(req);
string responseid = response.Results["Added"].ToString();
Guid qresponseid = ((EntityReference)response.Results["Addedguid"]).Id;
}
How to create new entity record using C# in MSCRM
Entity contact = new Entity("contact");//Created a new object for //contact entity
if(target.Contains("mo_name"))
{
contact["lastname"] = target["mo_name"].ToString(); //setting a string type value
}
if (target.Contains("mo_firstname"))
{
contact["firstname"] =target["mo_firstname"].ToString();//setting a string type value
}
if (target.Contains("mo_businessphone"))
{
contact["telephone1"] = target["mo_businessphone"].ToString();
}
if (target.Contains("mo_dateofbirth"))
{
contact["birthdate"] = ((DateTime)target["mo_dateofbirth"]); //setting a Datetime type value
}
if (target.Contains("mo_martialstatus"))
{
int maritalstatus = ((OptionSetValue)target["mo_martialstatus"]).Value;
contact["familystatuscode"] = new OptionSetValue(maritalstatus); //setting a optionset type value
}
if (target.Contains("mo_nationality"))
{
contact["mo_citizenship"] = ((EntityReference)target["mo_nationality"]);//setting a EntityReference (Lookup) type value
}
//update membership type
if (target.Contains("mo_studentmember") && target["mo_studentmember"].Equals(true))
{
contact["mo_studentmember"] = true; //setting a boolean type value
}
contact["mo_expirydate"] = DateTime.Today.AddYears(1); //setting a DateTime type value
contactId = service.Create(contact);
Gud post
LikeLiked by 1 person