Wednesday, March 6, 2013

Apply the run-time filter on top of the security privilege in MS CRM 2011



Apply the run-time filter conditions on top of the security privilege to filter/remove/hide the entity records.

Create a plugin which will trigger on pre (stage) of retrievemultiple (plugin message) of the entity.
Context will return you the Query object which will have entity name and the Query expression details. you can append your filter conditions to query expression to filter the records for the entity.

Below please find the complete Plugin code.
It will trigger on load of every CRM view, so always check the entity name in the plugin and apply the appropriate logic.


public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));            
            
             if (context.Mode == 0 && context.Stage == 20 && context.MessageName.Equals("RetrieveMultiple"))
            
                if (context.InputParameters.Contains("Query"))
                {
                    if (context.InputParameters["Query"] is QueryExpression)
                    {
                        QueryExpression objQueryExpression = (QueryExpression)context.InputParameters["Query"];
                        
                        if (objQueryExpression.EntityName == "product")
                        {
                            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                            service = serviceFactory.CreateOrganizationService(context.UserId);
                            ConditionExpression privateFlagCondition;
                            string SaleType = string.Empty;
                            string role = string.Empty;

                            role = getUserRole(context.UserId);
                            if (role.Contains("Sales"))
                            {
                                privateFlagCondition = new ConditionExpression()
                                {
                                    AttributeName = "statustype",
                                    Operator = ConditionOperator.Equal,
                                    Values = { "1" }
                                };                                
                            }
                            

                            FilterExpression newFilter = new FilterExpression()
                            {
                                FilterOperator = LogicalOperator.Or,
                                Conditions = { privateFlagCondition }
                            };

                            objQueryExpression.Criteria.AddFilter(newFilter);
                        }

                    }
                }
            }
        }