Monday, October 5, 2015

SLA vs KPI

Service Level Agreement (SLA) is an agreement between two parties regarding a particular service. Apparently SLA must contain quantitative measurements that:


  1. Represent a desired and mutually agreed state of a service
  2. Provide additional boundaries of a service scope (in addition to the agreement itself)
  3. Describe agreed and guaranteed minimal service performance


Key Performance Indicators (KPIs) are metrics that target service providers organization objectives – both tactical and strategic. Usually these metrics are used to measure:


  1. Efficiency and effectiveness of a service
  2. Service operation status.


If you have many customers for a service then SLAs may vary from customer to customer; however KPIs usually are common for a service.


  • SLA examples (for a particular customer): reaction time, resolution time, compliance to agreed deadlines
  • KPI examples (organization or service oriented): average reaction time for all customers, service desk employee load, incoming ticket volume trend, required capacity to fulfil SLA promises to customers

Thursday, September 3, 2015

Major Challenge in Data Migration

1. The Structure of the system you are migrating from be different than dynamics CRM.
2. Users of the old system may played games with the user of fields -Generally due to limitions in the system
3. Fields that must be separated may lead to "Column Drift"
4. Lack of unique identifiers can cause imports to fail

Data Migration Tools

Select a Tool to Use


When planning your data migration, you should select how the data will be transferred. In order to move data, there must be some way of connecting the two systems. Writing directly to the Microsoft Dynamics CRM database is not supported and highly discouraged.  Using one of the Microsoft Dynamics CRM data migration tools below will help ensure you are using a recommended process:


  1. Import Wizard
  2. Dynamics to CRM adapter
  3. Scribe
  4. SSIS


Import Wizard

The Import Wizard is the simplest way to get data into CRM, and it recommended for moving small batches of records (5,000 at a time). Data from the source needs to be put into a flat file (.xml, .csv, or .xls format). The import wizard then allows the user to select the columns of the flat file and map it to the specific entity and fields within CRM. It can be used to update existing or create new records. An option is available for Microsoft Dynamics CRM 2011 UR 13 and before to utilize duplicate detection while importing.

For more information on importing, see the data management chapter.

Dynamics to CRM Adapter

This is meant for connecting other Dynamics products with your Microsoft Dynamics CRM instance. The dynamics suite includes such products as:

Microsoft Dynamics AX (formerly Axapta)
https://mbs.microsoft.com/customersource/northamerica/AX/downloads/service-packs/mdax_dynamicsconnector

Microsoft Dynamics GP (formerly Great Plains)
https://mbs.microsoft.com/customersource/northamerica/GP/downloads/service-packs/mdgp_dynamicsconnector

Microsoft Dynamics NAV (formerly Navision)
https://mbs.microsoft.com/customersource/northamerica/NAV/downloads/service-packs/mdnav_dynamicsconnector

Microsoft Dynamics SL (formerly Solomon)
https://mbs.microsoft.com/customersource/northamerica/SL/downloads/service-packs/mdsl_dynamicsconnector

These products are available free of charge from Microsoft.  Each product has a standard template for integration points.  The image below lists the standard integration points that come out of the box for each ERP to CRM integration.  Additional integration points can be added and Connector does support custom entities in CRM.

CRM data migration tools - connector

Scribe
For more complex migrations and integrations that include scheduled jobs and data transformation Scribe should be considered. Scribe is a Microsoft supported tool that is a SAS tool with many different packages for different levels of service. This tool is great when trying to integrate with other databases that might not have an adapter built. The file format that is preferred if flat is .csv. Knowledge for Scribe would include knowledge of the tool and SQL scripting. The benefit of this tool is that it is easier to use because of a user friendly UI.

SSIS
When there is a tremendous amount of data to be moved, millions of records, an SSIS package might be necessary. This realm of an SSIS package would require a developer who has both C# and SQL knowledge. SSIS is able to do the same functionality as Scribe but it is a package being coded instead of the use of a UI. SSIS packages are more robust and transfers large amounts of data faster but could take more time to develop then building a Scribe job.

Choosing the right tool for your organization depends on your unique needs.  If you are just importing Accounts and Contacts or Leads, the Import Wizard is clearly the right choice.  However if you have more data to move, or numerous records linked together, then you may need to use Scribe.  If you have multiple integrations to complete, you might consider developing an expertise in Scribe or SSIS.  Also, look at your internal skillsets.  Most organizations use Scribe because it has less of a learning curve. If you already have a technical person who can do SSIS, then that is the way to go.

Business Unit ,Security Role,Privilege and Access Level

Business Unit :
A scoping mechanism that defines a grouping of users for security modeling purposes.
Business units are hierarchical in nature.
Business Units are framework upon which a security model is built.

Security Role :

A collection of privileges that reflect common roles of your organization or business units.

Privilege (Access Rights)
The definition of specific type of data access or action that can be granted as a right;
Privileges are granted through a security role and are cumulative
The following privileges that can be assigned :

1. Create 2.Read 3. Write 4.Delete 5.Append 6.Append To 7. Access 8.Share

Access Level :
The Access Level defines exactly to which records the privileges apply.

 1. None 2. User 3.Business Unit 4.Parent : Childs Business Unit 5 Organizations

Fetch Xml has Limitation

Fetch Xml has Limitation

1. Right Outer and full outer join not supported
2. Exists /in with Sub Query
3. No Union Selects
4. FetchXml reports cannot use Non- CRM online data sources
5. Max Records -50 k
6. Very different from SQL

Integration

Two main types of integrations :

1. System Integration
ADFS , Single Sign on , MS- Office
2. Data Integration
Exchange of for example customer data between systems

Integration Scenarios

1. Office 365 (Exchange online , sharepoint online ,SSO)
2. Web sites/Intranet
3. ERP
4. Service
=> Address Validation
=> Postcode Checks
=> Maps (Bing/ Soical Maps)
5. Social Media (Twitter , facebook, linkedin, yammer)


Integration Basics

1. Integration Basics
* Point to Point (Event based example create , update , delete)
* loosely coupled (Publisher -Subscriber)
2. Integration Technique
* Message based (MSMQ)
* Web Service
* Enterprise Service bus


Integration Patterns (Data)

1. One Time (Migrations)
a.Initial data
b.Static data
2. Batch Integration
a.Scheduled
b.Results seen later
3. Near to real time integrations
a. Continouse
b. (Almost) direct results

Cloud vs On Premise

1.Cloud
a. CRM Online
b. Partner Hosted (Shared & Private)
2. On Premise

a.ERP
b.Security

Software 

1. Dynamics Connector
2. Excel
3. Sql Server
a.Integration Service
b.Reporting Service
4. Scribe Insight
5. Biztalk
6. Tailor made solutions (Programming)


Success Factor 

1. Analyze /Design
2. Build
3. Test
=> Technical
4. Test
=> Functional
5. Test , more Testing
6. Go- Live

https://www.youtube.com/watch?v=OFezT58_gUM&spfreload=10

Tuesday, August 11, 2015

Dynamics CRM 2015 Enhanced Business Rules

Introduced in Dynamics CRM 2013, Business Rules enable logic execution to be applied to databases using in built tools which avoids the need, and expense, of writing custom scripting.

Improvements in the Dynamics CRM 2015 Update is a refresh to Business Rules which fixes this these restrictions and adds wider functions.


  1. Business Rules can now be executed on the server (previously client side only)
  2. Business Rule Scope should be set to Entity when building the rule
  3. Ensures your rule will fire when no matter how records are updated and not only via the form
  4. Synchronous and would be visible real time
  5. Set default values on record creation (e.g., all your Leads are generated in the United States so you can default the country on the Lead record when records are created)
  6. Added If.. Else If.. Else support
  7. Ability to combine expressions using And/Or

There are a set of limitations that everyone should be aware of:


  1. Cannot support nested if.. else
  2. No grouping of expressions in a condition
  3. Expressions can be combined either using And, or using Or, but not both
  4. Still single entity only (no ability to reach out to related records)

Queue


Queues are instrumental in organizing, prioritizing, and monitoring the progress of your work while you are using Microsoft Dynamics CRM.

The following information pertains to queues:



  1. All customizable entities can be enabled for queues. 
  2. Queues may be public or private. Private queue items are only visible to the members of the queue.
  3. A private queue is automatically created for each new user or team.
  4. A queue can contain multiple entity types, such as tasks, emails, or cases.
  5. A queue contains information about the user who is working on a particular queue item. This helps you manage your resources more efficiently and helps to prevent duplication of work. 
  6. Queues can be enabled for workflows and audit. This helps improve productivity and track the entity and attribute data changes for future analysis and reporting.

Filtered views

The benefits of Filtered views are

Filtered views won’t break after patches, services releases and maybe upgrades
Security is embedded in the view
All the column names are in lower case
Filtered views are automatically created and updated for custom entities
Datetime fields are held in datetime and UTC
Drop down values are held in filtered views


Problems with Filtered Views

1. filtered views can be performance and they have been known to run slowly.

a. One of the reasons for the slow speed of filtered views is you cannot apply indexes to the tables.
b. Another reason for poor performance is the filter view connects a number of tables together.

Friday, June 5, 2015

Control Type in CRM 2013

getControlType

Returns a value that categorizes controls.
Return ValueDescription
standard
A standard control.
iframe
An IFRAME control
lookup
A lookup control.
optionset
An option set control.
subgrid
A subgrid control.
webresource
A web resource control.
notes
A notes control.
timercontrol
A timer control.
kbsearch
A knowledge base search control.

Javascript in crm 2013

JavaScript libraries are Script (JScript) web resources that contain functions you can use to:




  1. Handle form and field events.
  2. Perform actions for controls configured in the Ribbon.
  3. Support other functions.





JavaScript programming best practices

1.Avoid using unsupported methods
2.Use a cross-browser JavaScript library for HTML web resource user interfaces
3.Do not use jQuery for form script or commands
4.Recognize limitations for content delivery network (CDN) libraries
5.Use feature detection when writing functions for multiple browsers
6.Do not access the DOM
7.Define unique names for your JavaScript functions
8.Use asynchronous data access methods


Execution context


Each event handler can be configured to accept an execution context object as the first parameter. The execution context includes functions that can be called to determine:


Depth: The relative order in which this handler is executed.


Event Source: A reference to the object that initiated the event.


This capability is important when you’re creating a function that may respond to events from several different form or field events.


Shared Variables: This allows a function to set a variable as a key/value pair that can be accessed by other event handlers.

Thursday, June 4, 2015

JavaScript in CRM 2013

Get the string value of a Text field:

Returns the string value in the text field.
var fieldValue = Xrm.Page.data.entity.attributes.get("fieldName").getValue();

Set the string value of a Text field:

Set the string value for Text field. 
Xrm.Page.data.entity.attributes.get("fieldName").setValue("New Value");

Retrieve Optionset Value/Text:

Returns the Value/Text of Optionset. 
var optionSet = Xrm.Page.data.entity.attributes.get("optionSetName");
var optionSetText = optionSet.getText();
var optionSetValue = optionSet.getValue();

Get the label name of the field:

Get the Label of the specified field. 
var fieldLabel = Xrm.Page.ui.controls.get("fieldName").getLabel();

Get the Lookup field value:

Get the value in given Lookup field. 
var lookupValue=Xrm.Page.data.entity.attributes.get("lookupFieldName").getValue()[0].name;

Get the Lookup field ID:

Returns the ID of the record to which the lookup pointing to. 
var lookupFieldId=Xrm.Page.data.entity.attributes.get("lookupFieldName").getValue()[0].id;

Get current entity name:

Returns the logical name of the current entity. 
var entityName = Xrm.Page.data.entity.getEntityName();

Get Type Code of lookup:

Returns the code type with respect to an entity the lookup pointing to. 
var objectTypeCode = Xrm.Page.getAttribute("lookupFieldName").getValue()[0].type;

Get reference entity name of lookup:

Returns the logical name of an entity the lookup pointing to. 
var entityName = Xrm.Page.getAttribute("lookupField").getValue()[0].entityType;

Check for Dirty:

Returns a Boolean value indicating if any fields in the form have been modified. 
var formChanged = Xrm.Page.data.entity.getIsDirty();

Set Lookup field:

Set the lookup field value. 
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = newId;
lookupValue[0].name = newName;
lookupValue[0].entityType = entityType;
Xrm.Page.getAttribute("lookupName").setValue(lookupValue);


Get event generated field value:

Returns the value of the field which generates the event. 

function fieldValue_onchange(obj) {
  var attribute = obj.getEventSource();
  alert(attribute .getValue());
  alert(Xrm.Page.ui.getCurrentControl().getAttribute().getValue());
}

Get Organization Name:

Returns the unique name of logged-in organization.
var orgName = Xrm.Page.context.getOrgUniqueName();

Get Organization Language Code:

Returns organization's language code(LCID).
var orgLanguage = Xrm.Page.context.getUserLcid();

Get Server URL:

Returns the base server URL.
var orgName = Xrm.Page.context.getServerUrl();

Get GUID of current record:

Returns GUID for the record. 
var guid = Xrm.Page.data.entity.getId();

Whether the field is disabled or not:

Returns a Boolean value indicating whether the control is disabled. 
var fieldDisabled = Xrm.Page.ui.controls.get("fieldName").getDisabled();

Get form type:

Returns an integer value, indicates the form type: 1-Create, 2-Update 
var FormType = Xrm.Page.ui.getFormType();

Get required fields in the form:

Returns required field names in the form: 
Xrm.Page.data.entity.attributes.forEach( function (attribute, index) { 
 if (attribute.getRequiredLevel() == "required" ) {
  requiredFields += attribute.getName()+"\n";
 }
} );
   

Form Save:

Save the current form. 
Xrm.Page.data.entity.save();

Form Save and Close:

Save and Close the form. 
Xrm.Page.data.entity.save("saveandclose");

Set Focus:

Set focus on the control.
Xrm.Page.ui.controls.get("fieldName").setFocus();

Hide a field:

Hide the specified control. 
Xrm.Page.ui.controls.get("fieldName").setVisible(false);

Disable and Enable a field:

Set field as Read only. 
Xrm.Page.ui.controls.get("fieldName").setDisabled(true);

Set field as editable(Enable). 
Xrm.Page.ui.controls.get("fieldName").setDisabled(false);

Close window:

Close the current opened window. 
Xrm.Page.ui.close();

Open New window:

Open a new browser window with specified URL. 
window.open("http://google.com", 
  'name', 
  'width=900,height=800,toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,modal=yes');

Get Logged-in User ID:

Get the Logged-in User ID. 
var userID = Xrm.Page.context.getUserId();

Attach Event to Control:

As CRM 2011 does not supports some events like onclick and ondblclick, we can attach a particular event to the control on form load. 
function onload_method() {
    var control = document.getElementById("fieldName");
    if (control) {
        control.attachEvent("onclick", control_clicked);
        control.attachEvent("oncdbllick", control_dblclicked);
    }
}

function control_clicked(){
    //This function fires on field click
    //onclick logic goes here
}

function control_dblclicked(){
   //This function fires on field double click
   //ondblclick logic goes here
}

Set Description field in E-mail entity:

The Description field in E-mail entity is inside an IFrame and since its made for text decoration, text inside this field is enclosed with html tags. So, we can't directly set the field value. Below is the solution to set this field OnLoad of the form. 

function onload_method() {
    var descriptionFrame = document.getElementById('descriptionIFrame');
    descriptionFrame.attachEvent('onreadystatechange', setValue);
}

function setValue () {
    var descriptionFrame = document.getElementById('descriptionIFrame'); 
    if (descriptionFrame.readyState != 'complete')
        return; 
    var htmlTag = "<:html> Value for Description field...<:/html>";
    var descriptionWindow = document.frames['descriptionIFrame'];
    descriptionWindow.document.body.innerHTML = htmlTag; 
}

Set IFrame URL:

To change the URL of IFrame and can also pass values in query string. 

function setIFrameURL() {
    var IFrame = Xrm.Page.ui.controls.get("IFRAME_GoogleMap");
    var countryName = Xrm.Page.data.entity.attributes.get("address1_country").getValue();
    var newTarget= "http://maps.google.com/maps?q="+countryName;
    IFrame.setSrc(newTarget);
}

Get Schema Names of the Attributes:

To get the Schema Names of all the attributes in given entity. 

function getSchemaNamesList(entityName) {
 var request = "<Request xsi:type='RetrieveEntityRequest'>" +
               "<MetadataId>00000000-0000-0000-0000-000000000000</MetadataId>" +
               "<EntityItems>IncludeAttributes</EntityItems>" +
               "<LogicalName>" + entityName + "</LogicalName>" +
               "<IsCustomizable>1</IsCustomizable>" +
               "<RetrieveAsIfPublished>true</RetrieveAsIfPublished>" +
               "</Request>";

 var result = queryMetadataService(request);
 var schemaNames = result.selectNodes("//EntityMetadata/Attributes/Attribute/SchemaName");
        var namesList = "";
        for (var i = 0; i < schemaNames.length; i++) {
  namesList += schemaNames[i].text +",";
        }
        alert("Schema Names: "+namesList)
}

function queryMetadataService(request) {
 var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 xmlhttp.open("POST", '/mscrmservices/2007/MetadataService.asmx', false);
 xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
 xmlhttp.setRequestHeader("SOAPAction", 'http://schemas.microsoft.com/crm/2007/WebServices/Execute');

 var soapMessage = "<?xml version='1.0' encoding='utf-8'?>" +
 "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
 "xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
 "<soap:Header>" +
 "<CrmAuthenticationToken xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
 "<AuthenticationType xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>" + AUTHENTICATION_TYPE +
 "</AuthenticationType>" +
 "<OrganizationName xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>" + ORG_UNIQUE_NAME +
 "</OrganizationName>" +
 "<CallerId xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>00000000-0000-0000-0000-000000000000"+
 "</CallerId>" +
 "</CrmAuthenticationToken>" +
 "</soap:Header>" +
 "<soap:Body><Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" + request +
 "</Execute></soap:Body>" +
 "</soap:Envelope>";

 xmlhttp.send(soapMessage);
 return xmlhttp.responseXML;
}


Get Teams of User:

Get all the Teams User belongs to.
var xml = "" +
 "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
 "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
 GenerateAuthenticationHeader() +
 " <soap:Body>" +
 " <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
 " <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
 " <q1:EntityName>team</q1:EntityName>" +
 " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
 " <q1:Attributes>" +
 " <q1:Attribute>name</q1:Attribute>" +
 " </q1:Attributes>" +
 " </q1:ColumnSet>" +
 " <q1:Distinct>false</q1:Distinct>" +
 " <q1:LinkEntities>" +
 " <q1:LinkEntity>" +
 " <q1:LinkFromAttributeName>teamid</q1:LinkFromAttributeName>" +
 " <q1:LinkFromEntityName>team</q1:LinkFromEntityName>" +
 " <q1:LinkToEntityName>teammembership</q1:LinkToEntityName>" +
 " <q1:LinkToAttributeName>teamid</q1:LinkToAttributeName>" +
 " <q1:JoinOperator>Inner</q1:JoinOperator>" +
 " <q1:LinkCriteria>" +
 " <q1:FilterOperator>And</q1:FilterOperator>" +
 " <q1:Conditions>" +
 " <q1:Condition>" +
 " <q1:AttributeName>systemuserid</q1:AttributeName>" +
 " <q1:Operator>EqualUserId</q1:Operator>" +
 " </q1:Condition>" +
 " </q1:Conditions>" +
 " </q1:LinkCriteria>" +
 " </q1:LinkEntity>" +
 " </q1:LinkEntities>" +
 " </query>" +
 " </RetrieveMultiple>" +
 " </soap:Body>" +
 "</soap:Envelope>";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
var resultXml = xmlHttpRequest.responseXML;
//alert(resultXml.xml);

// Save all entity nodes in an array.
var entityNodes = resultXml.selectNodes("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");

var teamnames = new Array();
var teamids = new Array();

for (var i = 0; i < entityNodes.length; i++) {

 var entityNode = entityNodes[i];
 var teamidNode = entityNode.selectSingleNode("q1:teamid");
 var teamNode = entityNode.selectSingleNode("q1:name");
 var teamid = (teamidNode == null) ? null : teamidNode.text;
 var team = (teamNode == null) ? null : teamNode.text;

 teamnames[i] = team;
 teamids[i] = teamid;
}

Filtered Lookup:

Filter the lookup view based the value selected in another lookup.

You can get fetchXml value from your CRM system by following the steps below.
Open Dynamics CRM
 à Click Advanced Find on ribbon à Select Target(say) in "Look for:" list à Select Owning Team(Team) in list below à Select Team under Owning Team(Team) à Leave Equals as default filter à In Enter Value lookup select one record à Click Download Fetch XML on ribbon. You will get fetch XML string and put that code in variable 'fetchXml' in below code and replace GUID from 'value' property in <condition> tag with dynamic variable, here it is _teamId.

function changeCustomView() {
//new_targetvalue is a lookup to new_target entity which we are filtering present on new_test entity form
//new_team is a lookup to Team on new_test entity form by which new_targetvalue lookup filtering
//new_targetid is a primary key attribute in new_target entity
//teamid is a lookup to Team on new_target entity form
 
   var entityName = "new_target"; //Filtering lookup entity name
   var _team = Xrm.Page.data.entity.attributes.get("new_team"); //Team on which filtering depends on
   var viewDisplayName = "CustomTargetFilteredView";

   // If new_team contains a value, then filter the new_targetvalue lookup based on new_team selected
   if (_team.getValue() != null) {
      var _teamId = _team.getValue()[0].id;
      var viewId = "{1DFB2B35-B07C-44D1-868D-258DEEAB88E2}"; // Unique viewID
      var fetchXml = "<?xml version='1.0'?>" +
        "<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>" +
        "<entity name='new_target'> <attribute name='new_targetid'/>" +
        "<attribute name='new_name'/>" +
        "<attribute name='createdon'/>" +
        "<order descending='false' attribute='new_name'/>" +
        "<link-entity name='team' alias='aa' to='owningteam' from='teamid'>" +
        "<filter type='and'>"+ 
        "<condition attribute='teamid' value='" + _teamId + "' uitype='team' operator='eq'/>" +
        "</filter> " +
        "</link-entity> " +
        "</entity> " +
        "</fetch>";

      var layoutXml = "<grid name='resultset' " +
        "object='1' " +
        "jump='new_name' " +
        "select='1' " +
        "icon='1' " +
        "preview='1'>" +
        "<row name='result' " +
        "id='new_targetid'>" +
        "<cell name='new_name'/>" +
        "width='100' />" +
        "</row>" +
        "</grid>";

      var lookup = Xrm.Page.ui.controls.get("new_targetvalue");
      lookup.addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
      lookup.setDefaultView(viewId);
      document.getElementById("new_targetvalue").setAttribute("disableViewPicker", "1");   
   }
}

Trigger the Workflow:

Trigger the workflow(process) using javascript. 

Steps to be followed to implement javascript to trigger workflow:
à Download JQuery here.
à Crate one JScript webresource and upload this downloaded JQuery.
à Create one JScript webresource for the below code and register to the CRM form where you want to run this script. 


function TriggerWorkflow() {

 // Get the Workflow ID
 var workflowId = GetProcessId();
 if (workflowId[0].results.length > 0) {
  var xml = "" +
  "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
  "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
  GenerateAuthenticationHeader() +
  "<soap:Body>" +
  "<Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
  "<Request xsi:type=\"ExecuteWorkflowRequest\">" +
  "<EntityId>" + Xrm.Page.data.entity.getId() + "</EntityId>" +
  "<WorkflowId>" + workflowId[0].results[0].WorkflowId + "</WorkflowId>" +
  "</Request>" +
  "</Execute>" +
  "  </soap:Body>" +
  "</soap:Envelope>" +
  "";
  var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
  xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", true);
  xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");
  xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
  xmlHttpRequest.send(xml);
 }
}

function GetProcessId() {
 // Pass the workflow name manually to get the Id of the workflow
 var processName = "My Workflow Name";

 // Get the server URL
 var serverUrl = Xrm.Page.context.getServerUrl();
 var oDataUri = serverUrl + "/xrmservices/2011/OrganizationData.svc/WorkflowSet?$select=WorkflowId&$filter=Name eq '" + processName + "' and ActiveWorkflowId/Id ne null";
 var jSonArray = new Array();

 jQuery.ajax({
  type: "GET",
  contentType: "application/json; charset=utf-8",
  datatype: "json",
  url: oDataUri,
  async: false,
  beforeSend: function (XMLHttpRequest) {
   XMLHttpRequest.setRequestHeader("Accept", "application/json");
  },
  success: function (data, textStatus, XmlHttpRequest) {
   if (data && data.d != null) {
    jSonArray.push(data.d);
   }
  },
  error: function (XmlHttpRequest, textStatus, errorThrown) {
   alert("Error :  has occured during retrieval of the workflowId");
  }
 });
 return jSonArray;
}

Set field value using query string parameter:

When we click on some ribbon button or on some event, the new Account window will open with setting the Account Name field by passing that value in query string parameter. 

function openAccountWindow(value) {
 var windowProperties = 'width=900,height=800,toolbar=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,modal=yes';
 var encodedParam = encodeURIComponent("name = New Test Account");
 window.open("http://serverName/OrgName/main.aspx?etc=1&extraqs="+ encodedParam +"&pagetype=entityrecord",
'accountWindow',
windowProperties);
}

Change the Status and Status Reason of the record:

We can not change the Status and Status Reason of the record directly or by REST call. We can do so using SOAP request. And Status and Status Reason should be matched to perform this action. 
function SetState(entityName, entityId, statusReason, state) {
   var serverURL = Xrm.Page.context.getServerUrl();
   var setStateRequest = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">' +
    '<s:Body>' +
       '<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">' +
          '<request i:type="a:UpdateRequest" xmlns:a="http://schemas.microsoft.com/xrm/2011/Contracts">' +
             '<a:Parameters xmlns:b="http://schemas.datacontract.org/2004/07/System.Collections.Generic">' +
                '<a:KeyValuePairOfstringanyType>' +
                   '<b:key>EntityMoniker</b:key>' +
                   '<b:value i:type="a:EntityReference">' +
                      '<a:Id>' + entityId + '</a:Id>' +
                      '<a:LogicalName>' + entityName + '</a:LogicalName>' +
                      '<a:Name i:nil="true"></a:Name>' +
                   '</b:value>' +
                '</a:KeyValuePairOfstringanyType>' +
                '<a:KeyValuePairOfstringanyType>' +
                   '<b:key>State</b:key>' +
                   '<b:value i:type="a:OptionSetValue">' +
                      '<a:Value>' + state + '</a:Value>' +
                   '</b:value>' +
                '</a:KeyValuePairOfstringanyType>' +
                '<a:KeyValuePairOfstringanyType>' +
                   '<b:key>Status</b:key>' +
                   '<b:value i:type="a:OptionSetValue">' +
                      '<a:Value>' + statusReason + '</a:Value>' +
                   '</b:value>' +
                '</a:KeyValuePairOfstringanyType>' +
             '</a:Parameters>' +
          '<a:RequestId i:nil="true"></a:RequestId>' +
          '<a:RequestName>SetState</a:RequestName>' +
          '</request>' +
       '</Execute>' +
    '</s:Body>' +
   '</s:Envelope>';

   var req = new XMLHttpRequest();
   req.open("POST", getServerUrlForSetState(), false);
   
   req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
   req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
   
   req.send(setStateRequest);
   
   if (req.status != 200) {
      getError(req.responseXML);
   }
}

Get the current form name:

Returns the name of the selected form in the record. 
Xrm.Page.ui.formSelector.getCurrentItem().getLabel();

Refresh the form:

Refresh the current form. 
window.parent.location.reload();

Hide left navigation item:

Hide the left navigation item based on some condition. 
var items = Xrm.Page.ui.navigation.items.get();

for (var i in items) {
   var item = items[i];

  if (item.getLabel() == "Accounts") {
    item.setVisible(false);
   }
}

Set field requirement level in run time:

Set the field requirement level to either Required or Recommended or NoConstraint in run time. 
// No Constraint 
Xrm.Page.getAttribute("field_name").setRequiredLevel("none");   

// Business Required 
Xrm.Page.getAttribute("field_name").setRequiredLevel("required");   

// Business Recommended 
Xrm.Page.getAttribute("field_name").setRequiredLevel("recommended");

Get the CRM Organization URL:

Retrieve the CRM Organization URL with respect to the current domain name.
For example, if you are browsing the CRM instance with IP, then the return value would be like this: http(s)://<IP>/<OrgName>
If you are browsing with domain name, it would be like this: http(s)://<DomainName>/<OrgName> 

function GetServerUrlRegExp(location) {
    var urlReg = new RegExp(/http[s]?:\/\/[0-9.:]+\/[^\/]+/);
    var ServerUrl = Xrm.Page.context.getServerUrl();
    if (window.location.href.match(urlReg) != null) {
        ServerUrl = window.location.href.match(urlReg).toString();
    }
    if (ServerUrl.match(/\/$/)) {
        ServerUrl = ServerUrl.substring(0, ServerUrl.length - 1);
    }
    return ServerUrl;
}

New capabilities in JavaScript in CRM 2013

New capabilities to replace unsupported methods

The following table highlights new capabilities available using the Xrm.Page that were only possible using unsupported methods in earlier versions. If you have used unsupported methods to achieve these results, you should plan to changes your scripts so that they use these supported methods after you upgrade.

 

GoalXrm.Page method
Show custom tooltips.
Edit the attribute description. The attribute description text will appear as a tooltip. No code required.
Show form and control notifications.
Use Xrm.Page.ui control.setNotification to set a notification message on a control and prevent save of the record until Xrm.Page.ui control.clearNotification is called to clear it.
Use Xrm.Page.ui control.setFormNotification to set a form level notification and useXrm.Page.ui.clearFormNotification to clear it.
Manipulate views presented for a lookup field.
Use the new PreSearch Event just before the search dialog opens when setting a lookup value. This event doesn’t have a user interface to set an event handler in the application, it can only be set using the Xrm.Page.ui control.addPreSearch method. Use this event with the addCustomFilteraddCustomView and setDefaultViewmethods to control the views opened when people search for a record to set as the value of a lookup field.
Specify whether a date control should show the time portion of the date.
Use Xrm.Page.ui control.setShowTime.
Change the labels that appear in the form.
Use the setLabel method for tabs, sections, controls and navigation items.
Hide form elements.
Use the setVisible method for tabs, sections, controls and navigation items.
You can use the tab.setDisplayState method to expand or collapse a tab.
Set focus on a form tab or navigation area.
Use the setFocus method available for tab, control, and navigation items.
Set the required level for controls.
Use the attribute.setRequiredLevel method.
Add additional functions to an event using code.
Use the attribute.addOnChange or entity.addOnSave methods.
Hiding menu items or buttons.
The only capability in Xrm.Page to affect the ribbon is to use the refreshRibbon method. To hide or disable controls present in the ribbon you must configure <EnableRule> (RibbonDiffXml) and <DisplayRule> (RibbonDiffXml) within <CommandDefinition> (RibbonDiffXml) elements.
These rules allow for a number of data-driven rules you can apply to hide or disable controls for a form. If your logic requires data that isn’t available from any of the rule elements provided, you can create a <CustomRule> (RibbonDiffXml) that calls a function in a JScript library. More information: Define ribbon display rules