Total Pageviews

Thursday, 21 April 2016

Generate Early Bound Class for specific entities

Generate Early Bound Class for specific entities:

As a crm developer we need to write plug-in, workflows, console application for migration purpose. Writing the code is not a matter but while executing the code we may get some field miss spelling issues or before writing the code we need to waste our time to get the details of fields in order to work properly . These things may waste the time . To save the time MS team has given the feature to generate the ear ly bound classes for each entity.

Using these early bound classes we may not get the error’s like misspelling field names and also it provides the intelligence.

But while generating early bound classes crm will generate all the classes for all entities , it may cause increase the class file size.

To overcome this i am goanna show you how to generate the early bound classes only for specific entities.

Step 1: 

Create one Class Library project and add CrmSvcUtil.exe(which will find in Crm Sdk) as References.

Step 2: 

Add the below class to the project which you created recently.

using System;
using System.Collections.Generic;
using System.Xml.Linq;
using Microsoft.Crm.Services.Utility;
using Microsoft.Xrm.Sdk.Metadata;

namespace GenerateSpecificEntityClasses
{
    public class CodeWriterFilter : ICodeWriterFilterService
    {
        //list of entity names to generate classes for.
        private HashSet<string> _validEntities = new HashSet<string>();

        //reference to the default service.
        private ICodeWriterFilterService _defaultService = null;

        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="defaultService">default implementation</param>
        public CodeWriterFilter(ICodeWriterFilterService defaultService)
        {
            this._defaultService = defaultService;
            LoadFilterData();
        }

        /// <summary>
        /// loads the entity filter data from the filter.xml file
        /// </summary>
        private void LoadFilterData()
        {
            XElement xml = XElement.Load("filter.xml");
            XElement entitiesElement = xml.Element("entities");
            foreach (XElement entityElement in entitiesElement.Elements("entity"))
            {
                _validEntities.Add(entityElement.Value.ToLowerInvariant());
            }
        }

        /// <summary>
        /// /Use filter entity list to determine if the entity class should be generated.
        /// </summary>
        public bool GenerateEntity(EntityMetadata entityMetadata, IServiceProvider services)
        {
            return (_validEntities.Contains(entityMetadata.LogicalName.ToLowerInvariant()));
        }

        //All other methods just use default implementation:

        public bool GenerateAttribute(AttributeMetadata attributeMetadata, IServiceProvider services)
        {
            return _defaultService.GenerateAttribute(attributeMetadata, services);
        }

        public bool GenerateOption(OptionMetadata optionMetadata, IServiceProvider services)
        {
            return _defaultService.GenerateOption(optionMetadata, services);
        }

        public bool GenerateOptionSet(OptionSetMetadataBase optionSetMetadata, IServiceProvider services)
        {
            return _defaultService.GenerateOptionSet(optionSetMetadata, services);
        }

        public bool GenerateRelationship(RelationshipMetadataBase relationshipMetadata, EntityMetadata otherEntityMetadata, IServiceProvider services)
        {
            return _defaultService.GenerateRelationship(relationshipMetadata, otherEntityMetadata, services);
        }

        public bool GenerateServiceContext(IServiceProvider services)
        {
            return _defaultService.GenerateServiceContext(services);
        }
    }
}

Step 3:
For now I just want to be able to determine which entities are generated, so in the constructor I read from an XML file (filter.xml) that holds the list of entities to generate and put the list in a Hashset.  The format of the xml is this:

<filter>
  <entities>
    <entity>systemuser</entity>
    <entity>team</entity>
    <entity>role</entity>
    <entity>businessunit</entity>
  </entities>
</filter>
Note:create xml file and give the name what ever you wish . but that name should pass in above method LoadFilterData()  
In above Xml file i just given four entities you can include as many entities as you want.

Take a look at the methods in the class. In the GenerateEntity method, we can simply check the EntityMetadata parameter against our list of valid entities and return true if it's an entity that we want to generate.

For all of the other methods we want to just do whatever the default implementation of the utility is.  Notice how the constructor of the class accepts a defaultService parameter.  We can just save a reference to this default service and use it whenever we want to stick with the default behavior.  All of the other methods in the class just call the default service.

To use our extension when running the utility, we just have to make sure the compiled DLL and the filter.xml file are in the same folder as CrmSvcUtil.exe, and set the /codewriterfilter command-line argument when running the utility (as described in the 
SDK):
Step 4:
Now we have class library project and xml file . All we have to do is build the project and copy the xml file and paste it in bin folder of project which we compiled now.
Step 5:
Now we need to run the CrmSvcUtil.exe as
Open command prompt and change the directory to the class project library bin->debug folder and execte the command as like :
CrmSvcUtil.exe  /url:<Url>    /out:<OutputFileName>.cs /username:<UserName> /password:<password> /namespace:<Nampespace> /serviceContextName:<servicecontext> /codewriterfilter:<ClasslibraryProjectNameSpace>.<ClassName>,<ClasslibraryProjectNameSpace>

That’s all we have to generate the early bound classes .



Monday, 14 March 2016

Get the Assembly or DLL from online MS CRM using c#

How to get plug-in DLL from online CRM?

For suppose in online CRM getting a issue from one plug-in and you need to solve that issue. If have source code we can easily solve it but if you don’t have source code then what you will do?

If it is in on premise CRM easily we can get the DLL content from PluginAssemblyBase table and convert that content to bytes and save it to your local disk and using .NET Reflector you can decompile the DLL.

we can get the dll using solution like create new solution , add plug-in to it and can export the solution. From that solution we can get the dll , suppose if you don't have the permission of create solution and export solution then how will do? At this situation we can get the dll using c# code as :

Using c# code we can get the DLL content and save that file to local disk from there you can decompile the DLL using .NET Reflector.

C# Code to get DLL content from Online CRM is:
ServerConnection conn = new ServerConnection();
            OrganizationServiceProxy service = ServerConnection.GetOrganizationProxy(conn.GetServerConfiguration());
           
            QueryExpression query = new QueryExpression();
            query.EntityName = "pluginassembly";
            query.ColumnSet = new ColumnSet(true);
            query.Criteria.AddCondition (new ConditionExpression ("pluginassemblyid", ConditionOperator.Equal, new Guid ("a02b8de6-9551-479f-94c1-aa552ea30e87")));
            EntityCollection coll = service.RetrieveMultiple (query);

You can get the plug-in id from the registration tool
After retrieving the plug-in save the content to local folder:
byte[] data = Convert.FromBase64String (coll.Entities[0]["content"].ToString());
            FileStream fs = new FileStream("C:\\Kranthi\\" + coll.Entities[0]["name"].ToString()+".dll", FileMode.Create, FileAccess.ReadWrite);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(data);
            bw.Close();

by using above code you can save the DLL into your local folder.

Export the solution using c# code from MS CRM

Hi friends ,

Today i was surprised , when i am trying to export  unmanaged solution not able to get the solution file from crm. I tried with chrome , firefox and ie but no result. i tried to export the solution so many times but solution not exported and other side client is waiting for the solution , think once if u people have the same situation what you will do ? of course at this situation may have some tense , some frustration.

At last i exported the solution successfully . How ?

With the help of c# code .

 public static void ExportSolution(OrganizationServiceProxy service)
        {
            ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest();
            //here i am exporting solution as unmanaged , if you want to export as managed means put true.
            exportSolutionRequest.Managed = false;
            //give solution unique name
            exportSolutionRequest.SolutionName = "DllSol";

            ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)service.Execute(exportSolutionRequest);

            byte[] exportXml = exportSolutionResponse.ExportSolutionFile;
            string filename = "DllSol.zip";
//give path where the solkution file need to store
            System.IO.File.WriteAllBytes(@"C:\Kranthi\" + filename, exportXml);
        }

using this peace of code i exported the solution.


Workflow Customization's in MS CRM

Workflow Customization’s

Workflow is the one of the interesting feature in ms crm to automate the business processes. It’s easy to configure even non developers also configure the workflow’s.

Workflow’s are limited to do only some operations and also cannot do bulk operations means if we want to update 10 contacts when parent account is updated at this situation we cannot use system workflow. Need developer to write custom workflow.

Before 2013 only two types of workflows are there

1.       Workflow

2.       Dialog

From 2013 version two more processes are added

1.       Business Process Flow

2.       Actions

Workflow Configuration and its options:

1.       Go to Settings->Processes

2.       Click on new will open window

Above Screen have the options need to fill:

    Process Name: Name of the process

    Category: Select work flow category.

    Entity: On which entity need to configure the workflow.

   Type: This option tells that do you want to create a new empty workflow or do you want to create a workflow with existing template.

  After filling these details click on ok button. Then will open another window that is
 

In above screen we can see basic information filled in previous information and have additional settings need to configure. Here i am taken an example to create post on account wall when contact is created to an account.

To achieve this i did some configuration and will look into each option in deep.
Below the basic information of workflow have a tab called Available To Run in this tab have three check box options

1.       Run this workflow in the background (recommended)

This option allow us to set whether the workflow to run background or to run in real time .From 2013 version this option available. If we want to convert the workflow to real time workflow need to click on button “Convert to Real Time Workflow” on top of workflow, we cannot directly modify this option because it is read-only.

2.       As on-demand process

This option allows us to trigger workflow on demand or automatically .If we select this option workflow will trigger in on-demand and if not workflow will trigger automatically through code or through some other workflow.

3.       As a child process

If we select this option workflow is available as child workflow with in another workflow.

Keep logs for workflow jobs that encountered errors: if we select this option it will keep the error log details when exception occurred.

Scope: This is a dropdown control having four options
1.      User: If we select this option Workflow will execute only the user who is created
2.      Business-Unit: If we select this option workflow will execute for all the user’s who ever in that business unit. Other business unit user’s cannot execute this workflow.
3.      Parent-Child Business Unit: If we select this option the user’s who ever in parent business unit and child business unit can execute workflow.
4.      Organization : If we select this option all user’s in a organization can execute workflow.

Have the options need to select when workflow should trigger:
From 2013 version new options are introduced if we set workflow as real time workflow those options are :
We can configure the workflow to start before and after the core operation and we can select whether the workflow want to execute only for the owner of the workflow or the user who made changes to the record.

Now i am going to create a step for create a post on account entity show as below.
Click on set properties to set fields
Save and close and activate the workflow.

Testing:
First i am creating sample account with name as “Kranthi”.
In above only one post is there. Now i am going to create contact and attach to this account then automatically one post is created on account wall says that “Contact is created check the details”
Above screen contact is created and attached to Kranthi account. Now again go to Kranthi account record and will check what’s happened.

Above screen can see new post automatically created by workflow.

Use of plug-in in ms crm

Use of plug-in's :-

Every day we will use plug-in's but actually we can not concentrate on the questions like why use plug-in ? 

Plug-in's are very use full in ms crm to do some of the operations automatically when we are doing some other works. For example need to go update the account record having exact count value of its related contact records when contact is added to it or removed from it.

So plug-in's will work as triggers like as triggers in sql , when one operation is completed it will automated and performed another work.

When to use plug-in's , scripts and workflows :-

This question keeps on strike on so many developers while working , we can achieve the same task with different ways like using script, using plug-in's,using workflow's.Need to choose correct way to solve the problem, of course its complicated.But if we have some idea about all these concepts we can easily choose the correct path. I am trying to give little bit information which i know.

Script :- 

Basically script is useful to validate the client side data like field validation,show/hide fields,show/hide tabs and sections. Don't try to use plug-in's here .
scripts can be use when work with ribbon customization for enable/disable rules , display rules and click events.
scripts also can use if we want to update or create few related records when parent record is created or updated.We can do update or create huge records also but it may affect on performance.its not recommended.
scripts can use to trigger workflows and plug-ins when ribbon button clicked or on load of form or on change of field on form
scripts can use to open html dialogs when click on buttons.
scripts can use when developing the custom html pages..

Plug-in :- 

Mostly plug-in's  can be used when we want to perform some bulk operations before and after events 
Plug-in's can be used to update or create related records when parent record is updated or created or deleted.
Plug-in's can use for 1-N ,N-1 and N-N relationship.

Workflows :-

workflows are usefull to perform some events with out need of custom code like sending email,change status,create or update records.
workflows can only work N-1 relationship means we can not perform the update of all related records when parent record is updated.we can only do if child record is updated then we can update the parent record.
if we want to perform updation to all child records when parent is updated need to write custom workflow.
workflow's have the advantage is can call child workflow's .
workflow's can be used to schedule the process to run at particular time on daily bases or monthly or yearly .This thing we can not do in plug-in's.
.




Plug-in Customization in MS CRM

Plug-in Customization’s:-

Plug-in: Plug-in is a custom business logic used to extend the standard functionality of Microsoft Dynamics CRM. For Example if we want to do operations after creation or updating of record or before deletion of record we can use plug-inn’s to extend the operations.

Plug-inn’s can be written and compiled in .net framework and deploy in ms crm database using plug-in registration tool or by using code or by deploying manually in case of on premise crm.

Plug-in Registration steps:-

1.       Write a plug-in code and compile code.

2.      Open registration tool and connect to organization.

3.       Register a new assembly.



When click on Register New Assembly will pop up a window is


In above screen can see multiple options like Specify Isolation Mode , Specify the location where the assembly should stored.

Specify Isolation Mode
1 Sandbox: Sandbox mode is fully secure means it won’t allow third party dll’s.For online crm must and should register plug-inn in sandbox mode only.

2 None: This mode can allow third party dll’s also, basically we can use this option in On Premise or IFD crm’s .If the plug-in using any third party dll then those dll’s also need to deploy in server bin/assembly folder then only plug-in work properly.

Specify the Location where the Assembly is stored

Database: Dll will store in database. Its default option and it’s a strongly recommended to select database while register plug-in because it’s easy to move dll from one environment to other.

Disk: if we select Disk option dll will store in bin/assembly folder. if we use this option we need to manually copy and paste the dll while moving solution one environment to other. Because while moving solution actually dll is not stored in database, just it stores the information where the plug-in is stored those information only moved to another environment. While executing crm tries to load the plug-in using the path but it couldn’t find because there is no plug-in in that location. So need to copy and paste the dll manually.

GAC: This mode also works same as disk but dll is stored in GAC folder in crm server.

4.  Next need to select the registered assembly. It can contain multiple plug-ins. Select the plug-in you are adding steps to, and register one or more steps.
In above screen we have multiple options need to fill in order to create a plug-in step:

Message: when we type in this field it auto populate the message names. It represents on which message to register event.

Primary Entity: It allows selecting entity on which plug-in step will be registered.

Secondary Entity: In 4.0 version this option is used while registering a plug-in on 
associate/dissociate messages. Now this option is deprecated but still we can use.

Filtering Attributes: this option allows to user to select the fields, and it represents that plug-in will fire only these fields are changed.

Run in User’s Context: this option used to execute the plug-in on behalf of other user not on logged in user.

Execution Order: if we have two plug inn’s on same message we can set the execution order so that crm will execute the plug inn’s in that order only.

Event Execution Pipeline:

Pre Validation: Plug inn’s get executed prior to the form validation.
It is use full when we need to capture the deleting records, means some scenarios we cannot capture the deleting records data even in pre operation also. For example if take parental cascade behaviour if we delete parent record then all its child records also deleted. Now the requirement is need to capture the child records while the parent record is deleting. In this scenarios we can use pre validation plug inn’s.
Pre Validation plug inns execute outside transaction means if something went wrong while executing plug-in it won’t roll back.

Pre Operation: plug inn’s get executed before the data is saved to database. These are within database transaction only.

Post Operation: plug inn’s get execute after the data is saved to database.
Execution Mode

Synchronous: Plug inn’s execute immediately and it will show impact on performance because synchronous plug inn’s runs on same crm main process.untill plug inn execution is completed it won’t allow the user to do other operation’s.

Asynchronous: Plug inns are moved to queue and will execute later. it will not affect the performance because these plug inn’s execute under different processes.
5 that’s all we have done the registration of plug inn then go to crm and create or update the record to run a plug inn.