SPClientSideDeployment 3.3 adds option to publish on deployment

With SPClientSideDeployment 3.3 you can now have the file(s) published automatically on deployment from Visual Studio. This option is disabled by default as it would require additional calls to SharePoint during deployment.

To enable this option, go to Tools \ Options \ SPClientSideDeployment, and set the Publish on Deployment option to true.


You can download this extension from the Visual Studio Marketplace.

I hope you find this addition useful, and would love to receive feedback or suggestion.

Posted in SharePoint, SPClientSideDeployment | Leave a comment

CRMQuickDeploy 2.8 automatically adds web resources to CRM solution and allows right-click deploy from Solution Explorer

Add web resources to CRM solution on deployment

CRMQuickDeploy 2.8 now automatically adds web resources to CRM solution on deployment.

A new property has been added for project nodes in the Solution Explorer, namely CRM Solution Name:

When a web resource is deployed, it is automatically added to the CRM solution specified in this property. A warning is generated in the Output window if this property is not specified.

Right-click deploy from Solution Explorer

It is now possible to right-click multiple files and folders in the Solution Explorer and click the Deploy to CRM command from the context menu to trigger deployment for the selected items.

This command is available under the following conditions:

  • All selected items are under the WebResources folder – the command will deploy selected items as web resources.
  • A single RibbonDiff item is selected – the command will deploy the selected item as a RibbonDiff. Multiple selection of RibbonDiff items is not supported at this stage.


You can download this extension at the Visual Studio Marketplace.

I hope you find this addition useful, and would love to receive feedback or suggestion.

Posted in CRM, CRMQuickDeploy | Leave a comment

Identifying default organisation for user in CRM

This is a rehash of several posts by other people.

A user in CRM has a default organisation. This is the first organisation where the user was created. Use the SQL script below to identify the default organisation for a user:

select a.domainname, a.systemuserid, d.DatabaseName, d.uniquename 
from <Org Name>_MSCRM.dbo.systemuserbase a WITH (NOLOCK)
inner join MSCRM_CONFIG.dbo.SystemUserOrganizations b WITH (NOLOCK)
on a.SystemUserId = b.CRMUserId
inner join MSCRM_CONFIG.dbo.SystemUser c WITH (NOLOCK)
on b.UserId = c.id
inner join MSCRM_CONFIG.dbo.Organization d WITH (NOLOCK)
on c.DefaultOrganizationId = d.id
where a.domainname ='DomainUsername'

The script above was posted by Susan in the comment section of this post: https://blogs.msdn.microsoft.com/arpita/2013/01/23/how-to-find-default-organization-for-any-user-in-multiple-organization-crm-deployment/, which describes how the underlying data hang together to determine the default organisation for a user.

When does this might come in handy?

When a user runs a report in CRM, CRM appears to check for the user against their default organisation. The report will not be rendered correctly if this organisation is disabled. I found this information at this post: https://crmbrewer.wordpress.com/2016/05/05/crm-reports-error-error-sys-is-undefined/.

In our particular case, we found the below stack trace in the Event Viewer. My guess is that this is a MS bug that may one day be addressed. This was observed on CRM 2016 on-prem.


Exception type: CrmException

Exception message: The CRM organization you are attempting to access is currently disabled.  Please contact your system administrator

at Microsoft.Crm.BusinessEntities.SecurityLibrary.ValidateOrganizationState(IOrganizationContext context, LocatorServiceContext locatorServiceContext)

at Microsoft.Crm.BusinessEntities.SecurityLibrary.CheckDisabledStatus(IUser user, IOrganizationContext context)

at Microsoft.Crm.BusinessEntities.SecurityLibrary.ValidateUserEnabled(Guid userId, Guid organizationId)

at Microsoft.Crm.Authentication.Claims.AuthenticationProvider.Authenticate(HttpApplication application)

at Microsoft.Crm.Authentication.AuthenticationStep.Authenticate(HttpApplication application)

at Microsoft.Crm.Authentication.AuthenticationPipeline.Authenticate(HttpApplication application)

at Microsoft.Crm.Authentication.AuthenticationEngine.Execute(Object sender, EventArgs e)

at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()

at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Posted in CRM | Leave a comment

Handling pre-save action for publishing pages in JavaScript for SharePoint

In SharePoint 2013 it is fairly well known that you can catch and handle the pre-save action in JavaScript for list item forms by implementing the PreSaveAction() method. This however does not work for publishing pages as this method is not called by SharePoint for publishing pages.

You essentially have two options for catching and handling the pre-save action for publishing pages in JavaScript:

  1. Hide the OOTB Save button and provide your own Save button
  2. Override the JavaScript function that the OOTB Save button uses

Hiding the OOTB Save button and providing your own Save button

The problem with this option is that there are multiple buttons that could trigger the save event, including:

  1. Main Save button (top left)
  2. Clicking on the drop down arrow on the main Save button above gives you these additional ones:
    1. Save
    2. Save and Keep Editing
    3. Stop Editing (clicking OK on the prompt will save the page)
  3. Main Check In button
    1. Check In button on drop down menu
  4. Main Publish button
    1. Publish button on drop down menu
    2. Submit button on drop down menu
  5. Save icon at top right

You’d need to replace all of the above buttons to ensure that you always catch the pre-save action.

If you do choose this option, then here is a good guide on implementing this: http://sharepoint.stackexchange.com/questions/20646/attach-a-javascript-function-to-an-ootb-ribbon-button.

The trick is to call the handler function of the original OOTB button, which can be done using the method SP.Ribbon.PageManager.get_instance().executeRootCommand (thanks to article above).

The other trick is working out the command ID of the OOTB button. More on this toward the end of this post.

Overriding the JavaScript function that the OOTB Save button uses

With this option you’d store the OOTB function into a variable and replace the OOTB function with your own. In your custom function, you’d execute your pre-save logic, and then invoke the OOTB function using the variable that you stored previously.

With this option there are less things to override as most of the OOTB buttons (that trigger the save event) use the same function.

The trick with this option is to locate the function that the OOTB buttons use. In case you are not already aware, JavaScript for ribbon buttons in SharePoint are defined in a thing call Page Component (or declaratively in XML – but not for the buttons we need to worry about in this scenario). Here is a good introduction to implementing Page Component: http://www.andrewconnell.com/blog/Implementing-Page-Components-in-the-SharePoint-Ribbon.

Each Page Component has a handleCommand() function, and it is this function that performs the actual work of the ribbon button. It is this function that we need to replace.

Using the method SP.Ribbon.PageManager.get_instance().getPageComponentById() we can retrieve a Page Component by its ID. The Page Component ID that we want in this scenario is PageState.

The handleCommand() function however can be used to handle multiple ribbon buttons. Each button on the ribbon has a command ID, and this is passed to the handleCommand() function. In our custom function, we will need to check the incoming command ID and apply our pre-save logic only if the command ID is that of a button we are interested in.

The command IDs in this scenario are as follow (more on how to work out the command ID toward the end of this post):

Button Command ID
Main Save button (top left) PageStateGroupSaveSplit
Save (in drop down menu from main Save button) PageStateGroupSaveAndStop
Save and Keep Editing (in drop down menu from main Save button) PageStateGroupSave
Stop Editing (in drop down menu from main Save button – clicking OK on the prompt that appears will save the page) PageStateGroupStopEditing* (see special note below regarding this button)
Main Check In button  PageStateGroupCheckinSplit
Check In (in drop down menu from main Check In button)  PageStateGroupCheckin
Main Publish button  PageStateGroupPublishSplit
Publish (in drop down menu from main Publish button)  PageStateGroupPublish
Submit (in drop down menu from main Publish button)  PageStateGroupSubmitForApproval
Save icon at top right  PageStateGroupSaveAndStop

The JS below demonstrates how to hook in our pre-save action for each of the above buttons. One thing to note is that when invoking the OOTB handler, we need to restore the original this context back for the handler, i.e. the pageStateComponent object – and this is why the call method is used to invoke the original OOTB handler.

SP.SOD.executeOrDelayUntilScriptLoaded(function () {
	var pageManager = SP.Ribbon.PageManager.get_instance();
	var pageStateComponent = pageManager.getPageComponentById("PageState");

	var originalHandler = pageStateComponent.handleCommand;
	pageStateComponent.handleCommand = function (commandId, properties, sequence) {
		if (commandId === "PageStateGroupSaveSplit") {
			alert("Main Save button");
		} else if (commandId === "PageStateGroupSaveAndStop") {
			alert("Save button in drop down menu or Save icon at top right corner");
		} else if (commandId === "PageStateGroupSave") {
			alert("Save and Keep Editing button in drop down menu");
		} else if (commandId === "PageStateGroupStopEditing") {
			alert("Stop Editing button in drop down menu");
		} else if (commandId === "PageStateGroupCheckinSplit") {
			alert("Main Check In button");
		} else if (commandId === "PageStateGroupCheckin") {
			alert("Check In button in drop down menu");
		} else if (commandId === "PageStateGroupPublishSplit") {
			alert("Main Publish button");
		} else if (commandId === "PageStateGroupPublish") {
			alert("Publish button in drop down menu");
		} else if (commandId === "PageStateGroupSubmitForApproval") {
			alert("Submit button in drop down menu");
		originalHandler.call(pageStateComponent, commandId, properties, sequence);

	SP.Ribbon.PageState.ImportedNativeData.CommandHandlers["PageStateGroupSaveAndStop"] = "alert('Chose to save before continuing');" +
}, "sp.ribbon.js");

Special note for Stop Editing button

The one special case above is the Stop Editing button (on the drop down menu of the main Save button). This button presents the user with a JS confirmation box, and allows them to save the page before navigating away by clicking OK on the confirmation box. As you can see in the code above, handling the PageStateGroupStopEditing command ID only allows you to catch when the user has clicked the Stop Editing button – and not when they actually saves the page by clicking OK on the JS confirmation box.

When you click OK on the JS confirmation box, SharePoint evals a JS string that is stored in SP.Ribbon.PageState.ImportedNativeData.CommandHandlers[“PageStateGroupSaveAndStop”]. Therefore, to add a pre-save action for this particular scenario we’d need to update this JS with our custom code, such as below:

SP.Ribbon.PageState.ImportedNativeData.CommandHandlers["PageStateGroupSaveAndStop"] = "alert('Chose to save before continuing');" +

Working out the command ID of OOTB buttons

You can work out the command ID of most OOTB buttons by inspecting the HTML rendered on the page, and then cross-check with the CMDUI.xml file at SharePointRoot\TEMPLATE\GLOBAL\XML (which is the file that defines all OOTB ribbon buttons).

For example, inspect the Save button (in the drop down menu) and you can see that the aria-describedby (and also the id) attributes contain a value such as Ribbon.EditingTools.CPEditTab.EditAndCheckout.SaveEdit.Menu.SaveEdit.SaveAndStop.

Now search the CMDUI.xml file for this value and you should find a match such as below:

<Button Id="Ribbon.EditingTools.CPEditTab.EditAndCheckout.SaveEdit.Menu.SaveEdit.SaveAndStop" MenuItemId="Ribbon.EditingTools.CPEditTab.EditAndCheckout.SaveEdit.Menu.SaveEdit.SaveAndStop" Sequence="20" Alt="$Resources:core,save_15;" Command="PageStateGroupSaveAndStop" CommandValueId="PageStateGroupSaveAndStop" Image16by16="/_layouts/15/$Resources:core,Language;/images/formatmap16x16.png?rev=23" Image16by16Top="-197" Image16by16Left="-37" Image32by32="/_layouts/15/$Resources:core,Language;/images/formatmap32x32.png?rev=23" Image32by32Top="-103" Image32by32Left="-409" LabelText="$Resources:core,save_15;" ToolTipTitle="$Resources:core,save_15;" ToolTipDescription="$Resources:core,cui_STT_save;" />

The value of the Command attribute is the command ID for this button.


To attach a custom pre-save action your options include providing your custom ribbon buttons, or overriding the OOTB JS handler. Depending on the ribbon button/functionality you are targeting, one approach could be more advantageous than the other. The approach described in this post was specifically for the Save event, but should also be applicable to other events that are initiated from the ribbon.

Posted in SharePoint, SharePoint 2013 | Leave a comment

Tip for identifying button/command ID in Ribbon Workbench

Ribbon Workbench is a great tool for customising the ribbon in CRM. When you need to customise an OOTB button/command however, it can be a bit difficult to identify the correct button/command to work with. This is particularly true when some of the OOTB buttons appear the same on the Ribbon Workbench’s UI, such as the Add Existing buttons below.

One way to identify the correct button/command is to inspect the HTML on the CRM form.

In the example below, I can see that the ID of the + (add existing record) button on a sub-grid is Mscrm.AddExistingRecordFromSubGridAssociated.

I can then pick the right button to customise in Ribbon Workbench by selecting the button with the same ID for CommandCore:

Hope this helps increase your productivity with Ribbon Workbench.

Posted in CRM | Leave a comment

‘An unexpected error occurred’ and using early-binding in CRM plugins

Our plugin was throwing the error below when creating a new task record:

‘An unexpected error occurred.’

at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Create(Entity entity, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, Dictionary`2 optionalParameters)
at Microsoft.Crm.Extensibility.InprocessServiceProxy.CreateCore(Entity entity)

We were not doing anything fancy that led to this error – except we used early-binding classes:

var task = new Task
	Subject = "New task",
	Description = "Some description..."

task.Id = _organisationService.Create(task);

Our plugin was deployed to the database, and we used ILMerge to package everything into a single DLL as required by CRM under this deployment type. This was not the cause of our problem.

The strange thing is the plugin only error when running asynchronously. Changing the plugin step to be synchronous and everything works fine.

It turns out that this is because there are different behaviours between the CRM execution context for synchronous versus that for asynchronous.

Let’s take a step back in order to fully understand this. The IOrganizationService instance has a non-public property _proxyTypesAssembly that points to the assembly where the early-binding classes are defined. This must be set for the service instance to be able to work with early-binding classes properly. When things are good, this is what it looks like when you debug:

The error occurs when this property is null.

So how does this property get set? In plugins we typically use an instance of IOrganizationServiceFactory to get access to an instance of IOrganisationService:

serviceFactory = (IOrganizationServiceFactory) serviceProvider.GetService(typeof (IOrganizationServiceFactory));
service = serviceFactory.CreateOrganizationService(userId);

It is at this point that the _proxyTypesAssembly property is set for the IOrganizationService instance by the IOrganizationServiceFactory.

Below is a screenshot of inspecting the IOrganizationServiceFactory when the plugin in running synchronously. Note that the public ProxyTypesAssembly property is automatically set.

Also note that the type of the IOrganizationServiceFactory instance (serviceFactory) is Microsoft.Crm.Extensibility.PipelineExecutionContext.

Below is a screenshot of the same plugin running asynchronously. Note that the public ProxyTypesAssembly property is null, and the type of the IOrganizationServiceFactory is different compare to when running synchronously.

This is why by default plugins that use early-binding work fine in synchronous mode, but fail when running asynchronously.

To fix this issue we need to set the ProxyTypesAssembly property of the IOrganizationServiceFactory instance. While this property is not exposed on this interface, Darko Micic has found that the IOrganizationServiceFactory interface can be casted to IProxyTypesAssemblyProvider, which allows us to set this property.

The code to retrieve an instance of IOrganizationService therefore becomes:

var serviceFactory = (IOrganizationServiceFactory) serviceProvider.GetService(typeof (IOrganizationServiceFactory));
var proxyTypesAssemblyProvider = serviceFactory as IProxyTypesAssemblyProvider;

if (proxyTypesAssemblyProvider != null)
	proxyTypesAssemblyProvider.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

service = serviceFactory.CreateOrganizationService(userId);

Note that in Darko’s post he mentioned casting the execution context to IProxyTypesAssemblyProvider. In my debugging I have found that IOrganizationServiceFactory and IPluginExecutionContext actually points to the same instance when retrieved from the service provider. I therefore have chosen to cast the IOrganizationServiceFactory instance instead.

Posted in CRM | Leave a comment

How to set EntityCollection property of service response for unit testing purposes [CRM]

When unit testing CRM C# codes, you may find that you need to mock the response of calls to CRM’s Organisation service. A number of response classes in the SDK contain an EntityCollection property. This property however is null and is read-only, which means you cannot populate it with mock entries – or at least it seems that way.

This will not work:

var mockResponse = new InstantiateTemplateRequest();

//This won't compile as EntityCollection property does not have a setter
mockResponse.EntityCollection = new EntityCollection();

Neither will this:

var mockResponse = new InstantiateTemplateRequest();

//This will give you a run-time exception as EntityCollection property is null.
mockResponse.EntityCollection.Add(new Entity());   

Behind the scene, the EntityCollection property is actually a facade for reading a key from the Results property. The Results property is defined on the base class of all response classes.

You therefore can set and populate the EntityCollection property as follow:

//The mock response
var response = new InstantiateTemplateResponse();
response.Results["EntityCollection"] = new EntityCollection(new List<Entity> { new Entity() });

//response.EntityCollection will now contain one mock entity that we have just configured above.
Posted in CRM, Unit Test | Leave a comment