Friday, April 20, 2018

No Microsoft Dynamics CRM user exists with the specified domain name and user ID


A Microsoft Dynamics CRM user record does not exist with the specified domain name and user ID.

Crm Exception: Message: No Microsoft Dynamics CRM user exists with the specified domain name and user ID, ErrorCode: -2147220652

 Error while retrieving userId. Exception: Microsoft.Crm.CrmSecurityException: Unable to find Active Directory object for SID
   at Microsoft.Crm.SecurityUtils.GetGuidFromSidLimitingSearches(String domain, Byte[] sid)
   at Microsoft.Crm.SecurityUtils.GetUserId(String domainName, Boolean limitGlobalCatalogSearches)

We were getting such error for only certain users after we migrated our CRM organization from CRM 2011 to CRM 2016.

Initial Investigation and results.
  • User was enabled.
  • User has all security roles assigned.
  • Even one of Service Account having System Administrative access was not able to login.

Understanding CRM Tables

There are four main tables where CRM user detail must exist for CRM authentication.

MSCRM_CONFIG.dbo.SystemUserOrganizations
MSCRM_CONFIG.dbo.SystemUserAuthentication
MSCRM_CONFIG.dbo.SystemUser
YourOrgName_MSCRM.dbo.SystemUserBase

Here is a query which should give an outcome with important details for a given CRM User.

select DomainName,ActiveDirectoryGuid,AuthInfo,A.UserId
from MSCRM_CONFIG.dbo.SystemUserOrganizations O
join MSCRM_CONFIG.dbo.SystemUserAuthentication A on A.UserId=O.UserId
join Staging.dbo.SystemUserBase B on B.SystemUserId=O.CrmUserId
Where B.DomainName like '%itsit\vipin.jaiswal%'


If you are not getting SQL Result, then it might be possible that there is missing entry for a CRM user in one of the table.

So, we need to verify in which table we are missing the respective crm user entry and verification must be done in specific order as described here.

First :
Please note SystemUserID of the respective user as this would be an input for our second query.

Select DomainName,SystemUserID
From Staging_MSCRM.dbo.SystemUserBase
Where DomainName like '%itsit\vipin.jaiswal%'



Second :
The SystemUserId from above is an input to below query in where clause.

Select CrmUserId,Id,OrganizationId,UserId,IsDeleted
From MSCRM_CONFIG.dbo.SystemUserOrganizations
Where CrmUserId = 'F2B56B91-CE43-E811-9103-005056A83905'



Note the UserId from above it will be an input to our Third and Fourth Query.

Third and Fourth :

Select AuthInfo,Id,UserId,IsDeleted
From MSCRM_CONFIG.dbo.SystemUserAuthentication
Where UserId = 'F9B56B91-CE43-E811-9103-005056A83905'

Select DefaultOrganizationId,Id,IsDeleted
From MSCRM_CONFIG.dbo.SystemUser
Where Id = 'F9B56B91-CE43-E811-9103-005056A83905'




In most cases we have got an entry in table YourOrgName_MSCRM.dbo.SystemUserBase and rest other 3 tables were missing the entry.

I have created a stored Procedure which will create missing entry in the respective table accordingly.

Disclaimer: As always, any direct changes in the CRM tables are unsupported.

Please Note:

SP require an Active Directory ID of  a CRM User and I know two ways to get it.

     1) Get the ID from your any other existing organization  from below query.
Select AuthInfo,Id,UserId,IsDeleted
From MSCRM_CONFIG.dbo.SystemUserAuthentication
Where UserId = @CrmUserConfigId

      2) Get the ID from running power shell command

Get-ADUser -Filter {SamAccountName -eq 'YourUserName'}



-------------Stored Procedure---------------


Create Procedure usp_CreateCrmUser
(@OrgName varchar(100), 
 @CrmUserName varchar(100), 
 @CrmUserACtiveDirectoryID varchar(100))
As

/* 
----Run this Stored Procedure as

Exec CreateCrmUser 'Staging_MSCRM','itsit\Vipin.Jaiswal','W:S-1-5-21-1328376081-1279679187-339368940-342572' 
*/

Begin

Declare @OrganizationID uniqueidentifier
Declare @CrmUserConfigID uniqueidentifier
Declare @SystemUserID uniqueidentifier

Select @OrganizationID = Id
From MSCRM_Config.Dbo.Organization Where DatabaseName = @OrgName

Select @CrmUserConfigID = NEWID()

Select @SystemUserID = SystemUserId
From Staging_MSCRM.dbo.SystemUserBase Where DomainName = @CrmUserName

       If @OrganizationID IS NULL
       Begin
              Select [Output] = 'Organization Name  ''' + @OrgName + '''  does not exists'
              return
       End

       If @SystemUserID IS NULL
       Begin
       Select [Output] = 'User  ''' + @CrmUserName + '''  does not exists in Organization : '' ' + @OrgName + ''''
       return
       End
      
       Insert into MSCRM_CONFIG.dbo.[SystemUser] (DefaultOrganizationId,Id,IsDisabled,Name,IsDeleted)
       Values (@OrganizationID,@CrmUserConfigID,null,null,0)

       Insert into MSCRM_CONFIG.dbo.SystemUserOrganizations (CrmUserId, Id, OrganizationId, UserId, IsDeleted)
       Values (@SystemUserID, NEWID(), @OrganizationID, @CrmUserConfigID, 0)

       Insert into MSCRM_CONFIG.dbo.SystemUserAuthentication (AuthInfo,Id,UserId,IsDeleted)
       Values (@CrmUserACtiveDirectoryID, NEWID(), @CrmUserConfigID, 0)    
             
    Select [Output] = 'User  ''' + @CrmUserName + '''  Created for Organization : '' ' + @OrgName + ''''

       Select DomainName,ActiveDirectoryGuid,AuthInfo,A.UserId
       From MSCRM_CONFIG.dbo.SystemUserOrganizations O
       join MSCRM_CONFIG.dbo.SystemUserAuthentication A on A.UserId=O.UserId
       join Staging_MSCRM.dbo.SystemUserBase B on B.SystemUserId=O.CrmUserId
       Where B.DomainName = @CrmUserName

End

Invoking a stored procedure entered the appropriate missing entry in SQL table and users were able to log-on.

Thanks,
Vipin Jaiswal
vipinjaiswal12@gmail.com


ID3242: The security token could not be authenticated or authorized.



Microsoft Dynamic CRM v9.0 and TLS and SSL protocols.


I was trying to log-on to Dynamic 365 CRM v9.0 from Internet Explorer and getting below error page.



This is because Microsoft is enforcing TLS 1.2 protocol when accessing Dynamics 365 v9.0
As this error message clearly mentioned that one is to edit Internet explorer setting.

I am explaining what exactly needed to be done.
1)  Open the Internet Explorer setting. Go to Tools > Internet Options.
2)  Go to Tab Advanced and scroll down and look for heading Security.


 3)  Under heading Security, look for Use TLS 1.2, check the box as depicted in below image.



Try accessing CRM and I hope without any further error, CRM will be accessible.

From a coding perspective if any application is trying to access Dynamic 365 v9.0 we need to invoke below commands to ensure that application is making use of TLS protocol 1.2.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;



FOR SSRS Report try downloading latest Report Authoring Extension - Click here


I hope this will save a lot of time.

Thanks,
Vipin Jaiswal

Here are some other links for Troubleshooting and learning:

·       Plugin in Dynamic 365 CRM

·       Connect to Dynamic 365 CRM from Console App using Azure Authentication

·       Could not load file or assembly 'System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies

·       Unable to Login to Dynamics CRMOrganizationWebProxyClient is null

·       Assembly 'Microsoft.Crm.Sdk.Proxy' with identity 'Microsoft.Crm.Sdk.Proxy, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' uses 'Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' which has a higher version than referenced assembly 'Microsoft.Xrm.Sdk' with identity 'Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

·       Could not load file or assembly 'Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.

·       Could not load file or assembly 'Microsoft.Xrm.Sdk, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies


Friday, March 16, 2018

Vulnerability issues associated with SQL Browser Service


Recently one of my Client asked to provide remediation for different vulnerability issues for various hosted applications on different Internet facing servers.
 
Microsoft Dynamic CRM was one of the hosted application too and it so happens that few of the action steps which needs to be taken as a remediation for vulnerabilities issues has impacted CRM and we were forced to modify configuration in Microsoft Dynamic CRM web and associated database to bring CRM up and running and keeping its protected from any unknown attack.

I would like to share my learning with you all today!

Let’s understand SQL Browser Service and Issue associated

SQL browser service helps in providing information related to SQL Server instances installed on the computer.

It listens on port 1434/udp and accepts unauthenticated requests by using SQL Server Resolution Protocol (SSRP). When this feature is enabled and publicly accessible from the Internet, attackers may use this service to launch denial of service attacks (amplification attacks using forged UDP packets).

So, Network Team decided to turn OFF SQL browser service and we need to look for some alternate approach to have CRM accessible.

It is possible to install Dynamic CRM On-premises using SQL Server named instance?

Answer is YES, we can install CRM on SQL Server named instance. 

When I looked over internet, I was getting just to turn on SQL browser service to resolve named instance (without its hidden impact). I decided to play around on an extra CRM slot that we use for our RnD.

The Challenges

The moment you turn off SQL browser service and do any of below actions, CRM will not be accessible.
  • Recycle CRM Application Pool
  • Re-Start IIS (Internet Information Services) 
  • Re-Start CRM Application Server

Microsoft CRM Application without SQL Browser Service

We need to provide SQL port number to CRM, so it correctly points SQL Server Named instance during any of these actions:
  • Fresh CRM Installations – from CRM installation wizard.
  • Importing Existing Organization – from deployment manager.
  • Creating a New Organization – from deployment manager


So syntax would be     :           SQLSERVER\InstanceName,PortNumber

An Example                  :           CLUB-VIPINJA01\NO15,1433

Note: After forward slash (\) its a SQL instance name and after comma (,) its a SQL Port



Resolution steps when CRM is already installed

      1) Changes in the Registry of CRM Application Server – (regedit)

The Key path that need  to be changed
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSCRM\configdb

OLD Value
Data Source= CLUB-VIPINJA01;Initial Catalog=MSCRM_CONFIG;Connection Timeout=60;Integrated Security=SSPI

NEW Value
Data Source= CLUB-VIPINJA01\NO15,1433;Initial Catalog=MSCRM_CONFIG;Connection Timeout=60;Integrated Security=SSPI

2) Changes in SQL Server DB

Select * From MSCRM_CONFIG.dbo.Organization

Output
Provider=SQLOLEDB;Data Source=NUEW-SQEKWNP01;Initial Catalog=Production_MSCRM;Integrated Security=SSPI

Update the Connection string using SQL query.

Update Organization
Set ConnectionString = 'Provider=SQLOLEDB;Data Source=CLUB-VIPINJA01\NO15,1433;Initial Catalog=Production_MSCRM;Integrated Security=SSPI'

We can verify if CRM web is still accessible even after restarting IIS or recycling the CRM application pool.



How to check the SQL Port Number of our SQL Server installed.





I hope information provided here is valuable.

Thanks. 

Tuesday, March 6, 2018

Email reminders to a Contact associated to an Account need to be mange well in Dynamic 365 CRM.


I came across a very common and usual requirement one day.

A business would like to send notifications using Microsoft Dynamic CRM to the contact added on the Invoice entity on due of Invoice end date.

I guess workflows would be the best suitable option here to send an email notifications, probably using the template and adding dynamic content would add a personal touch and even who is not from a developer background can construct a beautiful workflow.

But let me tell you a simple workflow may sometimes can be a very nasty to handle and play around.

Let me outline an example and share my small tips and learning.

On Invoice entity we have following relationships:
  •         Company              : One-to-Many Relationship between Account and Invoice.
  •          Primary Contact    : One-to-Many Relationship between Contact and Invoice.
  •          Due Date              : Date when Invoice is due.


We customize Primary Contact field to allow only contact associated under Company.





Now we will create our workflow which would simply send reminder email to a contact on Invoice due date.

I am creating a very basic workflow and not handling complex logic for workflow getting multiple times when an invoice due date get updated, just to stay focus on showcasing a different situation.







  

We are done with creating our workflow and we have activate it.

Now, we would test it with some sample data.
We have a Account with two contacts in CRM.




We created an invoice with information as depicted in below diagram.




According to our provided business scenario we need to send an email notification to Mr. Vipin Jaiswal on Invoice Due date (31-Dec-2018).

But let assume here on 1st-Apr-2018 that is before Invoice due date is reached, Mr. Vipin Jaiswal is no longer a Primary Contact for Account Microsoft.

The changes had happened on Account entity and Vipin Jaiswal was removed from the Contact sub grid. But on the Invoice entity CRM is still referring to Vipin Jaiswal as his Primary contact.
Our workflows would still be sending an email to the contact which is no longer associated with the account which invoice is related to.

The business would be interested in sending email notification to the changed Primary contact of an account which is been reflected at the account entity level.

Typically we should always be sending such email notification to the current contact which is associated to the account and not the contact that is got recorded on the Invoice creation.

Conclusion

• Account and Primary contact are tightly coupled.
• At the time of Invoice creation, we select Account first and then we are allowed to select only related contact as a Primary Contact.
• A Primary Contact can move from one organization to other, account will remains the same.
• In this case, we should always send an email notification to the Primary Contact of the Account and not the Primary Contact of any Invoice.

Thanks.

Please let me know if someone came across such issue and resolutions steps taken towards it.

Monday, December 25, 2017

Cancel Workflow using JavaScript and Web API in Microsoft Dynamic CRM

It was just another casual task, when business scenario got me into cancelling a specific waiting workflow in Microsoft Dynamic CRM for some specific entity.

First, I googled it looking around if someone had written something about it. I was getting lot of articles to execute workflows, but I was looking to cancel the waiting workflows. I decided to go-ahead and use SQL to find the Guid of specific workflow instance, so that I can execute my code to try canceling it.

I got surprised when I found multiple records of my workflow, but then on CRM UI it was just one.


Then I took a closer look at the workflow table and try to differentiate them and finally I was able to write a query to filter out the one that I was interested in.

(If you are not seeing multiple, just activate and deactivate a workflow few times and it will generate multiple records of the workflow)

So how to find the Guid of exact workflow that would get triggered based on name only?

Select top 100 categoryname,name,workflowid,statecodename,statuscodename, parentworkflowid,parentworkflowidname 
From FilteredWorkflow
Where name like '%Hold on%'
And category = 0 -- Workflow
And statecode = 1
And parentworkflowid is not null


Rest API request would be like:


"WorkflowSet?$select=WorkflowId
&$filter=StateCode/Value eq 1
and ParentWorkflowId/Id ne null
and Name eq \'' + workflowName + "\"



How to find the Async Job Id that get triggered and it’s associated to our workflow?

From the above query, we can find the workflow Id which is responsible for activating the instance of the workflow. That’s why it may have been named as Workflow Activation Id in AsyncOperation Table/Entity.

Now we use workflow id to filter out the instances, which we actually might be interested in.


/api/data/v8.1/asyncoperations?$select=asyncoperationid
&$filter=primaryentitytype eq 'invoice'
and operationtype eq 10
and  statecode eq 1
and ( statuscode eq 0 or  statuscode eq 20 or  statuscode eq 10)
and  _regardingobjectid_value eq 638F13B4-4AE9-E711-80DA-6C626DCF4746

and ( _workflowactivationid_value eq 98CA71E7-EEE6-E711-80D9-6C626DCF4746
      or _workflowactivationid_value eq 1AC0E180-39E9-E711-80DA-6C626DCF4746)


Finally, to cancel the workflow, here is a code.

function Cancel_Waiting_Workflows(asyncId)
{
       var entity = {};
       entity.statecode = 3;
       entity.statuscode = 32;

       var req = new XMLHttpRequest();
       req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v8.1/asyncoperations(" + asyncId + ")", false);
       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=\"*\"");
       req.onreadystatechange = function() {
              if (this.readyState === 4) {
                     req.onreadystatechange = null;
                     if (this.status === 204) {
                           //Success - No Return Data - Do Something
                     } else {
                           Xrm.Utility.alertDialog(this.statusText);
                     }
              }
       };
       req.send(JSON.stringify(entity));
}



It was great to explore in Dynamic CRM.

Keep Learning!!!

Sunday, October 15, 2017

Failed to import Business Process 'Lead to Opportunity Sales Process' in Microsoft Dynamic 365 CRM

I am here to explain one problem that I faced, when doing import of a solution in Microsoft Dynamic 356 CRM environment. I got an exception when I tried to import my managed solution from one Dynamic 356 CRM environment to other newly instantiated one.

Before I promote my solution to Production instance, I wanted to make sure that my solution is error free and there is no component dependency, which usually one have faced during import of a solution.

So I decided to make a new test environment and do testing there and if everything is working well, I can take further steps to move it to production environment.

I did some of the changes in existing standard business process flow like removing some of the fields and adding few as my client business requirements. When I exported the solution both in managed and un-managed formed, I did not receive any complaints from Dynamic CRM platform.

When I tried to import the managed solution to my new test environment, the import wizard complains about below listed error.

Failed to import Business Process 'Lead to Opportunity Sales Process' because solution does not include corresponding Business Process entity 'leadtoopportunitysalesprocess'.

Failed to import Business Process 'Opportunity Sales Process' because solution does not include corresponding Business Process entity 'opportunitysalesprocess'.

Solution:

We need to add corresponding entity to our solution, as we did some changes in Standard out the box business process.
  • These corresponding entities do not appear under standard entity list.
  • They also don’t get added when you may try to add all required components.
  •  In fact, I found them under 1:N relationship of respective entity.

Here is a screen shot of an Opportunity Sales Process as a Related entity which appear in 1:N relationship of Opportunity entity.

Similarly, we can add Lead to opportunity Sales Process entity under 1:N relationship of Lead entity. Once we do this, we can see both entities which were missing in above exception are listed in entities list of solution.















After adding these entities, my import customization went successful.