Tuesday, 10 December 2013

Restrict Auto Save in MSCRM 2013

function stopAutoSave(context) {
    var saveEvent = context.getEventArgs();
    if (saveEvent.getSaveMode() == 70) { //Form AutoSave Event
        saveEvent.preventDefault(); //Stops the Save Event

Sunday, 8 December 2013

Creste Email using CRM 2011 Plug In

private void SendEmail(IOrganizationService service, Guid recieverUserId, Guid senderUserId, Guid regardingObjectId, string emailBody, string emailSubject)
Entity email = new Entity();
email.LogicalName = “email”;
//Set regarding object property (i.e. The entity record, which u want this email associated with)
EntityReference regardingObject = new EntityReference(“{entity_name}”, regardingObjectId);
//Defining Activity Parties (starts)
EntityReference from = new EntityReference(“systemuser”, senderUserId);
EntityReference to = new EntityReference(“systemuser”,recieverUserId);
//Derive from party
Entity fromParty = new Entity(“activityparty”);
//Derive to party
Entity toParty = new Entity(“activityparty”);
toParty.Attributes.Add(“partyid”, to);
EntityCollection collFromParty = new EntityCollection();
collFromParty.EntityName = “systemuser”;
EntityCollection collToParty = new EntityCollection();
collToParty.EntityName = “systemuser”;
email.Attributes.Add(“to”, collToParty);
//Defining Activity Parties (ends)
//Set subject & body properties
email.Attributes.Add(“description”, emailBody);
//Create email activity
Guid emailID = service.Create(email);
//Sending email
SendEmailRequest reqSendEmail = new SendEmailRequest();
reqSendEmail.EmailId = emailID;//ID of created mail
reqSendEmail.TrackingToken = “”;
reqSendEmail.IssueSend = true;
SendEmailResponse res = (SendEmailResponse)service.Execute(reqSendEmail);

Wednesday, 4 December 2013

how to refresh parent ms crm 2011 form on child aspx custom page close?


I have button custom button in contract entity ribbon area. (MS CRM 2011).

In that button click I am opening an .aspx page through “window.showModalDialog”.

In the .aspx I want to access the contract entity record some attributes to set values for it.

But I am unable to access the CRM from.

I have tried like

window.top.opener.document.getElementById("'iaah_cohortyesclicked'").value = "value";

It is not working.


In the contract entity javascript where I am opening the window.showModalDialog

Now I am passing the CRM form windows object as parameter to showModalDialog.

//In javascript

window.showModalDialog(strSourceURL,window, "dialogHeight:200px;dialogWidth:550px;center:yes; resizable:0;maximize:0;minimize:0;status:no;scroll:no");

Before I was opening the dialog as

window.showModalDialog(strSourceURL,null, "dialogHeight:200px;dialogWidth:550px;center:yes; resizable:0;maximize:0;minimize:0;status:no;scroll:no");

Instead of null I am passing window.

Now I can able to access the CRM form attributes in my .aspx page.


var parentWindow = window.dialogArguments;



Sunday, 1 December 2013

CRM 2013 Custom Actions


CRM 2013 adds a new handy feature called Custom Actions. Custom Actions provide the ability for non-developer administrators to write reusable modules of logic that developers can trigger through client-side or server-side code. Custom Actions are built using a similar UI as workflows with the same capabilities. The actions are run synchronously and can take in parameters as well as return values. Custom Actions can be pretty powerful and are a great way to share logic between both JavaScript and plugins. Below is a great example we came up with to show how we can replace a 2011 style configuration entity with 2013 Custom Actions.

In CRM 2011, if you need to reference values in code that would change between deployments, the best practice is to create a new entity (typically called Configuration) and add necessary attributes for configurable values such as a “Server URL” of an integration web service. The sole purpose of this entity is to hold one record that would contain the correct values that your custom code can reference, usually for integration purposes. The downside to this approach is that it adds overhead by needing to create a whole entity that will only ever have one record and you need to manually import that record into your target environment. Below is a step-by-step guide on how we can avoid a configuration entity in CRM 2013 using Custom Actions.

In CRM 2013, go to Settings and then Processes. Create a new Process and set the Category to “Action” and the Entity to “None (global)”.

Once the process is created, click the plus icon to add a new argument and set the name to the configuration value such as “ServerUrl”. Set the Type appropriately based on your value and set the Direction to Output. Do this for each configuration value needed.

Scroll down to the designer and click “Add Step” and then “Assign Value”.

Click Properties and in the new dialog window, type in the value for your configuration attribute.

Now save and activate your new custom action.

The custom action is now live so we can use the CrmSvcUtil to generate an SDK message for the action so that we can easily use it with server-side code. You can use the CrmSvcUtil the same way in 2013 as you did in 2011 but you will need to add the “/a” flag to generate an SDK message for your custom actions.

Note: You will need the latest CrmSvcUtil which is provided here in the 2013 SDK.

CrmSvcUtil /url:http://server/org/XRMServices/2011/Organization.svc /out:Demo.cs
/serviceContextName:DemoContext /namespace:Demo.Model /a

Now we can reference the new_GetConfigurationValuesRequest and execute it to get the ServerUrl value from CRM. Even though we specified the custom action as global, we are still required to pass in an EntityReference otherwise CRM will throw an error. Our workaround for this is to pass in the ID of the current user.

var request =
new new_GetConfigurationValuesRequest()
Target = new EntityReference("systemuser", GetCurrentUserId()),

var response = (new_GetConfigurationValuesResponse)_service.Execute(request);
var url = response.ServerUrl;

So there you have it! Executing this request returns “http://server” that I had set in the custom action and now we can use it to replace a configuration entity. As you can see, custom actions can be pretty powerful. One improvement we’re hoping for in the future is to allow custom actions to execute custom code, similar to a workflow assembly. This would allow developers to easily kick off server-side code from JavaScript.


Thursday, 28 November 2013

How to get get and Set the Party list in Javascript:

To retrieve values by jscript: 

var partylistItem = new Array;
//get the items/values in a field named"resources"

partylistItem  = Xrm.Page.getAttribute("resources").getValue();

To set values by  jscript :
To set  values we also  need to  get an  array.
 var partlistset= new Array();
partlistset[0] = new Object();
partlistset[0].id = id; // provide a guid type value
partlistset[0].name = name; // provide a suitable name
partlistset[0].entityType = entityType; // provide the entity  name  of the item  ie account/ contact etc .

How to get the Contact Guids from a PartyList in a Plugin?

EntityCollection Recipients;
Entity entity = (Entity) context.InputParameters["Target"];

IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
Content = entity.GetAttributeValue<String>("subject");
Recipients = entity.GetAttributeValue<EntityCollection>("to");
for (int i = 0; i < Recipients.Entities.Count; i++)
            ActivityParty ap = Recipients[i].ToEntity<ActivityParty>();
            string contactid = ap.PartyId.Id.ToString(); 
            Contact c = (Contact) service.Retrieve(Contact.EntityLogicalName,ap.PartyId.Id,new ColumnSet(new string[]{"mobilephone"}));
            string mobilephone = c.MobilePhone;
              //Do something with the mobile phone nr


Friday, 11 October 2013


Looking ahead to 2014 with the next release due in Q1 (codenamed Mira), Microsoft have indicated their CRM roadmap includes:
• Marketing Pilot Integration – to connect mid-market and enterprise level marketing automation with CRM including multi-channel campains
• Netbreeze Integration – connecting social listening and monitoring with CRM to analysis social sentiment among customers
• Enhancements to Microsoft Lync & Skype integration
• Case management and service level agreement enhancements
• Extended mobile device support

MSCRM 2013 Heighlights

  • Redesigned User Experience: Cleaner, faster, more intuitive interfaces with no pop ups or flipping from one application to the next.
  • Process Agility: Agile process guidance so you can respond to rapidly changing business needs.
  • CRM on the Go: New Windows 8 and iPad mobile applications that make your sales team smarter no matter where they are by delivering a seamless experience across the web and devices.
  • Social in Context: Work across boundaries to create the right customer experiences with the enterprise power of Yammer.
  • Base and Extension Tables - If you have been working with CRM in the past you are probably aware of the table splitting for each entity within CRM. With CRM 2013, the extension tables will be merged during the upgrade.
  • Server-side Synchronization - This new feature within CRM 2013 will allow administrators to easily manage the sync of email, appointments, tasks and contacts between versions of CRM and Exchange.
  • Access Teams - With the new feature of record-based Access Teams, you can add a user to the record and give them access.

MSCRM 2013 Image Data Types SDk

  • You can access images via a URL. The URL of the image is a read only value available via the SDK off of the Image as an absolute address. Image URLs behave in a similar fashion to Web Resources and Attachments. The primary difference is that images are returned as binary data and Web Resources and Attachments are returned as base-64 encoded MIME types.
  • ImageAttributeMetadata is being added to the MetadataService class. This class inherits from AttributeMetadata and represents the metadata for an attribute of type Image

  • Images can be returned as part of FetchXML queries or RetrieveMultiple calls. There will be an option to return binary data, URL, or both.
  • Binary data must be requested explicitly. A query that specifies “All” fields would only return the image URL. This accounts for the scenario where a user inadvertently queries all fields on an entity with a large number of images.
  • Microsoft Dynamics CRM for Outlook does not have direct support for images in CRM 2013 so images will not be synced. Image fields would be ignored in query results and offline view filters.

MSCRM 2013 Image Data type Storage

  • On upload via the web application or SDK, images are validated, resized, and stored as a common binary data format in the CRM database.
  • Regardless of upload format, all images are all formatted to JPG on create or update. On average, this puts most images at about 5k at max.
  •  The uploaded image is always resized to the minimum size necessary to support CRM 2013 and a smaller sized copy with the same aspect ratio as the original gets stored to the database.
  • The bounding box in CRM 2013 is hardcoded for all image fields: 144pixels x 144pixels. This value will be stored in attribute metadata as Height and Width

MSCRM 2013 Image Data Type Data Modeling

  • The display name can be set for images but SchemaName is always “entityImage” for any image-enabled entities and cannot be changed. 
  • The image data type is not searchable. 
  • A PrimaryImageAttribute metadata has been added to the entity. 
  • Only a single image attribute can be defined per OOB/custom entities. This helps keep storage in check especially for CRM online customers. 
  • PrimaryImageAttribute is set by default to the single “entityimage” attribute when it gets added to a custom entity. This is used to determine what image should be displayed in the header of the form. Note, that the grid does not display these images since that would require a smaller icon. 
  •  If there are no image attributes on the specific entity OR the system customizer has selected not to display any image for the entity, the PrimaryImageAttribute value would be set to [None]. 

MSCRM 2013 Image Data Type

In CRM 2011, images are stored in notes as MIME encoded text. As a result, images get converted to a displayable format for every read and no pre-cached thumbnails exist. In CRM 2013, images are being introduced as a first class data type. You can now add images as a field, capture/store images and improve query operations on images.
You can capture and maintain images for User Profile, Contacts and Leads, and Account logos.

Data Modelling
·         Image data type as a field type to the application customization experience.
·         Support for only one Image field per entity.
·         Image stored as binary data in the CRM database.
·         Resize images server-side to conserve storage space and improve performance.
    § Original image uploaded not saved.
·         CRUD Operations
   § Support standard CRUD operations of Images the same as any other CRM data type.

   § Reference images via URL- ability to include URL and binary data in a RetrieveMultiple or   FetchXML call. 

MSCRM 2011 Customizable Tooltips

In CRM 2011, tool tips are minimal and typically repeat the display name attribute of the field. These type of tool tips are useful for unlabeled UI, however most form fields have labels assigned to them and users need more information when entering or selecting data. Explanatory tooltips provide helpful text to address known user questions, explain terminology or concepts, and help end-users make good decisions to stay on task.

In CRM 2013, custom tooltips aim to improve the user experience by:

  •  Providing information on how to use and complete forms, right on the page.
  • Allowing organizations to display their business-specific information and processes to their users right in the CRM forms.

The system customizers can update tool tips when they are customizing an entity or entity attribute. The following points are to be noted:

Attribute Tool Tips
You can display entity attribute “Description” as tool tips on fields, buttons, etc. on existing forms for customizable entities. This will work against OOB and custom attributes.

Form Tool Tips
You can define tool tips to be displayed and the browser determines how the tool tip is displayed and for how long it would get displayed.

Rewritten Descriptions for Use as Tooltips – Refresh Forms
Specifically for Refresh Forms: All descriptions that can be displayed on the forms have now been rewritten for use as customizable tooltips.

Standard Customization Path
You can customize these tool tips simply by editing Description via the Settings > Customization UI> Form editor or field editor.

MSCRM 2013 New Phone Number Format

In the December 2012 Service Update, Phone Format was added for a number of telephone number fields on OOB entities. Most phone number fields in the OOB entities were also migrated as part of the release, but some fields, such as Fax number, did not get the Phone format.

In CRM 2013, this format with the label Phone Number is being added to the list of available formats in the attribute editor.
Fields with this format type enable a click-to-call experience for your telephony provider such as Lync or Skype.

Thursday, 10 October 2013

Parsing Whole Number value while Setting in MSCRM 2011

Int i;
if (Int32.TryParse(TextBox_Employees.Text, out i))
 mylead["numberofemployees"] = i;

Get selected Option Set value label in mscrm 2011 C#

                      RetrieveAttributeRequest request = new RetrieveAttributeRequest();
                       request.EntityLogicalName = targetEntity.LogicalName;
                       request.LogicalName = optionsetLogicalName;
                       request.RetrieveAsIfPublished = true;          

                      RetrieveAttributeResponse response = (RetrieveAttributeResponse)service.Execute(request);
                       PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)response.AttributeMetadata;

                       var query = from option in picklist.OptionSet.Options
                                   where option.Value == int.Parse(Statusvalue.ToString())
                                   select option.Label.UserLocalizedLabel.Label;
                        SselectedOptionSetlLabel = query.FirstOrDefault().ToString();

Monday, 7 October 2013

Limitations for Business Rules in MSCRM 2013

Limitations for Business Rules
·         Business rules in this release are intended to address common actions. Compared to what a developer can do using form scripts, business rules have limitations. However, business rules are not intended to replace form scripts.
·         The primary limitation you may find compared to form scripts is that all conditions in the Business rules are evaluated using AND. All the conditions must be true before the actions will be applied. There is no support for OR or Else operators to provide for more complex logic. To apply OR in your conditions you need to create separate rules for each condition you want to test. This can be done efficiently by using the Save As option and creating separate rules for each condition you want to test.
·         Business rules run only when the form loads and when field values change. They do not run when a record is saved.
·         Business rules work only with fields. Form scripts can interact with other visible elements such as tabs and sections within the form
·         When you set a field value using a business rule, any OnChange event handlers for that field will not run. This is to reduce the potential for a circular reference which could lead to an infinite loop.
·         If a Business Rule references a field that is not present on a form, the rule will simply not run. There will be no error message.
·         Calling other javascript web resources in the system via the business rule editor is not possible.

·         There is no ability to connect to external data sources.

Business Rules in MSCRM 2013 (Notes)

Miscellaneous Topics
·         Business rules cannot be run across different entities. They have to be defined within the same entity.
·         By default, the business rules are always created in a deactivated/draft state and must be activated to start executing for the form.
·         If there are multiple business rules for a control, the rules will run in the order they were added to the system. The last modified business rule runs last.
·         If you try to delete an attribute that has an active associated business rules, an error is triggered:
            "Process Error"
·         Business Rules can run on the web client (all browsers), Outlook (online and offline), iPad and CRM for tablets. However, they can only be customized through the Web Client or Outlook (Online/connected mode).
·         A new privilege for “Activate Business rules” under the customization tab for security roles has been added. Without activating the business rule first, it will not be executed.
·         Business Rules are imported/exported with the entities that they are attached to. It is not possible to export or import just a collection of business rules.
·         If there are multiple solutions, business rules will be run in the order in which the solutions were imported and the latest installed solution’s rules will run last.
·         If you package a managed/unmanaged solution, the states of the Business rules will be transported as is into the target system:
1.       activated rules will be activated
2.       deactivated rules will be deactivated

·         There are no limits on number of actions that can be attached to the business rule. 

Bussiness Rule Configuration Actions in MSCRM 2013

Validate data and show error message rules

Data in fields (as values) can be validated and comparison can be made between different fields.
 If the action states throwing an error message, you can define the control that should display the message.

Show or Hide a field rules

 You can change whether the field is displayed in the form. The options are Show Field and Hide Field.
 These are applicable to only fields and not for tabs, sections or controls like web resources and iframes.
If you do not specify any conditions, this is similar to setting state by default.

Enable or disable field rules

The options are Lock and Unlock. When the field is locked, you will not be able to edit the value in the field.
 If you do not specify any conditions, this is similar to locking/unlocking the field by default.

Set field value rules

Choose the Field and Type. There are three types:


Use this type to set the value of one form field with the value of another field.

Use this type to set the value of a form field with a value you enter.

This option only appears for numerical or date data types. It does not appear for fields that contain text. Use this type to set the value to the result of a simple calculation that may use either a value in another form field or a value you enter.
 If you do not specify any condition, this is similar to setting a default value for the field.

Set field requirement rules

 The options are Not Business Required and Business Required. There is no option to set this to business recommended.
If you do not specify any condition, this is similar to setting the default business requirement state.

Friday, 4 October 2013

Quick Forms in MSCRM 2013

Quick Forms:

A quick form is a special type of CRM form that gives you the ability to display data from related entities onto the main form of any entity.

Quick forms will also be known as “Quick View Forms” since this form can be placed inside other main forms. They are rendered as read only so that quick form’s fields are not editable when placed on another form


·         These forms can be exported/imported as part of solutions.
·         These forms can be created/updated or deleted through the SDK.
·         Quick forms can be created/modified using the main form editor.
·         Only sections, spacers, fields and subgrids can be added.
·         A single column tab is used for quick forms and this cannot be changed.
·         No iframe or webresources are allowed.
·         Notes controls are not allowed.
·         There is no header or footer in quick forms.

Thursday, 26 September 2013

Set Default View in Party Lookup (Regarding)Type in MS CRM 2011

Set Default View in Party Lookup (Regarding)Type in MS CRM 2011

Use the following code to set the Regarding Lookup to Incident instead of Account and set the default view.
document.getElementById(“regardingobjectid”).setAttribute(“defaulttype”, “112″);
Xrm.Page.getControl(“regardingobjectid”).setDefaultView(“Guid of the View to be displayed”);

Monday, 23 September 2013

How to create an email activity using REST Endpoints in CRM2011

How tough it can be to create an activity using code? It sounds very easy but there are few issues, if you are using REST Endpoints.

REST Endpoints do not support all the CRM data types. One of those data type is PartyList. PartyList is very important to create most of the activity like emails, appointments, phone calls etc.

To set the value of the PartyList field you need an array of PartyLists as you can have more than value for those fields. For e.g you can have more than one recipient for an email or you can have more than resource for an appointment.

As I mentioned earlier, REST Endpoints do not support PartyList, So its is impossible to assign value to these fields. If you look at DataSet returned by the Rest Endpoints, It looks like they are treating PartyList fields like string fields.


These values does not even return the guid or name of the PartyList entity. if you look at sender field in the screen shot above, it does not have guid or the name of the system user who sent this email.
I tried the same using following code:

var partlistcollection = new Array(); //tried to create an array of PartyLists

partlistcollection[0] = {Id: "8384E684-7686-E011-8AF0-00155D32042E",LogicalName: "contact",Name: "Amreek Singh"};

But it did not work, if you pass a string value to the PartyList fields, You won’t get any error message but you won’t see any value in those fields on a created entity.

Now here is the solution. You need to create an activity (in this case it’s  an email) first and then create a PartyList entity and link it back to the created activity.

function CreateEmail() {
alert("CreateEmail Begin");

var email = new Object();
email.Subject = "Sample Email Using REST";
SDK.JScriptRESTDataOperations.Create(email, "Email", EmailCallBack, function (error) { alert(error.message); });

// Email Call Back function
function EmailCallBack(result)
var activityParty=new Object();
// Set the "party" of the ActivityParty // EntityReference of an entity this activityparty relatated to. 
activityParty.PartyId = {
  Id: "8384E684-7686-E011-8AF0-00155D32042E",//replace this with the contactid from your system.
  LogicalName: "contact"
// Set the "activity" of the ActivityParty
// EntityReference.
activityParty.ActivityId = {
  Id: result.ActivityId, 
  LogicalName: "email"
// Set the participation type (what role the party has on the activity).
activityParty.ParticipationTypeMask = { Value: 2 }; // 2 mean ToRecipients
SDK.JScriptRESTDataOperations.Create(activityParty, "ActivityParty",ActivityPartyCallBack , function (error) { alert(error.message); });

function ActivityPartyCallBack(reuslt)
alert("Process Completed");
activityParty.ParticipationTypeMask = { Value: 2 }; is very important as it will specify if this PartList is sender/recipient/resource etc  of the activity.

Here is the link to complete list of activityParty.ParticipationTypeMask click here.
For this sample, I have used the generic REST CRUD data operations library created by Jim Daly.
Add references to following Java Script  web resources to try the solution.
  • SDK.JScriptRESTDataOperations
  • JSON2
Here is the link to unmanaged solution RESTEmailSolution_1_0
  • I hope this helps.

Call A Dialog from Ribbon in MSCRM 2011

  function getOrg() {
        /// get organisation
        var Org = "";
        if (typeof GetGlobalContext == "function") {
            var context = GetGlobalContext();
            Org = context.getOrgUniqueName();
        else {
            if (typeof Xrm.Page.context == "object") {
                Org = Xrm.Page.context.getOrgUniqueName();
            { throw new Error("Unable to access Organisation name"); }
        return Org;

    function getUser() {
        /// get logged in user
        var User = "";
        if (typeof GetGlobalContext == "function") {
            var context = GetGlobalContext();
            User = context.getUserId();
        else {
            if (typeof Xrm.Page.context == "object") {
                User = Xrm.Page.context.getUserId();
            { throw new Error("Unable to access the UserId"); }
        return User;

    function callDialog() {
    var url="/" + getOrg() + "/cs/dialog/rundialog.aspx?DialogId=%7bB7D825D7-7EF6-4713-AC11-284546FEB260%7d&EntityName=systemuser&ObjectId=" + getUser();
    window.open(url, "", "status=no,scrollbars=no,toolbars=no,menubar=no,location=no");

The JavaScript Webresource has three function
  • getOrganisation() – to get context organisation
  • getUser()-to get the logged in user
  • callDialog()- will call the dialog. you can change the DialogId to call your own dialog.
This example is using a dialog attached to the user entity, so we don’t need to create any record to run the dialog. The code picks up the logged in user and run the process.