Sonoma Partners Microsoft CRM and Salesforce Blog

CRM 2016 Knowledge Articles and Full Text Knowledge Search

Today’s guest blogger is Rob Swafford, a Senior Developer at Sonoma Partners

I recently had to build an integration with the new-to-CRM 2016 Knowledge Management entities for a client. As you probably know, previous versions of Dynamics CRM had some Knowledge Base functionality through kbarticle entities. These served their basic purpose, but had their limitations.

Knowledge Article Introduction

For CRM 2016, Microsoft has introduced an all-knew knowledgearticle entity that incorporates the basic KB Article functionality along with translations and versioning for articles. These are available under Service –> Collateral –> Articles, from the yellow callout bar above the Articles grid:

image

Clicking that link will bring you to the new Engagement Hub where you’ll find not only the new Knowledge functionality, but also active and resolved Cases and emails:

image

From there, click on the arrow by Service, then click on Knowledge Articles in the Site Map:

image

This finally brings you to the new Knowledge Article management screen. Hopefully Microsoft will make it a little faster to access in a future patch. From here you can view the articles that exist in your current CRM system. Note that these do *not* overlap with the old-style kbarticle entity at all.

image

From here, you can create and edit articles as needed.

Full Text Search

For my project, I needed to be able to execute full-text searches against these Knowledge Articles. Our user base wanted to send in a search string and have the system search across the full text of the article body for the words in that search string, including alternate tenses of verbs. Not an easy task when all you have is FetchXML. But wait! CRM 2016 ships with a brand-new SDK request called FullTextSearchKnowledgeArticleRequest, and a correspondingly long-winded FullTextSearchKnowledgeArticleResponse. This request/response object pair takes care of all of the heavy lifting for my exact use case.

The FullTextSearchKnowledgeArticleRequest object has a number of public properties that need to be filled in to work properly:

Name

Type

Description

QueryExpression

QueryExpression

Sets a QueryExpression object that is used to set additional query criteria beyond the SearchText, language filtering for example.

RemoveDuplicates

Boolean

True to remove duplicate versions of the same Knowledge Article

SearchText

String

Sets the text to search for in Knowledge Articles

StateCode

Integer

Sets the StateCode of Knowledge Articles to search for. Required – so you can’t search for both Published and Draft articles in one request.

UseInflection

Boolean

True to use inflectional stem matching when searching articles. This is what enables us to search for different verb tenses – run versus ran for example.

 

Gotchas

Over the course of developing this search client, we ran into a few undocumented “gotchas”, primarily surrounding the required QueryExpression member in the Request object:

  • The QueryExpression’s ColumnSet in our experience has to be set up to return all columns. Specifying a subset of columns here caused the OrganizationService to return errors. This may be a bug that Microsoft has yet to fix.
  • The QueryExpression *must* have PageInfo data filled in. We had success specifying only a PageNumber and Count values
  • The FullTextSearchKnowledgeArticleRequest does rely on SQL Server Full-Text Search under the hood. This means that the articles have to be indexed by the SQL Full Text Indexer service before they can be found by this SDK method. This indexing does take some time, and we found we had to wait a couple of hours sometimes before newly published articles would be surfaced.

Our final, functional implementation looks something like this:

image

As you can see, we have the QueryExpression set up as I described above, we are using the Inflection and Duplicate Removal options, and filtering down to only Published articles. The Response object that comes back has an EntityCollection that will contain all of your matched article entities:

image

And with that, you have a working Knowledge Article search. I hope this has been helpful to you!

Topics: Microsoft Dynamics CRM 2016

Deploy Dynamics CRM with PowerShell Part 3: Auditing

Today's post is written by Ian Moore, a developer at Sonoma Partners.

Making sure that auditing is enabled and configured correctly is usually a critical step when setting up a new Dynamics CRM organization, especially a production instance. Everything related to auditing can easily be added to a deployment or setup script with a couple extra lines of PowerShell code.

The first step in configuring auditing for your organization is to make sure it is enabled at the system level. If it is not enabled here, no auditing will ever occur. Here is a simple code snippet to test if your CRM organization has auditing enabled, and to enable it if it does not:

From there, you will need to ensure that auditing is enabled at the entity level for all data where you want to track changes. If you’re not sure which entities have been configured to audit, you can actually use PowerShell to generate a simple report of your current entity audit settings:

clip_image001

Once you know which entities still need to have auditing enabled, you can use metadata updates to configure each entity. The following snippet would enable auditing for accounts:

As with any metadata changes, you will need to make sure to publish changes for the entity. The easiest way from your PowerShell script would be to use the Publish-CrmAllCustomization function. If you are only updating a handful of entities, you could also create a PublishXmlRequest similar to the UpdateEntityRequest above rather than publishing all changes.

Hopefully these snippets help eliminate necessary manual steps when configuring auditing in your CRM environment.

Make sure to download the Microsoft.Xrm.Data.PowerShell module from GitHub at https://github.com/seanmcne/Microsoft.Xrm.Data.PowerShell and follow https://blogs.msdn.microsoft.com/crminthefield/ for updates to the module!

Topics: Microsoft Dynamics CRM Microsoft Dynamics CRM Online

Mobile Friendly Experience with Dynamics CRM 2016

Microsoft Dynamics 2016 has recently been released, and with it comes a slew of new features.  Microsoft once again continued its investment in the mobile space and has made their free mobile client which is available from the app stores now have an extra level of configurability to give them an even better mobile touch.

Microsoft has constantly preached their “configure once, deploy everywhere” motto, and recent dynamics updates have continued that line of thinking by allowing users to configure the CRM record form once, and have it deploy to the Web client, Tablet client, and Phone client all at once without having to configure them separately.

Now with 2016 Microsoft has added the ability to add a little bit of mobility flavor to the form configuration.  They’ve realized that there needs to be more creativity in an application versus just a form and a list of fields, especially with mobile devices.  And with such thinking they are allowing users to configure the form once, but for the Phone and Tablet client, allowing users to specify a mobile friendly control to wrap around that field.

What does this mean?  It means that instead of having an integer field show up as a text box that allows numbers only, it can show up as a slider control that can be easily dragged and dropped when on a mobile device.  It means that instead of having a field that opens up a dropdown list of values, that the options show up as tabs that are clickable in which clicking selects that value for the field.

Sounds pretty neat right?  Well it is and below we go into more details about how to set this up.

Configuring the Mobile Friendly Controls

As mentioned above, this is all configured from the single Form definition, and administrators don’t need to go to a different location in order to enable the mobile friendly controls for the Phone client or Tablet client.  By double clicking on a field and going to the “Controls” tab, you’re able to add a control, of which you can then apply it to the Phone client, Tablet client, or both.

image61

image51

As you can see above, you can also populate some parameters per the control.  For example, on the Linear Slider on a currency field, you’re able to specify the minimum amount, maximum amount, and what the step amount is each time you move the slider left and right.  This configurable value can be hardcoded to a static value, or you can actually bind it to another value on the form which makes your controls much more dynamic based on the data you have in your environment.

Available Controls

Now that you’ve seen how to configure the controls, lets dive deeper and see a preview of what each of the controls looks like.  For each of the controls below I’ve first provided a screenshot of configuring the control that shows what types of fields it can be used with, and then I provide a screenshot of the actual control as it appears on the Tablet App.

Calendar

The Calendar Control replaces any list on a dashboard, view, sub grid on form. This isn’t available for only Activity related records, but will work for any entity that has a date (e.g., displaying Opportunities by Created On or Estimated Close Date on the Account form)

image image

Arc Knob

The Arc Knob control binds to numeric controls and allows you to visualize the value of your field in an arc that has configurable min/max/step values.

image image

Auto-Complete

The Auto complete control provides your users a way to enter data to a Single Line Text field, using a predetermined list of values.  The values can be bound to an Option Set, or to an Entity with a specific  View.  A great use case for this control would be a list of States and Countries, where you can have an entity for the State and Country values, but provide users a quick way of entering that data versus the expensive route of using lookup controls.

image
image image

Bullet Graph

The Bullet Graph control allows you to to see the value of your field in relation to a target.  You’re required to set a min value, max value, and a target value.  Then you can also provide a “Good” and “Bad” value which will further assist end users with visualizing how they’re doing compared to the company standards.  A great use case of this would be binding to the Actual Revenue and Estimated Revenue fields on an Opportunity to visualize actual versus estimated revenue.

In my example below, my min is 1, max is 100, and target is 75.  Then I have a good marker of 90, and bad marker of 50.  Given the value of the field which is 60, you can see how the other values are represented on the control.

image
image image 

Flip Switch

The Flip Switch control is another way of visualizing a bit field with only two options.  Instead of a checkbox, or radio buttons, the control displays the selected value in an “on/off” electrical switch type of manner.

image image

Input Mask

Input Mask controls are a great way to get data in a Single Line of Text field formatted a specific way.  For example, if you want to have all of your phone numbers formatted with parenthesis and dashes, then you’d have your Mast value set to the following:

(000)-000-0000

Doing so provides the end user an experience as displayed in the screenshots below.  The user will not be able to save the value entered in the field until the entire input mask is honored.

However, note that the data IS NOT stored in the database field with the mask.  That means for my example below, if I entered (312) 627-0700, the data would appear on the CRM web form (and in the database) as 3126270700.

image
image image image

Linear Gauge

The Linear Gauge control is another visual representation of a number / currency field.  It gives you the ability to configure a min, max, and step values.  This is very similar to the other numeric controls but simply another variation to provide you with multiple options.

image image

Linear Slider

Similar to Linear Gauge, Linear Slider is another variant on displaying a number / currency field in a more visual aspect.  The same min, max, and step values are configurable on this control.

image image

Multimedia

The Multimedia control is a great way to take a URL field (Single Line of Text formatted as such) and have it play audio or video directly within the application without having to leave and visit a web browser.

image

Number Input

Another way to quickly update number and currency fields is the Number Input control.  This provides users the ability to type a number directly in the middle white area, or use the plus and minus buttons to quickly increment or decrement the value based on the step that’s configured within the control on the form.

image image

Option Sets

The Option Set control is used with, well you probably already guessed it, Option Set fields.  The control provides tabs in a horizontal line with the available options for the user to quickly tap and select a value.

Note that this control is best used with a small number of options (2 or 3) and also ideal for option sets where the length of the text in the values is short.  You want to make sure that the options horizontally visually fit in a single line otherwise your users won’t see the benefit of this control.

image image

Pen Control

The Pen Control is a way to use the touch feature of mobile devices such as a Surface or iPad, in order to capture free form drawings or written text.  The control is only available for Multi Line Text fields

 image image

Radial Knob

The Radial Knob control is yet another flavor of how to display a number or currency field on a mobile device.  With this control, clicking and dragging clockwise around the knob increments the value of the field based on the step configured.

image  image

Star Rating

The Star Rating control allows you to set a numeric value via the use of up to 5 stars.  Since the field in CRM could have a max larger than 5, what happens is that the tablet would represent any value of 5 or higher as 5 stars.  Similarly, any value of 0 or less will be represented as 0 stars.

imageimage

Website Preview (CRM Online Only)

This control allows any Single Line of Text URL field to preview the beginning of a website entered into it.  Microsoft provides a disclaimer with using this control indicating that you consent to allow users to share certain identifiable device information with an external system as this makes use of an external service.  Note that this control is only available for CRM Online orgs.

image image

What Next?

As you can see the focus on mobility by the Dynamics CRM team has led to great improvements in the mobile clients and we’re excited to see where the product goes next.

If you have any questions about the mobile clients, CRM 2016, or anything else please don’t hesitate to reach out and Contact Us.

Topics: CRM Upgrade Microsoft Dynamics CRM 2016

Utilizing the Audit History for Fun and Profit

Today's post is written by Rob Montague, a developer at Sonoma Partners.

I was working on a project for a customer that wanted to send an email to all of the previous owners of a case when a case is resolved.  We had auditing enabled, and everything looked like it should be some simple fetch queries, but it wasn’t quite so simple.  Here were the catches.

Even though you have auditing turned on for a field, be sure to check to make sure that the auditing is enabled for the entity type you are using (especially if it’s native) 

  1. Settings -> System -> Auditing -> Global Audit Settings -> Start Auditing
  2. Make sure the entity types that you are using are enabled. In Global Audit Settings, under Enable Auditing in the Following Areas I had to enable Customer Service Entities to enable auditing on Case.
  3. Make sure you test to make sure your user will have access to the audit history field that you are accessing
  4. If you have an administrator that clears out audit logs OR you have an automated process to do so, you could possibly lose some historical data in the audit trail.

You can’t query the audit history directly, you must make an API call. I had tried fetching against the audit history table and the API would deny the request.  This is the call I had to make:

1

The call will get all of the field changes to the target field (in this case, ownerid) that have been done to the record (in this case incident which is the system name for the Case entity).

The audit detail records will have two properties Old Value and New Value. I then created a dictionary of owners so that I wouldn’t have duplicates when I was sending the emails out and went through the audit collection. With this approach you could notify salespeople that have modified a record when a contact buys a product, or when their contract is about to expire.



 

Topics: Microsoft Dynamics CRM

How to Use Word Templates in CRM 2016

Today's post is written by Chelsea Paice, a Sales Engineer at Sonoma Partners.

One of the great new features just released with Dynamics CRM 2016 Online is the ability to use Word Templates on individual records. These templates allow you to create easy-to-edit, pre-formatted Word documents that are already populated with your CRM data.

It’s a great way to create invoices, account summaries, form letters, and more for your CRM records.

In this post I’ll walk you through creating your own Word Template in Dynamics CRM 2016. Though they can be used on any kind of individual record, in this scenario, I’m generating a client/account summary for a partner in an accounting firm.

Download our free Dynamic Forms for Microsoft Dynamics CRM 2016 to create complex form rules using a web-based editor.

Generate a Base Template

The first step is to export a base template from CRM so that you can make your edits in Word. If you are a System Administrator or Customizer, you can get to the Templates area from the Settings Page. Go to Settings > Templates > Document Templates, and create a new template from there. If you don’t have admin permissions, you can still create personal templates by going to any individual record or view, and looking for the Word Templates option in the record’s toolbar.

1

Once you click Create Word Template, you’re given your choice of Excel vs. Word Template, and asked to choose the appropriate entity. This will be the basis of all of the other related entity information you will be able to pull in, so make sure you choose the correct one.

2

Next you can select the relationships you’d like to include in your template. This is what determines which fields will be available to you, so make sure you include everything you need. In my client summary example, I’d like to include a list of opportunities we’ve had with them, so I’ll include that from the 1:N Relationship list, and then click Download Template.

3

Editing your Template

After the template downloads, open it in Word. You need to make a couple of changes to Word before you can edit the template properly. First, enable the Developer tab. Go to File > Options > Customize Ribbon, and make sure the Developer item is checked in the Main Tabs area on the right.

4

While still in the Options window, go to Proofing in the left-hand menu, and select AutoCorrect Options. Here, you need to deselect Capitalize first letter of sentences, and Automatically use suggestions from the spelling checker. This is vital because it prevents AutoCorrect from making automatic changes to your content controls, which can cause Word to freeze.

5

6

Now you’re all set to begin editing your document template. Open the developer tab in your Word ribbon, and click XML Mapping Pane.

7

When the pane opens, it will have the default schema selected. You’ll need the CRM schema instead, so open the dropdown and select the correct one - it will start with “urn:microsoft-crm/document-template/”.

8

Now you have all of the fields in the entities you selected available to you in the XML Mapping Pane.

It’s time to go nuts!

You can insert these fields into your Word template at will, putting them in your preferred order, formatting, etc.

Some key things to remember:

  1. Insert a field (here called a Content Control) by right-clicking on it in the XML Mapping tab. In the resulting menu, make sure to only choose either Plain Text or Picture - otherwise, Word will freeze and your template won’t work.
    9

  2. If you have something in your document that should appear in a repeating list (such as, in our example, a list of opportunities related to the client), create a table with one row (plus a header, if you want one) that contains the fields you want from the related entity. Once that row is complete, select the entire row, then go the XML Mapping Pane and right-click on the entity relationship which contains the fields you used. Then under Insert Content Control, select Repeating.
    10
    11
  3. Quick tip: If you want to add in the image associated with the record, that field is called entityimage by default. Add it in as a picture!

    Here’s what my example client summary looks like now that I’m done putting in all of my content control fields:
    12

Adding your template to CRM

Save the document, and you’re ready to add it into CRM. Go back to your browser and follow the exact same step you took at the beginning to get your original template, but this time, click upload.

13

Select your edited template as requested, and click Upload. Keep in mind that if you are a non-admin, this template will only be available to you. However, if it turns out well, you could share the document with your CRM Admin so that they could make it more widely available to others.

Once the template is uploaded, you will be taken to the template’s CRM record, where you can rename it if you like, and add a description.

14

Now your template is ready to use. Go to any individual record in the entity you used as the base entity for the template, and navigate to Word Templates. If you don’t see your new template’s name there, try re-opening your browser window. Once you see it, just click it and get your new document! Here’s what my example looks like for a sample client, Aetna:

15

As you can see, the new Word Templates feature allows you to quickly and easily generate a formatted document that’s specific to your business. For more detail on word templates, you can access Microsoft’s how-to here: http://www.microsoft.com/en-us/dynamics/crm-customer-center/using-word-templates-in-crm.aspx.

Check out other new features from the 2016 update here: http://www.microsoft.com/en-us/dynamics/crm-customer-center/what-s-new.aspx.

 

 

Topics: Microsoft Dynamics CRM 2016

Deploy Dynamics CRM with PowerShell Part 2: Importing SLAs

Today's post is written by Ian Moore, a Developer at Sonoma Partners.

If your Dynamics CRM deployment includes Service Level Agreements, you have probably encountered the following error in the import log when importing solutions from a dev environment to a testing environment:

“You can't edit an active SLA. Deactivate the SLA, and then try editing it.”

clip_image002

This error occurs because your solution contains an SLA that is active in the current environment. Having an SLA in your solution can complicate imports if you forget to deactivate the SLA before starting, as the error will come at the end of the import process and you will have to start over. Thankfully we can use PowerShell to automatically deactivate any active SLAs and re-activate after importing an updated solution.

For this example we will use a simple solution that contains one SLA component, and try importing it into an organization that already has an active previous version of the SLA.

clip_image004

After getting a connection with Get-CrmConnection, we can query for active SLA’s with Get-CrmRecords in the org we will be importing to:

$crmOrg = Get-CrmConnection –InteractiveMode

# get any active SLAs in the org
$SLAresults = Get-CrmRecords -conn $crmOrg -Entitylogicalname sla -Fields slaid, statecode, isdefault -FilterAttribute statecode -FilterOperator -eq -FilterValue Active

From here we can deactivate the SLAs with Set-CrmRecordState and import the solution:

# deactivate the active SLAs
$SLAresults['CrmRecords'] | % { Set-CrmRecordState -conn $crmOrg -CrmRecord $_ -StateCode Draft -StatusCode Draft }

# import solution
Import-CrmSolution -conn $crmOrg -SolutionFilePath C:\Path\To\Solutions\CaseEnhancements.zip -ActivatePlugins -PublishChanges

With the SLAs in draft status, the solution should import successfully. Once it is completed, we can re-activate the SLAs. One catch to this process is that any SLA that was not marked as Default will not be restored when it is reactivated – so after reactivation we can use Set-CrmRecord to update the “Is Default” property as necessary.

# re-activate SLAs
$SLAresults['CrmRecords'] | % { Set-CrmRecordState -conn $crmOrg -CrmRecord $_ -StateCode Active -StatusCode Active }

# update any default SLAs to be default again
$SLAresults['CrmRecords'] |
? { $_.isdefault -eq 'Yes' } |
% { Set-CrmRecord -conn $crmOrg -EntityLogicalName sla -Id $_.slaid -Fields @{'isdefault'=$true} }

Now any SLAs should be restored to their original state, and the solution with SLA updates is imported and applied. Here is a sample script that shows the whole process:

Make sure to download the Microsoft.Xrm.Data.PowerShell module from GitHub at https://github.com/seanmcne/Microsoft.Xrm.Data.PowerShell and follow https://blogs.msdn.microsoft.com/crminthefield/ for updates to the module!

Topics: Microsoft Dynamics CRM Microsoft Dynamics CRM Online

Dynamics CRM – Specialized Operations

Specialized Operations were introduced in Dynamics CRM 2015 Online Update 1 and now included in Dynamics CRM 2016 as well.  They provide the ability to do what used to take separate messages (such as Assign or SetState) all in a single Update message. 

The following is the list of special messages that can now be executed in a single Update message:

  • AssignRequest
  • SetStateRequest
  • SetParentSystemUserRequest
  • SetParentTeamRequst
  • SetParentBusinessUnitRequest
  • SetBusinessEquipmentRequest
  • SetBusinessSystemUserRequest

Let’s jump into some sample code.  Before CRM 2015 Online Update 1, this is what it would look like to make an update to a record and then assign it to a different owner.

    var update = new Entity("contact");
    update.Id = contactId;
    update["firstname"] = "Blake";
   
    orgService.Update(update);
   
    var assignRequest = new AssignRequest();
    assignRequest.Assignee = new EntityReference("systemuser", ownerId));
    assignRequest.Target = new EntityReference("contact", contactId);

    orgService.Execute(assignRequest);

As you can see, both the Update message and the Assign message need to be executed.

Now with CRM 2015 Online Update 1 and now CRM 2016, the Assign message can be merged into the Update message and save an extra round-trip to CRM as shown below.

    var update = new Entity("contact");
    update.Id = contactId;
    update["ownerid"] = new EntityReference("systemuser", ownerId));
    update["firstname"] = "Blake";

    orgService.Update(update);

This new feature also has an impact for plug-ins and workflows.  If you perform an Update message that contains the Owner field then any workflow or plug-ins that are registered on Update will trigger once for all non-owner fields and then again for the owner fields.  The same goes when updating state/status fields.

Topics: Microsoft Dynamics CRM Microsoft Dynamics CRM 2015 Microsoft Dynamics CRM 2016

How many tables and records are in your Dynamics CRM Database?

Today's post is written by Keith Mescha, Principal Architect at Sonoma Partners.

There are many reasons to want to know how many records are in each table in your MSCRM database. One of the primary instances in which we use this information is when we are assessing the level of effort required to upgrade a client from older versions of CRM, or from MSCRM On-Premise to MSCRM Online.

When migrating customers from one version of MSCRM to another, it's good to get a handle on what's in the current system from both an entity and record count standpoint. This is also a good way to know which entities are being used, and which are not. It's also very easy to pick out non-native objects as they will have a prefix on them. Sometimes you will see more than one prefix, which will indicate that 3rd party solutions are installed or they have had many different groups or people in their customizing without maintaining consistency.

There are a few tools out there that do this type of thing, but if you are On-Premise and have access to the underlying SQL database, and have a little bit of experience working in SQL, this can be quite simple.

BTW if you have an Online Microsoft Dynamics CRM org and want to get some record counts, see this blog to learn about Dynabacus, an application we built to help count records within Microsoft Dynamics CRM Online.

Once you get into that database via SQL Server Management Studio (SSMS) you can get row counts for all tables in a couple of different ways. One easy way is to run this simple SQL query and copy and paste the data from the results pane to Excel, and then start analyzing from there.

/* Change <orgname_dbname> to be the name of your organization database* */

USE <orgname_dbname>

GO

 

SELECT t.name, s.row_count, s.index_id

from sys.tables t

JOIN sys.dm_db_partition_stats s

ON t.object_id = s.object_id

AND t.type_desc = 'USER_TABLE'

AND s.index_id <2

order by 1

 

Depending on what version of SQL Server you are running there are also some built-in reports into SSMS you can use if you right click on the database name in SSMS and select the reports option. Run the Disk Usage by Table report. This will query the database and return you a simple interactive report where you can do some basic sorting. This will help you quickly uncover which tables have the most records, or which tables are taking up the most disk space.

Photo 1


Finally, within SSMS there is the ability to use the Object Explorer Details option from the View menu. You can then drill into the tables object. This will bring up a list of all your tables and some SQL technical stuff you don't care much about. If you right click on the header row you can select and deselect what columns to show. To make it cleaner, I typically remove all the other columns and only add the Row Count column. This is my go-to method when trying to get a quick glance at how many rows are in the tables in a MSCRM Org. The nice part about this one is your column selection is saved, so next time you go in you just browse to the tables and you get a quick read of the row counts.

 

Photo 3


Photo 4

 

Want to discuss the tables and records in your Dynamics CRM Database? Contact us to learn. In the meantime, download Dynabacus, the Microsoft Dynamics CRM Record Count Tool.

Dynabacus the Microsoft Dynamics CRM Record Count Tool

 

Topics: Microsoft Dynamics CRM

Dynamics CRM 2016 – Turn Any Text Field into an Auto-Complete

Before the holidays I wrote about the new keypress events that exist in Dynamics CRM 2016 and how they can be used to provide more rich data validation but also with the release of Dynamics CRM 2016, the keypress events can be utilized to provide even more functionality by way of auto-complete controls.  Auto-completion methods were added to the Xrm client-side library which can be used in conjunction with the keypress events to turn any text field into an auto-complete control.  This can come in handy if you want to pull data from a third-party source and display it as if it were a native lookup control in CRM. 

A great example of this would be turning the native State and Country address fields into an auto-complete using live data from another source.  Without further ado, lets jump into some code on how this can be accomplished using the native Country field.

In this example I will be using the geognos free web service to retrieve a list of countries as well as their respective flags.

Note:  The free web service is http only so if you are using it in an https-enabled CRM environment then you will have to manually allow access through a browser prompt.

First setup a standard onload event in your JavaScript and register it on your form.

Then make an ajax call to the geognos web service which will retrieve all countries and add them to a list along with a URL to an image of the country flag.

$.ajax({
     url: 'http://www.geognos.com/api/en/countries/info/all.jsonp',
     dataType: "jsonp",
     jsonpCallback: 'callback',
    success: function(data) {
          for (var country in data.Results) {
              countries.push({
                   id: country,
                   name: data.Results[country].Name,
                   icon: "http://www.geognos.com/api/en/countries/flag/" + country + ".png",
                   fields: [data.Results[country].Name] 
              });
          }
    }
});

Next we will write a function using the keypress event for the native address1_country field which will utilize the new auto-completion methods to hide and show a list of countries.  The kepress event needs to handle the logic to filter the list of countries based on what the user types so we will compare what the user typed to the name of the country in the list to filter it down and pass the results to the showAutoComplete method.  If the data passed into showAutoComplete has an icon property set (a url to an image) then it will display an icon next to the list item which we will utilize to display the country’s flag.

var keyPressFcn = function (ext) {
     try {
          var resultSet = { results: [] };
          var userInput = Xrm.Page.getControl("address1_country").getValue();
          var userInputLowerCase = userInput.toLowerCase();
          for (i = 0; i < countries.length; i++) {
               if (userInputLowerCase === countries[i].name.substring(0, 
                  userInputLowerCase.length).toLowerCase()) {
                     resultSet.results.push({
                          id: i,
                          fields: [countries[i].name],
                          icon: countries[i].icon
                     });
               }
               if (resultSet.results.length >= 10) break;
          }
          if (resultSet.results.length > 0) {
              ext.getEventSource().showAutoComplete(resultSet);
         }
         else {
             ext.getEventSource().hideAutoComplete();
         }
     } catch (e) {
          console.log(e);
     }
};

Lastly, we need to register the keypress function we wrote above to the address1_country keypress event

Xrm.Page.getControl("address1_country").addOnKeyPress(keyPressFcn);

Once we add the script to CRM and register the onload function we can now check it out in action!

Note:  The user can still type free-form text into the control and by default CRM won’t validate that the user selected something from the list but JavaScript validation could be added to make sure an item from the list was used if necessary for your business.

Here is the complete script for this example:

Topics: Microsoft Dynamics CRM Microsoft Dynamics CRM 2016 Microsoft Dynamics CRM Online

Deploy Dynamics CRM with PowerShell Part 1: Duplicate Detection Rules

Today's post is written by Ian Moore, a Developer at Sonoma Partners.

The Dynamics CRM PFE team recently released Microsoft.Xrm.Data.PowerShell, which is a PowerShell module with cmdlets for interacting with data in a CRM Organization. It includes cmdlets that allow automation of solution exports and imports, changing system settings, and administration tasks. In this series of blogs, we will look at how these cmdlets can be used to automate common tasks that are encountered in deploying solutions for Dynamics CRM. The first part will be how to enable duplicate detection rules from PowerShell.

When importing a solution that contains an entity, it is not uncommon for CRM to unpublish any duplicate detection rules for the entity.

clip_image002

This requires any affected rules to be published manually after the solution is imported. We can automate this process in a few lines of PowerShell.

First, create the following function:

This function takes in the CrmServiceClient created by the Get-CrmConnection cmdlet, and an array of guids for duplicate rules. Each guid is piped to the small “Create-PublishRuleRequest” function to create an SDK request, and the piped to the code block that executes the request and returns the response as a PublishDuplicateRuleResponse.

Now for the script, we need to make sure the module is imported and can create a connection to Dynamics CRM with Get-CrmConnection.

if (-Not (Get-Module -Name Microsoft.Xrm.Data.Powershell)) {
     Import-Module Microsoft.Xrm.Data.Powershell
}

$crmOrg = Get-CrmConnection –InteractiveMode

Before importing the solution, we can query for the duplicate rules that are currently published with Get-CrmRecords. By filtering for only active rules, we can make sure we don’t unintentionally publish a rule that wasn’t active prior to importing the solution.

$duplicaterules = Get-CrmRecords -conn $crmOrg 'duplicaterule' -FilterAttribute statecode -FilterOperator -eq -FilterValue Active

$duplicateruleIds = $duplicaterules['CrmRecords'] | select -ExpandProperty duplicateruleid

Now we have the guids we need for publishing, so we can import our solution to the organization with Import-CrmSolution, and call our publish function.

Import-CrmSolution -conn $crmOrg -SolutionFilePath C:\Path\To\Solutions\DevSolution_1_0_0.zip -PublishChanges

Publish-CrmDuplicateRules -conn $crmOrg -RuleIds $duplicateruleIds

Here is a sample script that shows the whole process.

Make sure to download the Microsoft.Xrm.Data.PowerShell module from GitHub at https://github.com/seanmcne/Microsoft.Xrm.Data.PowerShell and follow https://blogs.msdn.microsoft.com/crminthefield/ for updates to the module!

Topics: Microsoft Dynamics CRM Microsoft Dynamics CRM Online