Using Upsert in Microsoft Dynamics CRM 2015 Update 1

Another useful feature that is introduced in Dynamics CRM 2015 update 1 is support for upsert operation. Upsert allows us to create or update record in CRM in single call, so we don’t need to bother if there is any existing record with the same keys or combination of other fields. This is specially useful in case of integration, when we are not sure that record from other system is already integrated with CRM or not. We can use upsert with alternate keys, Please refer our earlier post for how to use alternate keys. Let’s take below example where we are writing a account request, using upsertrequest,

Entity account = new Entity(“account”, “accountnumber”, “UPST601″);
account[“name”] = “Upsert Demo”;
account[“revenue”] = new Money(5000);

UpsertRequest request = new UpsertRequest()
{
Target = account
};

UpsertResponse response = (UpsertResponse)service.Execute(request);
if (response.RecordCreated)
Console.WriteLine(account[“name”] + ” Created with Revenue: ” + account.GetAttributeValue<Money>(“revenue”).Value);
else
Console.WriteLine(account[“name”] + ” Updated with Revenue: ” + account.GetAttributeValue<Money>(“revenue”).Value);

Console.WriteLine(“———————————–“);
account[“revenue”] = new Money(15000);
UpsertRequest request1 = new UpsertRequest()
{
Target = account
};
response = (UpsertResponse)service.Execute(request);
if (response.RecordCreated)
Console.WriteLine(account[“name”] + ” Created with Revenue: ” + account.GetAttributeValue<Money>(“revenue”).Value);
else
Console.WriteLine(account[“name”] + ” Updated with Revenue: ” + account.GetAttributeValue<Money>(“revenue”).Value);
Console.ReadLine();

As you can see in above code we are executing upsert request two times, so first time as this record is not available in CRM, it will create it, but while executing next statement it will update existing record instead of creating it,

upsert

HIMBAP | Need any help in Microsoft CRM 2015 Development Contact US !!

Leave a comment

Filed under MS CRM 2015 Update 1

Using Alternate key to update entity record- Microsoft Dynamics CRM 2015 Update 1

If you have worked on integrating CRM with another system like ERP, you might have maintain different keys for your ERP records for the synchronization purpose. But now you do need to that any more !! Microsoft Dynamics CRM 2015 Update 1 introduced new feature which allows us to assign alternate unique keys to entity which can help us to update entity record, this is specially useful for integration because you need to keep both keys from both the system to synchronization of the data between two systems. This key can help you to create/update data in CRM without querying entity record primary GUID, which means alternate key will act like a primary key. You can add alternate keys by following below steps

  1. Navigate to Settings-> Customizations->Customize the System
  2. Select your entity and expend it, let’s say in our case we want to use Account entity.
  3. Click on Keys->New to setup alternate key for account.
  4. Provide display name for your alternate key, let’s say we want to name it as Integration key
  5. Select source field where want to store this key, so let’s say want to utilize Account Number field, select Account Number and click on Add button.
  6. Save and Close key dialog.

alternamekeys

Now this field will be holding another key field for us that we can use to update this record. So let say first we want to create account record and by setting this key, we can use following code:

//Create Account object with alternate key field and value

Entity account = new Entity(“account”, “accountnumber”, “ERP12345″); 

account[“name”] = “Alternate Key Test”;

service.Create(account);

So our account record is created like below

Capture

Now as this account is created with alternate key, we can simply update this account with the help of alternate key without using accountid field (primary key) like below

Entity accountUpd = new Entity(“account”, “accountnumber”, “ERP12345″);

accountUpd[“name”] = “Alternate Key Demo”;

accountUpd[“websiteurl”] = “www.himbap.com”;

service.Update(accountUpd);

Now our account record is updated:

Capture11

So, we can use alternate keys to update entity records now !!

HIMBAP | Need any help in Microsoft CRM 2015 Development Contact US !!

Leave a comment

Filed under MS CRM 2015, MS CRM 2015 Update 1

Improved update method –Microsoft Dynamics CRM 2015 Update 1

Microsoft Dynamics CRM 2015 Update 1 released some new features that will be very help for developers. In this post we will discuss new improvement in Update method. In earlier version we had different request for the special operations for example AssignRequest for changing owner once record is created, SetStateRequest to change the status of entity record. But now with the release of CRM2015 Update 1 we don’t need to use request (they are deprecated). We can simply apply these operation in the update request only.

For example below is the request to update account record and assign to another user and change status to inactive:

OrganizationService service=GetCrmService();

//Create account object

Entity account=new Entity(“account”);

//set account id

account[“accounted”]=new Guid(“af393105-2a98-407b-9215-6113f19498ad”);

//Assign this record to dev user

account[“ownerid”]=new EntityReference(“systemuser”, new Guid(“af80d7b3-e5e1-4b52-a141-a594f24ee015”);

//set account status to inactive

account[“statecode”]=new OptionSetValue(1);

account[“statuscode”]=new OptionSetValue(2);

//call update method

service.Update(account);

Before: 

Capture1

After:

Capture2

HIMBAP | Need any help in Microsoft CRM 2015 Development Contact US !!

Leave a comment

Filed under MS CRM 2015 Update 1, Uncategorized

Deleting Microsoft Dynamics CRM 2013 Organization from SQL

Requirement: Delete Microsoft Dynamics CRM Organization

Solution: We can follow below steps to delete Dynamics CRM Organization from DB.

  1. Connect to CRM DB server and right click on CRM organization DB (for example DEMO_MSCRM)
  2. Select Delete and make sure to select Close existing connections

MDMD

This will delete organization DB , but we also need to remove Organization references from MSCRM_CONFIG DB, so follow below steps.

  1. Fire below select statement against MSCRM_CONFIG DB

select * from [dbo].Organization

  1. Note down ID of your organization, we need it for below queries.
  2. Execute following commends against MSCRM_CONFIG DB, you can change parameter and run all of them in one go

         delete from [dbo].[OrganizationFeatureMap] where OrganizationId=’ORG_GUID’

         delete from [dbo].SystemUserOrganizations where OrganizationId=’ORG_GUID’

         delete from [dbo].[OrganizationProperties] where Id=’ORG_GUID’

         delete from dbo.Organization where DatabaseName=’ORGNAME_MSCRM’

Note: This is an unsupported method of removing Organization DB and should be used only when not able to delete organization from Deployment Manager for specific reasons.

Hope it will help someone !!

Leave a comment

Filed under Uncategorized

Removing Stored Credentials for Microsoft Dynamics CRM SDK Samples

If you want to remove credentials stored in configuration file for Microsoft Dynamics CRM SDK sample then this post is going to help you to implement that.

Requirement: Remove stored credentials from configuration file.

Solution: When you will try to run Microsoft Dynamics CRM SDK sample code first time it will ask you for credentials details like below (we are doing demo with Microsoft Dynamics CRM 2015 Online)

fistconfiguration

Once connected, it will store your credentials details in Credentials.xml file and next time when you will try to run sample again it will show you option to select existing configuration to connect to your CRM server.

multipleocnfiguration

We can add maximum 9 configuration, and if you want to remove any stored credentials details, you can go to C:\Users\<username>\AppData\Roaming\CrmServer\Credentials.xml location and can open credentials.xml file in any text editor. We can remove particular configuration or can delete all configuration based on requirement. Save your changes and now next time when you will try to run application it won’t show your that configuration details.

configurationdetails

HIMBAP | Need any help in Microsoft CRM 2015 Development Contact US !!

Leave a comment

Filed under CRM Dvelopment Series

Overriding out of box command button behavior – Step by Step

Did you get a requirement to override a system ribbon or command button?? If yes then this blog post going to help you to implement your requirement.

Requirement: Let’s say we have requirement to prompt user before saving the record and based on select we need to save or cancel save operation.

Solution: We can create a custom button to replicate out of box button, we will be calling same method that is called on out of box button. Once our button is ready we will hide out of box button. To implement our requirement use following steps

  • Download and install RibbonWorkBench solution
  • Create a Demo solution and add account entity to our solution.

Note: You can follow our previous post to get RibbonWorkBench solution, to create demo solution and adding existing entities. We are going to override Save button on account entity

Open Demo solution and add new web resource by navigating Components ->Web Resources -> New

  • Fill below properties and click on Text Editor button
    • Name: OnSave.js
    • Display Name: OnSave.js
    • Type: Script (Jscript)
  • At this point create a blank function like below

function OverrideSave()

{   //We will be changing it in later step   }

  • Save and Publish web resource

Now we will create a custom button and will copy properties or save button. Using following steps:

  • Open RibbonWorkBench and select our Demo solution
  • Drag Button from Toolbox and leave it next to Save under Form section
  • Right click on system Save button and select Customize Command
  • Use same properties of system Save button to our custom button except Sequence and CommandCore properties (we need to copy and paste these properties one by one)SaveButtons

Now we need to check command which is associated with system save button and need to see which function and parameter used for that. Follow below steps

  • Select Mscrm.SavePrimary under Commands and click on Actions lookup to check for function name and parameter, we got this command name from Save button commandcore property

systembutton

  • Right click on Command and select Add New, we need to add command for your custom Save button
  • Click on Actions lookup -> click on Add and select JavaScript Function Action
  • Write our function name and select our web resource.
  • Click on Parameters lookup->click on Add and select Crm Parameter
  • Select Primary Control under Value drop down
  • It should look like below

override

  • Select our custom Save button and select our command name under command drop down
  • Right click on system Save button and select Hide Button option
  • Click on Publish button to publish your changes.
  • Open our java script web resource and change function definition like below

function OverrideSave()

{//Capture response

var response=confirm(“Do want to save ??”);

if(response==true){

//system function

Mscrm.RibbonActions.saveForm();

} }

  • Save and Publish web resource and open any account record.
  • Chang some field value and click on Save button you should get prompt like below

prompt

HIMBAP | Need any help in Microsoft CRM 2015 Contact US !!

Leave a comment

Filed under MS CRM 2015

Calling Java Script on click of command button MS CRM 2015 – Step by Step

In this blog we will provide step by step process to call your java script function from command button. We are using RibbonWorkbench editor to create command button. You can download RibbonWorkbench tool from here and import it your crm organization by navigating Settings->Solutions->Import. Let’s first add our demo java script function, use following steps:

  • Create a solution by navigating Settings->Solutions->New and using following settings
    • Name: Demo
    • Publisher: Select default publisher of your organization
    • Version: provide version number for example 1.0
    • Click Save
  • Select Web Resources from left components tree and click on New
  • Fill name and display name for your web resource and select Script (Jscript) under Type drop down
  • Click on Text Editor button and add hello function like below

function Hello() {   alert(“This is custom button”); }

  • Click on Ok button and Save and Publish your web resource

Let’s say we want to add custom command button on account form, so let’s add account entity to our solution, follow below steps to add account entity to your solution

  • Select Entities and click on Add Existing button
  • Select Account entity from list and click on Ok
  • Select “No, do not include Required Components” under Missing Required Components dialog and click Ok

Now we need to open RibbonWorkBench tool to use our custom solution. Follow below steps

  • Open RibbonWorkBench solution and select our Demo solution
  • Drag a button and leave it next to Save button under Form section like below
  • DragbuttonExpend button under Solution Elements and setup properties from right hand section like below
  • setpropertyRight click on Commands tree and select Add New
  • Click on Actions lookup and click on Add button
  • Select Javasript Funciton Action and click on Ok
  • Use our Hello function and select our javascript web resource under library lookup and click on OK
  • Select our button again and associate command it with it like below

showdialog

  • Click on Publish button to publish all the changes.
  • Create new account record or open existing account, you should get your custom button and on click on this button we should get alert

alert

HIMBAP | Need any help in Microsoft CRM 2015 Contact US !!

2 Comments

Filed under CRM Dvelopment Series

Fixing “Description name must be specified Parameter name: description” Error

We may get this error while deploying workflow assembly using Developers toolkit if we missed to fill description field while adding new Workflow Activity Class.

2015-02-22_12-29-51

We can fix this error using following steps:

  • Navigate to workflow project properties (Right Click on workflow project ->Select Properties)
  • Select Application tab and click on Assembly Information button
  • Fill information under Description field
  • Build try to Deploy your solution again

2015-02-22_12-36-14

But we may still get this error if RegisterFile.crmregister file is not updated automatically, so we may need to update this file manually by adding Description property like below, now we should be able to deploy our workflow solution without any issue.

2015-02-22_12-54-31

HIMBAP | Need any help in Microsoft CRM 2015 Contact US !!

Leave a comment

Filed under MS CRM 2013

Creating html web resource to show image attached in Notes Part 2

In our previous post we explained how we can get image from notes using OData endpoints, in this post we are going to explain how we can create html web resource and use our java script method to get and display image. We need to implement two steps:

  •   Create html page
  •   Deploy html page and SDK.REST.js using web resource

Create html page

Create html page using any html editor, use following code for html page

<html lang=”en-us”><head>
<script src=”../ClientGlobalContext.js.aspx”></script>
<script type=”text/javascript” src=”SDK.REST.js”></script>
<script type=”text/javascript”>
//check if document is loaded or not
var imgControl = document.createElement(“IMG”);
//Check if documented loaded fully
document.onreadystatechange = function () {
if (document.readyState == “complete”) {
getnotesImages();
}
}
//this function is used to get image from notes
function getnotesImages()
{ //get regarding object id
var regardingObjectId=window.parent.Xrm.Page.data.entity.getId();
//assign notes entity name
var entitySchemaName=”Annotation”;
var odataQuery = “?$top=1&$select=AnnotationId,DocumentBody,MimeType&” +
“$filter=ObjectId/Id eq guid'” + regardingObjectId +
“‘ and IsDocument eq true and startswith(MimeType,’image/’) “;
//call retrieveMultipleRecords method in SDK.REST javascript script library
SDK.REST.retrieveMultipleRecords(entitySchemaName, odataQuery, getnotesImagesCallback, function (error) { alert(error.message); }, function(){});
}
//process callbanck result
function getnotesImagesCallback(resultSet)
{
if (resultSet.length > 0) {
var mimeType = resultSet[0].MimeType;
var body = resultSet[0].DocumentBody;
imgControl.src=”data:” + mimeType + “;base64,” + body;
document.getElementById(‘imagediv’).appendChild(imgControl);
}
}
</script>
<meta charset=”utf-8″></head><body style=”zoom: 1;”>
<div style=”width: 100px;” id=”imagediv”></div>
</body></html>

Deploy html page and SDK.REST library using web resource

Using following steps to deploy html page and SDK.REST library in MS CRM.

  •       Navigate to Settings -> Customization-> Customize the System from top navigation bar
  •       Navigate to Components -> Web Resources-> New
  •       Fill details like following screen

saveimg

  • Click on browse button and select your html web resource.
  •        Click on Save and then Publish
  •        Navigate to Components -> Web Resources-> New
  •        Fill details like following screen

sdk.rest

  • Click on browse and select SDK.REST.js from MS CRM SDK

Note: Please refer previous post for SDK.REST.js location.

Now we can place our html web resource in the account entity form by navigating Insert  -> Web Resource options. Save your changes and then publish account entity form.

form

When you will try to open your account record you should be able to see attached images loaded into html web resource.

img

HIMBAP | Need any help in Microsoft CRM 2015 Contact US !!

Leave a comment

Filed under MS CRM 2011, MS CRM 2013, MS CRM 2013 Web Resource, MS CRM 2015

Creating html web resource to show image attached in Notes Part 1

Microsoft Dynamics CRM 2013 introduced new entity image feature, so we can have one image attribute and can use that to store entity image. But we can have only one image attribute per entity. So in this article we are going to demonstrate how we can build an image slider using the java script.

Microsoft Dynamics CRM store all the notes and attachment in annotation entity. Most of the out of box entity used to have relationship with this entity, but while creating our custom entity we can specifically select if we want to associate our custom entity with notes or not using following option under Communication & Collaboration. Keep in mind once you enable this option, there is not supported way to disable this option, but if you are not sure, if you need notes or not at the time of your entity creation better to leave this option un-selected, so that you can select this option after sometime if required.

notesoption

Note: The default size for notes attachment is 5 MB but if required you can increase this limit up to 32 MB.

For our demo purpose we are going to use account entity which already have relationship with notes entity. We will utilize attachment feature to attach image and use that in our html web resource for display. So basically we are going to implement below steps

  •     Get entity image from notes
  •     Create and deploy html web resource.

Get entity image from notes

We can attach image in notes using social pane in Microsoft Dynamics CRM 2015, like following screen.

attachimage

Once image is attached to notes, we can retrieve it using OData or Soap endpoint, we are going to use OData endpoints in this article. To retrieve data from notes we need to query annotation entity based on ObjectId field, that we can get entity id using getId method. We need to write retrieve multiple call to get image record, we can use SDK.REST.js java script library that comes with MS CRM SDK and call it’s retrieveMultipleRecords method to get data based our query. Please download MS CRM SDK to get details about this library and it’s method.

function getnotesImages()
{ //get regarding object id
var regardingObjectId=window.parent.Xrm.Page.data.entity.getId();
//assign notes entity name
var entitySchemaName=”Annotation”;
var odataQuery = “?$top=1&$select=AnnotationId,DocumentBody,MimeType&” +
“$filter=ObjectId/Id eq guid'” + regardingObjectId +
“‘ and IsDocument eq true and startswith(MimeType,’image/’) “;
//call retrieveMultipleRecords method in SDK.REST javascript script library
SDK.REST.retrieveMultipleRecords(entitySchemaName, odataQuery, getnotesImagesCallback, function (error) { alert(error.message); }, function(){});
}
//process callbanck result
function getnotesImagesCallback(resultSet)
{
if (resultSet.length > 0) {
var mimeType = resultSet[0].MimeType;
var body = resultSet[0].DocumentBody;
imgControl.src=”data:” + mimeType + “;base64,” + body;
document.getElementById(‘imagediv’).appendChild(imgControl);
}}

Note: You can download latest CRM SDK from here and find SDK.REST.js under SDK\SampleCode\JS\RESTEndpoint\JavaScriptRESTDataOperations\JavaScriptRESTDataOperations\Scripts.

Stay tuned for our next post to create and deploy html web resource using above method to get and display image.

HIMBAP | Need any help in Microsoft CRM 2015 Contact US !!

Leave a comment

Filed under MS CRM 2011, MS CRM 2013, MS CRM 2015