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.