Tuesday, March 27, 2018

Check if Case contains Note/Annotation in Dynamics CRM


            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            // Obtain the organization service reference.
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
           
            // ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            if (context.InputParameters.Contains("IncidentResolution") && context.InputParameters["IncidentResolution"] is Entity)
            {
                
                Entity incidentResolution = (Entity)context.InputParameters["IncidentResolution"];
                Guid relatedIncidentGuid = ((EntityReference)incidentResolution.Attributes["incidentid"]).Id;

               
                QueryExpression NotesQE = new QueryExpression { EntityName = "annotation", ColumnSet = new ColumnSet(true) };
                LinkEntity incident = new LinkEntity
                {
                    LinkFromEntityName = "annotation", //annotation
                    LinkToEntityName = "incident", //Case
                    LinkFromAttributeName = "objectid", 
                    LinkToAttributeName = "incidentid"
                };
                OrderExpression orderbycreatedon = new OrderExpression("createdon", OrderType.Descending);
                incident.LinkCriteria.AddCondition("incidentid", ConditionOperator.Equal, relatedIncidentGuid);
                NotesQE.Orders.Add(orderbycreatedon);
                NotesQE.LinkEntities.Add(incident);
                EntityCollection NotesRetrieveQE = service.RetrieveMultiple(NotesQE);
                
                    if (NotesRetrieveQE != null && NotesRetrieveQE.Entities.Count > 0 && NotesRetrieveQE.Entities[0].Attributes.Contains("filename"))
                    {
                        String filename = NotesRetrieveQE.Entities[0].Attributes["filename"].ToString();
                        string[] splitfilename = filename.Split('.');
                        if (splitfilename[splitfilename.Length - 1] == "pdf")
                        { return; }
                        else
                        {
                            throw new InvalidPluginExecutionException("Notes not Found.");
                        }
                    }
                    else
                    {
                        throw new InvalidPluginExecutionException("Notes not Found.");
                    }            
            }

Wednesday, March 21, 2018

Deactivate a record using Plugin in D365

//Deactivate a record
        public static void DeactivateRecord(string entityName, Guid recordId, IOrganizationService organizationService)
        {
            var cols = new ColumnSet(new[] { "statecode", "statuscode" });
            //Check if it is Active or not
            var entity = organizationService.Retrieve(entityName, recordId, cols);
            if (entity != null && entity.GetAttributeValue<OptionSetValue>("statecode").Value == 0)
            {
                //StateCode = 1 and StatusCode = 2 for deactivating Account or Contact
                SetStateRequest setStateRequest = new SetStateRequest()
                {
                    EntityMoniker = new EntityReference
                    {
                        Id = recordId,
                        LogicalName = entityName,
                    },
                    State = new OptionSetValue(1),
                    Status = new OptionSetValue(2)
                };
                organizationService.Execute(setStateRequest);
            }
        }

Sample Console Application to connect to Dynamics 365

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Tooling.Connector;
using System;
using Microsoft.Xrm.Sdk.Client;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm.Sdk.Messages;
using System.ServiceModel.Description;
using System.Data;
using System.ComponentModel;
using System.IO;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Client;

namespace SampleConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
  //you can add the dlls from nuget package manager
                //In Solution Explorer, right - click either References or a project and select Manage NuGet Packages....
                //The Browse tab displays packages by popularity from the currently selected source
                //Select the desired version from the drop-down and select Install.Visual Studio installs the package and its dependencies into the project.You may be asked to accept license terms. When installation is complete, the added packages appear on the Installed tab. Packages are also listed in the References node of Solution Explorer

               
                // for CRM online instance
                ClientCredentials Credentials = new ClientCredentials();
                Credentials.UserName.UserName = "username";
                Credentials.UserName.Password = "password";

                string connectionString = "Url=https://domainname.crm.dynamics.com; Username=username; Password=password; authtype=Office365";
                CrmServiceClient conn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionString);
                var serviceProxyPROD1 = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                var serviceProxyPRODOnline = conn.OrganizationServiceProxy;

                //try to fetch any record from CRM I am fetching case record here
                Entity incidentrecord = serviceProxyPROD1.Retrieve("incident", new Guid("A2BDAA1F-E711-E611-80F1-480FCFF4B5B1"), new Microsoft.Xrm.Sdk.Query.ColumnSet("title"));

                ////To run Action from C#
                OrganizationRequest organizationRequest = new OrganizationRequest("rollbackname");
                organizationRequest["Target"] = new EntityReference("incident", Guid.Parse("A2BDAA1F-E711-E611-80F1-480FCFF4B5B1"));
                OrganizationResponse organizationResponse = serviceProxyPRODOnline.Execute(organizationRequest);

                //Create View from Console Application
                var fetchXML = "<fetch distinct='true' mapping='logical' output-format='xml-platform' version='1.0' >";
                fetchXML += "  <entity name='incident' >";
                fetchXML += "    <attribute name='title' />";
                fetchXML += "    <attribute name='ticketnumber' />";
                fetchXML += "    <link-entity name='annotation' from='objectid' to='incidentid' alias='an'  link-type='outer'>";
                fetchXML += "      <attribute name='objectid' />";
                fetchXML += "      <filter type='and' >";
                fetchXML += "        <condition attribute='isdocument' value='0' operator='eq' />";
                fetchXML += "      </filter>";
                fetchXML += "    </link-entity>";
                fetchXML += "    <filter type='and' >";
                fetchXML += "      <condition entityname='an' attribute='objectid' operator='null' />";
                fetchXML += "    </filter>";
                fetchXML += "  </entity>";
                fetchXML += "</fetch>";

                Entity entity = new Entity("savedquery");
                entity["name"] = "Cases with Attachments";
                entity["fetchxml"] = fetchXML;
                entity["returnedtypecode"] = "incident";
                entity["querytype"] = 0;
                serviceProxyPROD1.Create(entity);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

Unable to access CRM records after upgrading to Dynamics 365


1. Please navigate to Internet Explorer Options > Settings > Click on View Files> Clear the folder
2. Go to Run > %temp% > Clear the folder and empty recycle bin and try accessing CRM.


Solution 1
 ·         Please navigate to Internet Explorer Options > General > Delete > Select All check boxes > Click Delete
·         Please navigate to Internet Explorer Options > General > Settings > Click on View Files> Clear the folder
·         Go to Run > %temp% > Clear the folder and empty recycle bin.
·         Restart the machine as the restarting browser mayn’t help. Then access CRM from IE.     

Solution 2 ( Try solution 2 if Solution 1 doesn’t resolve the issue)
 ·         Please navigate to Internet Explorer Options > Advanced > Reset > Select - Delete personal settings > Reset
·         Note: It will remove toolbars, default browser settings so please read the instructions before you delete these settings. 
·         Restart the machine as the restarting browser mayn’t help. Then access CRM from IE.     

Friday, December 23, 2016

Validation of Telephone Number using Javascript

function telephone_Onchange(fieldname) {
    var targetattribute = Xrm.Page.getAttribute(fieldname);
    var phonenumber = targetattribute.getValue();
    var targetcontrol = Xrm.Page.getControl(fieldname);
    if (phonenumber == null) {
        targetcontrol.clearNotification();
        return;
    }
    if (phonenumber.length == 0) {
        targetcontrol.clearNotification();
        return;
    }
    phonenumber = phonenumber.replace(/\+/g, "");
    phonenumber = phonenumber.replace(/\(/g, "");
    phonenumber = phonenumber.replace(/\)/g, "");
    phonenumber = phonenumber.replace(/\-/g, "");
    phonenumber = phonenumber.replace(/\s/g, "");
    phonenumber = phonenumber.replace(/\./g, "");
    if (isNaN(phonenumber) || phonenumber.length < 10 || phonenumber.length > 12) {
        targetcontrol.setNotification("Telephone number not validIt ");
        return;
    }
    targetcontrol.clearNotification();

}

Web API in MS CRM 2016

//Used to set Line of Business on create of Account record (Fetch LOB from the User Entity)
function onLoadSetLineOfBusiness(LineofBusiness) {
    var logInUser = Xrm.Page.context.getUserId();
    var retrieveRecordsReq = new XMLHttpRequest();
    var serverUrl = Xrm.Page.context.getClientUrl();
    // Adjust URL for differences between on premise and online
    if (serverUrl.match(/\/$/)) { serverUrl = serverUrl.substring(0, serverUrl.length - 1); }

    //Web API Calls
    var req = new XMLHttpRequest();
    if (logInUser != null && logInUser != "") {
        req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/systemusers?$select=_new_lineofbusiness_value&$filter=systemuserid eq " + logInUser.replace('{', '').replace('}', '') + "", true);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
        req.onreadystatechange = function () {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 200) {
                    var LOBName = JSON.parse(this.response);
                    if (LOBName.value.length > 0) {
                        //to set the LookUp Value we have to use Formatted Value
                        if (LOBName.value[0]._new_lineofbusiness_value != null && LOBName.value[0]._new_lineofbusiness_value != "") {
                            var LOBvalue = new Array();
                            LOBvalue[0] = new Object();
                            LOBvalue[0].id = LOBName.value[0]._new_lineofbusiness_value;
                            LOBvalue[0].name = LOBName.value[0]['_new_lineofbusiness_value@OData.Community.Display.V1.FormattedValue'];
                            LOBvalue[0].entityType = "new_business";
                            Xrm.Page.getAttribute(LineofBusiness).setValue(LOBvalue);
                            Xrm.Page.getAttribute(LineofBusiness).setSubmitMode("always");
                        }
                    }
                }
                else {
                    alert(this.statusText);
                }
            }
        };
        req.send();
    }
}


Set the Default form in MS CRM

If we have more than one Form in an Entity and want to set a default form on Create/Update. Currently The below code will show if we are creating a New record then it will automatically redirect to Account-Create form

//Navigate to Account-Create Form onLoad
function NavigateToAccountCreateForm() {
    if (Xrm.Page.ui.getFormType() == 1) {
        var formLabelName = Xrm.Page.ui.formSelector.getCurrentItem().getLabel();
        if (formLabelName != "Account-Create") {
            var infIndex = null;
            Xrm.Page.ui.formSelector.items.forEach(function (item, index) {
                var itemLabelName = item.getLabel();
                if (itemLabelName == "Account-Create")
                { infIndex = index; }
            });

            if (infIndex != null) { Xrm.Page.ui.formSelector.items.get(infIndex).navigate(); }
            else { alert("Account-Create form not found. You cannot create new Account, Please contact your system administrator."); }
        }
    }

}

Another Method

function showDefaultForm() {
    //if the form is Create form
    if (Xrm.Page.ui.getFormType() == 1) {
        //check if the current form is Information Form
        if (Xrm.Page.ui.formSelector.getCurrentItem().getLabel() != "Information") {
            var items = Xrm.Page.ui.formSelector.items.get();
            for (var i in items) {
                var item = items[i];
                var itemId = item.getId();
                var itemLabel = item.getLabel()
                if (itemLabel == "Information") {
                    //navigate to the form
                    item.navigate();
                } //endif
            } //end for
        } //endif
    }
    //if the form is update form
    if (Xrm.Page.ui.getFormType() == 2 || Xrm.Page.ui.getFormType() == 4) {
        // variable to store the name of the form
        var lblForm;

        // get the value picklist field
        var relType = Xrm.Page.getAttribute("hsl_formtype").getValue();

        // switch statement to assign the form to the picklist value
        //change the switch statement based on the forms numbers and Formtype values
        switch (relType) {
            case 864630000:
                lblForm = "Information0";
                break;
            case 864630001:
                lblForm = "Information1";
                break;
            case null:
                lblForm = "Information2";
                break;
            default:
                lblForm = "Information";
        }
        //check if the current form is form need to be displayed based on the value
        if (Xrm.Page.ui.formSelector.getCurrentItem().getLabel() != lblForm) {
            var items = Xrm.Page.ui.formSelector.items.get();
            for (var i in items) {
                var item = items[i];
                var itemId = item.getId();
                var itemLabel = item.getLabel()

                if (itemLabel == lblForm) {
                    //navigate to the form
                    item.navigate();
                } //endif
            } //end for
        } //endif
    }//endif

} //end function