Thursday, July 18, 2013



To hide the Ribbon toolbar of a form, use the below mentioned code snippet.
window.top.document.getElementById(“crmTopBar”).style.display = “none”;

MS CRM 2011 – Accessing Parent Form

If you want to access a parent form’s Xrm.Page object in MS CRM 2011, use the below mentioned code.
window.top.opener.parent.Xrm.Page

MS CRM 2011 – Auto populate unit on selection of a product in Opportunity Product

In MS CRM 2011, In the Opportunity Product form when a product is selected the unit field will not be automatically populated. So in order to populate value in the unit based on the product selected, we require a java script code to be written. So your function would look like the one mentioned below:
function ProductOnChange_SetUOM() {   
   if (Xrm.Page.getAttribute("productid").getValue() != null) {
      SetUomId();
  }
}
But there is a problem here. After placing the above code in your Product on-change event, still the unit value would not populate. Even though the Code written by you is absolutely correct, still unit value is not set. In such scenarios do not spend much time  debugging or analyzing the problem, just follow the solution mentioned below.
On product on-change, the unit field will still be read-only and hence the value set by you through code would not be assigned. So to solve this issue use the below mentioned code. On the Product on-change event call your SetUomId() method with a slight  delay, so that the unit field would not be a read-only field when you set the value.
function ProductOnChange_SetUOM() {   
   if (Xrm.Page.getAttribute("productid").getValue() != null) {
      // delay of 100ms, because uomid is readonly
    window.setTimeout("SetUomId()", 100);
  }
}


MS CRM 2011 – JavaScript – getUserRoles

getUserRoles

Returns an array of strings representing the GUID values of each of the security roles that the user is associated with.
Xrm.Page.context.getUserRoles()
Return ValueType: Array
Example: This user has only one security role associated with their user account. The JSON representation of
this array with a single value is: ["cf4cc7ce-5d51-df11-97e0-00155db232d0"]

MS CRM 2011 – JavaScript – Entity Methods – Xrm.Page.data.entity

Example:Xrm.Page.data.entity.addOnSave([function reference])

function addMessageToOnSave() {
 Xrm.Page.data.entity.addOnSave(displayMessage);
}
function displayMessage() {
 alert("message");
}
getDataXml – Returns a string representing the xml that will be sent to the server when the record is saved.
Example:Xrm.Page.data.entity.getDataXml()
In this example, the following three fields for an account record were updated:
  • name , accountnumber, telephone2
"<account>
<name>Contoso</name>
<accountnumber>55555</accountnumber>
<telephone2>425 555-1234</telephone2>
</account>"
getEntityName – Returns a string representing the logical name of the entity for the record.
Example:Xrm.Page.data.entity.getEntityName()

In this example, an account record was being edited.
"account"
getId – Returns a string representing the GUID id value for the record.
Example:Xrm.Page.data.entity.getId()

The GUID Id value for the record.
"{825CB223-A651-DF11-AA8B-00155DBA3804}"
getIsDirty – Returns a Boolean value that indicates if any fields in the form have been modified.
Example:Xrm.Page.data.entity.getIsDirty()
removeOnSave – Removes a function from the OnSave event hander.
Example:Xrm.Page.data.entity.removeOnSave([function reference])

function removeMessageFromOnSave() {
 Xrm.Page.data.entity.removeOnSave(displayMessage);
}

function displayMessage() {
 alert("message");
}
save- Saves the record. This method has three possible parameters.
Example:Xrm.Page.data.entity.save( null | "saveandclose" |"saveandnew" )
Arguments
save()->If no parameter is included the record will simply be saved. This is the equivalent of the user clicking the Save button in the ribbon. 
save("saveandclose")->This is the equivalent of the user clicking the Save and Close button in the ribbon. 
save("saveandnew")->This is the equivalent of the user clicking the Save and New button in the ribbon.


MS CRM 2011 – Set focus to a field

var field = Xrm.Page.ui.controls.get(“AttributeName”);
field.setFocus();

MS CRM 2011 – Show/Hide Tab/Section

Xrm.Page.ui.tabs.get(1).SetVisible(false);
Show a tab/section
Xrm.Page.ui.tabs.get(1).SetVisible(true);

MS CRM 2011 – JavaScript – Attribute Methods – Xrm.Page.data.entity

Method - addOnChange
Applicable - All
Description - Sets a function to be called when the value is changed.
Example - Xrm.Page.getAttribute(“[Attribute Schemaname]”).addOnChange(displayMessage);

          function displayMessage() {
                 alert("message");
          }
Method - fireOnChange
Applicable - All
Description - Causes the OnChange event to occur on the attribute so that any script associated to that event can execute.
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).fireOnChange();
Method - getAttributeType
Applicable - All
Description - Returns the type of attribute (string).
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getAttributeType();
Method - getFormat
Applicable - All
Description - Returns formatting options for the attribute (string).
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getFormat();
Method - getInitialValue
Applicable - boolean, optionset
Description - Returns the initial value for Boolean or optionset attributes.
 Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getInitialValue(); 
Method - getIsDirty
Applicable - All
Description - Returns a Boolean value indicating if there are unsaved changes to the attribute value.
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getIsDirty();
Method - getMax
Applicable - money, decimal, integer, double
Description - Returns the maximum allowed value for an attribute (number).
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getMax();
Method - getMaxLength
Applicable - string, memo
Description - Returns the maximum length of a string or memo attribute (number).
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getMaxLength();
Method - getMin
Applicable - money, decimal, integer, double
Description - Returns the minimum allowed value for an attribute (number).
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getMin();
Method - getName
Applicable - All
Description - Returns the logical name of the attribute.
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getName();
Method - getOption
Applicable - optionset
Description - Returns an option object with the name matching the argument passed to the method.
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getOption([Attribute Value]);
Method - getOptions
Applicable - optionset
Description - Returns the valid options for an optionset attribute (an array of option objects). 
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getOptions();
Method – getParent
Applicable - All
Description - Returns the entity object that is the parent to the attribute.
Example - Xrm.Page.data.entity.attributes.get(0).getParent()
Method - getPrecision
Applicable - money, decimal, double, integer
Description - Returns the number of digits allowed to the right of the decimal point.
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getPrecision();
Method - getRequiredLevel
Applicable - All
Description - Returns a string value indicating whether a value for the attribute is required or recommended.
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getRequiredLevel();
Method - getSelectedOption
Applicable - optionset
Description - Returns the option selected in an optionset attribute.
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getSelectedOption();
Method - getSubmitMode
Applicable - All
Description - Returns a string indicating when data from the attribute will be submitted when the record is saved.
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getSubmitMode();
Method - getText
Applicable - optionset
Description - Returns the text for the currently selected option for an optionset attribute.
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getText();
Method - getUserPrivilege
Applicable - All
Description - Returns an array of privileges that contain Boolean values indicating if the user can create, read or update data values for an attribute.
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getUserPrivilege();
Method - getValue
Applicable - All
Description - Retrieves the data value for an attribute.
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).getValue();
Method - removeOnChange
Applicable - All
Description - Removes a function from the OnChange event hander.
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).removeOnChange(displayMessage);
         function displayMessage() {
                 alert("message");
          }
Method - setRequiredLevel
Applicable - All
Description - Sets whether data is required or recommended for the attribute before the record can be saved.
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).setRequiredLevel(“required“);
Method - setSubmitMode
Applicable - All
Description - Sets whether data from the attribute will be submitted when the record is saved.
Example – Xrm.Page.getAttribute(“[Attribute Schemaname]”).setSubmitMode(“always“);
Method - setValue
Applicable - All
Description - Sets the data value for an attribute.
Examples –   var today = new Date();
          var futureDate = new Date(today.setDate(today.getDate() + 5));
          Xrm.Page.getAttribute(“[Attribute Schemaname]”).setValue(futureDate);
 
          var textToAdd = "sample";
          Xrm.Page.getAttribute(“[Attribute Schemaname]”).setValue(textToAdd);
 
          var olookup = new Object();
          olookup.id = “[Guid]”
          olookup.entityType = “[entityName]”;
          olookup.name = “[Name]”;
          var olookupValue = new Array();
          olookupValue[0] = olookup;
          lookupAttribute.setValue(olookupValue);




Format Phone number

//Handles 7, 10 and 11 digit phone numbers
function formatPhoneNumber(val) {
    try {
        if (val == null) return "";

        var fmtPhone = (val).replace(/^\s*|\s*$/g, '');
        fmtPhone = fmtPhone.split(' ').join('');

        if (fmtPhone.length == 10)
        {
            fmtPhone = fmtPhone.replace(/\D/g, '').replace(/^(\d{3})(\d{3})/, '$1-$2-');
        }
        else if (fmtPhone.length == 7)
        {
            fmtPhone = fmtPhone.replace(/\D/g, '').replace(/^(\d{3})(\d{4})/, '$1-$2');
        }
        else if (fmtPhone.length == 11)
        {
            fmtPhone = fmtPhone.replace(/\D/g, '').replace(/^(\d{1})(\d{3})(\d{3})/, '$1-$2-$3-');
        }

        return fmtPhone;
    }
    catch (e)
    {
    alert("Error formatting phone number \"" + val + "\": " + e.message);
    }
}


Problem When I try opent Download Import Template Excel for Import Data In MS CRM 2011


Problem When I try opent Download Import Template Excel for Import Data In MS CRM 2011
to resolve this Proplem i Remove The special Charcters From field names
like " * ? . / \

Tuesday, September 13, 2011

CRM 2011 data caching

 

For many CRM 2011 applications, caching of commonly retrieved data is important for maintaining a high performance system. Typically, you want to cache any data that is retrieved frequently but does not change often. In a CRM system this is usually either configuration data or CRM entity metadata.
In CRM 4.0, the way you typically extended a CRM application was by creating another ASP.NET web-app that connected to CRM through the CRM web-services, and it was fairly simple to cache common data on the server using the asp.net HttpRuntime cache.  For CRM 2011, the landscape has changed a bit, mostly due to the introduction of web-resources and the more frequent use of CRM Online as a hosting option.  Now, the recommended best-practice is to not extend CRM using a separate ASP.NET application (if possible), but to create all of your custom UI elements using Silverlight or JavaScript web-resources, and handle all of your server-side business logic in CRM plug-ins.  Here's a couple of things to keep in mind when using this new model: 

You can get free client-side caching if your data is stored as a web-resource.
XML web-resources are an ideal way to store configuration info on the CRM server.  When the xml file is retrieved by your client-side Silverlight or JavaScript UI components, the browser will automatically cache the retrieved file for you.  This works great for most configuration info, but not for any sensitive data.  All web-resources can be viewed by any user with access to CRM, and there’s no way to lock down specific resources by role.  So anything sensitive such as connection strings or passwords will still need to be stored in a custom entity (which can be locked down by role).  Also, CRM 2011 is designed to effectively clear any browser-cached web-resources whenever they are modified and re-published.  Which leads to..

Always reference web-resources using relative URLs or the $webresource syntax.
If you reference a CRM web-resource using its full URL (for example:  http://CRMServer/Org/WebResources/new_/MyWebResource.htm) you're browser won't actually cache the file. When CRM serves the file the cache-control header on the response will be set to expire immediately, and so All requests using the full URL will always retrieve the file from the server. To get browser-caching you need to reference the file using a special relative URL, which looks like this:
http://CrmServer/Org/%7B634380644480000000%7D/WebResources/new_/UI/ClientBin/MyWebResource.htm
Notice the magic number inserted into the URL?  When CRM serves files from URLs in this format the cache-control header on the response will be set to expire in one year, so the browser will cache the file properly.  CRM will also automatically change the unique number whenever web-resources are modified and published, causing the browser to retrieve the new version of the file.
If you add a web-resource to a CRM form using the “Add Web Resource” button, then CRM will automatically use the special URL for you. But If you are referencing a web-resource in a ribbon or in the sitemap XML then you need to make sure you always use the $webresource:MyWebResourceName syntax.  This ensures that caching is enabled on the web-resource file.  And if you are referencing web-resources from other web-resources (e.g., retrieving a config xml file from a Silverlight app), you should always use relative paths so that the URL contains the unique number.   

Server-side caching is not available for sandboxed plug-ins.

CRM Online only lets you run plug-ins in the “sandboxed” isolation mode.  This pretty much restricts your ability to use any kind of server-side caching.  Using the ASP.Net http-runtime cache is not allowed, and you cannot even cache data in static variables because the sandboxing system effectively hosts the plug-in in a new process each time the plug-in is fired.  You can, however, achieve a very limited sort of caching using plug-in shared variables. This data can only be shared across different plug-ins in the same execution pipeline, but it can be useful in some situations.  For example: if you had multiple plug-ins on the same message that each require retrieving the same metadata, you can temporarily cache the metadata in the shared variables collection.  

Clearing server-side caches on load-balanced systems.

 For an on-premise CRM deployment you don’t need to run plug-ins in sandbox mode, so you can take advantage of server-side caching.  However, for systems that are load-balanced and have multiple platform and application web-servers, it can be tricky to make sure that the cached data on each system is properly synchronized.  To outline the problem, suppose you have a CRM system that stores data in a custom entity, and several CRM plug-ins that use this data. To reduce the number of database retrieves, the plug-ins cache the data using the ASP.NET cache. Also, you have three load-balanced application servers. Each server has its own in-memory cache, so when the configuration information changes, you need to clear the cache on all three servers.
One way to handle this is to piggy-back off of the internal messaging system that CRM uses whenever the configuration string for a plug-in is updated. Whenever you register a CRM plug-in you are given the option to define a config string that is then passed to the constructor of the plugin when it is instantiated.  If the configuration string is updated (from any server), the new string will be passed to the constructor of the plug-in on all servers.  So if we want to clear the cache on all servers at once, we can just change the config string to a new unique value:
QueryExpression findPluginStep = new QueryExpression(SdkMessageProcessingStep.EntityLogicalName);
findPluginStep.Criteria.AddCondition("name", ConditionOperator.Equal, "MyPluginStepName");

foreach
(SdkMessageProcessingStep step in service.RetrieveMultiple(findPluginStep).Entities)
{

    //give the plugin step a new unique config string (the current datetime)

    step.Configuration = DateTime.Now.ToString();

    service.Update(step);

}
Then, in the plugin’s constructor, if the configuration string changes, you know it’s time to clear your cache:
private static string _oldConfig = null;
            
//constructor
public MyPlugin(string config)
{
if (_oldConfig != config)
       {
             HttpRuntime.Cache.Remove(CACHE_KEY);
_oldConfig = config;
}
}
This is an easy way to synchronize cached data across multiple servers, as CRM does the messaging for you without any extra overhead.

Monday, September 12, 2011

CRM 2011 Useful JavaScript

Get the value from a CRM field

 
1var varMyValue = Xrm.Page.getAttribute(“CRMFieldSchemaName”).getValue() ;

Set the value of a CRM field

 
1Xrm.Page.getAttribute(“po_CRMFieldSchemaName”).setValue(‘My New Value’);

Hide/Show a tab

 
1Xrm.Page.ui.tabs.get(5).setVisible(false);
2Xrm.Page.ui.tabs.get(5).setVisible(true);

Hide/Show a section

 
1Xrm.Page.ui.tabs.get(5).sections.get(0).setVisible(false);
2Xrm.Page.ui.tabs.get(5).sections.get(0).setVisible(true);

Call the onchange event of a field

 
1Xrm.Page.getAttribute(“CRMFieldSchemaName”).fireOnChange();

Get the selected value of picklist

 
1Xrm.Page.getAttribute(“CRMFieldSchemaName”).getSelectedOption().text;

Set the requirement level

 
1Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“none”);
2Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“required”);
3Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“recommended”);

Set the focus to a field

 
1Xrm.Page.getControl(“CRMFieldSchemaName”).setFocus(true);

Stop an on save event

 
1event.returnValue = false;

Return array of strings of users security role GUIDs:

 
1Xrm.Page.context.getUserRoles()

Get record GUID

 
1var recordId = Xrm.Page.data.entity.getId()l
2var recordIdWithoutCurlyBraces = Xrm.Page.data.entity.getId().substring(1,37);

Get event source

 
1var eventSource = executionContext.getEventSource(); // tick Pass execution context as first parameter

Get event source (fieldname)

 
1var fieldName = executionContext.getEventSource().getName(); // tick Pass execution context as first parameter

Get event source (value)

 
1var fieldValue= executionContext.getEventSource().getValue(); // tick Pass execution context as first parameter

Set Lookup Value

 
1Xrm.Page.getAttribute('new_fieldid').setValue([{ id: 'guid', name: fullName, entityType: 'entityTypeName'}]);

Disable/Enable field

 
1Xrm.Page.getControl(fieldName).setDisabled(true);
2Xrm.Page.getControl(fieldName).setDisabled(false);

field

 
1Xrm.Page.ui.controls.get(fieldName).setVisible(false);
2Xrm.Page.ui.controls.get(fieldName).setVisible(true);

Get CRM Form Type

 
01var FORM_TYPE_CREATE = 1;
02var FORM_TYPE_UPDATE = 2;
03var FORM_TYPE_READ_ONLY = 3;
04var FORM_TYPE_DISABLED = 4;
05var FORM_TYPE_QUICK_CREATE = 5;
06var FORM_TYPE_BULK_EDIT = 6;
07  
08var formType = Xrm.Page.ui.getFormType();
09if (formType == FORM_TYPE_CREATE) {
10}
11else {
12}

Manage Dynamics CRM 2011 with PowerShell

With the beta of Dynamics CRM 2011, Microsoft offers the ability to script deployment management tasks with PowerShell.
The server role ‘Deployment Tools’ contains a set of PowerShell cmdlets to script Deployment Manager tasks.
After you have installed the Deployment Tools role you are able to add the Dynamics CRM PowerShell-Snap-In to your PowerShell session.
To use the cmdlets you have to enter following command into a PowerShell console, which adds the PowerShell-Snap-In to your active session.
Add-PSSnapin Microsoft.Crm.PowerShell
After this the CRM Snap-In will be listed when you enter this command
Get-PSSnapIn
Make sure that the result contains
Name : Microsoft.Crm.PowerShell
PSVersion : 2.0
Description : A Windows PowerShell snap-in containing cmdlets that manage components of Microsoft Dynamics CRM.
Now, you can view the cmdlets which are defined in the Snap-In with following command
Get-Command -Module Microsoft.Crm.PowerShell
At the moment of writing this post, following cmdlets are available
Disable-CrmOrganization
Disable-CrmServer
Edit-CrmOrganization
Enable-CrmOrganization
Enable-CrmServer
Get-CrmCertificate
Get-CrmDefaultOrganization
Get-CrmDeploymentAdministrator
Get-CrmEtmSettings
Get-CrmOrganization
Get-CrmServer
Get-CrmSetting
Get-CrmThrottleSettings
Import-CrmOrganization
New-CrmDeploymentAdministrator
New-CrmOrganization
Remove-CrmCertificate
Remove-CrmDeploymentAdministrator
Remove-CrmOrganization
Remove-CrmServer
Set-CrmCertificate
Set-CrmEtmSettings
Set-CrmSetting
Set-CrmThrottleSettings
Update-CrmOrganization
This is a great enhancement for managing a crm deployment. You can speed up your administrative tasks, if you add this Snap-In to your profile. See http://technet.microsoft.com/en-us/library/dd315342.aspx

Microsoft Dynamics CRM 2011 Installation

 

Firstly, start with a clean Windows Server 2008 R2 build or remove the existing Microsoft Dynamics CRM installation.

I had to perform the following additional tasks to get past several environment verification checks:
  • Repair the Microsoft .NET Framework 4 (Net.TCP Port Sharing Service errors)
  • Delete existing Microsoft Dynamics CRM Databases
  • Use Network Service security account for Microsoft Dynamics CRM services (optional)
  • Don't specify Email Router settings

 
 
 
 
 
 
 
 
 

Disable All Fields in a Section Based on the Value of Another Field (CRM 2011)

//THIS FUNCTION DISABLES ALL THE FIELDS IN THE SECTION LABELED "FINANCIAL INFO"
//IF A BOOLEAN OPTION FIELD IN ANOTHER SECTION CALLED new_toggleSectionFlds = TRUE

function DisableSectionAttributes() {
    function setFldDisabled(ctrl) {
        ctrl.setDisabled(true);
    }
    function setFldEnabled(ctrl) {
        ctrl.setDisabled(false);
    }
    var toggleSectionFlds = Xrm.Page.getAttribute('new_toggleSectionFlds').getValue();
    var ctrlName = Xrm.Page.ui.controls.get();
    for (var i in ctrlName) {
        var ctrl = ctrlName[i];
        var ctrlSection = ctrl.getParent().getLabel();
        if (toggleSectionFlds == true) {
            if (ctrlSection == "Product Info") {
                setFldDisabled(ctrl);
            }
        }
        else {
            if (ctrlSection == "Product Info") {
                setFldEnabled(ctrl);
            }
        }
    }
}