Friday, July 27, 2018

ExecuteMultiple in Dynamics CRM/Retrieve All Records in Dynamics FetchXML

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System.Collections;
using System.Configuration;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Globalization;
using System.IO;

namespace Timer_for_Accounts
{
    class Program
    {
        public static void Main(string[] args)
        { 
            string strLogText = "Execution Started at :" + DateTime.Now;
            Console.WriteLine("Execution Started..");
            ClientCredentials Credentials = new ClientCredentials();
//Retrieve UserName and Password from App.config
            Credentials.UserName.UserName = ConfigurationManager.AppSettings["UserName"];
            Credentials.UserName.Password = ConfigurationManager.AppSettings["Password"];
            string uri = ConfigurationManager.AppSettings["uri"];
            OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(new Uri(uri), null, Credentials, null);
            Console.WriteLine("Connected to Server Successfully.");
            //WE NEED TO USE {0} IN FETCHXML WHEN YOU WANT TO RETRIEVE ALL RECORDS
            var fetch = "<fetch {0} version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                "  <entity name='new_account'>" +
                                "    <attribute name='new_name' />" +
                                "    <attribute name='ownerid' />" +
                                "    <attribute name='createdon' />" +
                                "    <attribute name='createdby' />" +
                                "    <attribute name = 'modifiedon' />" +
                                "    <order attribute='createdon' descending='true' />" +
                                "      <filter type='and'>" +
                                "        <condition attribute='statecode' operator='eq' value='0' />" +
                                "      </filter>" +
                                "  </entity>" +
                                "</fetch>";
            EntityCollection recordstobeupdated = new EntityCollection();
            var accountRecords = RetrieveAllRecords(serviceProxy, fetch);
            for (int accountCount = 0; accountCount < accountRecords.Count; accountCount++)
            {
                recordstobeupdated.Entities.Add(accountRecords[accountCount]);
            }
            #region ExecuteMultiple to update records
            EntityCollection updateRecords = recordstobeupdated;
            ExecuteMultipleRequest requestForUpdates = new ExecuteMultipleRequest()
            {
                Requests = new OrganizationRequestCollection()
            };
            try
            {
                int remainingcount = updateRecords.Entities.Count % 100; ;
                int count = 0;
                int updatedcount = 0;
                requestForUpdates.Settings = new ExecuteMultipleSettings();
                requestForUpdates.Settings.ContinueOnError = true;
                requestForUpdates.Settings.ReturnResponses = true;
                Console.WriteLine("Started at :" + DateTime.Now.ToString());
                foreach (var entity in updateRecords.Entities)
                {
                    TimeSpan difference = DateTime.Now - (DateTime)entity.Attributes["createdon"];

                    int DifferenceDays = difference.Days + 1;
                    entity.Attributes["new_accountCountopendays"] = DifferenceDays;
                    UpdateRequest updateRequest = new UpdateRequest { Target = entity };
                    requestForUpdates.Requests.Add(updateRequest);
                    count = count + 1;
                    if (requestForUpdates.Requests.Count == 100)
                    {
                        //WE ARE EXECUTING 100 RECORDS AT A TIME YOU CAN INCREASE THE COUNT BASED ON YOUR REQUIREMENT
                        serviceProxy.Execute(requestForUpdates);
                        updatedcount = updatedcount + 100;
                        Console.WriteLine("Updated :" + updatedcount);
                        Console.WriteLine("Completed at :" + DateTime.Now.ToString());
                        requestForUpdates.Requests = new OrganizationRequestCollection();
                        count = 0;
                    }
                }
                if (count == remainingcount)
                {
                    serviceProxy.Execute(requestForUpdates);
                    int totalcounnt = updatedcount + count;
                    Console.WriteLine("Updated Remaining:" + totalcounnt);
                    requestForUpdates.Requests = new OrganizationRequestCollection();
                }
            }
            catch (System.ServiceModel.FaultException<OrganizationServiceFault> ex)
            {
                Console.WriteLine("Update request failed for the account{0} and the reason being: {1}",
                    ((ExecuteTransactionFault)(ex.Detail)).FaultedRequestIndex + 1, ex.Detail.Message);
            }
            #endregion ExecuteMultiple for update records
        }

        public static List<Entity> RetrieveAllRecords(IOrganizationService service, string fetch)
        {
            var moreRecords = false;
            int page = 1;
            var cookie = string.Empty;
            List<Entity> Entities = new List<Entity>();
            do
            {
                var xml = string.Format(fetch, cookie);
                var collection = service.RetrieveMultiple(new FetchExpression(xml));
                if (collection.Entities.Count >= 0) Entities.AddRange(collection.Entities);
                moreRecords = collection.MoreRecords;
                if (moreRecords)
                {
                    page++;
                    cookie = string.Format("paging-cookie='{0}' page='{1}'", System.Security.SecurityElement.Escape(collection.PagingCookie), page);
                }
            } while (moreRecords);
            return Entities;
        }
    }
}

Script to exclude Weekends and Public Holidays in SSRS

=IIF(DateValue(Fields!createdon.Value)=DateValue(Fields!modifiedon.Value),"0",
(DateDiff(DateInterval.day, DateValue(Fields!createdon.Value), DateValue(Fields!modifiedon.Value)))
- (DateDiff(DateInterval.WeekOfYear, DateValue(Fields!createdon.Value), DateValue(Fields!modifiedon.Value))*2)
- IIF(Weekday(DateValue(Fields!createdon.Value),1) = 1,1,0)
- IIF(Weekday(DateValue(Fields!createdon.Value),1) = 7,1,0)
- IIF(Weekday(DateValue(Fields!modifiedon.Value),1) = 1,1,0)
- IIF(Weekday(DateValue(Fields!modifiedon.Value),1) = 7,1,0)
-IIF(DateValue(Fields!createdon.Value)<=DateValue("January 01, 2017") and DateValue("January 01, 2017") <=DateValue(Fields!modifiedon.Value),1,0)
)

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();

}