Counting Total number of records retrived by Fetch Xml using Custom workflow
We have done a custom workflow by using fetchxml to get the count of total opened tasks in CRM instance.
Script:
protected override void Execute(CodeActivityContext context)
{
ITracingService tracingService = context.GetExtension<ITracingService>();
IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId);
String query = @"<fetch version='1.0' mapping='logical' distinct='false' >
<entity name='task'>
<attribute name='subject' />
<attribute name='createdby' alias='countAlias' />
<order attribute='subject' descending='false' />
<filter type='and'>
<condition attribute='statecode' operator='eq' value='0' />
</filter>
</entity>
</fetch>";
FetchExpression fetch = new FetchExpression(query);
EntityCollection results = service.RetrieveMultiple(fetch);
int count = results.Entities.Count; //show this in your message box;
this.count.Set(context, count);
var countname = ((AliasedValue)count.["createdby"]).Value;
systemuser.Set(context, countname);
}
[Output("Count")]
public OutArgument<int> count { get; set; }
}
}
JavaScript in OData portals
We have done odata services in CRM Portals to achieve through java script.
Step 1: Enable the
portal entity list(Contact,Account,etc)
Go to Portal > Entity List. Create
a new Entity List for Case Entity.
Step2: Enable
Odata feed with entity type and views also in entity list
Step3: Now, To retrieve the data, Hit the URL in browser.
URL : Portal_URL/_odata
URL : Portal_URL/_odata/Entity_Set_Name
: To retrieve the
data
Here we can see the
<atom:title type=”text”>Cases</atom:title>
Step4: Upload
your JavaScript in your respective “entity form”.
Below script :
if
(window.jQuery) {
(function ($) {
$(document).ready(function () {
if (typeof (Page_Validators) ==
'undefined') return;
// Create new validator
var newValidator =
document.createElement('span');
newValidator.style.display =
"none";
newValidator.id = "titleValidator";
newValidator.controltovalidate =
"title";
newValidator.errormessage =
"<a href='#title_label'>This Case has been already
generated.</a>";
newValidator.validationGroup =
""; // Set this if you have set ValidationGroup on the form
newValidator.initialvalue =
"";
newValidator.evaluationfunction =
function () {
var count = GetCase();
if (count > 0 )
return false; // Return false mean apply validation.
else
return true; // Return true mean successful.
};
// Add the new validator to the page
validators array:
Page_Validators.push(newValidator);
// Wire-up the click event handler of
the validation summary link
$("a[href='#title_label']").on("click", function ()
{ scrollToAndFocus('title_label','title'); });
});
}(window.jQuery));
}
function
GetCase(){
var count = 0;
var title=$("#title").val();
$.ajax({
type: "GET",
contentType: "application/json;
charset=utf-8",
datatype: "json",
url: "~/_odata/Cases?$filter=title eq
'"+title+"'",
beforeSend: function(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept",
"application/json");
},
async: false,
success: function(data, textStatus, xhr) {
count = data.value.length;
},
error: function(xhr, textStatus,
errorThrown) {
Xrm.Utility.alertDialog(textStatus +
" " + errorThrown);
}
});
return
count;
}
Step5: If
duplicate case is created then it will show you like “This
Case has been already generated.”
Please refer to below screenshot.
To get the Dialog Popup box through html on entity form in Dynamics 365 CRM
We have requirement in Dynamics CRM to get dialog popup box through html.
To get the html
<html><head>
<title> Account Type</title>
<script src="ClientGlobalContext.js.aspx"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
//To get parent form data on popup write logic
function GetAllAccountsRecords()
{
//custom logic
}
function btnSubmit()
{
//on submit button perform action
var crmWindow = parent.Alert.getCrmWindow();
//write here to perform action on submit button
parent.$("#alertJs-wrapper").hide();
}
</script>
</head><body onload="GetAllAccountsRecords()">
<br><p>Please, select data.</p><br>
<br>
<input onclick="btnSubmit();" value="Submit" style="height: 24px;font-family: Segoe UI,Tahoma,Arial;border: 1px solid #C6C6C6; background-image: none;margin-top: 10px; width: auto !important; min-width: 80px;white-space: nowrap; color: #444444; background-color: #FFFFFF" type="Button">
</body>
</html>
To get the html
<html><head>
<title> Account Type</title>
<script src="ClientGlobalContext.js.aspx"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
//To get parent form data on popup write logic
function GetAllAccountsRecords()
{
//custom logic
}
function btnSubmit()
{
//on submit button perform action
var crmWindow = parent.Alert.getCrmWindow();
//write here to perform action on submit button
parent.$("#alertJs-wrapper").hide();
}
</script>
</head><body onload="GetAllAccountsRecords()">
<br><p>Please, select data.</p><br>
<br>
<input onclick="btnSubmit();" value="Submit" style="height: 24px;font-family: Segoe UI,Tahoma,Arial;border: 1px solid #C6C6C6; background-image: none;margin-top: 10px; width: auto !important; min-width: 80px;white-space: nowrap; color: #444444; background-color: #FFFFFF" type="Button">
</body>
</html>
To get lookup details through Plugin in Dynamics Crm
We did a plugin to get lookup reference and set the data in current form. Plugin on post operation,
Update method.
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
try
{
// Refer to the lead entity .
if (entity.LogicalName == "lead")
{
if (entity.Attributes.Contains("parentcontactid"))
{
//to get data of lookup we used entityrefernce
var currency = ((EntityReference)(entity.Attributes["parentcontactid"]));
var actualCurrency = service.Retrieve(currency.LogicalName, currency.Id, new ColumnSet(true));
var currencyName = actualCurrency["firstname"].ToString();
var last = actualCurrency["lastname"].ToString();
//throw new InvalidPluginExecutionException("The contact123" + last);
entity.Attributes["firstname"] = currencyName;
//throw new InvalidPluginExecutionException("The contact" + entity["firstname"]);
entity.Attributes["lastname"] = last;
}
}
// Obtain the organization service reference.
service.Update(entity);
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("Howdy! error occurred" +ex.Message);
}
}
Update method.
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
try
{
// Refer to the lead entity .
if (entity.LogicalName == "lead")
{
if (entity.Attributes.Contains("parentcontactid"))
{
//to get data of lookup we used entityrefernce
var currency = ((EntityReference)(entity.Attributes["parentcontactid"]));
var actualCurrency = service.Retrieve(currency.LogicalName, currency.Id, new ColumnSet(true));
var currencyName = actualCurrency["firstname"].ToString();
var last = actualCurrency["lastname"].ToString();
//throw new InvalidPluginExecutionException("The contact123" + last);
entity.Attributes["firstname"] = currencyName;
//throw new InvalidPluginExecutionException("The contact" + entity["firstname"]);
entity.Attributes["lastname"] = last;
}
}
// Obtain the organization service reference.
service.Update(entity);
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("Howdy! error occurred" +ex.Message);
}
}
To get more than 50 records through ODATA Services
In Dynamics CRM, There is a page limit of 50 records through Odata services. To increase that we should use paging to get more than 50+ records.
//To get account records through Odata services
relatedAccounts = [];
function GetAllAccountsRecords() {
debugger;
var serverUrl = Xrm.Page.context.getClientUrl();
var oDataUri = serverUrl + "/xrmservices/2011/OrganizationData.svc/AccountSet?$select=AccountId,Name";
GetRecords(oDataUri);
var totalRecords = relatedAccounts.length;
//alert("Total records :" +totalRecords);
}
//Calling Odata
function GetRecords(url) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: url,
async: false,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (data && data.d != null && data.d.results != null) {
AddRecordsToArray(data.d.results);
FetchRecordsCallBack(data.d);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("Error : has occured during retrieval of the records ");
}
});
}
//To get more records through Odata services
function AddRecordsToArray(records) {
for (var i = 0; i < records.length; i++) {
relatedAccounts.push(records[i]);
}
}
//To get next page records through Odata services
function FetchRecordsCallBack(records) {
if (records._next != null) {
var url = records._next;
GetRecords(url);
}
}
//end of Odata services
//To get account records through Odata services
relatedAccounts = [];
function GetAllAccountsRecords() {
debugger;
var serverUrl = Xrm.Page.context.getClientUrl();
var oDataUri = serverUrl + "/xrmservices/2011/OrganizationData.svc/AccountSet?$select=AccountId,Name";
GetRecords(oDataUri);
var totalRecords = relatedAccounts.length;
//alert("Total records :" +totalRecords);
}
//Calling Odata
function GetRecords(url) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: url,
async: false,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (data && data.d != null && data.d.results != null) {
AddRecordsToArray(data.d.results);
FetchRecordsCallBack(data.d);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("Error : has occured during retrieval of the records ");
}
});
}
//To get more records through Odata services
function AddRecordsToArray(records) {
for (var i = 0; i < records.length; i++) {
relatedAccounts.push(records[i]);
}
}
//To get next page records through Odata services
function FetchRecordsCallBack(records) {
if (records._next != null) {
var url = records._next;
GetRecords(url);
}
}
//end of Odata services
Subscribe to:
Posts (Atom)