Tuesday, 6 May 2014

Fire a Workflow in Dynamics CRM 2011 using C#

The following is a code sample that calls two methods: GetWorkflowId and ExecuteWorkFlow to run Workflow Programatically either C# or Plug-In :


One important thing to note is that the workflow we are executing must be marked as an on-demand or child workflow; otherwise you will receive an error below.

"Workflow must be marked as On Demand or Child Workflow"


 public void Execute(IServiceProvider serviceProvider)
        {
            // Get Workflow or Process Id
            // "Test_WF"  = Workflow Name
            // "workflow" = Process Schema name
            // "incident" = Entity Name on which workflow will run
            // "false"    = either workflow must be 'ondemand' or 'child workflow'
            //  1         = indicate Type of workflow 1-Activate, 2- Draft

            Guid processId = GetProcessId(service, "workflow", "Test_WF","incident",false,1).Id;


            // Execute Workflow or Process
            ExecuteWorkFlow(service, processId, new Guid("BF2184E0-51D4-E311-A7B2-7427EA0AF460"));
           

        }



 private Entity GetProcessId(IOrganizationService service,string Process,string WorkflowName,string EntityName,bool IsOnDemand,int Type)

                        //Internal method used to search for entity records
                        {
                     
                        QueryExpression query = new QueryExpression(Process);

                        query.ColumnSet = new ColumnSet(true);

                        query.Criteria.AddCondition(new ConditionExpression("name", ConditionOperator.Equal, WorkflowName));

                        query.Criteria.AddCondition(new ConditionExpression("type", ConditionOperator.Equal, Type));

                        query.Criteria.AddCondition(new ConditionExpression("primaryentity", ConditionOperator.Equal, EntityName));

                        query.Criteria.AddCondition(new ConditionExpression("ondemand", ConditionOperator.Equal, IsOnDemand));

                        try

                        {

                        EntityCollection response = service.RetrieveMultiple(query);

                        if (response != null && response.Entities.Count > 0)

                        return response.Entities[0];

                        else { return null; }

                        }

                        catch (Exception ex)

                        {

                        //Do error handling

                        throw ex;

                        }

                   }
          }





private void ExecuteWorkFlow(IOrganizationService service, Guid workFlowId, Guid entityId)
        {
            try
            {

                // Create an ExecuteWorkflow request.

                ExecuteWorkflowRequest request = new ExecuteWorkflowRequest()
                {

                    WorkflowId = workFlowId,

                    EntityId = entityId,

                };

                // Execute the workflow.

                ExecuteWorkflowResponse response =

                (ExecuteWorkflowResponse)service.Execute(request);

            }

            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException();
            }

        }


Cheerssss :)

Friday, 2 May 2014

Error - 'Solution File is Invalid' while importing Solution in MSCRM 2011

Today I was trying to import Contact Entity solution after done some changes in customization.xml and i found below error :

"Error while Importing a solution in CRM 2011 – The solution file is invalid. The compressed file must contain the following files at its root: solution.xml, customizations.xml, and [Content_Types].xml"



After spending a huge amount of time checking and rechecking my code, I was finally sure that the issue had to be somewhere else.

Problem Was - I was zipping up the solution folder, this then creates a zip file with a folder at the root and then the three solution files
Hosk Solution
[Content Types].xml
solution.xml
customizations.xml

What i was doing : 




Solution Is - What you have to do is select the three xml files and then zip them up.  This then doesn’t create the root folder. :)

What had to do : 



Cheerssssss :) :)

Thursday, 1 May 2014

Find vs Advanced Find in MSCRM

Which one is Faster FIND or ADVANCED FIND ?

Find :  Find perform a search on an attribute for which it is defined.
Advanced Find : Advanced Find perform search on the conditions and the attributes for which user customizes or runs it. 

Find : Normal Find is faster as it looks for one attribute and matches with that and returns the result
Advanced Find: Advanced Find searches for all the attributes and conditions while parsing through the records.

Find : Find is applicable on only active records and it finds only on 2 or 3 column which we have defined in the find view and even it returns any those column which is there in the view
Advanced Find : Advanced find is applicable to all the records and it finds all the columns and even it returns all the column and filter criteria can be on any column and most important

Find : Find filters on just one condition
Advanced Find : But adv find filters on multiple condition at one time.. 

So Find is faster than Advanced Find.


Significance of Secondary Entity in Plugin Registration Tool while Registering Plug-In in MSCRM

"Secondary Entity use when you have to trigger plugin or retrieve record from Intersect Entity(contactleads) having records of Entities(Contact and Lead) having N:N Relationship"

While using the Plugin Registration tool in Dynamics CRM, we might have rarely or even never used the ‘Secondary Entity’ field and almost always assigned it as ‘none’, but there are some scenarios where this field comes into play.



When is ‘Secondary Entity’ required

The following 2 messages require the ‘Secondary Entity’ to be specified while registering a step in Plugin registration:
  • SetRelated
  • RemoveRelated
These two methods were extensively used in Dynamics CRM 4.0, but they were deprecated from Dynamics CRM 2011 onwards; although you can still use them in 2011 and 2013.

What are the supported ‘Secondary Entities’

Following is the table depicting the out-of-the-box ‘Primary Entity’ and ‘Secondary Entity’ that are supported for both ‘SetRelated’ and ‘RemoveRelated’ messages:
Primary EntitySecondary EntitySupported Relationships
InvoiceContactcontactinvoices_association
LeadAccountaccountleads_association
LeadContactcontactleads_association
OpportunityAccountopportunity_customer_accounts
OpportunityContactopportunity_customer_contacts
OpportunityCompetitoropportunitycompetitors_associationor
ProductLeadleadproduct_association
ProductCompetitorcompetitorproduct_association
QuoteContactcontactquotes_association
SalesLiteratureCompetitorcompetitorsalesliterature_association
SalesLiteratureProductproductsalesliterature_association
SalesOrderContactcontactorders_association
You can also find this entire list in the Dynamics CRM SDK,

What does ‘SetRelated’ and ‘RemovedRelated’ do

These two messages are basically triggered when a primary entity record is associated/dissociated with/from the secondary entity record via the relationships supported, details of which are mentioned above. So, if you’re planning to execute some business logic on association of the above mentioned entities, you can register the plugin against the ‘SetRelated’ message. The ‘RemoveRelated’ works for dissociation of the entity records from each other.

From Dynamics CRM 2011 onwards, the ‘SetRelated’ and ‘RemoveRelated’ have been succeeded by the ‘Associate’ and ‘Disassociate’ messages respectively.


Tuesday, 29 April 2014

How to Debug Plugin in MSCRM 2011 On-Premise

The following steps describe how to debug a plug-in On-Premise :

Debug Synchronous Plugin in MSCRM 2011

  1.  First Build the Plug-in solution.
  2.   Register it on Plug-in registration tool
  3. While add assembly of Plug-in solution in PRT(Plugin Reg Tool), make sure “Disk” radio button must be checked and DLL of Plug-in should contain in “File Name In Server” text box.
  4. After Add assembly in PRT Copy .DLL and .PDB file of Plug-in from bin directory of our Plug-in.
  5. Paste both Copied file at below location :“C:\Program Files\Microsoft Dynamics CRM\Server\bin\assembly”
  6.  Go to Plug-in solution in Visual Studio 2012
  7. Add Debugger at specified location within code.
  8.  Attach process from Tools >Attach To Process > W3WP.exe > OK
  9.  Perform action for debugging Plug-in Solution
      
    Debug A-Synchronous Plugin in MSCRM 2011

            1   Firstly Build Plug-in solution
      2   Register it on Plug-in registration tool.
      3   Go to Plug-in solution in Visual Studio 2012
      4   Add Debugger at specified location within code.
      5   Attach process from 
                 Tools >Attach To Process >CrmAsyncService.exe(both) >OK
                6     Perform action for debugging Plug-in Solution









     



Plugin Assembly Table in MSCRM

One of my colleagues faced a situation where he had installed a plugin assembly into database but was not able to locate its DLL, and now he wanted to deploy it in some other server.

In MSCRM all plugins related information like its name, content, createdBy, createdOn. ModifiedBy, ModifiedOn etc store in PluginAssemblybase Table. You can get it by below Query result :
select * from PluginAssemblyBase
Below are some column description of PluginBaseTable :

Column Name
Description
Name
Store name of Plugin
Source Type     
Where the Plugin registered
       0 -      Database
       1 -      Disk
       2 -      GAC
content
Store content of DLL

These are the steps to get DLL from Content :

Get the encoded base 64 string representation of the plugin from PluginAssemblyBase table.

select name,content,*
from PluginAssemblyBase

Use that content and get the dll from the following site.


Set decode and export to binary file option there with filename having extension as .dll

Open the dll in the reflector tool and use the source code to build that assembly.


Monday, 28 April 2014

Clean Up AsyncOperation(System Jobs) Table to Improve CRM Performance.

Today i am going to explain SQL Procedure Steps to cleanup MSCRM AsyncOperation table :

Asynchronous Operation States :

State
Status
Numeric status value
Ready
WaitingForResources
0
Suspended
Waiting
10
Locked
InProgress
20
Locked
Pausing
21
Locked
Canceling
22
Completed
Succeeded
30
Completed
Failed
31
Completed
Canceled
32

Step 1 : Create Index on specific column of AsyncOperation Table
IF EXISTS (SELECT name from sys.indexes
WHERE name = N'CRM_AsyncOperation_CleanupCompleted')
DROP Index AsyncOperationBase.CRM_AsyncOperation_CleanupCompleted
GO
CREATE NONCLUSTERED INDEX CRM_AsyncOperation_CleanupCompleted
ON [dbo].[AsyncOperationBase] ([StatusCode],[StateCode],[OperationType])
GO

Step 2 : Delete all Succeeded, Failed and Canceled Jobs
declare @DeleteRowCount int
Select @DeleteRowCount = 2000
declare @DeletedAsyncRowsTable table (AsyncOperationId uniqueidentifier not null primary key)
declare @continue int, @rowCount int
select @continue = 1
while (@continue = 1)
begin
begin tran
insert into @DeletedAsyncRowsTable(AsyncOperationId)
Select top (@DeleteRowCount) AsyncOperationId from AsyncOperationBase
where OperationType in (1, 9, 12, 25, 27, 10) AND StateCode = 3 AND StatusCode in (30,31,32)
Select @rowCount = 0
Select @rowCount = count(*) from @DeletedAsyncRowsTable
select @continue = case when @rowCount <= 0 then 0 else 1 end
if (@continue = 1) begin
delete WorkflowLogBase from WorkflowLogBase W, @DeletedAsyncRowsTable d
where W.AsyncOperationId = d.AsyncOperationId
delete BulkDeleteFailureBase From BulkDeleteFailureBase B, @DeletedAsyncRowsTable d
where B.AsyncOperationId = d.AsyncOperationId
delete WorkflowWaitSubscriptionBase from WorkflowWaitSubscriptionBase WS, @DeletedAsyncRowsTable d
where WS.AsyncOperationId = d.AsyncOperationID
delete AsyncOperationBase From AsyncOperationBase A, @DeletedAsyncRowsTable d
where A.AsyncOperationId = d.AsyncOperationId
delete @DeletedAsyncRowsTable
end
commit
end

Step 3 : Drop the Index on AsyncOperation Table
DROP INDEX AsyncOperationBase.CRM_AsyncOperation_CleanupCompleted
Blogger Widgets