Wednesday, August 14, 2019

Set Default view in inline Lookup D365


function loadCustomDefaultView(){
debugger;
var subgrid= Xrm.Page.getControl("subgridname");
    if (subgrid != null || subgrid != 'undefined' || subgrid !='')) {
Xrm.Page.getControl("subgridname").setDefaultView("GUID");
   }
}

Update the content of Activated Quote in CRM


We got a situation as, the quote should activated for triggering a workflow and from workflow on based on some conditions we need to update the same quote. This is not possible as the quote becomes Read-Only immediately after you activate. 
 
If we want to update it, the option is revising the quote which closes the current quote and creates a new quote where we don't want to create new quotes.
 
After some search, we found a way for doing it and the way is very simple. Just change the state of quote to Draft, update the data and then change the quote state to Active which will not create any new quote.
 
We can do this using a system workflow and also from SDK.
 
System Workflow
 
SDK
// Change the Quote to Draft State
SetStateRequest draftQuote = new SetStateRequest();
draftQuote.EntityMoniker = new EntityReference("quote"newGuid(""));
draftQuote.State = new OptionSetValue(0); // Draft
draftQuote.Status = new OptionSetValue(1); // InProgress
objService.Execute(draftQuote);

// Update the Quote
Entity entQuote = new Entity("quote");
entQuote.Attributes["name"] = "testing1";
entQuote.Id = new Guid("DA5768B5-D62A-E511-80E0-FC15B4283778");
objService.Update(entQuote);

// Change the Quote to Active State.
SetStateRequest activateQuote = new SetStateRequest();
activateQuote.EntityMoniker = new EntityReference("quote"newGuid(""));
activateQuote.State = new OptionSetValue(1); // Active
activateQuote.Status = new OptionSetValue(2); // InProgress
objService.Execute(activateQuote);

Hope this helps.

Get AbsoluteURL from Document Locations in Dynamics 365

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using System.Activities;

namespace DocumentLocationURL

{
    public class DocumentLocationURL : CodeActivity
    {
        #region "Parameter Definition"
        [Input("SharePointDocumentID")]
        [Default("")]
        public InArgument<string> SharePointDocumentID { get; set; }

        [Output("AbsoluteURL")]

        public OutArgument<string> AbsoluteURL { get; set; }

        protected override void Execute(CodeActivityContext executionContext)

        {
            #region "Load CRM Service from context"
            // Create the context
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

            if (context == null)

                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();

            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
            #endregion

            #region "Read Parameters"

            string _FieldName = this.SharePointDocumentID.Get(executionContext);
            EntityReference _Target = null;
            if (this.SharePointDocumentID.Get(executionContext) == null )
                throw new InvalidPluginExecutionException("Enter Target Input.");
           
            #endregion

            #region "AbsoluteURL Execution"

            RetrieveAbsoluteAndSiteCollectionUrlResponse retriveResponse = new RetrieveAbsoluteAndSiteCollectionUrlResponse();

            RetrieveAbsoluteAndSiteCollectionUrlRequest retrieveRequest = new RetrieveAbsoluteAndSiteCollectionUrlRequest

            {
                Target = new EntityReference("sharepointdocumentlocation", context.PrimaryEntityId)//this.SharePointDocumentID.Get(executionContext).Id)
            };
            retriveResponse = (RetrieveAbsoluteAndSiteCollectionUrlResponse)service.Execute(retrieveRequest);
            //throw new InvalidPluginExecutionException(retriveResponse.AbsoluteUrl.ToString());
            this.AbsoluteURL.Set(executionContext, retriveResponse.AbsoluteUrl.ToString());
            #endregion
            

        }

        #endregion

    }

}

Create  Workflow on Document Location entity Create/Update whichever meets to your requirement.

Click on "Add Step" and look for our assembly name i.e DocumentLocationURL, click on this DocumentLocationURL will appear, click on this to add step.

Add update step, and set AbsoluteURL field as DocumentLocationURL  (Output Parameter given in code).

Workflow is completed; save and activate it.

Tuesday, August 13, 2019

I came across a situation where we need to find the Custom Workflow activity across Processes, to achieve this we can add the Plugin assembly and look for dependencies that's not at all possible in all the cases. 

To overcome this, I had written below FetchXML and executed this in XRMToolBox-->FetchXML Tester

<fetch mapping="logical" count="5000" version="1.0" >
    <entity name="workflow" >
        <attribute name="name" />
        <attribute name="category" />
        <link-entity name="dependency" from="dependentcomponentobjectid" to="workflowid" alias="dep" >
            <link-entity name="plugintype" from="plugintypeid" to="requiredcomponentobjectid" alias="pt" >
                <attribute name="assemblyname" />
                <attribute name="description" />
                <attribute name="friendlyname" />
                <attribute name="name" />
                <attribute name="typename" />
                <attribute name="workflowactivitygroupname" />
                <attribute name="isworkflowactivity" />
            </link-entity>
        </link-entity>
    </entity>
</fetch>

Friday, July 27, 2018

Retrieve All Organizations in CRM

using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Discovery;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.ServiceModel.Description;

namespace GetAllOrganizations
{
    static class Program
    {
        private static string DiscoverServiceURL = ConfigurationManager.AppSettings["DiscoverServiceURL"];
        private static string UserName = ConfigurationManager.AppSettings["UserName"];
        private static string Password = ConfigurationManager.AppSettings["Password"];
        private static ClientCredentials credentials = new ClientCredentials();

        public static OrganizationServiceProxy GetOrganizationService(Organization selectedOrganization)
        {
            credentials.UserName.UserName = UserName;
            credentials.UserName.Password = Password;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(new Uri(selectedOrganization.OrgServiceURL), null, credentials, null);
            return serviceProxy;
        }

        public static List<Organization> GetOrganizations()
        {
            credentials.UserName.UserName = UserName;
            credentials.UserName.Password = Password;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            using (var discoveryProxy = new DiscoveryServiceProxy(new Uri(DiscoverServiceURL), null, credentials, null))
            {
                discoveryProxy.Authenticate();

                // Get all Organizations using Discovery Service
                RetrieveOrganizationsRequest retrieveOrganizationsRequest = new RetrieveOrganizationsRequest()
                {
                    AccessType = EndpointAccessType.Default,
                    Release = OrganizationRelease.Current
                };

                RetrieveOrganizationsResponse retrieveOrganizationsResponse =
                (RetrieveOrganizationsResponse)discoveryProxy.Execute(retrieveOrganizationsRequest);

                if (retrieveOrganizationsResponse.Details.Count > 0)
                {
                    var orgs = new List<Organization>();
                    foreach (OrganizationDetail orgInfo in retrieveOrganizationsResponse.Details)
                    {
                        string orgServUrl = string.Empty;
                        orgInfo.Endpoints.TryGetValue(EndpointType.OrganizationService, out orgServUrl);
                        orgs.Add(new Organization()
                        {
                            OrgFriendlyName = orgInfo.FriendlyName,
                            OrgUniqueName = orgInfo.UniqueName,
                            OrgServiceURL = orgServUrl
                        });
                    }
                    return orgs;
                }
                else
                    return null;
            }
        }
    }

    public class Organization
    {
        public string OrgFriendlyName { get; set; }
        public string OrgUniqueName { get; set; }
        public string OrgServiceURL { get; set; }
    }
}

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