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");

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