Tuesday, December 29, 2015

Modify the Columns Shown in The Inline Lookup-CRM 2013 & 2015


How to modify the columns shown in the inline lookup in CRM 2013 Refreshed Entity User Interface and what can be done and what cannot be done.

image

In the example (lookup to Contact), it shows only Name, Company Name, and Email Address.

You found that Email Address is not important, you want to show Name, City, and Company Name.

Explanation:

1. Go to Form Editor

2. Go to the field and check the lookup that is used, in this case is Contact view (lookup view) and get the Default View of the Lookup field

image

*You can also use custom view as default view.

image

3. Go to the Contact Lookup View and then you add can re-order the position

Previously:

image

Change to:

image

*You cannot modify the Full Name position nor remove it.

4. Test the Result:

image

*The supported total column shown in the inline lookup is 3 only (including Name as the primary field that is not replaceable)

It shows Name, City, and Company Name as per your expectation.

5. You can also use a Composite field, for example, Address

image

Result:

image

And you can get the tooltip.

image

6. But, you cannot use to show field from related entity.

Example:

image

Order: Name, City, Industry of the Account, Company Name

Result:

image

You should ‘Look Up More Records’

image

Activate – Deactivate Record using JavaScript in CRM


Activate – Deactivate Record using JavaScript in CRM


//Params:entityname,entityGuid,stateCode,StatusCode
// Call the funtion
changeRecordStatus("contact", Xrm.Page.data.entity.getId(), 1, 2);


function changeRecordStatus(EntityLogicalName, RECORD_ID, stateCode, statusCode) {

    // create the SetState request

    var request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";

    request += "<s:Body>";

    request += "<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";

    request += "<request i:type=\"b:SetStateRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";

    request += "<a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";

    request += "<a:KeyValuePairOfstringanyType>";

    request += "<c:key>EntityMoniker</c:key>";

    request += "<c:value i:type=\"a:EntityReference\">";

    request += "<a:Id>" + RECORD_ID + "</a:Id>";

    request += "<a:LogicalName>" + EntityLogicalName + "</a:LogicalName>";

    request += "<a:Name i:nil=\"true\" />";

    request += "</c:value>";

    request += "</a:KeyValuePairOfstringanyType>";

    request += "<a:KeyValuePairOfstringanyType>";

    request += "<c:key>State</c:key>";

    request += "<c:value i:type=\"a:OptionSetValue\">";

    request += "<a:Value>" + stateCode + "</a:Value>";

    request += "</c:value>";

    request += "</a:KeyValuePairOfstringanyType>";

    request += "<a:KeyValuePairOfstringanyType>";

    request += "<c:key>Status</c:key>";

    request += "<c:value i:type=\"a:OptionSetValue\">";

    request += "<a:Value>" + statusCode + "</a:Value>";

    request += "</c:value>";

    request += "</a:KeyValuePairOfstringanyType>";

    request += "</a:Parameters>";

    request += "<a:RequestId i:nil=\"true\" />";

    request += "<a:RequestName>SetState</a:RequestName>";

    request += "</request>";

    request += "</Execute>";

    request += "</s:Body>";

    request += "</s:Envelope>";

    //send set state request

    $.ajax({

        type: "POST",

        contentType: "text/xml; charset=utf-8",

        datatype: "xml",

        url: Xrm.Page.context.getServerUrl() + "/XRMServices/2011/Organization.svc/web",

        data: request,

        beforeSend: function (XMLHttpRequest) {

            XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");

            XMLHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");

        },

        success: function (data, textStatus, XmlHttpRequest) {

            Xrm.Page.data.refresh(); // refresr current crm form

        },

        error: function (XMLHttpRequest, textStatus, errorThrown) {

            alert(errorThrown);

        }

    });

}

Friday, December 18, 2015

Using New Scripting Methods in CRM 2016

With the release of Dynamics CRM 2016, new client side methods introduced that we can use to make user experience more interactive while enter data in CRM forms. Following are the methods:
getValue
Keypress
Autocomplete

getValue Method – This method is used to get the latest value of the field. Earlier this method was only available in attribute collection, which provides value of the field only after Onchange event fired. Whereas when it is used with control collection, we can capture value as soon as users starts entering value in field, so it means if we have any requirement to validate data entry then we can use this method to make it more interactive. We can use this method like below:


Xrm.Page.getControl(field name).getValue();
Let’s take one example that we want to restrict user to enter only number between 0-9 under phone field in account entity, so we can simply use below code to do that:





function OnTelephone1KeyPress() {
    var phoneValue = Xrm.Page.getControl("telephone1").getValue().toString().replace(/[^0-9]/g, "");
    Xrm.Page.getAttribute("telephone1").setValue(phoneValue);
}
Above code will get character from telephone1 field as soon as user enters it and will replace character with null if it is not under 0 to 9 range. But we need to use above code with keypress events, so let’s understand use of keypress event first to complete our code.
Keypress Method – Below three keypress methods are added to work with controls:
addOnKeyPress – This method is used to associate method to KeyPress event of text or number, so it will fire when user will press any key. We can use this method like below:

1
Xrm.Page.getControl(field name).addOnKeyPress(name of function);
For example if we want to call above method on keypress event of telephone1 field then we can use it like below:
1
Xrm.Page.getControl("telephone1").addOnKeyPress(OnTelephone1KeyPress);
Now let’s deploy this code to CRM, we can create a java script web resource and use below code under text editor:









//validate character
function OnTelephone1KeyPress() {
    var phoneValue = Xrm.Page.getControl("telephone1").getValue().toString().replace(/[^0-9]/g, "");
    Xrm.Page.getAttribute("telephone1").setValue(phoneValue);
}
//add keypress event handler
function AccountOnLoad() {
    Xrm.Page.getControl("telephone1").addOnKeyPress(OnTelephone1KeyPress);
}
clientevent1
After that we need to attach this web resource to account entity form and need to call AccountOnLoad method OnLoad of account form like below and need save and publish our changes: clientevent2
Now when we will create a new account record or modify existing account record, we will see our code won’t allow us to enter non numeric character under phone field.

removeOnKeyPress – We can use this method to remove KeyPress event handler from the text or number field, that is added using addOnKeyPress method. We can use it like below:
1
Xrm.Page.getControl(arg).removeOnKeyPress(function name)
fireOnKeyPress – We can use this method to call KeyPress event handler for text or number field, we can use it like below:
1
Xrm.Page.getControl(field name).fireOnKeyPress()
Note: All the above methods are only supported for Web and Outlook client.

Wednesday, August 26, 2015

Rename and Delete business units

CRM 2011/2013 allows you to rename and delete business units, this can be very useful if you have spelt something incorrectly.
To rename a business unitSettings –> Administration –> business /units
click on the business unit you want, change the display name and press save
You can also delete a business but you must have one business unit.
to delete one of the child business units you go to business units
Settings –> Administration –> business units
click on the business unit you want to delete.
First you must disable the business unit by going Actions –> disable
you will then be able to delete the business unit

Saturday, August 22, 2015

Plug-in stages

Pre validation

Registered Plug-in run before the form is validated
Useful if you want to implement business logic before the actual validation starts.  i.e., Changes made in plug-in won’t be saved if the validation of the main system plugins complain because the changes are outside the database transaction.
Ex – Some “delete” plug-ins. Deletion cascades happen prior to pre-operation, therefore if you need any information about the child records, the delete plugin must be pre-validation.

Pre -operation

After validation and before the values are saved to the database
Post operation
Plugin will run after the values have been inserted/changed on the database

Example:

If and “update” plug-in should update the same record, it is best practice to use the pre-operation stage and modify the properties. That way the plug-in update is done within same DB transaction without needing additional web service update call.

Database Transactions in Plug-Ins

Plug-ins may or may not execute within the database transaction
You can check if the plug-in is executing in-transaction by reading the ‘IsInTransaction‘ property of IPluginExecutionContext
Stages 20 and 40 are part of the database transaction while stage 10 and 50 may be part of the transaction
If plugin throws an exception, every action done during the transaction will be rollback

Few more Points

Whether a plug-in executes synchronously or asynchronously, there is a 2 minute time limit imposed on the execution of a (message) request.
If the execution of your plug-in logic exceeds the time limit, a Timeout exception is thrown
If a plug-in needs more processing time than the 2 minute time limit, consider using a workflow or other background process
‘Pre-operation’ operations that CRM will do will not be carried out in pre-validation stage.
If you are deleting a record that has many-to-many relationship records with another entity; these relationship records will still be available in pre-validation stage, but not in pre-operation stage.
“Target” entity (i.e., pluginContext.InputParameters[“Target”])
It’s the entity on which plug-in registered
It only contains “dirty” attributes. if you convert to early bound, the value of the unchanged attribute will be null

Tuesday, July 28, 2015

Object-Oriented Programming Fundamentals in C#

Object-Oriented Programming (OOP) Terms


Basics

Object-Oriented Programming (OOP): An approach to designing and building applications that are flexible, natural, well-crafted, and testable by focusing on objects that interact cleanly with one another.
Class: The code describing a particular entity in the application, such as Customer, Order, or Address. The class contains the code defining the properties and methods (see below).
Property: The code defining the data managed by the class, such as CustomerName, OrderNumber, or EmailAddress.
Method: The code defining the actions or behaviors of the class, such as Validate or CalculateTotal. Methods are defined in the code with C# functions.
Members: Refers to the properties and methods for a class.
Object: An instance of a class that is created at runtime. In C#, an instance is created with the new keyword.
Object Variable: The variable used when creating an object. For example, var myCustomer = new Customer(); In this example,myCustomer is the object variable. Use the object variable to set the properties and call the methods. The object variable retains the state of the object.
Method signature: The code defining the method function including the function name and the set of parameters. The signature does notinclude the return type. Every function signature within a class must be unique. The signature is used to “match up” calls to the function.
Overloading: Methods that have the same name but different parameters. Example: public bool Retrieve() and public bool Retrieve(int id). The Retrieve method in this example is said to have “two overloads”.
Contract: The set of public properties and methods in a class define the classes contract. The class makes a promise that it will provide the defined properties and methods to any other code that needs them. This is also known as the “class interface“.
Constructor: Code that is executed each time an instance of the class is created.
Default Constructor: A constructor with no parameters.
Overriding: When using inheritance (see below), a child class can override a member of the parent class to provide its own implementation.
Interface: An explicit interface is a separate type (INotifyPropertyChanged for example) that defines a set of properties and methods with no implementation. Any class can then implement an interface to use the set of properties and methods provided in the interface. Think of an interface as a role that an object can play. For example, an ILoggable interface defines a logging role. An IEmail interface defines an emailing role. An Order class may implement both the ILoggable and IEmail interface to take on both roles. An Address class may implement only the ILoggable interface.

Four Pillars of Object-Oriented Programming

The pillars of OOP define the key characteristics of object-oriented programming and are:
Abstraction: The process of defining classes by simplifying reality, ignoring extraneous details, and focusing on what is important for a purpose. For example, a customer may have a name, title, address, marital status, pets, children, credit card information, vehicles, etc. But if the purpose of the application is to process orders, the application may only care about the customer’s name, address, and credit card information.
Encapsulation: A way to hide (or encapsulate) the data and implementation details within a class, thus hiding complexity. In C#, data elements are defined with private backing fields and exposed through property getters and setters. So the data is encapsulated.
Inheritance: A relationship between classes whereby child (or derived) classes inherit all of the members of the parent (or base) class. For example, an application may define a “business object base” class that all business objects inherit from. This base class can contain members common to all child classes, such as entity state information.
Polymorphism: Basically “many forms”. The concept that a single method can behave differently depending on the type of object that calls it. For example, the Validate method in Customer class performs differently from the Validate method in the Order class.
Inheritance-Based Polymorphism: Polymorphism in the case where the method is defined in a base class and behaves differently for each child class.
Interface-Based Polymorphism: Polymorphism in the case where the method is defined in an interface and behaves differently in each class that implements the interface.

Class Relationships

Collaboration: “Uses a” relationship. Objects can collaborate with other objects. For example: Customer Repository “uses a” Customer object to populate on a retrieve and serialize on a save.
Composition: “Has a” relationship. Objects can be composed of other objects. For example, Order “has a” Customer and Order “has a” shipping address.
Inheritance: “Is a” relationship. Objects can be subtyped. For example, a Business Type Customer “is a” Customer and a Residential Type Customer “is a” Customer.

C# OOP Terms

Auto-implemented properties: Properties that create and manage the encapsulated backing field automatically.
Static method: Adding the static modifier on a member of the class (property or method) defines that the member belongs to the class itself, not an instance of the class.
Sealed class: Class that cannot be used as a base class for an inheritance relationship.
Abstract class: Class that cannot be instantiated, so no objects can be created from the class. Nor can it be accessed by its class name. The class can only be used as a base class for other classes.
Concrete class: Class that can be instantiated. Basically, the opposite of an abstract class.
Static class: Class that cannot be instantiated, so no objects can be created from the class. The class members are instead accessed using the class name. A static class provides a shortcut to the members of the class when instancing is unwarranted. For example, the .NET Framework Console class is a static class. To call the WriteLine method you use Console.WriteLine. You don’t have to create a new instance of Console.
Abstract method: Method with no implementation (basically no code). The method must be overridden by a child class.
Virtual method: Method with an implementation that can be overridden by a child class.

Wednesday, July 15, 2015

Setting null value using Javascript.in MS CRM

I had an odd error where I was trying to null a lookup field in Javascript in CRM 2013.When the user changed a lookup field, I wanted to blank out a few fields to make them select those fields again.  The fields being nulled were dependant on selection of the first lookup field and the options and values they could pick changed.
if (Xrm.Page.getAttribute("field1").getValue() != null) {
    Xrm.Page.getAttribute("field1").setValue(null);
}
if (Xrm.Page.getAttribute("field2").getValue() != null) {
    Xrm.Page.getAttribute("field2").setValue(null);
}
field1 was correctly set to null but field2 refused to be set to null
I changed my code to set the required level to none, set field2 to null and then reset the required level to required.

//I had to set required level to none because assign null wasn't working, might be fixed in future roll ups
    if (Xrm.Page.getAttribute("field1").getValue() != null) {
            Xrm.Page.getAttribute("field1").setValue(null);
        }

        Xrm.Page.data.entity.attributes.get("field2").setRequiredLevel("none");
        if (Xrm.Page.getAttribute("field2").getValue() != null) {
            Xrm.Page.getAttribute("field2").setValue(null);
        }

        Xrm.Page.data.entity.attributes.get("field2").setRequiredLevel("required");

Monday, July 13, 2015

The Under Operator in MS CRM 2015

Advanced Find now includes two new operators which work in conjunction with the new hierarchies feature in Dynamics CRM 2015. These operators are called “Under” and “Not Under” and can be used when querying lookup fields in Advanced Find.

Microsoft Dynamics CRM 2015 Advanced Find - The Under Operator
I have currently set up the Users in our Dynamics CRM system such that the Managerfor each user has been specified. This builds a user hierarchy in the system so we can easily see who reports to who. Let’s assume we have an organisational structure where there are multiple managers at different levels.Microsoft Dynamics CRM 2015 Advanced Find - The Under Operator
It would be a tricky in previous versions of Dynamics CRM if I wanted to build a query to show everyone who sat below Bob Jones. In CRM 2015, I can simply use the “Under” operator to find these people.
Microsoft Dynamics CRM 2015 Advanced Find - The Under Operator

Running this query gives me everyone who sits below Bob Jones, whether they are a direct relationship with that record or not.
 Microsoft Dynamics CRM 2015 Advanced Find - The Under Operator

Thursday, July 2, 2015

Business Process Flow 2013/2015

CRM 2013 BPF
Business process Flows are a new enhancement to dynamics CRM 2013, and they bring the power of guided business rules to the application.
Unlike workflow processes, BPFs are designed to work with users and guide them through a variety of business processes.

Key Benefits CRM 2013 BPF
1.       BPF allow organization to define the specific steps that need to be taken for something to happen. BPF allow org. to track where in the process the record is.

2.       BPF allow for “stage-gating”, which requires data to be entered before proceedings to the next step. BPF are visually represented on the record.
3.       BPF can be controlled through portable business logic and workflow. An example of this is when a field is hidden via a PBL or a value is populated via a workflow, the BPF incorporates this changes as well.
4.       BPF allow for multiple entities in the BPF(up to five)
5.       There can be 10 active BPF per entity
6.       Users with appropriate security permissions can edit the BPF in the real time to incorporate new rules.
7.       Users can switch BPF midstream to new BPF if the situation changes. A common example of this is when an inbound call creates a case with a Case to RMA (Return Merchandise Authorization) process, but it turns out the user just has a question; in this case, the user might change the BPF to Case to KB.

Limitations of BPF
1.       An entity once selected during design of the BPF cannot be reference again (except to close the record), and no more than 5 entities can be referenced.
2.       If a user’s security permission does not allow using a BPF, the BPF will be visible but a maximum of 10 BPF per entity can be active. (You can have more, but only 10 can be active.)
3.       There is a maximum of 30 stages per BPF

Microsoft Dynamics CRM 2013 comes with at least three BPF but they are designed to be illustrative and allow for an understanding of how BPF work (althrough in our experience we have found them to be practical).
The 3 BPF are as follows:
1.       Led to opportunity sales process
2.       Opportunity sales process
3.       Phone to Case process

Ready to use BPF
Microsoft has included a package of 12 other BPF in the system, but they need to be deployed.
To deploy them, navigate to setting, Data Management and Select Add Ready-to-Use Business Processes.
Enable an entity for BPF
You can enable the BPF features for an entity by allowing this on the form customization. To do so go to Customization>Customize the system and then select an entity for which you want to enable business process.
Once it is enable, you cannot reverse it. It create two new fileds for the entity named processeId(process) and staged(process stage).

ProcessID is used to hold the ID of the process associated with the current record, and similarly holds the ID of the current stage of the record in the process

Business Rule in CRM 2015
one of the new exciting features for Microsoft Dynamics CRM 2013 is portable business logic, also known as business rules.
In the past, to customize a form and display an error message or show and hide a field, you had to learn and implement some JavaScript to make work. With PBL, you can do it with any javascript.
The following action are available with PBL:(Action to
1. Show error message.
2. Set field value.
3. Set business required.
4. Set visibility.
5. Lack or Unlock field.
CRM 2015 Improvements:
1. Support for enriched business logic including if/else.
2. Combining expressions usings and / or conditional rules.
3. Using Rule to set default field values
4. Synchronous server side Business Rule logic execution.
5. Visual editing.

Server Side Business Logic Execution.
Another improvement to dynamics CRM Business Rules is server side execution that enables a synchronous workflow to be executed.
As well as being a real time operation this offers greater control by defining the scope that will be set to the entity.
This also ensure your rule will fire no matter how CRM records are updated, even if fields are automatically updated via integrated solutions.


Set Date Time Field to Now in Plugin Dynamics CRM 2011

In Dynamics CRM 2011 when you are creating or updating records through a plugin, you will sometimes be required to set a date field to the current date and time of the plugins execution.
There are two ways of doing this with a plugin. One method is using DateTime.Now, which will give you the local time of the CRM Server. The other method (the recommended method) is using DateTime.UtcNow. This will give you the CRM Server time, but it will be converted into UTC time.
 Set Date Time Field to Now in Plugin Dynamics CRM 2011
Dynamics CRM 2011 stores all Date/Time fields in UTC time, so by using the ‘DateTime.UtcNow’ approach our dates will be converted into UTC time before hitting the database. When our users read the date through CRM it will be converted back into their local time zone, and will read correctly for them.
If we check the database, we can see how the date from the image above is actually stored in the database using UTC time:
 Set Date Time Field to Now in Plugin Dynamics CRM 2011
If you were to set a date using ‘DateTime.Now’, the exact server time would be saved into the database with no conversion to ‘UTC’ time first. When the user reads the date in CRM it would then be converted into their local time, and will read incorrectly for them.
I’ve created a scenario to better describe how this works. One using each method:
Using DateTime.Now:
Your CRM Servers time zone is UTC+13:00. You trigger a plugin on 7/03/12 at 3:00pm which creates a Task. The Tasks Due Date is set using DateTime.Now. The Due Date stored in the Database is 7/03/12, 3:00pm (the exact server time). When you open the Task, the Due Date reads incorrectly as 8/03/12, 4:00am.
Using DateTime.UtcNow:Your CRM Servers time zone is UTC+13:00. You trigger a plugin on 7/03/12 at 3:00pm which creates a Task. The Tasks Due Date is set using DateTime.UtcNow. The Due Date stored in the Database is 7/03/12, 2:00am (UTC time). When you open the Task, the Due Date reads correctly as 7/03/12, 3:00pm.
Here is an example of how you should set your date fields in your plugins using DateTime.UtcNow:
        Entity task = new Entity("task"); 
        task["scheduledend"] = DateTime.UtcNow;
        task["subject"] = "Lottery Ticket!"
        sdk.Create(task);

In some cases it might make sense to use DateTime.Now as appose to DateTime.UtcNow, for example if you are comparing a date with the current date, and you want it to use the local time rather than the UTC time. Whenever you are setting the value of Date/Time fields though, you should always use the UTC time rather than the CRM Server local time.       

Monday, June 29, 2015

How to convert textbox to hyperlink in MS CRM

function ConvertToLink(fieldName,urlFieldName) {
    var itemText = Xrm.Page.getAttribute(fieldName).getValue();
    if (itemText != null && itemText != '' && itemText != 'null') {
        var url = Xrm.Page.getAttribute(urlFieldName).getValue();
        var btn = "<a href='javascript: void(0);' onclick=\"window.open(\'" + url + "\', \'windowname1\');  return false;\" style='color:blue;text-decoration:underline !important'>" + itemText + "</a>";
        var ctrl = Xrm.Page.ui.controls.get(fieldName)._control;
        // Add the new button
        ctrl.get_element().innerHTML += btn;
        // Hide the textbox
        ctrl.get_element().firstChild.style.display = 'none';
    }
}

Early Binding and Late Binding In MS CRM 2015

Late Binding

In Microsoft Dynamics CRM 2015 and Microsoft Dynamics CRM Online 2015 Update, you can use the Entity class when you work with entities. 
When initialized, the Entity class contains the logical name of an entity and a property-bag array of the entity’s attributes. 
This lets you use late binding so that you can work with types such as custom entities and custom attributes that weren’t available when your application was compiled. 
The key difference between early and late binding involves type conversion. While early binding provides compile-time checking of all types so that no implicit casts occur, late binding checks types only when the object is created or an action is performed on the type. 
The Entity class requires types to be explicitly specified to prevent implicit casts.

//Get the Value from optionset.

int val = ((OptionSetValue)account.Attributes["schemaname"].Value;

// Get the Text from OptionSet

String optiontext=account.FormattedValue["schemaname"].ToString();

// Set Value to the optionset

account.Attributes["schemaname"] = new OptionSetValue(1000);

// Get the lookup value

Guid ID = (EntityReference)account.Attributes["schemaname"].Id;

// Set lookup value

account.Attributes["schemaname"] = new EntityReference("contact",Guid);


Early Binding

The examples shown previously used late binding. When using late binding, accessing and using the Organization Service is difficult and you need to explicitly type both the entity and attribute’s names.
This makes the code cumbersome to write, and sometimes prone to errors.
Instead of using late binding, you can use early binding which provides IntelliSense support and better code development and use of .NET technologies such as the .NET Framework Language-Integrated Query (LinQ). 
To use early binding, you must generate the entity classes by using the code
generation tool called CrmSvcUtil.exe, a console application that you can find in the SDK\bin folder of the CRM 2013 SDK.
Here is an example of calling this tool:
Click here to view code image
CrmSvcUtil.exe /url:http://columbuscrm/demo1/XRMServices/2011...
/out:GeneratedCode.cs /username:bill /password:p@ssword!


Get files of last hour in Azure Data Factory

  Case I have a Data Factory pipeline that should run each hour and collect all new files added to the data lake since the last run. What is...