Sunday, December 14, 2014



Preferred Error Handling Technique


function myErrorHandling()
{
// put in code that generates an error
// change this code to throw various error types
// and see how the errors are being captured
try
{
throw new URIError("This is a URIError thrown...");

// throw new RangeError("This is a RangeError thrown...");
// throw new TypeError("This is a TypeError thrown...");
// throw new SyntaxError("This is a SyntaxError thrown...");
// throw new Error("This is a Custom Error thrown...");
}
catch(err)
{
switch(err.name)
{
case "URIError":
alert(err.name + " || " + err.message);
break;
case "RangeError":
alert(err.name + " || " + err.message);
case "TypeError":
alert(err.name + " || " + err.message);
break;
case "SyntaxError":
alert(err.name + " || " + err.message);
break;
case "CustomError":
alert(err.name + " || " + err.message);
break;
}
}
finally
{
alert("This block executes at all times");
}
}

Blocking The Events 



1 ) function BlockSave(context)
{
var _canSave = Xrm.Page.getAttribute("new_cansave").
getSelectedOption().text;
if(_canSave == "No")
{
Xrm.Page.context.getEventArgs().preventDefault();
}
}

Associate the BlockSave function to the form OnSave event.
Make sure you check the checkbox for Pass execution context
as first parameter.



2)  Forcing a Save

Xrm.Page.data.entity.save();

3) Save and New
Xrm.Page.data.entity.save('saveandnew');

4) Save and Close

Xrm.Page.data.entity.save('saveandclose');

Error Handling in MS-CRM



1) Handling UnExpected User Input

Some standard field formats in CRM include elements of user input
validation. Upon data entry, users are prompted if their input is
invalid, and the focus returns to the field, while the incorrect
input is cleared. Take the date field as an example. Enter in a
date field a string of abc123 to observe the behavior. The
following prompt gets displayed:

Once you click on OK, your input is cleared, and the focus is
returned to the field you were trying to modify. But let's see how
we can achieve the same result on a standard text field.
We want to check that the input starts with a capital letter, is
longer than three characters, and does not contain spaces. If these
requirements are not met, we'll bring up a notification message,
clear the field, and return the focus to it.




HOW To Achieve Desired Result

function CheckUserInput()
{
var _userInput = Xrm.Page.getAttribute("new_singlename").
getValue();
var _isValid = false;
if(_userInput != null && _userInput != "")
{
if(_userInput.match(/^[A-Z][a-z]+$/))
{
www.it-ebooks.info
Chapter 5
111
_isValid = true;
}
}
if(_isValid == false)
{
// clear the field
_userInput = "";
Xrm.Page.getAttribute("new_singlename").
setValue(_userInput);
// alert
alert("The input is not valid!");
// set focus
Xrm.Page.getControl("firstname").setFocus(true);
Xrm.Page.getControl("new_singlename").setFocus(true);
}
}


In the first part, we retrieve the user input, we check to make
sure that there is in fact some input, and we run it against a regular
expression.
In the second part, once we have determined that there is no match,
we execute our script to clear the field, bring up the notification
alert for the user, and set the focus back to the same field.



2)  Types Of Error encountered in General with MS-CRM

a) Generating a URIError: We are decoding a string that is not a valid
URL, resulting in the following type of error:
try
{
decodeURIComponent("%");
}

b) Generating a RangeError: In this example we are checking that a
defined age is lower than 100, and we throw a new RangeError with
our own custom message:

var _age = 120;
try
{
if(_age > 100)
{
throw new RangeError("Age cannot be over 100");
}
}

c) Generating a ReferenceError: A reference error is the result of,
in this case, trying to access a variable or method that is not defined.
Observe though that when running this code, you will see a TypeError instead.
That is the default browser behavior, as follows:
try
{
// use an undeclared variable
trying.thisone;
// TypeError due to browser
}

d) Generating an EvalError: An EvalError, while not a common one, is the result
of using the eval function in an unsupported manner. In this case, we use it
as a declaration. Again, due to browser-specific interpretation, the actual
error returned is a TypeError:
try
{
var y = new eval();
// TypeError due to browser
}

e) Generating a SyntaxError: Contrary to the name of this error, it does not have
anything to do with improper syntax. When encountering improper syntax, the error
you will see will be more along the lines of the following screenshot:
A SyntaxError is the result of improper use of the eval() function. In our example
we are evaluating the sum of a string with an integer, thus resulting in a syntax
error:
try
{
var _x = "some string";
var _y = 10;
var _total = eval(_x + _y);
}

Different Types of Events Supported by Jscript in MS-CRM



1) OnLoad : This is a form event. Executes when a form is loaded.
Most common use is to filter and hide elements on the
form.

2) OnSave : This is a form event. It executes when a form is saved.
Most common use is to stop an operation from
executing, as a result of a failed validation procedure.

3) TabStateChange : This is a form event. It executes when the
DisplayState of the tab changes.

4) OnChange : This is a field specific event. It executes
when tabbing out of a field where you've changed
the value. Please note that there is no equivalent
for onfocus and onblur.

5) OnReadyStateComplete : This event indicates that the content
of an IFrame has completed loading.


2) Preventing the Default behaviour of MS-CRM form


function StopSave(context)
{
var _isSpecialSelection = null;
var _isSpecial = Xrm.Page.getAttribute("new_isspecialcustomer");
if(_isSpecial != null)
{
_isSpecialSelection = _isSpecial.getValue();
}
if(_isSpecialSelection == false)
{
alert("You cannot save your record while the Customer is not a
friend!");
context.getEventArgs().preventDefault();
}
}

3) Show and Hide a Tab

function ShowTab()
{
Xrm.Page.ui.tabs.get("notes and activities").setVisible(true);
}

function HideTab()
{
Xrm.Page.ui.tabs.get("notes and activities").setVisible(false);
}


4) Hide and Show a Section

function HideSection()
{
Xrm.Page.ui.tabs.get("notes and activities").sections.
get("activities").setVisible(false);
}

function ShowTab()
{
Xrm.Page.ui.tabs.get("notes and activities").setVisible(true);
}




Saturday, December 13, 2014



Using Filtered Lookup Funtionality in MS-CRM 



Shown with concept of Responsible contact on case form 
and  can also be used for city ,State , Country.

 And Finally Populating Values in the Base Field
address1_city , address1_state , address1_country in case of city state country lookup








One of the most common Customized  features in Microsoft Dynamics CRM has
 always been filtered lookup fields.  
For example, say you replace country and state
text fields with lookup fields—it is a very common request to filter the available states 
based on the country selected. 

 CRM has taken a major step forward with the introduction of 
filtered lookup fields.  In this example, I want to filter the Case form “Responsible Contact” 
lookup to only include the contacts associated with the selected Case account. From the
 case form customization view, I’m going to select the “Contact” field. By clicking 
the “Change Properties” button, I will see the field properties for the contact lookup.










  Under the Related Records Filtering section of this form, I can check a check box that will filter the available values of this lookup field to records related to the value selected in another lookup field.  In this example, I said to only show contacts contained in the case account. Note that I can select whether or not to allow users to turn off the filter—this gives me the ability to choose whether my filter is “hard,” limiting my users to just the filtered records, or “soft,” allowing users to select something outside of the filter.  This is important because some filters are there to prevent users from selecting invalid record combinations, while others are there for user convenience, but may need to be overridden for exceptions.




 JScript to be used with City , State and Country Look up Fields 




function UpdateCountry()
{
var _country = new Array();
_country = Xrm.Page.getAttribute("new_country").getValue();
if(_country != null)
{
Xrm.Page.getAttribute("address1_country").setValue(_country[0].name);
}
}
function UpdateState()
{
var _state = new Array();
_state = Xrm.Page.getAttribute("new_state").getValue();
if(_state != null)
{
Xrm.Page.getAttribute("address1_stateorprovince").setValue(_state[0].name);
}
}
function UpdateCity()
{
var _state = new Array();
_state = Xrm.Page.getAttribute("new_city").getValue();
if(_state != null)
{
Xrm.Page.getAttribute("address1_city").setValue(_state[0].name);
}
}
Applying Validation to the Fields in MS-CRM 
with JScript 



 Validating Fields in MS-CRM

 1 ) E-mail Field Validation

function checkEmail(emailField)
{
var email=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([azA-Z])+/;
if(email.test(emailField))
{
// alert("true");
return true;
}
}

The checkEmail() function we have just presented is meant to be used
as a generic function we can call for any field we need to validate as 
e-mail. In order to validate the field we have just created we can create
a new function, retrieve the value of the field, and pass it into
our function.


2) For Multiple Email Container Field

function checkInput(inputField)
{
var flag = true;
var emailArray = inputField.split(",");
for(var i = 0; i < emailArray.length; i++)
{
if(!checkEmail(emailArray[i]))
{
flag = false;
break;
}
}
return flag;
}

3) Handling erroneous input

alert("You have entered an incorrect email address!");

var field = Xrm.Page.ui.controls.get("fieldName");
field.setFocus();

4) URL Field Validation

function ValidateLinkedIn()
{
var _url = Xrm.Page.getAttribute("new_linkedin").getValue();
var _regex = /^http:\/\/www.linkedin.com\/profile\/view\?.*/;
if(!_url.match(_regex))
{
alert("The URL entered is not a LinkedIn profile!");
}
}

5) Ticker Field Validation

function CheckTicker()
{
var tickerValue = Xrm.Page.getAttribute("new_ticker").getValue();
if(!CheckTicker(tickerValue))
{
alert("The Ticker symbol provided does not exist!");
}
}

6) Formatting PhoneNumber Field Validation


// call this function to format any north american phone number(10 digit)
// in the following format: (xxx) xxx-xxxx
// pass context to the function
function FormatPhoneNo(context) {
try {
var nvsField = context.getEventSource().getValue();
var nvsTmp = nvsField;
if (typeof (nvsField) != "undefined" && nvsField != null)
{
nvsTmp = nvsField.replace(/[^0-9]/g, "");
switch (nvsTmp.length) {
case 10:
nvsTmp = "(" + nvsTmp.substr(0, 3) + ") " + nvsTmp.substr(3, 3) + "-" + nvsTmp.substr(6, 4);
break;
default:
alert("Phone must contain 10 numeric digits.");
break;
}
}
context.getEventSource().setValue(nvsTmp);
}
catch (err) {
}
}


7) Formatting Postal Field Validation

// Function to format postal code
// for both Canadian and US postal codes
function FormatPostalCode(context)
{
var oField = context.getEventSource().getValue();
var sTmp;
if(typeof(oField) != "undefined" && oField != null)
{
// check for US ZIP code
if(oField.match(/^[0-9]{5}$/))
{
context.getEventSource().setValue(oField);
return true;
}
// check for Canadian postal code
sTmp = oField.toUpperCase();
if (sTmp.match(/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/))
{
sTmp = sTmp.substr(0,3) + " " + sTmp.substr(3,3);
context.getEventSource().setValue(sTmp);
return true;
}
if (sTmp.match(/^[A-Z][0-9][A-Z].[0-9][A-Z][0-9]$/))

{
context.getEventSource().setValue(sTmp);
return true;
}
// code is invalid
// alert("Incorrect ZIP/Postal Code format.");
// code could be any other country, so leave as is
}
}



Scripting form fields in MS-CRM 2011 , 2013 , 2015 with Java Script



Retrieving and Setting Value of  Fields  In MS-CRM  with JAVA SCRIPT



1 ) Working with text field :


function AlertTextField() 
{
    var MainPhone = Xrm.Page.data.entity.attributes.get("telephone1").getValue();
    alert(MainPhone);
}

2 ) Writing information back to the text field

    try
{
Xrm.Page.getAtribute("new_number").setValue("AAA");
}
catch(err)
{
alert("Error: " + err.message);
}

3 )  Working with Currency field :

function ReadCurrency()
{
var myCurrencyField;
myCurrencyField = Xrm.Page.getAttribute("new_
currencyfield").getValue();
alert("The value of this Currency field is: " +
myCurrencyField);
}
4 ) Writing information back to the Currency field

try
{
var myCurrencyValue = 6.25;
Xrm.Page.getAttribute("new_currencyfield").setValue(parseFloat(myCurrencyValue));
}
catch(err)
{
alert("Error: " + err.message);
}
5 ) Working with Date and Time field :
function ReadBirthday()
{
var myContactBirthday;
myContactBirthday = Xrm.Page.getAttribute("birthdate").getValue();
alert("Contact birthday is: " + myContactBirthday);
var year = myContactBirthday.getFullYear();
var month = myContactBirthday.getMonth(); // from 0 to 11
var day = myContactBirthday.getDate(); // from 1 to 31
month = month + 1;
alert("Year: " + year + ", Month: " + month + ", Day: " + day);
}
6 ) Writing information back to the Date and Time field
try
{
var currentDateTime = new Date();
Xrm.Page.getAttribute("new_myDate").setValue(currentDateTime);
}
catch(err)
{
alert("Error: " + err.message);
}
7 )  Working with Option Sets field :

function GetOSValue()
{
var sval = Xrm.Page.getAttribute("new_optionset").getSelectedOption().text;
alert("Selected value: " + sval);
}
Alternate Method :
var sval = Xrm.Page.getAttribute("new_optionset").getSelectedOption().value;

8 ) Writing information back to the Option set field
Assigning a value programmatically

function SetOSValue (osName, osLabel){
try
{
var options = Xrm.Page.getAttribute(osName).getOptions();
for(i = 0; i < options.length; i++)
{
if (options[i].text == osLabel)
Xrm.Page.getAttribute(osName).setValue(options[i].value);
}
}
catch(err)
{
alert("Error: " + err.message);
}
}
calling Jscript Function
function SetMe()
{
SetOSValue("new_optionset","Example C");
}
9 ) Working with LookUP field :

function ReadState()
{
var state = new Array();
state = Xrm.Page.getAttribute("new_state").getValue();
if(state != null)
{
var stateText = state[0].name;
var stateId = state[0].id;
var stateType = state[0].entityType;
alert("State is: " + stateText + ", ID: " + stateId + " of type: " + stateType);
}
}

10 ) Writing information back to the lookup field
Clearing a lookup 
function ClearState()
{
var state = Xrm.Page.getAttribute("new_state");
if (state != null)
{
Xrm.Page.getAttribute("new_state").setValue(null);
}
}
Changing a lookup selection
function SetStateToNY()
{
var state = new Array();
state[0] = new Object();
state[0].id = "{BA0762E4-64D2-E111-909E-00155D6C871A}";
state[0].name = "New York";
state[0].entityType = "new_state";
Xrm.Page.getAttribute("new_state").setValue(state);
}
function setOTBState()
{
var state = new Array();
state = Xrm.Page.getAttribute("new_state").getValue();
if(state != null)
{
var stateText = state[0].name;
if(stateText != "Other")
{
Xrm.Page.getAttribute("address1_stateorprovince").setValue(stateText);
Xrm.Page.ui.controls.get("address1_stateorprovince").setVisible(false);
}
else
{
Xrm.Page.getAttribute("address1_stateorprovince").setValue("");
Xrm.Page.ui.controls.get("address1_stateorprovince").setVisible(true);
}
}
}

Tuesday, December 2, 2014



Relating Custom fields on different Entities



A way to accomplish this is through the mapping of fields from parent records to related, child records. The key to making the mapping work is that the users need to create the new, child record from the parent record. For example, if you have an Opportunity record open, you would then select Quote from the left navigation and then click the ‘Add New Quote’ button from the ribbon when it changes.
To setup the mapping, do the following:
  1. Get to ‘Customizations’.  One way to do this is to go to ‘Settings’, ‘Customizations’, and then choose ‘Customize the System’.



  1. Select arrow to the left of the parent entity to expose the sub-menu items. In our example, that is the Opportunity.


  1. Once there, go to the Opportunity entity and click on the ’1:N Relationships’.


  1. Next click on ‘Mappings’ and then the ‘New’ button.


  1. Lastly, choose the source and target fields, click ‘OK’ and you’re done.