Generics in C#

Generics introduced in C# 2.0. Generics allow you to define a class with placeholders for the type of its fields, methods, parameters, etc. Generics replace these placeholders with some specific type at compile time.

A generic class can be defined using angle brackets <>. For example, the following is a simple generic class with a generic member variable, generic method and property.

Example: Generic class

class MyGenericClass<T>
{
    private T genericMemberVariable;

    public MyGenericClass(T value)
    {
        genericMemberVariable = value;
    }

    public T genericMethod(T genericParameter)
    {
        Console.WriteLine("Parameter type: {0}, value: {1}", typeof(T).ToString(),genericParameter);
        Console.WriteLine("Return type: {0}, value: {1}", typeof(T).ToString(), genericMemberVariable);
            
        return genericMemberVariable;
    }

    public T genericProperty { get; set; }
}

As you can see in the above code, MyGenericClass is defined with <T>. <> indicates that MyGenericClass is generic and the underlying type would be defined later, for now consider it as T . You can take any character or word instead of T.

Now, the compiler assigns the type based on the type passed by the caller when instantiating a class. For example, the following code uses the int data type:

Instantiate generic class:

MyGenericClass<int> intGenericClass = new MyGenericClass<int>(10);

int val = intGenericClass.genericMethod(200);
Output:

Parameter type: int, value: 200
Return type: int, value: 10

The following figure illustrates how the compiler will replace T with int in MyGenericClass.

Generic class

The above MyGenericClass<int> class would be compiled, as shown below.

Example: Generic class

class MyGenericClass
{
    private int genericMemberVariable;

    public MyGenericClass(int value)
    {
        genericMemberVariable = value;
    }

    public int genericMethod(int genericParameter)
    {
        Console.WriteLine("Parameter type: {0}, value: {1}", typeof(int).ToString(), genericParameter);
        Console.WriteLine("Return type: {0}, value: {1}", typeof(int).ToString(), genericMemberVariable);

        return genericMemberVariable;
    }

    public int genericProperty { get; set; }

}

You can use any type while instantiating a MyGenricClass. For example, the following example uses a string type.

Example: Generic class

MyGenericClass<string> strGenericClass = new MyGenericClass<string>("Hello Generic World");

strGenericClass.genericProperty = "This is a generic property example.";
string result = strGenericClass.genericMethod("Generic Parameter");
Output:

Parameter type: string, value: Generic Parameter
Return type: string, value: Hello Generic World

Generic base class:

When deriving from a generic base class, you must provide a type argument instead of the base-class’s generic type parameter as shown below.

Example: Generic base class

class MyDerivedClass : MyGenericClass<string>
{ 
    //implementation
}
    

If you want the derived class to be generic then no need to specify type for the generic base class.

Example: Generic derived class

class MyDerivedClass<U> : MyGenericClass<U>
{ 
    //implementation
}
    

If the generic base class has constraints, the derived class must use the same constraints.


class MyGenericClass<T> where T: class 
{
        // Implementation 
}

class MyDerivedClass<U> : MyGenericClass<U> where U: class
{ 
        //implementation
}

Generic Delegates:

As you have already learned in the previous section, the delegate defines the signature of the method which it can invoke. A generic delegate can be defined the same way as delegate but with generic type.

For example, consider the following generic delegate that takes two generic parameters.

Example: Generic Delegate

class Program
{
    public delegate T add<T>(T param1, T param2);

    static void Main(string[] args)
    {
        add<int> sum = AddNumber;

        Console.WriteLine(sum(10, 20));

        add<string> conct = Concate;

        Console.WriteLine(conct("Hello","World!!"));
    }

    public static int AddNumber(int val1, int val2)
    {
        return val1 + val2;
    }

    public static string Concate(string str1, string str2)
    {
        return str1 + str2;
    }
}
Output:

30
Hello World!!

In the above example, add delegate is generic. In the Main() method, it has defined add delegate of int type variable sum. So it can point to the AddNumber() method which has int type parameters. Another variable of add delegate uses string type, so it can point to the Concate method. In this way, you can use generic delegates for different methods of different types of parameters.

Note :A generic delegate can point to methods with different parameter types. However, the number of parameters should be the same.

Generics can be applied to the following:

  • Interface
  • Abstract class
  • Class
  • Method
  • Static method
  • Property
  • Event
  • Delegates
  • Operator

Advantages of Generic:

  1. Increases the reusability of the code.
  2. Generic are type safe. You get compile time errors if you try to use a different type of data than the one specified in the definition.
  3. Generic has a performance advantage because it removes the possibilities of boxing and unboxing.

Further reading:

Points to Remember :

  1. Generics denotes with angel bracket <>.
  2. Compiler applys specified type for generics at compile time.
  3. Generics can be applied to interface, abstrct class, method, static method, property, event, delegate and operator.
  4. Generics performs faster by not doing boxing & unboxing.
Advertisements

Difference between Retrieve and Retrieve Multiple

Retrieve retrieves a single record given the record ID, the method requires 3 parameters: the entity logicalname, the record ID and the columns (attributes) you want to retrieve. It throws an exception if the record ID is not found.

RetrieveMultiple runs a Query against CRM, normally a QueryExpression is used that defines the entity logicalname, the conditions of the query and the columns (attributes) you want to retrieve. It returns always an EntityCollection object and the Entities property contains the list of the records that satisfy the query conditions, so you can have 0, 1 or n records returned.

Retrieve:

Retrieve retrieves a single record given the record ID, the method requires 3 parameters: the entity logicalname, the record ID and the columns (attributes) you want to retrieve. It throws an exception if the record ID is not found.

For better performance, use this method instead of using the Execute method with the Retrieve message.
Returns the BusinessEntity requested. The BusinessEntity contains only the columns specified by the columnSet parameter. The entity is of the type specified by the entityName parameter.

  1. It is used to retrieve a single entity.
  2. This method is strongly typed.
  3. Retrieves an entity instance using the specified ID.

Parameters :

entityName

Specifies a String containing the name of the entity to retrieve. For more information, see Entity Names.

id

Specifies a Guid containing the ID of the entity to retrieve.

columnSet

Specifies the set of columns to retrieve. Pass null to retrieve only the primary key. To retrieve all columns, pass a new instance of the AllColumns class. See ColumnSetBase.

Return Value

Returns the BusinessEntity requested. The BusinessEntity contains only the columns specified by the columnSet parameter. The entity is of the type specified by the entityName parameter.

 Synatx :

public BusinessEntity Retrieve(

string  entityName,

Guid  id,

ColumnSetBase  columnSet

);

Example :

 // Instantiate an account

object.Entity account = new Entity(“account”);

// Set the required attributes.

For account, only the name is required.

// See the Entity Metadata topic in the SDK documentation to determine

// which attributes must be set for each

entity.account[“name”] = “Fourth Coffee”;

// Create an account record named Fourth Coffee.

_accountId = _service.Create(account);

Console.Write(“{0} {1} created, “, account.LogicalName, account.Attributes[“name”]);

// Create a column set to define which attributes should be

retrieved.ColumnSet attributes = new ColumnSet(new string[] { “name”, “ownerid” });

// Retrieve the account and its name and ownerid

attributes.account = _service.Retrieve(account.LogicalName, _accountId, attributes);

Console.Write(“retrieved, “);

// Update the postal code

attribute.account[“address1_postalcode”] = “98052”;

// The address 2 postal code was set accidentally, so set it to null.account[“address2_postalcode”] = null;

// Shows use of Money.

account[“revenue”] = new Money(5000000);

// Shows use of

boolean.account[“creditonhold”] = false;

// Update the account.

_service.Update(account);Console.WriteLine(“and updated.”);

 RetrieveMultiple :

RetrieveMultiple runs a Query against CRM, normally a QueryExpression is used that defines the entity logicalname, the conditions of the query and the columns (attributes) you want to retrieve.

It returns always an EntityCollection object and the Entities property contains the list of the records that satisfy the query conditions, so you can have 0, 1 or n records returned.

Retrieves a collection of entity instances based on the specified query criteria.

  1. The ColumnSet specified within the QueryExpression can only include the objects of the type of the calling entity.
  2. This method will return the result as a BusinessEntityCollection.
  3. (Multiple records of an a Single entity).Use this method to retrieve one or more entity instances based on criteria specified in the QueryExpression.

Syntax :

public BusinessEntityCollection RetrieveMultiple(

QueryBase  query

);

Parameters

query

Specifies either a QueryExpression or a QueryByAttribute object derived from the QueryBase class. This is the query to be executed for an entity.

The QueryExpression or QueryByAttribute object contains the type information for the entity.

Return Value: A BusinessEntityCollection that is a collection of entities of the type of specified in the query parameter.

 Remarks

Use this method to retrieve one or more entity instances based on criteria specified in the QueryExpression. For better performance, use this method instead of using the Execute method with the RetrieveMultiple message.

To perform this action, the caller must have access rights on the entity instance specified in the request class.

For a list of required privileges, see Retrieve Privileges.

The ColumnSet specified within the QueryExpression can only include the objects of the type of the calling entity.

For more information, see Using ColumnSet.

Example :

 // Create the ColumnSet that indicates the properties to be retrieved.

ColumnSet cols = new ColumnSet();

// Set the properties of the ColumnSet.

cols.Attributes = new string [] {“fullname”, “contactid”};

// Create the ConditionExpression.

ConditionExpression condition = new ConditionExpression();

// Set the condition for the retrieval to be when the contact’s address’ city is Sammamish.

condition.AttributeName = “address1_city”;

condition.Operator = ConditionOperator. Like;

condition.Values = new string [] {“Sammamish”};

// Create the FilterExpression.

FilterExpression filter = new FilterExpression();

// Set the properties of the filter.

filter.FilterOperator = LogicalOperator.And;

filter.Conditions = new ConditionExpression[] {condition};

// Create the QueryExpression object.

QueryExpression query = new QueryExpression();

// Set the properties of the QueryExpression object.

query.EntityName = EntityName.contact.ToString();

query.ColumnSet = cols;

query.Criteria = filter;

// Retrieve the contacts.

BusinessEntityCollection contacts = service.RetrieveMultiple(query);

 Execute Method:

The Execute method executes business logic.

  • It returns a Response object and accepts a parameter as the input of the Request type.
  • You can use this method as a wildcard for all the other methods.
  • This means that you can create an Account by using this method because the class called CreateRequest derives from Request and can be used as the input parameter;
  • you receive a CreateResponse as the result.
  • The same happens for UpdateRequest, UpdateResponse, RetrieveRequest, and RetrieveResponse.
  • The Execute method executes a message that represents either a specialized method or specific business logic.
  •  This method is strongly typed.
  •  It is used to retrieve a single entity.
  • The return types will be a Business Entity.

 Syntax :

 public Response Execute(  Request  Request);

 Parameters :

Request

Specifies a specific Request instance.

Return Value

Returns an instance of a Response. You must cast the return value of the Execute method to the specific instance of the response that corresponds to the Request parameter.

Remarks

To perform this action, the caller must have the necessary privileges to the entity type specified in the request class. The caller must also have access rights on the entity instances specified in the request class.

Example :

 // Set up the CRM

Service.CrmAuthenticationToken token = new CrmAuthenticationToken();

// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory

authentication.token.AuthenticationType = 0;

token.OrganizationName = “AdventureWorksCycle”;

CrmService service = new CrmService();

service.Url = “http://<servername&gt;:port>/mscrmservices/2007/crmservice.asmx”;

service.CrmAuthenticationTokenValue = token;

service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the request

object.AddItemCampaignRequest add = new AddItemCampaignRequest();

// Set the properties of the request

object.add.CampaignId = campaignId;

add.EntityId = productId;

add.EntityName = EntityName.product;

// Execute the

request.AddItemCampaignResponse added = (AddItemCampaignResponse) service.Execute(add);

Fetch Method

Retrieves entity instances in XML format based on the specified query expressed in the FetchXML query language.

1. Use this method to execute a query expressed in the FetchXML query language
2. Results single or multiple entity
3. This method will return the resultant XML as a string.
4. Not strongly Typed

 Syntax :

public string Fetch(

string  fetchXml

);

Parameters :

fetchXml

Specifies a String that contains the fetch query string to be executed.

Return Value

Returns an XML String type that contains the results of the query.

Remarks

Use this method to execute a query expressed in the FetchXML query language.

To perform this action, the caller must have the Read privilege to the entity types being retrieved and access rights on the entity instances retrieved.

Example :

 // Set up the CRM

Service.CrmAuthenticationToken token = new CrmAuthenticationToken();

// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory

Authentication.token.AuthenticationType = 0;

token.OrganizationName = “AdventureWorksCycle”;

CrmService service = new CrmService();

service.Url = “http://<servername&gt;:<port>/mscrmservices/2007/crmservice.asmx”;

service.CrmAuthenticationTokenValue = token;

service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Retrieve all attributes for all accounts.

// Be aware that using all-attributes may adversely affect

// performance and cause unwanted cascading in subsequent

// updates. A best practice is to retrieve the least amount of

// data

required.string fetch1 = @”   <fetch mapping=””logical””>                  <entity name=””account””>                     <all-attributes/>                  </entity>               </fetch>”; // Fetch the results.String result1 = service.Fetch(fetch1); // Retrieve the name and account ID for all accounts where// the account owner’s last name is not Cannon.string fetch2 = @”<fetch mapping=””logical””>                  <entity name=””account””>                     <attribute name=””accountid””/>                     <attribute name=””name””/>                     <link-entity name=””systemuser”” to=””owninguser””>                        <filter type=””and””>                           <condition attribute=””lastname”” operator=””ne”” value=””Cannon””/>                        </filter>                     </link-entity>                  </entity>               </fetch>”;

// Fetch the results.

String result2 = service.Fetch(fetch2);

 Pre-Validate, Pre-Operation, Post-Operation :

In Microsoft Dynamics CRM 2011, plugins can be triggered to fire on a variety of messages (update, create, win etc).

However you can also specify when exactly the plugin will fire in relation to the given message.

Your choice is the following:

Pre-validation of the given message (pre-validation of a record deletion for example).

Pre-operation (pre-operation of a record update for example).

Post-operation (post-operation of a record create).
What trigger point you choose here can be very important, I will attempt to explain here when you should use each type:

Pre-Validation
Pre-Validation plugins run before the actual operation is validated within CRM and could allow the user to do such things as custom checks to determine if a record can be deleted at this point in time.
Basically the Pre-validation should allow your plugin to run outside the SQL transaction, so it runs before the form is validated.

Pre-Operation
Plugins that fire on this message tend to involve operations which could result in the updating of the target record itself before it is actually saved in the system.

The Pre-operation runs after validation and before the values are saved to the database

Post-Operation
Note, avoid using this mode if your plugin is going to be updating the current entity. This mode is best utilized when the plugin simply needs to reference the newly created record (but not actually update it) in order to perform further operations on other records in the system.  Problems can arise if you try to update the target entity in a post-op plugin, for example if you have a plugin that runs post-update of an entity and the same plugin updates the target entity, then an infinite loop will occur.

The Post-Operation operation plugin runs after the values have been inserted/changed in the database.

Event Stage name Stage number Description
Pre-Event Pre-validation 10 Stage in the pipeline for plug-ins that are to execute before the main system operation. Plug-ins registered in this stage may execute outside the database transaction.

Security Note
The pre-validation stage occurs prior to security checks being performed to verify the calling or logged on user has the correct permissions to perform the intended operation.
Pre-Event Pre-operation 20 Stage in the pipeline for plug-ins that are to execute before the main system operation. Plug-ins registered in this stage are executed within the database transaction.
Platform Core Operation MainOperation 30 In-transaction main operation of the system, such as create, update, delete, and so on. No custom plug-ins can be registered in this stage. For internal use only.
Post-Event Post-operation 40 Stage in the pipeline for plug-ins which are to execute after the main operation. Plug-ins registered in this stage are executed within the database transaction.

what is crmsvcutil exe?

Developer Extensions for Microsoft Dynamics CRM 2015 provides an extension to the CrmSvcUtil.exe command-line tool, called the Microsoft.Xrm.Client.CodeGeneration extension. 

Advanced Developer Extensions for Microsoft Dynamics CRM provides a command-line code generation tool called CrmSvcUtil.exe that is used to generate a data context class as well as data transfer objects (DTOs) for all Microsoft Dynamics CRM entities.

We use CrmSvcUtil to generate early bind classes in CRM2011. Also, we have an option to generate Organisation service context. The only problem is that it is a command line tool. We have to go to command prompt, type the command with required parameters and then move the generated file to our project. It is a bit annoying.
How to use CrmSvcUtil tool in Visual Studio. Here are the steps.

  1. In Visual Studio, create a new “Class Library” project as shown in the following screen shot
  2. Delete the class file “class1.cs” created by the Visual Studio.
  1. Add the following files to the project from SDK\Bin folder of CRM SDK.
  • CrmSvcUtil.exe
  • Microsoft.Crm.Sdk.Proxy.dll
  • Microsoft.Xrm.Sdk.dll
  1. Add an  application configuration file to the project and name it “CrmSvcUtil.exe.config”. This file will contain all the parameters we can pass to “CrmSvcUtil.exe”. The solution explorer will look like a following screen.
  2. Here is a list of all the parameters we can use with CrmSvcUtil.
  3. Add the following keys to CrmSvcUtil.exe.config file.

<?xml version=”1.0″ encoding=”utf-8″ ?>

<configuration>

<appSettings>

<add key=”url” value=”https://cdc.crm5.dynamics.com/XRMServices/2011/Organization.svc”/&gt;

<add key=”o” value=”CrmProxy.cs”/>

<add key=”u” value=”username@live.com”/>

<add key=”p” value=”password”/>

<add key=”servicecontextname” value=”XrmContext”/>

</appSettings>

</configuration>

  1. Now the interesting part, right click on project node and press properties.
  2. It will pop up a following dialog box. Click on the “Debug” tab
  3. Select “Start external program” and choose the CrmSvcUtil.exe, we added in step 3.
  4. Now choose the “Working directory” where you want the output file to go.
  5. Debug the code and it will come up with following screen.
  6. You can check the “Output Window” of  Visual Studio for the result. If everything goes smoothly, it will create “CrmProxy.cs” file in the folder selected in “Working directory” in step
  7. Include the “CrmProxy.cs” file into the project.
  8. Check the CrmProxy.cs, it will have all the crm entities classes and “XrmContext”.

Tips

You can add, remove and edit keys in CrmSvcUtil.exe.config to pass parameters to code generator tool.Try accessing the CRM through the browser before debugging, if you are working with CRM Online. You can add this project to any of your crm solution. Change the “Working directory” of the project to generate the CrmProxy file in a desired folder.

Life cycle of plug-in

Event Stage name Stage number Description
Pre-Event Pre-validation 10 Stage in the pipeline for plug-ins that are to execute before the main system operation. Plug-ins registered in this stage may execute outside the database transaction.

Security Note
The pre-validation stage occurs prior to security checks being performed to verify the calling or logged on user has the correct permissions to perform the intended operation.
Pre-Event Pre-operation 20 Stage in the pipeline for plug-ins that are to execute before the main system operation. Plug-ins registered in this stage are executed within the database transaction.
Platform Core Operation MainOperation 30 In-transaction main operation of the system, such as create, update, delete, and so on. No custom plug-ins can be registered in this stage. For internal use only.
Post-Event Post-operation 40 Stage in the pipeline for plug-ins which are to execute after the main operation. Plug-ins registered in this stage are executed within the database transaction.

 Difference between Secure / Unsecure Configuration of Plugin Registration tool 

Unsecure Configuration of

Plugin Registration tool in CRM 2011

Secure Configuration of Plugin

Registration tool in CRM 2011

 

 

Unsecure configuration information could be read by any user in CRM. Remember its public information (Eg: Parameter strings to be used in plugin could be supplied here)

The Secure Configuration information could be read only by CRM Administrators.(Eg: Restricted data from normal user could be supplied here)
Imagine that you include a plugin, plugin steps and activate them in a solution. Later solution was exported as Managed Solution to another environment. In this scenario, the supplied Unsecure configuration values would be available in the new environment.  

Imagine that you include a plugin, plugin steps and activate them in a solution. Later solution was exported as Managed Solution to another environment. In this scenario, the supplied Secure configuration  information would NOT be available in the new environment. The simple  reason behind this is to provide more security to the contents of Secure Configuration.

 What is Metadata?

 Microsoft Dynamics CRM 2015 and Microsoft Dynamics CRM Online uses a metadata driven architecture to provide the flexibility to create custom entities and additional system entity attributes.

All the information necessary for Microsoft Dynamics CRM server to operate is stored in the Microsoft Dynamics CRM metadata. This includes information about entities, attributes, relationships, and option sets.

Metadata object Description
Entity An entity is a container for data, similar to a table in a traditional database. Each entity contains a set of attributes. For Microsoft Dynamics CRM, there are a set of entities that exist when you first install. Some of these are customizable. In addition, you can create custom entities to contain business data.
Attribute An attribute is a container for a piece of data in an entity. Microsoft Dynamics CRM supports a wide variety of attribute types.
Relationship A relationship defines an association between two entities: one-to-many, many-to-one, many-to-many, and self-referential.
Option Set An option set defines a set of options provided for a picklist. Several picklist attributes may use a global option set so that the options they provide are always the same and can be maintained in one location.
Option An option is one of the values available in an option set. Each option in an option set has a unique integer value and an associated set of localized labels.

 Note: Want to know the quickest way to view CRM metadata? This short and sweet blog will show you how you how to you can use the Organization Data service’s $metadata option to generate a quick view of the CRM entities.

Simply navigate to System > Customization > Developer Resources to see the Organization Data service endpoint.

Click on the link and a new window will be displayed.

Append the /$metadata option at the end of the URL and hit Enter.

Registering and Deploying Plug-ins

 Registering and deploying plug-ins can be done using the plug-in registration tool.

  1. Connect to your organization.

If you have access to multiple organizations in the server, choose the one to connect to.

  1. Register a new assembly.
  2. Browse the assembly file, select Isolation Mode and specify where the assembly is stored.
  3. Next you’ll need to select the registered assembly. It can contain multiple plug-ins. Select the plugin you are adding steps to, and register one or more steps.
  4. Fill in the following information for the steps:

Message

Entity

Filtering Attributes if applicable. In above example, the plugin will only trigger for statecode or salesstagecode updates. Selecting the attributes will prevent plugin triggering accidentally or needlessly when unrelated field is updated.

Event Pipeline

Execution Mode

  1. Fill in the Unsecure Configuration/Secure Configuration sections.These sections can be used to pass configuration information to the plug-in, such as user credentials or URLs. The difference between secure and unsecure configuration is as follows:

Secure Configuration does not move with solutions. It has to be re-configured for each environment.

Secure Configuration can be viewed only by CRM administrators.

  1. If applicable, select step and register an image. Choose whether it’s a Pre Image or Post Image.

You’ll also need to select attributes that you would like to be contained within the image.

  1. After the plug-in and the steps have been registered, they can now be included in CRM solutions and deployed with unmanaged or managed solutions.

 DEPLOYING THE PLUGIN

Now you have finished writing the code, it’s time to deploy the plugin in CRM.  Your user will need to be a CRM Administrator.  If you are deploying plugins which are not in sandbox Isolation mode then you will also need to be a Deployment Administrator.

As I am deploying to CRM 2013 online then the plugin has to be only a CRM Administrator because the plugin has to be in sandbox isolation mode.

Right Click on CrmPackage

Press the Deploy button

You will either get an error or it will have worked.  Often when it has worked it will inform you the RegisterFile.crmregister file has changed, this is CRM 2013 Developer Toolkit updating the file with Guid’s for the plugins.

Check the plugin has been registered in the CRM organisation\database by looking at the CRM Explorer and checking in the Plug-in Assemblies section, you should see your new plugin highlighted in green

You can also check by opening your Solution and looking in the plugin assembles section.

Step by step plugin tutorial using Developer’s Toolkit

Install the developer’s toolkit.The Developer toolkit for Microsoft Dynamics CRM 2011 was released as part of UR5 SDK release and is available for download here.

  1. Create a new solution in CRM2011. I named my solution “CRM Plugin Solution”. This is optional but I would recommend you do that.
  2. Open Visual Studio 2010. Select File—New –Project. It will display new project templates dialog as shown in the screen sheet below
  3. Select “Dynamics CRM 2011 Package” project. This is also optional. You can go ahead and select “Dynamics CRM 2011 Plugin Library”, But then you cannot deploy the plugin straight from the Visual Studio. You have to use Plugin Registration tool to register the plugin. Enter the name of project/solution.
  4. VS studio will display following dialog.Enter you CRM 2011 server details.Select the solution name we created in step 1 and click ok
  5. Now right click on the solution and add “Dynamics CRM 2011 Plugin Library” project to the solution. The plugin project will already have a plugin.cs file.
  6. Now sign the plugin assembly. Right click on Plugin Project and select properties. Select Signing tab from left navigation of project property page. On the Signing tab, select the Sign the assembly check box and set the strong name key file of your choice.At a minimum, you must specify a new key file name. Do not protect your key file by using a password.
  7. If you cannot see the “CRM Explorer” window on the upper left side of the VS studio, click on View menu and select “CRM Explorer”.
  8. Now expand “Entities” Node. Right Click the entity on want to create the plugin for and select “Create Plugin”.
  9. It will display a following screen.It is equivalent to “Create Step” screen in plugin registration tool. The dialog will pick up the name of the entity and other information. Choose the message and the pipeline stage. You can also change of the Class attribute. Press Ok.
  10. It will create a .cs file with name mentioned in “Class” attribute in screen shot above. Double click on the class file(PostAccountCreate) and scroll down to following lines of code. You write your business logic here.
  11. protectedvoidExecutePostAccountCreate(LocalPluginContext localContext){      if(localContext ==null)      {          thrownewArgumentNullException(“localContext”);      }      // TODO: Implement your custom Plug-in business logic.

}

  1. The first thing you will do is to get the plugin context, CRMService instance and TracingService instance using localContext passed to the function. All these objects are defined in the built in plugin.cs class.
  2. IPluginExecutionContext context = localContext.PluginExecutionContext;IOrganizationService service = localContext.OrganizationService;

//ITracingService tracingService = localContext.TracingService;

  1. Here is code. It will check if the “account number” is null or empty and  create a task for a user to enter the account number.
  2. protectedvoidExecutePostAccountCreate(LocalPluginContext localContext){       if(localContext ==null)       {           thrownewArgumentNullException(“localContext”);       }           // TODO: Implement your custom Plug-in business logic.       // Obtain the execution context from the service provider.       IPluginExecutionContext context = localContext.PluginExecutionContext;       IOrganizationService service = localContext.OrganizationService;       //ITracingService tracingService = localContext.TracingService;               // The InputParameters collection contains all the data passed in the message request.       if(context.InputParameters.Contains(“Target”)&&       context.InputParameters[“Target”]isEntity)       {           // Obtain the target entity from the input parmameters.           Entity entity =(Entity)context.InputParameters[“Target”];                              //EntityReference pp = entity.GetAttributeValue(“primarycontactid”);           //tracingService.Trace(pp.LogicalName);                                                try           {               //check if the account number exist                   if(entity.Attributes.Contains(“accountnumber”)==false)               {                       //create a task                   Entity task =newEntity(“task”);                   task[“subject”]=”Account number is missing”;                   task[“regardingobjectid”]=newEntityReference(“account”,newGuid(context.OutputParameters[“id”].ToString()));                       //adding attribute using the add function                   // task[“description”] = “Account number is missng for the following account. Please enter the account number”;                   task.Attributes.Add(“description”,”Account number is missng for the following account. Please enter the account number”);                                              // Create the task in Microsoft Dynamics CRM.                   service.Create(task);                       }           }               catch(FaultException ex)           {               thrownewInvalidPluginExecutionException(“An error occurred in the plug-in.”, ex);           }           }

}

I also left few commented lines in the code to show “How to use tracingservice to write in trace log”. You will able to see the trace only if there is an error in the plugin.

  1. Now right click on CRM Package project we created in step 2 and select deploy. It will register the plugin assembly as well as step for the plugin. Click on CRM Explorer to check the deployed plugin as shown in the following screen shot.
  2. Create a new account and test the plugin.

Context.Depth

 Used by the platform for infinite loop prevention. In most cases, this property can be ignored.

Every time a running plug-in or Workflow issues a message request to the Web services that triggers another plug-in or Workflow to execute, the Depth property of the execution context is increased. If the depth property increments to its maximum value within the configured time limit, the platform considers this behavior an infinite loop and further plug-in or Workflow execution is aborted.

The maximum depth (8) and time limit (one hour) are configurable by the Microsoft Dynamics CRM administrator using the PowerShell command Set-CrmSetting. The setting is WorkflowSettings.MaxDepth.

   (or)

 This property is read only.

A plug-in can invoke a Web service call which causes another plug-in to executed, and so on. The system limits depth to a value of eight (8). After a depth of 8, an exception is thrown by the system to avoid an infinite loop.

Used for infinite loop prevention. In most cases, this property can be ignored.

context.Depth   :  It returns integer value.

Example:

  1. User clicks save on a form for an entity which has a plugin registered.  This plugin will have a Depth = 1.  The plugin logic creates an instance of another entity.
  2. The second entity has a plugin registered on the Create event and when fired from the about plugin during the update will get a Depth = 2.  If it was triggering directly from the form it would have a Depth of 1.
  3. Depth is specific to the context but not the message instance triggered.

What is Queue entity in MSCRM?

Queues are containers that hold activities and incidents (cases) in Microsoft Dynamics CRM 4. They make it easier for these entities to be moved around the system, handled and assigned to different individuals within the system.

A queue is a collection of unassigned cases and activities for an organization. You can move activities and incidents (cases) between queues using the Route message. Incidents can also be assigned to a queue by a workflow rule. There are three types of queues:

  • A public queue is created by the business unit to help organize where activities and cases should be routed. The business unit can add queues, delete queues, and update queues.
  • A private queue contains all items assigned to a user that they have not started working on yet. This queue is fixed and the user cannot delete it. Each user has a private queue.
  • A work in progress queue contains all items assigned to a user that they are currently working on. Each user has a work-in-progress queue. This queue is fixed and the user cannot change it.

 Queue is a holding place for work that needs to be done.

  1. Queue can be filled with cases to respond to or activities to complete.
  2. You might also be able to send leads, accounts, contacts or other records to queues.
  3. Queues improve dropping and sharing of work by making cases and activities to be available at some centralized place that everyone can access.
  4. Queue items are either assigned to you or to the team you are member of.
  5. After you select an item only you can work on it until you reset back to the queue or else assign someone else to work on.

 

Early binding and Late binding

Early Binding:
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
CrmSvcUtil.exe /url:http://crmwoifd/demo/XRMServices/2011&#8230;
After installing it we get GeneratedCode.cs through which we can write Early binding code.
Early binding which provides IntelliSense support and better code development after using of .NET technologies. For example we r writing code for account when we will write account. it will give all the field name and so on.

Compiler binds the objects to methods at the compile time.All the type checking will be done at compile time only. This is called early binding or static binding. Function overloading is example for early binding.

Late Binding:
Compiler binds the objects to methods at the runtime. All the type checking will be done at runtime rather than Compile time.This is called late binding or dynamic binding. Function overriding is example for 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 can lead to make mistakes while writing the code and get an error.

Performance issue:
The Late-binding has a good performance as compared to early binding bcoz late-binding process starts fast and remain constant throuhout the process but in the case of early binding the process starts slow and keep increasing its process speed but it never crosses the process speed of late binding as I read in Microsoft MSDN.

note : /out:GeneratedCode.cs /username:bill /password:p@ssword!

In early biniding we r able to download a proxy classes which is something like a service classes, when we r consuming the web sservices at that tym we r able to download WSDL files and proxy files which will automatically create the classes by the help of those classes we r able to write some coding that is early binding.
In Early binding which provides IntelliSense support and better code development after using of .NET technologies such as the .NET Framework Language-Integrated Query (LinQ). suppose we r writing code for account when we will write account. it will give all the field name and so on.

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.

we r defining the structure when we r executing the codes that tym it will validate for all the datatypes means all the checking will be done at runtime but in the case of early all the type checking and all it will done when we r building the application

 

 

 

Sample Console Application Using Service End Point-WhoAmIResponse

new_name —- Zipcode
new_owner1 —-Owner
new_firstname —FirstName
new_lastname —-Lastname
new_name —–Name
new_emailaddress —- Email Address
new_salary ——- Salary

new_iscontactcreatedbycrm
new_city
new_dateofbirth

/*using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm.Sdk;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Client;
using System.Configuration;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Client.Services;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Client;
*/
namespace Datatypes
{
class Program
{
private Guid _accountId;
static IOrganizationService _orgService;
static void Main(string[] args)
{

//String ConnectionString = ConfigurationManager.ConnectionStrings[“connection”].ToString();
//String[] appConfigEntity = ConfigurationManager.ConnectionStrings[“ConnectionString”].Split(‘,’);
//CrmServiceClient conn = new CrmServiceClient(ConfigurationManager.ConnectionStrings[“Connection”].ConnectionString);
////var connection = CrmConnection.Parse(“Url=crm url; Domain=org22ddaf0b; Username=yourusername; Password=yourpassword;”);
//_service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

//Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;
////SystemUser systemUser = (SystemUser)_service.Retrieve(“systemuser”, userid, new ColumnSet(new string[] { “firstname”, “lastname” }));
////Console.WriteLine(“Logged on user is {0} {1}.”, systemUser.FirstName, systemUser.LastName);
//Console.ReadLine();

 

//String ConnectionString = ConfigurationManager.ConnectionStrings[“Crm”].ToString();
//CrmConnection connection = CrmConnection.Parse(ConnectionString);
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = “chaitanya@mkkgroup.onmicrosoft.com”;
credentials.UserName.Password = “uday@KIRAN1188”;
Uri serviceUri = new Uri(“https://mkkgroup.api.crm8.dynamics.com/XRMServices/2011/Organization.svc&#8221;);
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
proxy.EnableProxyTypes();
_orgService = (IOrganizationService)proxy;
//OrganizationService _orgService = new OrganizationService(connection);

//Guid userid = ((WhoAmIResponse)_orgService.Execute(new WhoAmIRequest())).UserId;
Entity contact = new Entity();
contact.LogicalName = “contact”;
Console.WriteLine(“To Fill the Account details to create an account Press Enter”);
Console.ReadLine();
Console.WriteLine(“Press enter to give City”);
if (Console.ReadLine() == “Hyderabad”)
{
OptionSetValue obj = new OptionSetValue(Convert.ToInt32(100000000));
contact.Attributes[“new_city”] = obj;
}
Console.WriteLine(“Type yes if it is from crm or else no “);
if (Console.ReadLine() == “yes”)
{
contact.Attributes[“new_iscontactcreatedbycrm”] = true;
}
Console.WriteLine(“Enter First Name”);
contact.Attributes[“firstname”] = Console.ReadLine().ToString();
Console.WriteLine(“Enter Date of Birth”);
Console.ReadLine();
Console.WriteLine(“Enter Day”);
String Day = Console.ReadLine().ToString();
Console.WriteLine(“Enter Month”);
String Month = Console.ReadLine().ToString();
Console.WriteLine(“Enter Year”);
String Year = Console.ReadLine().ToString();
DateTime dob = new DateTime(Convert.ToInt32(Year), Convert.ToInt32(Month), Convert.ToInt32(Day));
contact.Attributes[“new_dateofbirth”] = dob;
_orgService.Create(contact);
}
}
}

MSCRM Tricky Questions

1) If there are three entities..when I am updating field of Opportunity then it will update field of account and when it is being updated then field of contact will be updated…How to achieve this requirement??

Ans– Using OOB workflow

2)If there are three fields in an entity then how to make searchable through all these fields in Quick Find??

Ans– Under Quick find view –> Add Find Columns (for searching) Under Quick find view –> Add view columns(For displaying)

3)If there are Sales Manager and salesman and there are 3 fields like Itemcost, selling price and revenue…and revenue is not visible for Salesman…if those two fields is updated then revenue will be updated….How to achieve it??

Hint— Impersonation

Ans– Need to login with Admin context means here Sales Manager In Plugin if we are using Impersonation means login with Admin’s context then we r able to  trigger the plugin for updating the revenue field based on Itemcost but still that revenue field will be not visible.
So I think write answer will be If revenue field is not visible then we can find this field in Advanced Find.

If data of revenue is not visible then we need to apply field level security on that field means remove field level security of that field for that user means for Salesman.

4)If there  is a entity named as Account and it has related contacts records…if parent account record will be deleted then all its child record is deleted but when parent record is assigned to another entity then child record will not assigned… How to achieve this??

Ans– In Configurable cascade There are six options like Assign, Share , Unshare, Delete, Reparent, Merge.

We need to select Configurable Cascading  For Assign — Cascade None For Delete — Cascade All

5)There are 2 entities Account and Contact.. if field of Account is updated then it will update the field of contact..For this I used Plugin and if it is not working properly then what is the  resolution step for it…For this I used OOB Workflow and if it is not working properly then what is the resolution step for it…
Ans — If it is On-premise we can resolve it from back-end means from Sql Server
Right answer will be “Trace Message”means We have used trace service 10 times or 12 times in the code (If it is Online MSCRM instance) then we r able to trace means where the code has problem means giving error. We can see the error in tracingService.Tracelog record.

We can find Tracelog record in “Settings –> Plugin Trace Log Entity”.
For enable trace logSettings –> Administration –> System Settings –> Customization tab –> Enable logging to plugin tracing Bu default it is off, we need to choose All or Exception.
Note : The contents of this trace log is only output when an exception is thrown in a plugin/workflow activity.

With CRM2015 Update 1 – you can turn on trace logging for ‘All’ in the Settings and this will write to the ‘Plugin Trace’ entity.
For On-premise Tracing service is automatically enabled and we need to use Fiddler in which it will be traced and it will show upper left side when we click the that line of code it will show the error at the lower right side in fiddler.Or we can see in EventViewer(Eventvwr for opening using Windows+R) regarding tracing.

There we can find about tracing in Application.

Ans

Suppose plugin is synchronous then it will give error instantly and suppose it is asynchronous then we will check system jobs–> logAfter seeing error I’ll go to dev anf ifx it and deploy to Production.

6) If some ribbon buttons is not working properly then what will be the resolution step??Ans : That error can be catched in Fiddler from there wwe can resolve it or we need to check SDK , beacuse there can be an error in SDK file.If it is not catched in Fiddler Secondly we can debug using F12 button and place breakpoint for finding error if the ribbon button is not OOB button.And if it is a OOB button then first we need to open that entity in SDK –> Resources, Beacuse SDK has all entities RibbonXml . So open that particular entityRibbonXml and go to that ribbon button and check which function is used for that ribbon button. Copy function of that ribbon button  and search it in Debugger after pressing F12 and place Breakpoint multiple times where this function is called.

Note: For OOB button, function is called multiple times but      For Custom button, function is called only one time.

7) Can we hide the  ribbon buttons??

Ans – Using Enable/Disable rules.

if any ribbon button is not visible unintentionally then we need to check Enable/Disable rule.

8)Can we hide the Entity?

Ans — yes, using security role.Create a user and then assign any role for example Salesperson .

After that go to salesperson security role and give none for all privilege for any entity suppose Invoices then Invoice entity will be not visible for that user.
Note: Whatever we do customization in MSCRM (whether it is done bu any user), it happens at Organization level not user level.
Note : Impersonation can be applied on Plugin and synchronous workflow.

9)If  email is not receiving what would be the resolution step?? How to resolve it??Ans — If email is not receiving and if we used Server Side Synchronization then go to Settings –> Email Configuration –>Mailboxes

Double click on that user or customer and then click on “Test and enable Mailbox”and if we get an error then only we can say what is the problem and we’ll fix it.
Same if we use Email Router means In Email Router also we will test Mailbox means test for incoming mails and after getting error we will fix it.

10)Have U ever worked on integration part of CRM??

Ans — No Integration of CRM means Data Migration of CRM
11) If a customer wants a new dashboard/Chart which is not available in MSCRM then how to create that dashboard/chart??

Ans — For Dashboard we need to edit DashboardXml file secondly we can create a web portal using ASP.Net but it is not recommended.For creating new dashboard which is not in CRM then Create a web-resource and insert a IFrame and give URL of any .rdl file(means for SQL Server report, Fetch-xml report etc). Then in this scenerio we can create a dashboard.

12)How to connect A CRM with .NET application??

13) A customer wants to introduce some visual cues to their Opportunity records. You have a requirement to create a web resource that simply changes it’s background colour , based on the rating of the opportunity

When the rating is ‘Cold’ it must display Blue

for ‘Warm’ it should display Orange

And for ‘Hot’ it needs to display Red.

Please detail how you would approach this requirements, what steps you would take to create the components, display in on the form and an outline of how you would provide colour coding based on a record’s value.

Using the Client Side SDK, how would you approach the following requirement

  • On the create of a new Case
  • A user selects a customer before saving the form.
  • Once this customer is selected
  • Autocomplete a lookup on the form “Last Raised Case”
  • This value should be set as the last case raised for the Customer.

Please describe / pseudocode as much detail as possible

Using the Client Side SDK, how would you validate the value held in a phone number attribute, when a user types in a new value, to ensure it is always formatted in a specific way?

(e.g.  +44 1234 567 890)

Which types of Entity images are available, for a plugin step registered on a post operation stage of the execution pipeline?

You have created a plugin which is registered In the Pre-operation stage, of the execution pipeline.

 

The Plugin Is triggered on Create of a new contact.

The Target of the create request, is the contact entity.

 

You have been asked to make a change to the plugin to include the following logic.

  • When the contact creates
  • Set a field named “new_needsassesment” to the value of ‘true’

 

Please describe or Pseudocode below, the basic steps you would take to meet this need.

Using the CRM SDK, specifically the RetrieveMultiple Request of the Organisation Service, you have a requirement to retrieve all contacts in the system where the parent Company is

“Adventure Works”.  Each of the contacts needs to be updated, setting the field DoNotSendEmail as ‘true’.

 

The Response of this retrieve Multiple contains over 500 contacts.

 

Describe (or pseudocode) the most efficient way to update all these accounts.

Include the SDK messages you would use to perform this task.

You have been asked to write a plugin, which Sends an email to the customer assigned to a case record, once the case is resolved. The Plugin needs to send email using an existing template that is setup in the system.

When Interacting with Dynamics CRM, What SDK Message would you use to close a Quote?

(The standard Quote Entity, provided as part of the sales module)

Important Points To remember In MSCRM

Xrm.Page.getControl(“WebResource_DescriptionHTML“).getObject().contentWindow.document.getElementById(“divId1“) or (“bodyId“).

Context– Change data captured

PostImage will give all fields value

Plugin

A plugin is run in the response to an execution pipeline event for which it is registered. The execution starts from Execute method and we pass an IServiceProvider object as a parameter , which contains a number of useful objects.

  • IpluginExecutionContext,
  • IOraganisationServiceFactory
  • ITracingService

The IPluginExecutionContext holds contextual information passed into a plugin.

This information is different for each type of plugin because it contains things like
Stage

  • primaryentityid
  • parentContextInputParameters (e.g. which holds the Target)

Defines the contextual information passed to a plug-in at run-time.

Contains information that describes the run-time environment that the plug-in is executing in, information related to the execution pipeline, and entity business information.
IpluginExecutionContext : is a runtime environment that executes plugin Due to this we r able to get all CRM Context and all input methods and we r able to retrieve them.
Access the Plugin Execution Context IPluginExecutionContext contains information that describes the run-time environment that the plug-in executes, information related to the execution pipeline, and entity business information.

The context is contained in the System.IServiceProvider parameter that is passed at run time to a plug-in through its Execute method.

// Obtain the execution context from the service provider.

IPluginExecutionContext context =

(IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

When a system event is fired that a plug-in is registered for, the system creates and populates the context and passes it to a plug-in through the previously mentioned classes and methods.

The execution context is passed to each registered plug-in in the pipeline when they are executed.
Note:Context contains the recently changed data.

To access the Microsoft Dynamics CRM organization service, it is required that plug-in code create an instance of the service through the ServiceProvider.GetService method.

// Obtain the organization service reference.

IOrganizationServiceFactory serviceFactory  =

(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

IOrganizationService service =

serviceFactory.CreateOrganizationService(context.UserId);

Note:
It is not decided by DEV team whether we will go for managed or Unmanaged solution it depends on agreement b/n the customer and the comapnyif we dont want to share our source code then we should use Managed solutionthere is R&D team who is providing Managed solution they dont want to share source code bcoz it is being used by many teams.In our application there are Onsite and off-shore team and I am a part of Off-shore team and On-site team implemented some business logic and developed a managed solution in order to not to share with off-shore team.example: Third party vendor like Power Objects who are providing us managed solution bcoz they dont want to share the source code.

 

JavaScript Terminology In MSCRM

1)Get the value from a CRM field

Xrm.Page.getAttribute(“CRM Field Schema Name”).getValue();

OR

Xrm.Page.data.entity.attributes.get(“—-“).getValue();

 

2)Set the value of a CRM Field

Xrm.Page.getAttribute(“—“).setValue(“MyValue”);

 

3) Hide/Show field

  1. Xrm.Page.ui.controls.get(fieldName).setVisible(false);
  2. Xrm.Page.ui.controls.get(fieldName).setVisible(true);

OR

Xrm.Page.getControl(“CRM field name”).setVisible(true);

 

4) Hide/Show a Tab/section (for Tab 5)

Xrm.Page.ui.tabs.get(5).SetVisible(false);

Xrm.Page.ui.tabs.get(5).SetVisible(true);

 

5) Disable/Enable field

  1. Xrm.Page.getControl(fieldName).setDisabled(true);
  2. Xrm.Page.getControl(fieldName).setDisabled(false);

OR

Xrm.Page.ui.controls.get(fieldname).setDisabled(true);

 

6) Set the required level

Xrm.Page.getAttribute(“CRM field name”).setRequiredLevel(“none”);

setRequiredLevel(“required”);

setRequiredLevel(“recommended”);

 

7)Get the selected value of Picklist

Xrm.Page.getAttribute(“CRM Field Name”).getSelectedOption().value;

Xrm.Page.getAttribute(“CRM Field Name”).getSelectedOption().text; — for Text

 

8)Call the onchange event of a field.

Xrm.Page.getAttribute(“CRM field name”).fireOnChange();

 

9) Set the focus to a field

Xrm.Page.getControl(“CRM field name”).setFocus(true);

 

10) Get Form Type

Xrm.Page.ui.getFormType();

 

11) Get Control Type

Xrm.Page.getControl(“CRM fieldname”).getControlType();

 

12) Stop an event on save event

event.returnValue=false;

 

13) Return array of strings of users security role GUIDs

Xrm.Page.context.getUserRoles()

14) Xrm.Page.getControl(“Webresourcename “).getObject. contentWindow. document. getElementByID(“divId1”)or (“bodyID”)  — For Accessing webresource HTML

 

15) a) Prevent the AutoSave.

function preventAutoSave(context)

{

Var onsave=context.getEventArgs();returns the event on which the script is currently running on

If(Xrm.page.getAttribute(“schema name”).getValue())

{

onsave.preventDefault();//Prevents the form from saving

}

}

b)Stop  the AutoSave Event

function  stopSave(context)

{

Var onsave=context.getEventArgs();returns the event on which the script is currently running on

If(onsave.getSaveMode==70) //  70 indicates Form Autosave Event

{

onsave.preventDefault();//Prevents the form from saving

}}

All Save 1
All Save and Close 2
All Save and New 59
All AutoSave 70
Activities Save as Completed 58
All Deactivate 5
     All Reactivate 6
User or Team owned entities Assign 47
Email (E-mail) Send 7
Lead Qualify 16
Lead Disqualify 15

 

 

 

16) Return array of strings of users security role GUIDs:

Xrm.Page.context.getUserRoles()

Original link here.

 

17) Get record GUID

var recordId = Xrm.Page.data.entity.getId()

var recordIdWithoutCurlyBraces = Xrm.Page.data.entity.getId().substring(1,37);

 

18) Get event source

var eventSource = executionContext.getEventSource(); // tick Pass execution context as first parameter

 

19) Get event source (fieldname)

var fieldName = executionContext.getEventSource().getName(); // tick Pass execution context as first parameter

 

20) Get event source (value)

var fieldValue= executionContext.getEventSource().getValue(); // tick Pass execution context as first parameter.

 

21) Set Lookup Value

What is lookup field?

A Lookup field type represents the relationship attribute on the related entity.

 

Required Attributes of lookup fields

id : The GUID of the item. Required for set.

name : The name of the item to be displayed. Required for set.

entityType : The entity name of the item. Required for set.

 

How to get values of a lookup field?
1

2

3

4

5

6

7

8

9

function getLookupDetails() {

var entityName, entityId, entityLabel, lookupFieldObject;

 

// parentaccountid is the lookup field name that we try to reach its values

lookupFieldObject = Xrm.Page.data.entity.attributes.get(‘parentaccountid’);

if (lookupFieldObject.getValue() != null) {

entityId = lookupFieldObject.getValue()[0].id;

entityName = lookupFieldObject.getValue()[0].name;

entityLabel = lookupFieldObject.getValue()[0]. entityType;

}

 

Get a lookup value
var lookup = new Array();
lookup = Xrm.Page.getAttribute(“attributename”).getValue();
if (lookup != null) {
var name = lookup[0].name;
var id = lookup[0].id;
var entityType = lookup[0].entityType;
}

Set a lookup value
var lookup = new Array();
lookup[0] = new Object();
lookup[0].id = recorid;
lookup[0].name = recordname;
lookup[0].entityType = entityname;
Xrm.Page.getAttribute(“attributename”).setValue(lookup);

 

How to set a lookup field value?

The function below sets new_teamid lookup field:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

function setLookupField() {

 

var lookupData = new Array();

var lookupItem = new Object();

//Set the GUID

lookupItem.id = myTeamId;

//Set the name

lookupItem.name = myTeamName;

lookupItem.entityType = “team”;

lookupData[0] = lookupItem;

 

//If existing value is empty, then set new value

var existingValue = Xrm.Page.getAttribute(“new_teamid”).getValue();

 

if (existingValue === null) {

Xrm.Page.getAttribute(“new_teamid”).setValue([{

id: myTeamId,

name: myTeamName,

entityType: “team”

}]);

} else {

return;

}

}

 

 

Xrm.Page.getAttribute(‘new_fieldid’).setValue([{ id: ‘guid’, name: fullName, entityType: ‘entityTypeName’}]);

OR

Xrm.Page.getAttribute(“attributename”).setValue([{ id: recorid, name: recordname, entityType: entityname}]);

Original link here.

 

22) Get CRM Form Type

 

  1. var FORM_TYPE_CREATE = 1;
  2. var FORM_TYPE_UPDATE = 2;
  3. var FORM_TYPE_READ_ONLY = 3;
  4. var FORM_TYPE_DISABLED = 4;
  5. var FORM_TYPE_QUICK_CREATE = 5;
  6. var FORM_TYPE_BULK_EDIT = 6;
  7. var formType = Xrm.Page.ui.getFormType();

if(formType == FORM_TYPE_CREATE) {

}

else{

}

23)A) How to grab the selected value from an option set?

var selectedOptionSet = Xrm.Page.getAttribute(“new_fieldname”);

alert(selectedOptionSet.getSelectedOption().text);   alert(selectedOptionSet.getSelectedOption().value);

B)How to grab all the values in the option set??

var options = Xrm.Page.getAttribute(‘new_country’).getOptions();

for (var i in options)

{

alert(‘value :’ + options[i].value);

alert(‘Text :’ + options[i].text);

}

use this code to loop through the options available within the option set and get the respective value and text of the options.

 

In this tutorial we will cover how to work with crm option set value (OptionSetValue) fields using javascript in Microsoft Dynamics CRM.

This article covers examples about:

  • How to get an Option by passing value?
  • How to get selected CRM Option Set Valueitem?
  • How to get selected value of an CRM Option Set Value?
  • How to get Text of an CRM Option Set Value?
  • How to set an CRM Option Set Value (by numeric value)?
  • How to set an CRM Option Set Value by Text?

 

How to get an Option by passing value?

The code below returns an Option object with text and value properties. value argument represents the numeric value of the optinonsetvalue field for searching the Option:

1 var myOption = Xrm.Page.getAttribute(“fieldname”).getOption(value);

 

How to get selected CRM Option Set Value item?

The code below returns the Option object with text and value properties:

1 var selectedOption = Xrm.Page.getAttribute(“fieldname”).getSelectedOption();

 

How to get selected value of an CRM Option Set Value?

The code below gives us the numeric value of selected OptionSetValue field:

1 var optionsetValue = Xrm.Page.getAttribute(“fieldname”).getValue();

 

How to get Text of an CRM Option Set Value?

The code below gives us the text of selected OptionSetValue field:

1 var optionsetText = Xrm.Page.getAttribute(“fieldname”).getText();

 

How to set an CRM Option Set Value (by numeric value)?

The code below helps us to set the value of OptionSetValue by a numeric value passed to the setValue function:

1 Xrm.Page.getAttribute(“fieldname”).setValue(value);

 

How to set an CRM Option Set Value by Text?

Actually we can’t set the selected item by text but we can search all options until we find the one whose text (label) is the same as one the one you have then get its value like below:

1

2

3

4

5

6

7

function setOptionSetValueByText(“fieldname”, optionText) {

var options = Xrm.Page.getAttribute(“fieldname”).getOptions();

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

if (options[i].text == optionText) {

Xrm.Page.getAttribute(“fieldname”).setValue(options[i].value);

}

}

}

 

6) getClient

Returns a value to indicate which client the script is executing in.

JScript

context.client.getClient()

Client Value
Browser Web
Outlook Outlook
Mobile Mobile

 

7) getClientState

Use this instead of the removed isOutlookOnline method.

Returns a value to indicate the state of the client.

JScript

context.client.getClientState()

Client Values returned
Web, Outlook, Mobile Online
Outlook, Mobile Offline

 

I have one situation, login user has multiple security roles, if the login user has permission for particular role, show some buttons/fields otherwise the hide buttons/fields.

It is not stright forward to find out the security role, Soi wrote one javascript to find out the security role.

Here i am checking the user has “Content Manager” security role or not.

varCMRole = CheckUserRole(“Content Manager”);
if (CMRole) {
//true to show buttons
} else {
//false to hide buttons
}
This function will get all the user’s security role Id, passing security role id to get the security role name. If it match, it is true otherwise false.

 

functionCheckUserRole(roleName) {
var currentUserRoles = Xrm.Page.context.getUserRoles();
for (vari = 0; i<currentUserRoles.length; i++) {
var userRoleId = currentUserRoles[i];
var userRoleName = GetRoleName(userRoleId);
if (userRoleName == roleName) {
return true;
}
}
return false;
}

 

 

1) Have you implemented MS CRM with ur ASP.NET ??1) Have you implemented MS CRM with ur ASP.NET ??

Ans: yes, I have created one console application for creating a record in Account Entity and also created an aspx page for creating a record in Custom entity.
2) Give me a real example in which you used Managed solution and Unmanaged Solution??

Ans: In our application used Unmanaged solution always and Managed solution like which is not editable like third party Power Object’s Power Packs. They implemented a solution which is not editable and it can be used from any1 anywhere.
3) Suppose there is an entity in which a field is there whose datatype is different from a field of another entity. Can U assign same value to both fields while fields are having different different datatypes and in different entities fields are using OOB functionality??Ans: No we cannot achieve it through OOB functionality. We can achieve it through Javascript using string object.
4 ) Diff b/n Secure Configuration & Unsecure Configuration??

Ans:

Unsecure Configuration/Secure Configuration sections. These sections can be used to pass configuration information to the plug-in, such as user credentials or URLs.Secure Configuration does not move with solutions. It has to be re-configured for each environment.

Secure Configuration can be viewed/read only by CRM administrators.(E.g.: Restricted data from normal user could be supplied here) the Secure Configuration is not passed to plugins running in the CRM Outlook Client.

Unsecure configuration information could be read by any user in CRM. Remember its public information (E.g.: Parameter strings to be used in plugin could be supplied here)“Unsecure” config data will be stored along with the Plugin ‘Step’ registration information (i.e., In SdkMessageProcessingStep entity)

“Secure” config data will be stored in a separate entity named “SdkMessageProcessingStepSecureConfig”

Note: Both “Secured & Unsecured” configuration data stored as “Plain text” in DB
5) If there is a a form in which U have implemented a web-resource like HTML and inside HTML there is a field and U need to access this field using Javascript how to access this field??

Ans: Xrm.Page.getControl(“WebResource_DescriptionHTML”).getObject().contentWindow.document.getElementById(“divId1”) or (“bodyId”).
6)If U r creating 1:N relationship from A to B then on which entity we need to create lookup field?

Ans– Suppose there is a relationship between Account and Contact in which contact has N relation so we need to give lookup on contact.

Example:

  • One Account can have many contacts then we need to give Lookup on contact entity.
  • One customer can have many cases so we need to give lookup on case entity.

7) If there is N:N relationship b/n account and contact then How N:N relationship will be displayed?

Ans

  1. Goto any entity like suppose I am going contact then go to Navigation bar and from there open Account it’ll show associated view inside it there is + sign there we can add contact bcoz an account can have many contacts and vice-versa.
  2. again do the same thing for account.

8) Give an real time example when to create Organisation level entity and User level         entity??

Ans–

  1. Organisation is nothing but consists of Master Data(Taxonomy Data, Baseline Data
  2. User/Team consists Transnational Data like Account, contact etc.
  3. Master doesn’t require Owner means for suppose Country, state, Pincode, Category, Product.
  4. No one can be owner of these fields so it is accessible throughout the Organisation means any user within this organisation can use it.
  5. There is no need to provide the security.Transactional data means which is owned by the User/Team.
  6. Note: Organisational entity doesn’t hv Owner field.
    entities are used to model and manage business data. Some common entities that most Dynamics CRM users are familiar with are Account, Case, Campaign, Contact, Lead, and Opportunity.
  7. Types of Enity in MSCRM
  8. There are three main types of entities: system, business, and custom.
  9. In Dynamics CRM, system entities handle internal processes such as workflows.
  10. It is important to note that system entities cannot be deleted or customized.
  11. Business entities are the default entities within Dynamics CRM which include Case, Account, and Opportunity.
  12. One of the most important elements in Microsoft Dynamics CRM is customization.
  13. Custom entities are those entities which we need to create as per the requirement.
    Ownership is a key factor in how entities work.
  14. In Microsoft Dynamics CRM, most entities have an owner, which is determined by the ownership type.
  15. There are four ownership types in CRM: organization, business, user, and none.
  16. Organization-owned entities can be accessed by an entire organization.
  17. These records cannot be assigned to an individual owner (or shared).
  18. Business-owned entities belong to a Business Unit, while user-owned entities are owned by one specific CRM user and typically contain customer-related data.
  19. Accounts, Contacts, and Cases are examples of user-owned entities.
  20. A few entities in Dynamics CRM have no ownership type.
  21. They are not owned by another entity.
  22. For example, the uom (unit-of-measure) and workflowlog (workflow log) entities are not owned by another entity.

9) Once entity is created which field we cannot modified after creation of entity??

Ans–

Ownership Define as an activity entity.

Display in Activity Menus BPF

Under Communication & Collaboration Feedback Notes(includes attachments) Activities Connections Knowledge management.
10) if there is two entity like Contact and lead and contacts hv firstname, lastname and Email-Id if these fields are there(means in Lead) then we need to prioritised the lead how to do these things using Javascript, Workflow or Plugin??

Ans– Simply we can achieve it through OOB workflowif contact.lastname=——– , contact.firstname=——– and contact.EmailId=——–then status in lead equal to High so on.
11)what is scope of entity in MS CRM??
12)why we are using Iplugin interface in Plugin and Code activity class in Workflow??Ans– This is designed by the Microsoft and we r application developer not core developer ..it is responsibility of Core Developer to develop the from the scratchWhatever is providing by Microsoft we r simply using it.
13)How Case is getting created through EDM Portal or HRWEB Portal??
14)Diff b/n BR 2013 & BR 2015??how did U use BR on entity level??

Ans — Refer : http://www.inogic.com/blog/2014/09/business-rule-updates-in-dynamics-crm-2015/

Diff b/n BR-2013 & BR-2015.In BR-2013

i.  Business rules in CRM 2013 execute only Client Side.

ii. Has no if…else if…else support hence need to develop multiple rules to achieve rich business logic, means Earlier we were only allowed to write an If condition. There was no scope to write the else part for the condition within the same business rule.

iii.Scope of BR is form (Just that form) level.
In BR-2015

i.  Business rules in CRM 2015 now execute Client Side and server side as well, means If business rule is created with scope as “Entity” then the business rules will execute server side.

This means that you do not need the CRM form for the rules to be executed.

It can also be executed when you do updates to a record programmatically similar to the concept of Workflows and Plugins.

ii. It has support for If-else condition.

iii.AND/OR support, But you can only use one of them in a single condition i.e you still cannot create complex conditions that use a combination of AND and OR conditions.

iv. Default Value — So it only sets the value if no value has been provided as an input. You can set default value without any conditions to make sure the field getsthe value specified.

v.  Scope of BR in now Entity( All forms & Server), All forms (All forms) and Specific form (Just that form) level.
Still limitation in BR-2015

i.  Complex conditions are still not supported… perhaps asking for too much 🙂

ii. Still unable to set the value as null  for/clear value of a field.

iii.It only allows for a single If.. Else.. condition. Complex nested if..else is still not supported.

iv. Unable to update fields of related entity i.e a field of the record that is set as the lookup for the current record (N:1).

How did U use BR on entity level??

Ans– https://adisys.wordpress.com/2014/12/15/crm2015businessrules/https://community.dynamics.com/crm/f/117/t/167757

15) If there are 5 fields and we are updating 2 fields through plugin. Now we want all the fields value updated value of those two field and value of other field also whose value are not updated then whether I need to use Post-Image or Context will contain those values??

Ans– Context — change/Updated/Modified data captured

Post-Image will give all fields value.
16) Difference b/n Managed and Unmanaged Solution??

Ans–

Managed solution can’t be customized, but can be uninstalled easily, so there is a risk of data loss if we remove the solutions then all the customization will be removed.We can’t export managed solution.
Unmanaged solution can be customized, we can’t remove the components by uninstalling the solution, the solution acts as a container for the components means if we delete the solution the components still exist in the default solution.We can export the unmanaged solution.
Note: It is not decided by DEV team whether we will go for managed or Unmanaged solution it depends on agreement b/n the customer and the company.If we don’t want to share our source code then we should use Managed solution.There is R&D team who is providing Managed solution they don’t want to share source code bcoz it is being used by many teams.In our application there are Onsite and off-shore team and I am a part of Off-shore team and On-site team implemented some business logic and developed a managed solution in order to not to share with off-shore team.Example: Third party vendor like Power Objects who are providing us managed solution bcoz they don’t want to share the source code.
17)How to debug plugin??

Ans — Plugin using Developer tools
Debugging Plugins:

1) Plugin Profiler (Both online and on premise)

2) Remote Debugging (On premise)

Steps

Plugin Profiler (Both online and on premise)

Step1 : Go To plugin registration tool ->

Step2: click on “Install profiler” which installs the plugin profiler–

Step3: select the step on which we got an error and click on “Start Profiling” which makes the step as “(Profiled)”

Step4:– Now repeat the same process in CRM.

Step5: Download the error file and save it.

Step6: Again go to  plugin registration tool and click on replay plug-in execution and select the downloaded error file– select the registered assembly

Step7: Go To Visual Studio and place the debugger in the code  -> click on tools -> Attach to Process -> Select Plug-in registration tool -> click Attach– After attaching go back to plugin registration tool and click on Start Execution

Step8: End
18) Diff b/n Plugin & Workflow??

Ans

  1. Workflows can only be triggered online
  2. Workflows have limited messages which is  triggered.
  3. Mostly these would be your basic create/update/delete/assign/state change.
  4. Plugins support different event execution pipelines.
  5. Workflows are always post operation.
  6. Workflow can be executed on-demand but plugin doesn’t.
  7. There is a Time limit in plugin means it is restricted to complete its execution within a 2 minute time limit but Workflows well for either short or long processes.
  8. Workflow support only one level of Hierarchy for example if there is an entity named Account and we are creating/Updating Account Entity record then it will create/Update the related contact entity and then product entity record will be created or updated.
  9. This requirement we can achieve through workflow but when we r updating or creating Account Entity and directly we r updating or creating product entity then workflow will not work. In this case we will use plugin.

19) Shared variable in plugins?

Shared Variables are used to pass variables/information from one plugin to another plugin registered on different stages but in the same transaction (the same message on the same record)

e.g. a pre-event plugin can pass information to a   post-event plugin.
20) Types of Relationships

Ans : There are three main types of relationships we can create in Dynamics CRM:

One to Many (for example “One Employer has many Employees”),

Many to Many (for example “Many Students can attend Many Courses”), and

Many to One (for example “Many Employees are employed by One Employer”).

The type of relationship you choose depends on internal rules within your business.

Type of relationship

Parental vs Referential Relationships

In a Parental Relationship, anything done to the parent record is also done to related records.

For example, if an Account is deleted all related Contacts for that Account are also deleted.

In a Referential Relationship, actions performed on the parent record do not affect related records.

The link between the parent and related records is simply removed.

When you have a One to Many relationship where a custom entity is the primary entity and a system entity is the related entity, the relationship type can only be referential.

For example:

if you have a custom entity called “Office” which has many Contacts and you delete the Office record, the related Contacts will not be deleted.

The link between the Office and its Contacts will be removed.

Native or Manual?

There are two types of Many to Many relationships:

Native and Manual.

The main difference between the two is that a when you create a Native Many to Many relationship,an intersect entity (Intermediate Entity) is automatically created for us.

For example, when you create a new Many to Many relationship between a “Course” entity and the “Contact” entity,an intersect entity will be created which has links to both the Course and Contact records.

This intersect entity cannot be customized and is not available on the CRM UI.

A Manual Many to Many relationship is actually two One to Many relationships.

In this case, you actually create the intersect entity yourself.

For example: to create a Manual Many to Many relationship between a “Course” and “Contact” entity:

1. Create a new “Course Attendee” entity in CRM.

2. Create a new One to Many Relationship from “Course” to “Course Attendee”.

3. Create a new One to Many Relationship from “Contact” to “Course Attendee”.

The advantage of a Manual Many to Many relationship is that we can customize the intersect entity to track attendance information which can then be available within workflows.

For example,

we can an Attended and Date Attended field to the “Course Attendee” entity so we can track if a particular Contact attended a Course.

If the Course spans over multiple time periods, we can also track the date that the Contact attended the Course.
Note:  There is a Native N:N relationship between Marketing List and Contact.

Due to this the intermediate entity that joins Contact with Marketing List entity is not available on the CRM UI.

Self-Referential Relationships

Self-Referential relationships allow you to create complex relationships between two records of the same entity type.

For example, you might want to link a User to another User so you can easily track employee hierarchies in CRM.

However, you cannot link a record to itself.

When defining relationships within your organization, it’s important to understand the types of relationships to use. In my next post, I will cover cascading rules in Microsoft Dynamics CRM.

Note:

Monitoring real-time workflows and actions–Real-time workflows and actions do not use System Job records because they occur immediately.

Any errors that occur will be displayed to the user in the application with the heading Business Process Error.
There is no log for successful operations.

You can enable logging for errors by checking the Keep Logs for workflow jobs that encountered errors option in the Workflow Log Retention area at the bottom of the Administration tab for the process.
To view the log of errors for a specific process, open the real-time workflow or action definition and go to the Process Session tab.

This will only show any errors logged for this process.
If you want a view of all the errors for any process, go to Advanced Find and create a view showing errors on the process session entity.

Diff 2015 & 2016

  1. In the case of BR, in 2016 the UI for BR is completely different and one ribbon button validate is added which is not in previous version.
  2. In Dynamics 365, in Customization section , customize the system, Publishers, Themes, Solutions are not showing .
  3. First go to security–> users–>select user–>Click on Promote to Admin…then only we can see all options.
  4. Interactive Service Hub
  5. Excel Integration
  6. Voice of the Customer Surveys
  7. The survey designer will include radio buttons, tick boxes, star ratings and smiley face satisfaction options to cater for virtually any survey type. – See more at:
  8. Invoke Business Rules by Process Flows
    Business Rules and Business Process Flows were added to Dynamics in CRM 2013 but previously these haven’t work too closely in tandem.
  9. For example, for requirements to invoke a form action (e.g. set a field as mandatory) when a Business Process Flow is set, or when a stage is reached these requirements would require custom code.
  10. With the release of CRM 2016 standard Business Rules can now handle this process. Let’s says you have two Business Process Flows for a lead entity that reflect different products, Product A is sold exclusively to the domestic marketing and Product B is sold worldwide.
  11. The form contains a field called ‘Exporter’ which is hidden by default as most sales are domestic and the default process flow is for Product A.
  12. However, when the international business process flow is selected the ‘Exporter’ field should be visible and set as a mandatory field.
  13. Thanks to Business Rule ‘Conditions’ this process can now be applied using the inbuilt functionality of CRM 2016 without the need to resort to external development. –
  14. Bulk Data Loader Now we can import or export large groups of data using the new CRM Online Bulk Loader will enable this data to be uploaded to a staging area where basic data changes

How to set value of a read only field using JavaScript Same only means

Xrm.Page.getAttribute(“Schema name”).set Value(“value”);

Regarding WEBAPI OData  version 3.0 Web API version 4.0 Create  —- PostRetrive —- GetUpdate —– Patch/put but we used patchDelete  —- delete

In WebAPI every request comes into JSon Format.

When we are using POST then we need to create an object.
How to implement On-fly form in CRM

form.

http://www.nalashaa.com/composite-controls-features-customization-dynamics-crm-2015/https://www.codeproject.com/articles/1032318/improve-user-experience-by-styling-and-coloring-mihttp://www.inogic.com/blog/2015/01/simplified-process-to-add-new-records-on-the-fly-in-dynamics-crm-2015/
********************************************How to register custom workflow in plugin registration tool************************

At which scenario you will use Custom workflow and Plugin?

Ans: The Main purpose of Creating custom work flow is to update or change the value of field item before save activity

3.What are the Plugin Pipeline Stages?
Ans:

Pipeline Stages:

Event Pipeline Stages are 4, in which we can register plugin in 3 Stages.
Stages

Synchronous vs. Asynchronous Plug-ins

Synchronous plug-ins are executed by the CRM Core System.

  • Synchronous execution means that triggering event will wait until the plug-in finishes the execution.
  • For example, if we have synchronous plug-in that triggers on the creation of account and user creates account record in CRM, the form will hang at save until the plugin has finished.

Asynchronous plug-ins are executed by asynchronous service.

  • Asynchronous plug-ins allow triggering event to finish before plug-in code runs.
  • Therefore these can never be used to prevent an action, validate data entry, or provide any error messages back to the user.

Plug-in vs. Processes

These are very similar, in fact workflows are just a skin on an asynchronous system plug-in.

The main differences:

  • Workflows can only be triggered asynchronously
  • Workflows can only be triggered online
  • Workflows have limited triggers. Mostly these would be your basic create/update/delete/assign/state change
  • Plugins support different event execution pipelines.
  • Workflows are always post operation.
  • Workflow execution logic can be easily modified, this allows encapsulation of code in custom workflow activity while still retaining possibility of frequent changes on execution logic by non-programmers.

How will you test your plugin code?

Ans: Unit Testing Plugins using Microsoft Fakes

If you are integrating third party application into CRM how will you authenticate Users?

OAuth /Odata and Single signOn
What is Pre-and Post-operations in Plugin?

  • Pre validation means you plugin will run before the form is validated
  • Pre -operation is after validation and before the values are saved to the database
  • Post operation is your plugin will run after the values have been inserted/changed on the database

7.what is WEBAPI? Why we need it?
8.What are the relationship behaviour types?
10.What is the difference between managed and unmanaged solution.
11.Explain in brief Sales Module.
12.How to integrate crm web applications.
13.Pre-validation and preoperation with scenarios
14.What is ODATA? how will form odata urls for select and conditions?
15. What is BPF? why to use?
16.Difference b/w Javascript and Business Rules?
17. How will create Security Roles?
18.Have you worked on Azure?
19.How can we use SSIS to data intigration?
20.what are the customizations you did in crm for your project?
21.what are the end points available in crm?
22.I have two workflows, one is sync and another one async. both are triggering on creating an account entity.
Both Tasks are

When an account record is created automatically task should be create

But
Sync workflow email filed dont have data account record should not create?
Am creation an account without email data?
Now how many tasks it will creating?
23.How to assign a security role to access team?
24.I have synchronous on post operation plugin and real time workflow on creating a record? Which will trigger first?

How to return values from CRM custom workflow?

 

Yes this is possible in a Custom Workflow Activity using Output ParametersThis blog post is useful.

In your C# code, outside of the Execute() function, define an Output Parameter like this:

[Output("Account Name")]
public OutArgument<string> AccountName { get; set; }

Then in your code (that executes within the Execute() function, set the value of your Output Parameter (in this case AccountName) like this:

AccountName.Set(executionContext, "account name"); Replace the "account name" string as appropriate.

Then in your workflow, every step after the step where you have called your custom step will have access to Account Name.

How to retrieve data using JavaScript?

Only query will change for different type of retrieve. Below are the different retrieve queries.

1. Retrieve top 1 record

var query = “/api/data/v8.0/accounts?$select=name&$top=1”

2. Retrieve records with lookup condition like records owned bay a user.

var query = “/api/data/v8.0/accounts? $select=name,accountnumber,_primarycontactid_value,createdon,accountcategorycode,revenue&$filter=_ownerid_value eq (212626EE-54B9-4E99-93F9-0BF5FDCA3481)”

3. Retrieve accounts whose name starts with B or C.

var query =”accounts?$filter=startswith(name,’B’) or startswith(name,’C’)”

4. Retrieve related entity attributes.

var query =”/api/data/v8.0/accounts(B14CC863-07E3-E511-80EE-3863BB2E4DE0)?$select=name,accountnumber,_primarycontactid_value,createdon,accountcategorycode,revenue&$orderby=name&$expand=primarycontactid($select=fullname,telephone1,email)”

Below is the sample java script code for retrieving record in CRM using java script.

CRM web API with java script

function retrieveRecord() {
var clientURL = Xrm.Page.context.getClientUrl();
var req = new XMLHttpRequest()
var query = “/api/data/v8.0/accounts?$select=name&$top=1”;
req.open(“GET”, encodeURI(clientURL + query), true);
req.setRequestHeader(“Accept”, “application/json”);
req.setRequestHeader(“Content-Type”, “application/json;charset=utf-8”);
req.setRequestHeader(“OData-MaxVersion”, “4.0”);
req.setRequestHeader(“OData-Version”, “4.0”);
req.onreadystatechange = function () {
if (this.readyState == 4) {
req.onreadystatechange = null;
if (this.status == 200) {
var data = JSON.parse(this.response);
if (data && data.value) {
for (var indxAccounts = 0; indxAccounts < data.value.length; indxAccounts++) {
var accountName = data.value[indxAccounts].name;
var eTag = data.value[indxAccounts][‘@odata.etag’];
}
}
}
else {
var error = JSON.parse(this.response).error;
alert(“Error retrieving Accounts – ” + error.message);
}
}
};
req.send(null);
}

Have you implemented MS CRM with ur ASP.NET ??

Ans: yes, I have created one console application for creating a record in Account Entityand also created an aspx page for creating a record in Custom entity.
Give me a real example in which you used Managed solution and Unmanaged Solution??Ans: In our application used Unmanaged solution always and Managed solution like which is not editable like third party Power Object’s Power Packs. They implemented a solution which is not editable and it can be used from any1 anywhere.

3) Suppose there is an entity in which a field is there whose datatype is different from a field of another entity. Can U assign same value to both fields while fields are having different different datatypes and in different entities fields are using OOB functionality??Ans: No we cannot achieve it through OOB functionality. We can achieve it through Javascript using string object.

4 ) Diff b/n Secure Configuration & Unsecure Configuration??Ans:Unsecure Configuration/Secure Configuration sections. These sections can be used to pass configuration information to the plug-in, such as user credentials or URLs.Secure Configuration does not move with solutions. It has to be re-configured for each environment.Secure Configuration can be viewed/read only by CRM administrators.(E.g.: Restricted data from normal user could be supplied here) the Secure Configuration is not passed to plugins running in the CRM Outlook Client.Unsecure configuration information could be read by any user in CRM. Remember its public information (E.g.: Parameter strings to be used in plugin could be supplied here)“Unsecure” config data will be stored along with the Plugin ‘Step’ registration information (i.e., In SdkMessageProcessingStep entity)“Secure” config data will be stored in a separate entity named “SdkMessageProcessingStepSecureConfig”Note: Both “Secured & Unsecured” configuration data stored as “Plain text” in DB

5) If there ia a form in which U have implemented a web-resource like HTML and inside HTML there is a field and U need to access this field using Javascript how to access this field??Ans: Xrm.Page.getControl(“WebResource_DescriptionHTML”).getObject().contentWindow.document.getElementById(“divId1”) or (“bodyId”).

6)If U r creating 1:N relationship from A to B then on which entity we need to create lookup field?Ans– Suppose there is a relationship between Account and Contact in which contact has N relation so we need to give lookup on contact.Example: One Account can have many contacts then we need to give Lookup on contact entity.One customer can have many cases so we need to give lookup on case entity.

7)If there is N:N relationship b/n account and contact then How N:N relationship will be displayed?Ans– Goto any entity like suppose I am going contact then go to Navigation bar and from there open Account it’ll show associated view inside it there is + sign there we can add contact bcoz an account can have many contacts and vice-versa. again do the same thing for account.

8)Give an real time example when to create Organisation level entity and User level entity??Ans— Organisation is nothing but consists of Master Data(Taxonomy Data, Baseline Data) and User/Team consists Transactional Data like Account, contact etc.Master doesn’t require Owner means for suppose Country, state, Pincode, Category, Product. No one can be owner of these fields so it is accessible throughout the Organisation means any user within this organisation can use it. There is no need to provide the security.Transactional data means which is owned by the User/Team.Note: Organisational entity doesn’t hv Owner field.
entities are used to model and manage business data. Some common entities that most Dynamics CRM users are familiar with are Account, Case, Campaign, Contact, Lead, and Opportunity. Types of Enity in MSCRMThere are three main types of entities: system, business, and custom. In Dynamics CRM, system entities handle internal processes such as workflows. It is important to note that system entities cannot be deleted or customized. Business entities are the default entities within Dynamics CRM which include Case, Account, and Opportunity. One of the most important elements in Microsoft Dynamics CRM is customization. Custom entities are those entities which we need to create as per the requirement.
Ownership is a key factor in how entities work. In Microsoft Dynamics CRM, most entities have an owner, which is determined by the ownership type. There are four ownership types in CRM: organization, business, user, and none. Organization-owned entities can be accessed by an entire organization. These records cannot be assigned to an individual owner (or shared). Business-owned entities belong to a Business Unit, while user-owned entities are owned by one specific CRM user and typically contain customer-related data. Accounts, Contacts, and Cases are examples of user-owned entities. A few entities in Dynamics CRM have no ownership type. They are not owned by another entity. For example, the uom (unit-of-measure) and workflowlog (workflow log) entities are not owned by another entity.

9)Once entity is created which field we cannot modified after creation of entity??Ans– Ownership Define as an activity entity. Display in Activity Menus BPFUnder Communication & Collaboration Feedback Notes(includes attachments) Activities Connections Knowledge management.

10)if there is two entity like Contact and lead and contacts hv firstname, lastname and Email-Id if these fields are there(means in Lead) then we need to prioritised the lead how to do these things using Javascript, Workflow or Plugin??And– Simply we can achieve it through OOB workflowif contact.lastname=——– , contact.firstname=——– and contact.EmailId=——–then status in lead equal to High so on.

11)what is scope of entity in MS CRM??

12)why we are using Iplugin interface in Plugin and Code activity class in Workflow??Ans– This is designed by the Microsoft and we r application developer not core developer ..it is responsibility of Core Developer to develop the from the scratchWhatever is providing by Microsoft we r simply using it.

13)How Case is getting created through EDM Portal or HRWEB Portal??

14)Diff b/n BR 2013 & BR 2015??how did U use BR on entity level??Ans — http://www.inogic.com/blog/2014/09/business-rule-updates-in-dynamics-crm-2015/
Diff b/n BR-2013 & BR-2015.In BR-2013i.  Business rules in CRM 2013 execute only Client Side.ii. Has no if…else if…else support hence need to develop multiple rules to achieve rich business logic, means Earlier we were only allowed to write an If condition. There was no scope to write the else part for the condition within the same business rule. iii.Scope of BR is form (Just that form) level.
In BR-2015i.  Business rules in CRM 2015 now execute Client Side and server side as well, means If business rule is created with scope as “Entity” then the business rules will execute server side.This means that you do not need the CRM form for the rules to be executed. It can also be executed when you do updates to a record programmaticallysimilar to the concept of Workflows and Plugins.ii. It has support for If-else condition.iii.AND/OR support, But you can only use one of them in a single condition i.e you still cannot create complex conditions that use a combination of AND and OR conditions.iv. Default Value — So it only sets the value if no value has been provided as an input. You can set default value without any conditions to make sure the field getsthe value specified.v.  Scope of BR in now Entity( All forms & Server), All forms (All forms) and Specific form (Just that form) level.
Still limitation in BR-2015i.  Complex conditions are still not supported… perhaps asking for too much :)ii. Still unable to set the value as null  for/clear value of a field.iii.It only allows for a single If.. Else.. condition. Complex nested if..else is still not supported.iv. Unable to update fields of related entity i.e a field of the record that is set as the lookup for the current record (N:1).
How did U use BR on entity level??Ans– https://adisys.wordpress.com/2014/12/15/crm2015businessrules/https://community.dynamics.com/crm/f/117/t/167757

 

15) If there are 5 fields and we are updating 2 fields through plugin. Now we want all the fields value updated value of those two field and value of other field also whose value are not updated then whether I need to use Post-Image or Context will contain those values??Ans– Context — change data capturedPost-Image will give all fields value.

16)Difference b/n Managed and Unmanaged Solution??Ans– Managed solution can’t be customized, but can be uninstalled easily, so there is a risk of data loss if we remove the solutions then all the customization will be removed.We can’t export managed solution.
Unmanaged solution can be customized, we can’t remove the components by uninstalling the solution, the solution acts as a container for the components means if we delete the solution the components still exist in the default solution.We can export the unmanaged solution.
Note: It is not decided by DEV team whether we will go for managed or Unmanaged solution it depends on agreement b/n the customer and the company.If we don’t want to share our source code then we should use Managed solution.There is R&D team who is providing Managed solution they don’t want to share source code bcoz it is being used by many teams.In our application there are Onsite and off-shore team and I am a part of Off-shore team and On-site team implemented some business logic and developed a managed solution in order to not to share with off-shore team.Example: Third party vendor like Power Objects who are providing us managed solution bcoz they don’t want to share the source code.

17)How to debug plugin??Ans — Plugin using Developer tools:—————————–
Debugging Plugins:——————1) Plugin Profiler (Both online and onpremise)2) Remote Debugging (Onpremise)

 

 

 

Shared variable in plugins?

Shared Variables are used to pass variables/information from one plugin to another plugin registered on different stages but in the same transaction (the same message on the same record) e.g. a pre-event plugin can pass information to a   post-event plugin.

 

For theory
Note: Monitoring real-time workflows and actions Real-time workflows and actions do not use System Job records because they occur immediately. Any errors that occur will be displayed to the user in the application with the heading Business Process Error.
There is no log for successful operations. You can enable logging for errors by checking the Keep Logs for workflow jobs that encountered errors option in the Workflow Log Retention area at the bottom of the Administration tab for the process.
To view the log of errors for a specific process, open the real-time workflow or action definition and go to the Process Session tab. This will only show any errors logged for this process.
If you want a view of all the errors for any process, go to Advanced Find and create a view showing errors on the process session entity.
Diff b/n Fetch Xml reports & Sql Reports

Using Business Rule we can achieve Recommendation

Lock/Unlock the field Hide/Show the fieldSet Field valueSet required levelset

Default value Show Error Message

1)In the case of BR, in 2016 the UI for BR is completely different and one ribbon button validate is added which is not in previous version.

2)In Dynamics 365, in Customization section ,, customize the system, Pulishers, Themes, Solutions are not showing …. first go to security–> users–>select user–>Click on Promote to Admin…then only we can see all options.

3)Interactive Service Hub

4)Excel Integration

5)Voice of the Customer

Surveys The survey designer will include radio buttons, tick boxes, star ratings and smiley face satisfaction options to cater for virtually any survey type. – See more at:

Invoke Business Rules by Process Flows

Business Rules and Business Process Flows were added to Dynamics in CRM 2013 but previously these haven’t work too closely in tandem. For example, for requirements to invoke a form action (e.g. set a field as mandatory) when a Business Process Flow is set, or when a stage is reached these requirements would require custom code. With the release of CRM 2016 standard Business Rules can now handle this process. Let’s says you have two Business Process Flows for a lead entity that reflect different products, Product A is sold exclusively to the domestic marketing and Product B is sold worldwide. The form contains a field called ‘Exporter’ which is hidden by default as most sales are domestic and the default process flow is for Product A. However, when the international business process flow is selected the ‘Exporter’ field should be visible and set as a mandatory field. Thanks to Business Rule ‘Conditions’ this process can now be applied using the inbuilt functionality of CRM 2016 without the need to resort to external development.

Bulk Data Loader Now we can import or export large groups of data using the new CRM Online Bulk Loader will enable this data to be uploaded to a staging area where basic data changes can be applied.

 

 

 

 

REST – Retrieve Example

REST CRUD (Create, Read, Update and Delete) Operations:

Initial Setup:

Download the Latest SDK.

For CRUD Operations, get the following Script files from the path

SDK\SampleCode\JS\RESTEndpoint\JavaScriptRESTDataOperations\JavaScriptRESTDataOperations\Scripts

Initial Setup

Create two JScript Web Resources

SDK Rest Webresource

Create a JScript Web Resource for CRUD Operations,

SDK Operations JScript

Retrieve Example:

Syntax: SDK.REST.retrieveRecord(id, type, select, expand, successCallback, errorCallback) 

Name Type Description
id String A String representing the GUID value for the record to retrieve.
type String The Schema Name of the Entity type record to retrieve.
select String A String representing the $select OData System Query Option to control which attributes will be returned. This is a comma separated list of Attribute names that are valid for retrieve.
If null all properties for the record will be returned
expand String A String representing the $expand OData System Query Option value to control which related records are also returned. This is a comma separated list of up to 6 entity relationship names
If null no expanded related records will be returned.
successCallback Function The function that will be passed through and be called by a successful response.
This function must accept the returned record as a parameter.
errorCallback Function The function that will be passed through and be called by a failed response.
This function must accept an Error object as a parameter.

 Task:Get the Contact details based on Contact Guid using Retrieve Method

Solution: Add the below Script in “new_sdkOperations” Webresource for Retrieving Contact details based on “ContactId”,

function retrieveContact(ContactId) {
SDK.REST.retrieveRecord(ContactId, "Contact", null, null, getDetails, errorHandler);
}

function getDetails(contact) {
alert("Full Name : "+ contact.FullName + "\n" +
"Company Name : " + contact.ParentCustomerId.Name + "\n" +
"Guid : " + contact.ContactId +"\n" +
"Preferred Method of Contact : " + contact.PreferredContactMethodCode.Value +"\n" +
"Bulk Email : " + contact.DoNotBulkEMail +"\n"+
"Birthday : " + contact.BirthDate
);
}

function errorHandler(error) {
alert(error.message);
}

Save and Publish the Web Resource “new_sdkOperations”.

Add the 3 Web Resources in Contact Entity as follows,

Webresources on Contact Form

Add OnLoad event, Library: new_sdkOperations &function retrieveContact

Attach Onload Event

Pass the Existing Contact Guid as a Parameter to test the function,

Pass Contact Parameter to Form

Save and Publish the entity. Open any record to get the below alert.

Final Output