Showing posts with label CRM 2011. Show all posts
Showing posts with label CRM 2011. Show all posts

Jun 25, 2014

Issue in setFocus in forms of CRM 2011

After spending some frustrating time I found a native CRM 2011 issue. When I try to set focus to a lookup field onload of form, it just doesnt work.

What I observed was it jumps to the expected field, but switches back to some other field in the top of the form in no time.

Then I found below fix.. thought of sharing here;

function onLoad() {
   window.setTimeout(focusFromField,100)
}

function focusFromField() {
  var _Control = Xrm.Page.ui.controls.get("new_officeid");
  _Control.setFocus();
}

Also learned this issue is fixed in CRM 2013.

Nov 10, 2013

Workflow that waits till a date in the record

This is something cool. If I elaborate this a bit; this will allow you to trigger something on an important day like contract end date or etc. This can actually replace the need of a windows service that checks something periodically.

Of course I wrote something similar sometimes back, but it is practically bad. It could make new instance again and again till the exact date reaches.

Now it is just one line waiting statement that does the magic.

Typical example I tried is to put a flag for insurance records when they reach expiry date.
 
In CRM 2011, it will be like this;
 
 
In CRM 2011 online it will be like this;

 
In CRM 2013 online
 
 
If you check the record after creation you will see the waiting statement in the workflow tab.
 
 
Since expiry date can be changed later on, it is also advisable to trigger on Update as well as on Create. If a user changes the expiry date later on, you will see an extra waiting record.
 
 
Anyway, as I tested, it worked for the correct expiry date. 


Jul 7, 2013

Coloring the Subgrid rows

As we discussed previously, we can use colours for branding purposes and improve the useability. Most clients seem happy to have different colours for different rows within the Subgrid depending on their status or etc.

For example: In my cases I have an Institute entity where sub institutes are in a Subgrid. I am going to give a colour for profit making institutes. (Highlighting expensive quote products within a Quote would make more sense for you). Outcome would be something like this;


How we going to achieve this? This consists of three steps.

1) Wait till Subgid is loaded

Biggest challenge of playing with Subgids is they load in an Asynchronous manner. In that case normal onload would not fire. So we attach a method for loading with a Delay. This is the code in loading;

setTimeout("attachGridAction();", 500);

Now we will implement the relevant method.  This got a trick. In catch statement delays and calls the method again. This allows you to wait and load the code again to see if Subgrid is loaded. Your real code will run only after that is accomplished.

function attachGridAction() 
{ 
  try 
  {
    var _grid = document.getElementById("Sub_Org_List");
    if ((_grid) && (_grid.readyState == 'complete'))
    {
        // Code goes here
    }
  }
  catch (err) 
  {
       setTimeout("attachGridAction();", 500);
  }
}

2) Determine the criteria

Now you need to determine the criteria of the records to be coloured. Actually you need to read the relevant Guids. Read the relevant Fetch XML as below. If you uncomment the second line, you will see the fetch xml statement of the Subgrid. Now you are free to retrieve those records and determine the Guids according to your criteria.

var _fetch = document.getElementById("effectiveFetchXml");
//alert(_fetch.value);

3) Colouring the row

Now you have the Guids ready. Now perform this code within a loop for your Guids; (I am just using one single record to make it clearer)

var _checkbox =   document.getElementById('checkBox_{4ACC296A-0CE5-E211-A9C3-00155D467A0E}');
var _checkboxParentParent = _checkbox.parentNode.parentNode;
_checkboxParentParent.bgColor = 'DarkKhaki'; 

Limitation;
As you may guess, this doesn’t work for next pages if paging is performed for Subgrid. What you can do is increase the items in the Subgrid allowing to have a scrollbar and ignore the paging option.

Jul 2, 2013

Change colour of Fonts, Sections and Tabs

Though Microsoft Dynamics CRM 2011 forms are nicely presented, there could be instances that you may need to change the colours. It can be for branding purposes or to improve useability aspects. Most of them could be done through loading Java Scripts. We will check some of basics here.

In these codes colour can be determined by HTML code or standard name.
Click this for a basic list of such names and relevent HTML codes.

1) Fonts and backgrounds of the Fields

//Colouring the background of the label
document.getElementById('new_name_c').style.backgroundColor="CornflowerBlue";

//Colouring the field value
document.getElementById('new_name').style.color="#8B0000";

//Colouring the label
document.getElementById('new_contactperson_c').style.color="DarkOrange";

//Colouring the background of the field value
document.getElementById('new_contactperson').style.backgroundColor = 'Gold'


2) Tabs

document.getElementById("tab1").style.backgroundColor = '#F0E68C';
 


3) Sections

document.getElementById('{883d8330-156d-e4e5-130b-934752157dd3}').style.backgroundColor = 'DeepSkyBlue';


We will look into much complex colouring options in another post.

Jun 25, 2013

Issues of using checkbox in CRM 2011

In a previous post I explained difference of using onChange and onClick in CRM 4.0

Now it has come the time to talk the same thing against CRM 2011. As same as 4.0, even in CRM 2011 we got only the onChange in native manner. As we all know the problem is you need to click somewhere else after clicking the checkbox to execute the event.  So we need to implement onClick to accomplish this. It is bit similar to  4.0, but there is a complication.

For some crazy reason, standard Xrm model that works for 2011 doesn’t work here and have to use the 4.0 style code. Other issue is execution take cyclic pattern and our code gets executed twice! So we need to change the focus as soon as we finish the code. Please check the working code (this should go in onload event);

MyCheckbox = function()
{
    crmForm.all.new_sample.onclick = function()
    {
       //Code
       //Change focus to another field  
    }
}

Issues are not finish yet! Practically, we might need to do something according to the value of the relevant check box. Biggest confusion comes here. Values given are completely opposite. When you check the checkbox you might get false instead of true and vice versa. Why this happens?

I am trying to understand it this way. (please correct me If I am wrong) This is not an error. We are executing the code on “click”. This doesn’t mean we have changed the value in the time we execute the code. Of course what we see is the "changed" situation through the form. Actually code happens for previous value of the check box. I think this is the reason Microsoft doesn’t provide this event in their native framework.

If we understand this, we are good to proceed with our work without any trouble. Only thing is do the opposite when playing around with the value of the checkbox upon onClick.

var _checkbox = Xrm.Page.getAttribute("new_sample").getValue();
if (_checkbox == true)
{ 
  //code for false 
}
else
{
  //code for true 
}

This is bit confusing.. but manageable.

Jun 4, 2013

Calculate total from related entity values

This is a very common scenario. For example Quote entity contains fields to have total of all the relevant quote product values. Yet, we don’t need to bother about it since CRM is taking care of those totals. Suppose we need to do such calculation in our custom scenario it will not be handled by CRM.

Just like Quote and Quote product (or Opportunity and Opportunity product), suppose we got entity that has related records as child records or line items. Each child record could have a value for surcharge and primary entity should have the total surcharge. How you accomplish this? In other terms, when child values get changed total should get changed.


Now we will consider the events that child values could change. They are Create, Update and Delete. Obviously we need to write plug-ins for those events to adjust the total. Below would be our algorithm;

Total (Surcharge) = Sum of All Line Item (Surcharge)

Now consider different events;

Post Create – Execute above algorithm

Post Update – Execute above algorithm

What about the delete?

This is the tricky part. Since there is nothing called post-delete, obviously we need to run this in pre-delete. Still we don’t get expected value by executing the same algorithm in pre delete. Why? This uses pre values. In this case total will not be affected by the calculation. Total will not get deducted the value of deleted child record. How we solve this?

You will only have to update the surcharge value of the deleting record to zero in pre delete plug-in. When you do this, post-update plug-in will execute and total will be set except for the record which will be deleted soon. So this is the correct out come!

Apr 29, 2013

How Queues work

This is a very good video on functionality of Queues of CRM 2011 works. This is simply yet clearly explained… though of sharing..



Apr 2, 2013

Creating notes programmatically

Adding notes for any data record is a powerful feature in Microsoft Dynamics CRM 2011. In this way, user can merge external information as files in different formats such as text, pdf, image or etc.


All these files are kept in CRM in Note entity. Schema name for this entity is annotation and it is not highly customizable. In fact, there will not be a need of doing it. However we might need to create and copy annotations. You can even retrieve data.

If you check the DB, you will realise how those notes are kept in the table fields.


For me, most exciting field is documentbody, that keeps the content as encoded data. Objectid is the other remarkable field, which is actually the lookup for related record. Now we will see a couple of code snippets;

This is how we can create an annotation using a text file. In my sample I am doing it for a specific record in quote. Record is mentioned by Guid.

string filePath = @"C:\Sumedha\log\Sumedha.txt";
byte[] fileContent = File.ReadAllBytes(filePath);
string encodedData = System.Convert.ToBase64String(fileContent);

Entity _annotation = new Entity("annotation");
_annotation.Attributes["objectid"] = new EntityReference("quote", new Guid("41613500-9F87-E211-905C-00155D467A0E"));
_annotation.Attributes["objecttypecode"] = "quote";
_annotation.Attributes["subject"] = "Demo";
_annotation.Attributes["documentbody"] = encodedData;
_annotation.Attributes["mimetype"] = @"text/plain";
_annotation.Attributes["notetext"] = "My Sample attachment";
_annotation.Attributes["filename"] = "MySample.txt";
service.Create(_annotation);

Now we will see how same thing is achieved using a pdf file. You will realise that encoding method and mimetype are different.

FileStream _stream = File.OpenRead(@"C:\Sumedha\log\TestPDF.pdf");
byte[] _bData = new byte[_stream.Length];
_stream.Read(_bData, 0, _bData.Length);
_stream.Close();
string encodedData = System.Convert.ToBase64String(_bData);

Entity _annotation = new Entity("annotation");
_annotation.Attributes["objectid"] = new EntityReference("quote", new Guid("41613500-9F87-E211-905C-00155D467A0E"));
_annotation.Attributes["objecttypecode"] = "quote";
_annotation.Attributes["subject"] = "Demo";
_annotation.Attributes["documentbody"] = encodedData;
_annotation.Attributes["mimetype"] = @"application/pdf";
_annotation.Attributes["notetext"] = "My Sample attachment";
_annotation.Attributes["filename"] = "MySample.pdf";
service.Create(_annotation);

Also you can do the same without a file, if you are interested in using just a string as the input. For that you can do the data encoding as below and do the rest as usual.

string _str ="Sample - file doesnt get created in server";
byte[] _bstr = Encoding.ASCII.GetBytes(_str);
string encodedData = System.Convert.ToBase64String(_bstr);

By the way, I found a nice blog article that provides a lot of code snippets in this regards. Please refer it here;
http://lakshmanindian.wordpress.com/2012/11/01/attachments-in-microsoft-dynamics-crm-2011/

Mar 20, 2013

Sales process – Part 4 – Modifying calculation of quote

In previous posts we discussed how quote pricing is done in the native way and modifying them in item level (i.e. Quote Product) in Microsoft Dynamics CRM 2011. As the final stage, we will look in to the ways of modifying the grand total (i.e. Quote) if we happen to do so.

This requirement could occur mainly as below;

a) add a surcharge, administration cost or insurance
b) give discount comes within a loyalty program or discount determined by total
c) calculation of commissions/ loyalty points according to total

Consider the pricing pane of the quote form.


Three fields I put within the green squares are editable fields. Check them with their schema names and types.

Name
Schema Name
Type
Quote Discount %
discountpercentage
Decimal
Quote Discount
discountamount
Currency
Freight Amount
freightamount
Currency

These are the field that can’t be edited. For ease of explaining, I am dividing them to two different categories.

None editable – Category A -Fields derived from the quote products

Name
Schema Name
Type
Detail amount
totallineitemamount
Currency
Total Tax
totaltax
Currency

None editable – Category B – Calculated fields

Name
Schema Name
Type
Pre-Freight Amount
totalamountlessfreight
Currency
Total Amount
totalamount
Currency

Considerations for plug-in development

Obviously we need to develop our own plug-ins to enhance/modify the current calculations. Now consider my research result on plugin behaviour in this regard. When “creating” the quote, calculations are not applicable since quote product addition comes in a later stage. In fact, we are talking about update plug-in.

Also it is important to understand user actions that update plug-in would fire.  (Will call this action type for ease of referencing)

i) Opening the Quote
ii) Saving the Quote
iii) Pressing Recalculate button
iv) Adding/ Modifying/ Deleting  a quote product

Please check below table. I use word “available” to say it is available in plug-in context. When I say “retrieve” it means retrieve the current value from database using the web service.

Update
Pre stage
Post stage
Editable fields
(of first table)
Available if changed, otherwise retrievable. Can be modified. *
Available if changed, otherwise retrievable. Can be modified.*
None editable (Both Category A and B)
Available only for Action type (iv).** Can be retrieved. Cannot modify.
Available only for Action type (iv). ** Can be retrieved. Cannot modify.
* If you modify the same entity in Update event, make sure you avoid infinite loops.
** Plug-in run by action of addition/modification/deletion of a quote product.


Revealed plug-in behaviour seems bit complex. None editable fields become available in plug-in context when update is executed by a change of a quote product.

Other exciting observation is, when I register the plug-in for pre-stage it get executed more than once depending on users actions (refer i, ii, iii, iv) . This is bit confusing and unexplained. However, this complexity keeps us away from writing codes for pre update stage.  I am happy if someone has figured out this and can share.

Good news is we don’t need to understand all these to do our modifications.  Most important behaviour is whenever we change the editable fields, calculations get updated accordingly, regardless of when you change.

As a summery we will stick in to some rules which will give us enough space for our work. Consider below facts;

Some points to think

1) Register your plug-in in post Update.

2) You can retrieve none editable category (A) fields and use for your logic. If you see carefully, you will realise these (sum of line item values and sum of taxes) are the important reference fields to implement any logic together with editable fields.  Anyway, never try to modify category (A) fields.

3) Never try to reference or modify category (B) fields. If you want to reference them determine the values by calculating. (Reference 2nd part of this article)

4) Out of three editable fields, quote discount and freight amount gives you the most needed space to enhance the functionality as you wish. One field is being added to the total while one is being subtracted. So whatever the adjustment you need to do can be done through these two fields. Think a bit.

5) Whatever the modifications you do, you have to be creative enough to use the native total fields and native functionalities. Our changes should be carefully pushed into the bult-in mechanism through given spaces.

1st part of this article: Sales process – Part 1 – Product Catalog
2nd part of this article: Sales process – Part 2 – Quoting
3rd part of this article: Sales process – Part 3 – Modifying calculation of quote product

Mar 14, 2013

Sales process – Part 3 – Modifying calculation of quote product

A couple of previous posts explained the standard way of working with quotations and its level of flexibility. In rare cases, it could need you to modify the standard calculations. In this article, we will analyse options and constrains of doing such tasks in Quote product. Most popular requirement that would come your way could be implementing automated tax (or GST) system. Natively TAX is just an editable field in quote product.

Consider the pricing pane of the quote product form.


Three fields I put within the green squares are editable fields. These are the editable fields with their schema names and types.

Name
Schema Name
Type
Quantity
quantity
Decimal
Manual Discount
manualdiscountamount
Currency
Tax
tax
Currency

These are the field that can’t be edited with their schema names and types.

Name
Schema Name
Type
Price per unit
priceperunit
Currency
Volume Discount
volumediscountamount
Currency
Amount
baseamount
Currency
Extended Amount
extendedamount
Currency

Considerations for plug-in development

Obviously we need to develop our own plug-ins to enhance/modify the current calculations. Now consider my research result on plugin behaviour in this regard.

 
Create
Update
Pre stage
Post stage
Pre stage
Post stage
Editable fields
(of first table)
Available, can modify
Available, can modify
Modified field available and others can be retrieved, can modify *
Modified field available and others can be retrieved, can modify*
Other field
(of second table)
Not available, cannot modify
Not available, cannot modify
Can be retrieved, cannot modify.
Can be retrieved, cannot modify.
* If you modify the same entity in Update event make sure you avoid infinite loops.

Essence of this result is we can only play around with Quantity, Manual Discount and Tax. Good news is any time you change those fields; calculations are done accordingly to newly changed values of those fields. In other terms “Extended amount” get the correct value regardless of where you change those fields.

It implies CRM does its own calculations after the plug-in engine has completed its performances. In fact, you should not/ cannot amend other fields such as Price per Unit, Volume Discount, Amount and Extended Amount.

Some points to think

1) If you want to introduce an auto tax calculation method, it’s possible. Better have the logic for both create and modify event plug-ins.

2) If you consider the fact that we have two fields (namely Tax and Manual discount) to play around; tax is being added and Manual discount is being subtracted from total automatically. So whatever the additions and subtractions you need can be pushed to the current calculation mechanism if you are creative enough. Think a bit.

3) There is a chance your logic needs fields which are unavailable in plug-in context such as Price per Unit, Volume Discount and Amount. In that case, you are still able to retrieve first two fields from Price List and Discount List entities respectively and Calculate Amount. Read my 1st and 2nd parts of this article for better understanding.

4) One would also think of give up the native total fields and introduce new custom fields, WHICH IS NOT RECOMMONDED AT ALL. This means you are rewriting your own calculation logic for entire quoting including quote product and quote. That will also push you to introduce your own recalculation button in Quote header. Also you are again facing problems when quote values are transferred to Order entity in a later stage. Personally, I don’t see any reason to go in to this mess.

1st part of this article: Sales process – Part 1 – Product Catalog
2nd part of this article: Sales process – Part 2 – Quoting
4th part of this article: Sales process – Part 4 – Modifying calculation of quote

Mar 10, 2013

Sales process – Part 2 – Quoting


(It is highly recommended to read the first part of this article before proceed.)

In Microsoft Dyanmics CRM, Quote products are the line items under the Quote. Each Quote Product represents quantity, price and etc. of a product which is of interest, in given quotation.

When creating a Quote there are few required fields such as Name, Potential Customer, Price List and Currency. Since I am going to explain the pricing of Quoting, I would urge the importance of assigning the Price List for a Quoting while all other fields are quite self-explainable.


Quote Product Units

Now we will pay attention to Quote Product and see how it works together with other components we learned in first Part of this article.

When creating Quote Products, it is required to populate Product, Unit and Quantity.



Now I am adding the Product Called “My Product 001” and Unit lookup pop-up shows all the Units under Unit Group of Primary Unit (Each). This is because, when we create this product in product entity we have specified that Unit Group. If we use a product which got Weight Unit Group, we might see all the Units associated to Weight such as 5kg Pack, 3Kg Pack and so on.

Quote Product Price Calculation

Now I save the Quote product with my values. Quantity is 7 and Unit is Each. Now we get auto calculated total for the Quote Product as below.


Price per Unit is the amount we mentioned in the Price List for “My Product 001” for “Each” unit. below is the calculation for Amount.

Amount = (Price per Unit – Volume Discount) x Quantity

In this case, Amount is also equal to Extended Amount too.

Now what is Volume Discount? If you read the first part of this article, it was explained about a lookup to set Discount List when creating Price List items. In this case, I have assigned a Discount List for the Pricelist Item of this product for Each Unit. Particular Discount List contains a Discount as below;


This simply tells to give $ 3 discount if quantity >= 6 and quantity <= 10.

Note: Since Discount List has to be assigned to Pricelist Items, it has to be assigned to all the Unit records for same product. In other terms, this same discount will not be applicable for the same product comes as Dozen or Cartoon unless it’s assigned for relevant PriceList Item records.

Apart from them, there are two more editable fields which I filling now. I put Manual Discount 50 and Tax 100 then save the record again. Below is the result.


In fact below is the equation of Extended Amount.

Extended Amount = Amount – Manual Discount + Tax

Dependencies you may note in Quote products

1) There are more products in the product entity, but I see fewer products in product lookup from the Quote Product form.

Explanation: You see only the products associated with the relevant Price List. In other terms, there should be at least one PriceList Item with the product to be seen here.

2) After populating a product to Quote Product, when try to set the Unit, I don’t see all the Units come under relevant Unit Group.



Explanation: Though this product is associated with relevant PriceList, it hasn’t got PriceList Item for all three Units, but only for the shown Units. In this example, PriceList got only one PriceList Item for this product and it is for Dozen Unit. (Need records for Each and Cartoon)

Quote Price Calculation

Once you complete play around with Quote Product, you are required to click the Recalculate button to get correct Quote totals. I got below sample totals for a Quote with a couple of Quote Products.


In fact, below are a couple of important formulas;

Detail Amount = Sum of Quote Products (Extended Amount – Tax)

Total Tax = Sum of Quote Products (Tax)

Quote total pane also got a couple of editable fields. I put my own values and recalculated to get new totals.


I have below formulas now;

Pre-Freight Amount = ( Detail Amount  x (100 - Quote Discount % ) / 100 ) – Quote Discount $

Total Amount = Pre-Freight Amount + Freight Amount + Total Tax

You will notice there are two kinds of Discount fields in the pane. One is percentage and other one is dollar amount. I have filled both fields to present a universal formula, but in practical world it’s advised to use one of those to keep it simple. These values are one time discounts that applied to the Quote total.

1st part of this article: Sales process – Part 1 – Product Catalog
3rd part of this article: Sales process – Part 3 – Modifying calculation of quote product
4th part of this article: Sales process – Part 4 – Modifying calculation of quote

Mar 7, 2013

Sales process – Part 1 – Product Catalog

Microsoft Dynamics CRM got flexible features to cater most of the pricing needs for products and services. Here I am explaining how they will fit in to your scenario. Here my starting point is Product Catalogue. Product Catalog is nothing more than few purposely designed entities. If you click settings > Product Catalog, you will see below screen with the entry points to four sections.

 

Unit groups and Units

First thing first! It is important to understand the relationship of Unit Groups and Units within the context of usability. This is fundamental physics! Any product should have a method of measuring.

Primarily most of the products can be count as integers (i.e. each). For example we can count Cars, Generators, computers, tables or etc. In day to day life, we have defined different packages of items for ease of usage such as cartoons, dozens and etc. Best example comes to my mind is beer. When we got o bar we can ask for one or two... but when we order them for a party we might order beer packs of 24 or 26 or etc. In CRM, these countable items can be defined as one Unit Group while, as same as the example mentioned, other “item packs” can be different Units under same Unit Group.

Now I am considering this Unit group as my Primary Unit group. CRM allows me to define many Units under this. Once you created one Unit Group, you can click the Unit link shown as an associate view, where you can add you’re Units. Suppose I define a dozen. Below is the simple form I need to fill. This explains dozen is created by multiplying Each by 12.


Also I can define a Cartoon which is 5 dozens.  This is the view I see all the relationships of Units under my Unit Group called “Default Unit (Each)”


Now I realize there can be different other products which can’t be measured with my primary unit group. Ex: Metal, Wheat, Cement and etc. Now I know they are measured by weight not the number of items. So I need another Unit Group for weight. Obviously, I can again define my Units under this Unit Group. Here I have added my second Unit Group;

 
Within Weight, I have defined different weights as Units. From this illustration you should realise that my primary unit for Weight Unit Group is 1kg and I have defined different packs of different weights based of 1kg.


Hope this explains that you can define whatever the measurement and units goes with your product or service. It can be length or time or etc.

Product and pricelist

Now only we can add records to products and pricelist.

When creating a new product you are required to populate both Unit Group and Default Unit. Always Default Unit look up shows you the values according to the Unit Group you selected.


Pricelist is the next important entity that keeps prices of products for their different units. Pricelist keeps all those information as PriceList Items. Please check a sample pricelist item as bellows;


This pricelist item says the price of the product for a Dozen. This implies, typically we need two more records for the same product for each and Cartoon.

Now we will consider this case. When I open my second product I see below error message in the beginning of the form. It says I haven’t set the default price list for the product.


In fact, now I am trying to open the lookup and set it, but I can’t see any pricelist in the pop-up lookup window!  This is because; price list doesn’t contain a pricelist item for this given product.
Now you are required to add a pricelist litem for this product before making any use of this product.

Discount Lists

In price list item, there is another special lookup called Discount List which obviously is to select a relevant Discount list for the record.


Discount List contains different Discounts under it. Discounts are simply discount amount /Percentage you get for buy different numbers. For example this Discount says that buyer gets $3 of discount if buy 4-10 of this. So user is free to define many Discounts under Discount List. Obviously user can have many Discount Lists to be attached to different pricelists.


When quoting, these discounts are being applied automatically.

2nd part of this article: Sales process – Part 2 – Quoting
3rd part of this article: Sales process – Part 3 – Modifying calculation of quote product
4th part of this article: Sales process – Part 4 – Modifying calculation of quote