Showing posts with label Crm_java Script. Show all posts
Showing posts with label Crm_java Script. Show all posts

Tuesday 4 February 2014

New JavaScript methods in Microsoft Dynamics CRM 2013

 Microsoft Dynamics CRM 2013 is providing some exciting new methods we can use with the JavaScript SDK on the entity forms, such as :
  • Easier way to set the form dirty
  • Custom lookup filters
  • Displaying form notifications as well as field specific notifications. 
Context
  • Xrm.Page.context.client.getClient()
    • Returns “Outlook”, “Web”, or “Mobile”
  • Xrm.Page.context.client.getClientState()
    • Returns “Online” or “Offline”
    • Xrm.Page.context.isOutlookOnline and isOutlookClient are now deprecated
Data
  • Xrm.Page.data.refresh()
    • Asynchronously refresh data on form without reloading the page
    • Can pass in a callback to execute on error or success
  • Xrm.Page.data.save()
    • Asynchronously save the form
    • Can pass in a callback to execute on error or success
  • Xrm.Page.data.getIsValid()
    • Returns a boolean telling whether the form can be saved or not
  • Xrm.Page.data.setFormDirty()
    • Sets the form as dirty
Entity
  • Xrm.Page.data.entity.getPrimaryAttributeValue()
    • Returns a string value of the primary attribute for the entity
UI
  • Xrm.Page.ui.setFormNotification()
    • Takes in a string value to set a form notification with the passed in string
    • Pass in “ERROR”, “INFORMATION” or “WARNING” to dictate the type of notification
  • crm 2013
  • Xrm.Page.ui.clearFormNotification()
    • Clears the form notification
All Controls
  • Xrm.Page.getControl(“new_name”).setNotification(“Field specific notification”)
    • Sets a notification specific to the field
  • crm 2013
  • Xrm.Page.getControl(“new_name”).clearNotification()
    • Clears the field specific notification
Number Fields
  • Xrm.Page.getAttribute(“new_precision”).setPrecision(2)
    • Override field’s precision
Date Fields
  • Xrm.Page.getControl(“createdon”).setShowTime(true)
    • Controls whether to show the time for a date field
Lookup Fields
  • Xrm.Page.getControl(“ownerid”).addCustomFilter(fetchFilter, entityType)
    • Applies a custom filter to the lookup view
    • entityType is optional and if it is not passed it will default to all entity views
  • Xrm.Page.getControl(“ownerid”).addPreSearch(handler)
    • triggers right before a lookup dialog pops open
  • Xrm.Page.getControl(“ownerid”).removePreSearch(handler)
    • removes event handler set from the addPreSearch method
Utility
  • Xrm.Utility.openWebResourceDialog(webResourceName, webResourceData, width, height)
    • opens a specified HTML web resource as a dialog

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
    }

Wednesday 4 December 2013

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

Issue:

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.parent.opener.Xrm.Page.data.entity.attributes.get('iaah_cohortyesclicked').setValue('yes');

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

It is not working.


Solution:

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.

Like

var parentWindow = window.dialogArguments;

parentWindow.Xrm.Page.data.entity.attributes.get('iaah_cohortyesclicked').setValue('yes');

 

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 .
Xrm.Page.getAttribute("resource").setValue(partlistset);

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.

image

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:

email.Sender="crm2011@emailops.com.au";
var partlistcollection = new Array(); //tried to create an array of PartyLists

partlistcollection[0] = {Id: "8384E684-7686-E011-8AF0-00155D32042E",LogicalName: "contact",Name: "Amreek Singh"};
email.ToRecipients=JSON.stringify(partlistcollection);

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() {
        ///<summary>
        /// get organisation
        ///</summary>
      
        var Org = "";
        if (typeof GetGlobalContext == "function") {
            var context = GetGlobalContext();
            Org = context.getOrgUniqueName();
        }
        else {
            if (typeof Xrm.Page.context == "object") {
                Org = Xrm.Page.context.getOrgUniqueName();
            }
            else
            { throw new Error("Unable to access Organisation name"); }
        }
       
        return Org;
    }

    function getUser() {
        ///<summary>
        /// get logged in user
        ///</summary>
      
        var User = "";
        if (typeof GetGlobalContext == "function") {
            var context = GetGlobalContext();
            User = context.getUserId();
        }
        else {
            if (typeof Xrm.Page.context == "object") {
                User = Xrm.Page.context.getUserId();
            }
            else
            { 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");
    //window.open(url);

    }
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.

Clone a record in MS CRM 2011 by Mohammad Yusuf Ansari

Sometime in CRM there is a need to copy the existing record.For example there may be a need to clone the existing case so that service representative can update some fields on the cloned case.

Q.How can we achieve it in MS CRM 2011
A. It can be achieved either by JavaScript or Plugin.

We will try to achieve with JavaScript using "Relationships" mappings feature in MS CRM 2011.

Q:What we need to do?
  
1)Add a ribbon button called "Clone Case"
2)Creating a 1:N relationship with Case to Case then generating mappings.
3)On button click Open the URL of the cloned Case.


Implementation:

1)Add a ribbon button called "Clone Case"

Add a ribbon button called "Clone Case".You can use ribbon workbech for this on click of this button it will call a Javascript function called "cloneCase" in "My_CustomRibbonJavascript" webresource.
Or you can do manually like.

1)Create a solution add "Case" entity to it.
2)Export the Solution.
3)Extract the Solution.
4)Open Customizations.xml in Visual studio.
5)Replace <RibbonDiffXmlwith the below given XML
6)Take care of adding the icons as given in below XML in CRM as webresources before import.

<RibbonDiffXml>
  <CustomActions>
 
    <CustomAction Id="My.MSCRM.incident.form.Clone.Button.CustomAction" Location="Mscrm.Form.incident.MainTab.Collaborate.Controls._children" Sequence="0">
      <CommandUIDefinition>
        <Button Command="MSCRM.incident.form.Clone.Command" Id="MSCRM.incident.form.Clone.Button" Image32by32="$webresource:My_Clone32" Image16by16="$webresource:My_Clone16" LabelText="$LocLabels:MSCRM.incident.form.Clone.Button.LabelText" Sequence="0" TemplateAlias="o1" ToolTipTitle="$LocLabels:MSCRM.incident.form.Clone.Button.ToolTipTitle" ToolTipDescription="$LocLabels:MSCRM.incident.form.Clone.Button.ToolTipDescription" />
      </CommandUIDefinition>
    </CustomAction>
 
  </CustomActions>
  <Templates>
    <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
  </Templates>
  <CommandDefinitions>
 
    <CommandDefinition Id="MSCRM.incident.form.Clone.Command">
      <EnableRules/>
      <DisplayRules>
        <DisplayRule Id="MSCRM.incident.form.Clone.DisplayRule" />
      </DisplayRules>
      <Actions>
        <JavaScriptFunction FunctionName="cloneCase" Library="$webresource:My_CustomRibbonJavascript" />
      </Actions>
    </CommandDefinition>
 
  </CommandDefinitions>
  <RuleDefinitions>
    <TabDisplayRules />
    <DisplayRules>
 
      <DisplayRule Id="MSCRM.incident.form.Clone.DisplayRule">
        <FormStateRule State="Create" InvertResult="true" />
      </DisplayRule>
 
    </DisplayRules>
    <EnableRules/>
 
  </RuleDefinitions>
  <LocLabels>
 
    <LocLabel Id="MSCRM.incident.form.Clone.Button.LabelText">
      <Titles>
        <Title description="Clone Case" languagecode="1033" />
      </Titles>
    </LocLabel>
    <LocLabel Id="MSCRM.incident.form.Clone.Button.ToolTipDescription">
      <Titles>
        <Title description="Clone Case" languagecode="1033" />
      </Titles>
    </LocLabel>
    <LocLabel Id="MSCRM.incident.form.Clone.Button.ToolTipTitle">
      <Titles>
        <Title description="Clone Case" languagecode="1033" />
      </Titles>
    </LocLabel>
 
  </LocLabels>
</RibbonDiffXml>

2)Creating a 1:N relationship with Case to Case then generating mappings.

Open the Case enity relationship(1:N) and Create a relationship with Case.Open the created relationship and generate mappings.

Refer below screenshots











3)On button click Open the URL of the cloned Case.

Add a new webresource called "My_CustomRibbonJavascript" add the  "cloneCase" function to it


function GetContext() {
    var _context = null;
    if (typeof GetGlobalContext != "undefined")
        _context = GetGlobalContext();
    else if (typeof Xrm != "undefined")
        _context = Xrm.Page.context;
    return _context
}
function cloneCase() {
 
    if (Xrm.Page.data.entity.getId() == null) {
        alert('First save the record before Clone Case')
 
    }
    else {
        var CRMContext = GetContext();
        var serverUrl = CRMContext.getServerUrl();
        var caseid = Xrm.Page.data.entity.getId();
        caseid = caseid.replace('{''').replace('}''');
 
        //Below URL is for CRM online  
        var url = serverUrl + 'main.aspx?etc=112&extraqs=%3f_CreateFromId%3d%257b' + caseid + '%257d%26_CreateFromType%3d112%26etc%3d112%26pagemode%3diframe&pagetype=entityrecord';
 
        openNewWindow(url, 900, 600, 'toolbar=no,menubar=no,resizable=yes');
    }
 
 
}


Note:How to create the URL

Since Case is in 1:N relationship It will appear in case left navigation pane.Click on Case button and add the new Case.Copy the created URL and make it dynamic.

For Onpresmise MS CRM 2011 URL will be like this

var url = serverUrl + '/cs/cases/edit.aspx?_CreateFromType=112&_CreateFromId=' +
 Xrm.Page.data.entity.getId();



 Hope it helps someone somewhere :)

Regards,

Yusuf

C# code to create a email record in MSCRM 2011


                    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("quote", targetEntity.Id);
                    email.Attributes.Add("regardingobjectid", regardingObject);

                    //Defining Activity Parties (starts)
                    //Derive ccparty

                  EntityReference cc1 = new EntityReference("systemuser", preparedById);
                    EntityReference cc2 = new EntityReference("systemuser", salesContactId);


                    Entity ccParty = new Entity("activityparty");
                    ccParty.Attributes.Add("partyid", cc1);
                    Entity ccParty1 = new Entity("activityparty");
                    ccParty1.Attributes.Add("partyid", cc2);

                    EntityCollection collccParty = new EntityCollection();
                    collccParty.EntityName = "systemuser";
                    collccParty.Entities.Add(ccParty);
                    collccParty.Entities.Add(ccParty1);
                    EntityCollection collToParty = new EntityCollection();
                    collToParty.EntityName = "contact";
                    collToParty.Entities.Add(toParty);
      //Derive to party
                    email.Attributes.Add("cc", collccParty);
                    Entity toParty = new Entity("activityparty");
                    EntityCollection contacts = GetContactsRelatedTOQuote(service, targetEntity.Id);
                    if (contacts.Entities.Count > 0)
                    {
                        foreach (Entity e in contacts.Entities)
                        {
                            toParty.Attributes.Add("partyid", new EntityReference("contact", e.Id));
                        }

                    }

                    email.Attributes.Add("to", collToParty);

                    //Defining Activity Parties (ends)

                    //Set subject & body properties
                    email.Attributes.Add("subject", "xxxxxx " + postMessageImage["name"].ToString());
                    email.Attributes.Add("description", "Test");

                    //Create email activity

                    Guid emailID = service.Create(email);

Creating email using Rest Javascript call In MSCRM 2011

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.

image

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:

email.Sender="crm2011@emailops.com.au";
var partlistcollection = new Array(); //tried to create an array of PartyLists

partlistcollection[0] = {Id: "8384E684-7686-E011-8AF0-00155D32042E",LogicalName: "contact",Name: "Amreek Singh"};
email.ToRecipients=JSON.stringify(partlistcollection);

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.