Search This Blog

Showing posts with label .CRM Plugin. Show all posts
Showing posts with label .CRM Plugin. Show all posts

Tuesday, March 5, 2019

In order to access security critical code, this assembly must be fully trusted.Assembly 'System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is a conditionally APTCA assembly which is not enabled in the current AppDomain. To enable this assembly to be used by partial trust or security transparent code, please add assembly name 'System.Web.Extensions

While using JavaScriptSerializer class (referencing System.Web.Extension dll in the plugin project) the below error thrown at the run time.

In order to access security critical code, this assembly must be fully trusted.
                     Assembly 'System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is a conditionally APTCA assembly which is not enabled in the current AppDomain. To enable this assembly to be used by partial trust or security transparent code, please add assembly name 'System.Web.Extensions

Solution:


  JavaScriptSerializer jss = new JavaScriptSerializer();  
           dynamic obj = jss.Deserialize<dynamic>(responsebody);  
           string token = obj["access_token"];  

 Instead of Above Code:
 public class AccessToken
    {
        public string access_token { get; set; }
    } 
using (var memorystream = new MemoryStream())  
           {  
             var deserializer = new DataContractJsonSerializer(typeof(AccessToken));  
             StreamWriter writer = new StreamWriter(memorystream);  
             writer.Write(responsebody);  
             writer.Flush();  
             memorystream.Position = 0;  
             AccessToken deserializedResult = (AccessToken)deserializer.ReadObject(memorystream);  
             string token1 = deserializedResult.access_token;  
           }   

Thursday, December 15, 2016

CRM Plugin Message Export,ExportAll,ExportCompressed,ExportCompressedAll fire in plugin


1. Connect to SQL Server where CRM DB is located.
2. Open SQL Management Studio, open new query with context of your CRM DB (CRM_MSCRM or other name).
3. Execute following T-SQL Script:
Update SdkMessageFilter
Set IsCustomProcessingStepAllowed = 1
Where SdkMessageId in (Select distinct SdkMessageId From sdkmessage where name = 'ExportSolution')
4. Make IISReset.

5. Restart plugin registration tool - ExportSolution should be available for handling with plugins.

Thursday, May 12, 2016

Create Email Activity in CRM Plugin


public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                IPluginExecutionContext context =
                   (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));


                // Get a reference to the Organization service.
                IOrganizationServiceFactory factory =                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                IOrganizationService service = factory.CreateOrganizationService(context.UserId);
             
 if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity objDetailDTO = (Entity)context.InputParameters["Target"];

                    ActivityParty fromUser = new ActivityParty
                    {
                        PartyId = new EntityReference(SystemUser.EntityLogicalName, objDetailDTO.Attributes["systemuserid"])
                    };

                    Email email = new Email();
                    email.From = new ActivityParty[] { fromUser };

                    email.To = new ActivityParty[] { /*Whom you want to send email(activityparty)*/ };

                    //email.Bcc = ccUsers.ToArray();

                    email.Subject = "subject";

                    email.Description = "body";

                    //Assign regarding    
                    email.RegardingObjectId = new EntityReference(objDetailDTO.Attributes["contactid"]);
                   
                    Guid emailGUID = service.Create(email);
                }
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                if (ex != null)
                    throw new InvalidPluginExecutionException(string.Format("An error occurred : {0}", 
ex.Message), ex);

            }
        }

Monday, January 4, 2016

Plugin error:The caller was not authenticated by the service or The request for security token could not be satisfied because authentication failed

Error : The caller was not authenticated by the service.
Stack Trace : Server stack trace:
   at System.ServiceModel.Security.IssuanceTokenProviderBase`1.DoNegotiation(TimeSpan timeout)
   at System.ServiceModel.Security.SspiNegotiationTokenProvider.OnOpen(TimeSpan timeout)

Error : The request for security token could not be satisfied because authentication failed.
Stack Trace : at System.ServiceModel.Security.SecurityUtils.ThrowIfNegotiationFault(Message message, EndpointAddress target)

Solution:
On-Premises

  • Check your plugin tool opened system timing and CRM server timing must be same or five mins different.
  • Try your username as domain\username or only username.



Thursday, November 26, 2015

Converting Managed Solutions to Unmanaged Solutions CRM 2013 and 2015

Converting Managed Solutions to Unmanaged Solutions CRM 2013 and 2015

If you have any doubt in the post please post comments. I will try to solve your problem with in a day.

1. Create a new staging organization in Dynamics CRM 2013 (lets say StagingOrg)
2. Import the managed solution you want to convert to unmanaged in this Organization (StagingOrg).
3. Now connect SQL server from the database of StagingOrg and run this Query after changing the name of your managed solution accordingly.
4. It will show some errors after running the script. I ignored them.
5. Now go into Settings > Customizations > Solutions > and export the solution as Unmanaged. Notice that it has become Unmanaged from managed now.
6. Save the zip file and extract it to a folder
7. Open the solution.xml file from the folder and search MissingDependency tag.
8. You will notice lot of MissingDependency elements, remove them all and self close the MissingDependency tag like this <MissingDependency />
9. Zip the files again and now import it to your development environment. Now you can import it as managed or unmanaged wherever you want.

SQL  Script

declare @solutionId uniqueidentifier, @systemSolutionId uniqueidentifier

-- specify the uniquename of the managed solution you'd like to unmanage here it is StagingOrg
select @solutionId = solutionid from SolutionBase where UniqueName='SuperGridSolution'

-- DO NOT TOUCH FROM HERE ON --
select @systemSolutionId = solutionid from SolutionBase where UniqueName='Active'

update PublisherBase set IsReadonly=0
where PublisherId in (select PublisherId from SolutionBase where SolutionId=@solutionId)

print 'updated publisher'


declare @tables table (id int identity, name nvarchar(100), ismanaged bit, issolution bit)
declare @count int, @currentTable nvarchar(100), @currentM bit, @currentS bit, @sql nvarchar(max)

-- go through all the tables that have the ismanaged/solutionid flag, find the related records for the current solution and move them to the crm active solution.
insert into @tables (name, ismanaged, issolution)
select name, 1, 0 from sysobjects where id in
(select id from syscolumns where name in ('IsManaged'))
and type='U'
order by name

insert into @tables (name, ismanaged, issolution)
select name, 0, 1 from sysobjects where id in
(select id from syscolumns where name in ('SolutionId'))
and type='U' and name not in ('SolutionComponentBase') -- ignore this table because it doesn't make a difference. it does cause dependency errors on the exported solution but we can manually edit the xml for that.
order by name

select @count = count(*) from @tables
while (@count > 0)
begin
select @currentTable =name, @currentM =ismanaged, @currentS =issolution from @tables where id=@count

if (@currentM = 1)
begin
select @sql ='update ' + @currentTable + ' set IsManaged=0 where SolutionId=N''' + cast(@solutionId as nvarchar(100)) + ''''
exec (@sql)

print 'updated IsManaged to 0 on: ' + @currentTable
end

if (@currentS = 1)
begin
select @sql ='update ' + @currentTable + ' set SolutionId=N''' + cast(@systemSolutionId as nvarchar(100)) + ''' where SolutionId=N''' + cast(@solutionId as nvarchar(100)) + ''''
exec (@sql)

print 'updated SolutionId on: ' + @currentTable
end

select @count = @count -1, @currentTable = NULL
end

Sunday, November 22, 2015

CRM Plugin Introduction and Execution Pipeline Message explanation

If you have any doubt in the post please post comments. I will try to solve your problem.

Plug-ins are handlers for events fired by Microsoft Dynamics CRM. It  is to enhance or modify the standard features/behavior of CRM by injecting custom business logic into the execution of nearly any task a user performs in CRM.

Plugin code can be triggered to run when a record is created or updated or perhaps even when a group of records are queried. 

The messages are processed by the Microsoft Dynamics CRM execution pipeline for the plug-in to execute.
There are four event execution stages of pipeline that we configure a plugin to trigger

  • Pre-validation
  • Pre-Operation
  • Post-Operation(Synchronous)
  • Post-Operation(ASynchronous)

Pre-validation:
It will trigger your plugin will run before the form is validated 
Pre -operation:
It will trigger your plugin will run  after validation and before the values are saved to the database
Post operation :
It will trigger your plugin will run after the values have been inserted/changed on the database and changes reflect to the UI immedietly because the form will wait once the plugin complete its work.
Post operation Asynchronous:
It will trigger  your plugin will run after the values have been inserted/changed on the database and changes has to reflect quite some time because the plugin in process in background
Message:
It is processed by the Microsoft Dynamics CRM execution pipeline for the plug-in to execute.
The following are some of the important message.

Create:
This message is helps to trigger the plugin whenever new record is created

Plugin parameter when fire:

Context.InputParameter:

  • Target-It contains entity object

Update:
This message is helps to trigger the plugin whenever existing record is updated

Plugin parameter when fire:

Context.InputParameter:

  • Target-It contains entity object

RetrievedMultiple:
This message is helps to trigger the plugin whenever multiple records is return to the CRM(grid display,lookup control data populate.

Plugin parameter when fire:

Context.InputParameter:

  • It contains fetch xml query

Context.OutputParameter:

  • It is only available at post-operation event 
  • Only synchronous post-event and asynchronous registered plug-ins have OutputParameters populated as the response is the result of the core platform operation.
  • It contains BusinessEntityCollectio that means output of the fetch xml query entity record set(rows data).

Example:
If you want to display "name" column as concatenating  first name and last name in the entity grid. 
Configure Plugin:
Message name:Retrieved multiple
PrimaryEntity: Entity
Operation: post-operation (synch)
Plugin code
   Get the data from context.outputParameter["BusinessEntityCollection"]
   and change the value inside list by concatenating  first name and last name.
PublishAllCustomization:
This message is helps to trigger the plugin whenever you click publish button in CRM

GrantAccess-Share
This message is helps to trigger the record is share

InputParameter
context.InputParameters["PrincipalAccess"] Example:

 //Obtain the principal access object from the input parameter
                Microsoft.Crm.Sdk.Messages.PrincipalAccess PrincipalAccess = (Microsoft.Crm.Sdk.Messages.PrincipalAccess)context.InputParameters["PrincipalAccess"];
                //Then got the User or Team and also Access Control that being Granted
                //***to Get User/Team that being Shared With
                var userOrTeam = PrincipalAccess.Principal;
                var userOrTeamId = userOrTeam.Id;
                var userOrTeamName = userOrTeam.Name;
//this userOrTeam.Name will be blank since entityReference only will give you ID
                var userOrTeamLogicalName = userOrTeam.LogicalName;
RevokeAccess-Unshare
This message is helps to trigger the record is unshare


InputParametercontext.InputParameters["Revokee"]

Example:

//Unshare does not have PrincipalAccess because it removes all, only can get the revokee
                //Obtain the principal access object from the input parameter
                var Revokee = (EntityReference)context.InputParameters["Revokee"];
                var RevokeeId = Revokee.Id;

                var RevokeeLogicalName = Revokee.LogicalName; //this one Team or User

Publish and Publish All message in CRM plugin


Before that please check my PreviousPost other messages

How context input parameter value differ in each message in CRM plugin

If you have any doubt in the post please post comments. I will try to solve your problem.

Message name:
PublishAllCustomization:

  • There is no value in the input parameter wherever you click publishAllCustomization.

Publish:

  • When you publish from "webresource" form the webresourceId value came in input parameter property of context in  plugin.
  • When you publish from "entity form" form the entity name value came in input parameter property of context in  plugin.


Get Entity type Code in CRM plugin code

If you have any doubt in the post please post comments. I will try to solve your problem.

In CRM each entity has separate object/entity type code. You can also get entity/object type code through plugin.          

Plugin Code:
 RetrieveEntityRequest request = new RetrieveEntityRequest();
 request.LogicalName = entity name;

// Retrieve the MetaData.
RetrieveEntityResponse response = (RetrieveEntityResponse)service.Execute(request);
int iEntityTypecode = response.EntityMetadata.ObjectTypeCode.Value;



Hide view in CRM

If you have any doubt in the post please post comments. I will try to solve your problem.

Some times we would need hide some view based on the roles. The below i have simply hide the view by the name starts with "my".

Plugin Code:
if (context.InputParameters.Contains("Query") && context.InputParameters["Query"] is QueryExpression)
                   {
                       QueryExpression qe = (QueryExpression)context.InputParameters["Query"];
                       if (qe.EntityName == "savedquery")
                       {
                           if (qe.Criteria != null)
                           {
                               if (qe.Criteria.Conditions != null)
                               {
//Custom logic can also apply
                                   /*The query is edited to look at views not starting with "my" at the begining of the View Name*/
                                   ConditionExpression queryCondition = new ConditionExpression("name", ConditionOperator.NotLike, "my%");
                                   qe.Criteria.Conditions.Add(queryCondition);
                               }
                           }
                       }
                   }
Plugin Configuration:
Meggage:  RetrieveMultiple
Primary Entity: savequery
Eventing Pipline: Pre-validation


Hide view based on Roles:
  • In custom logic code mention in the plugin area.
  • Get the role name based on the current logged in user
  • Form the list of roles that user have to display the view
  • Check if the user has able to display the view or not based on list
  • If not then filter with view name not to display 


Saturday, November 14, 2015

Which event fire first Plugin or Workflow

Which event fire first Plugin or Workflow

If you have any doubt in the post please post comments. I will try to solve your problem.

Let us see which event fir first plugin or workflow

We have created a new workflow and configure the workflow  as trigger at the time of new_name of testentity get change and update the same entity.

We also develop the plugin for the same testentity and configure the plugin as trigger at the time of new_name(with the help of filter attribute feature in plugin we can set the plugin to fire only particular attribute/column get fired) of  testentity get change.

Plugin configure as "pre-validation" and  Work-flow configure as Synchronous:

  • Plugin
  • Workflow

Plugin configure as "per-operation" and  Work-flow configure as Synchronous:

  • Plugin
  • Workflow
Post operation:
In plugin, we have to remove the attribute of new_name and update the testentity, otherwise 
infinite loop exception occur because we have  trigger the plugin at the time of new_name changed. In plugin if the new_name   updated in the database  even though new_name not change in the code. Thats while we remove attribute in the entity in plugin code.


Plugin configure as "post-operation with Synchronous"  and  Work-flow configure as Synchronous(new_name remove):

  • Workflow
  • Plugin

Plugin configure as "post-operation with Asynchronous"  and  Work-flow configure as Synchronous(new_name remove):

  • Workflow
  • Plugin

Plugin configure as "post-operation with Asynchronous"  and  Work-flow configure as  Asynchronous(new_name remove):

  • Plugin
  • Workflow

Plugin configure as "post-operation with synchronous"  and  Work-flow configure as  Asynchronous(new_name remove):

  • Plugin
  • Workflow is not triggered



Friday, October 9, 2015

Retrieving the COM class factory for component with CLSID {E5CB7A31-7512-11D2-89CE-0080C792E5D8} failed due to the following error: 800703fa Illegal operation attempted on a registry key that has been marked for deletion.

Retrieving the COM class factory for component with CLSID {E5CB7A31-7512-11D2-89CE-0080C792E5D8} failed due to the following error: 800703fa Illegal operation attempted on a registry key that has been marked for deletion.


Solution:
Re-booted the CRM app server is fixed (V 5.0.9688.34)

Tuesday, October 6, 2015

MyOrganizationCrmSdkTypes class generate using CrmSvcUtil.exe

MyOrganizationCrmSdkTypes class generate using CrmSvcUtil.exe
In CRM we can generate early-bound .NET Framework classes that represent the entity data model used by Microsoft Dynamics CRM by using CrmSvcUtil.exe.

You can get this exe from CRM SDK development tool kit.

Command to generate class from On-premises CRM
CrmSvcUtil.exe /url:http://<serverName>/<organizationName>/XRMServices/2011/Organization.svc    /out:<outputFilename>.cs /username:<username> /password:<password> /domain:<domainName>    /namespace:<outputNamespace> /serviceContextName:<serviceContextName>

 Command to generate class from Online CRM
CrmSvcUtil.exe /url:https://<organizationUrlName>.crm.dynamics.com/XRMServices/2011/Organization.svc    /out:<outputFilename>.cs /username:<username> /password:<password>     /namespace:<outputNamespace> /serviceContextName:<serviceContextName>
Example for online
CrmSvcUtil.exe /url:https://ASRworld.crm.dynamics.com/XRMServices/2011/Organization.svc    /out:MyOrganizationCrmSdkTypes.cs /username:@userName /password:@password








Tuesday, July 7, 2015

Access is denied in Plugin registration tool login

Access is denied in Plugin registration tool login 

If you have any doubt in the post please post comments. I will try to solve your problem.

When you try login plugin registration tool the below mentioned error occur.
Solutions:
Check your username and PWD has valid in the CRM login. If the username is not in the CRM user list then this error occur. 

Create a username and PWD in the CRM users(Settings->Security->Users). Then try login with that username and PWD in the plugin registration tool. You can successfully login.

Monday, June 15, 2015

Update the plugin in MS CRM 2015

Update the plugin in MS CRM 2015

If you have any doubt in the post please post comments. I will try to solve your problem.

1) Open the plugin registration tool and select the plugin that you want to update. Click update 
     button.



2) Click lookup button and select plugin dll that you want to update.



3) Checked the plugin and click "Sandbox" mode as isolation mode and click "Tab" two times(because there is no "Ok" button in the screen).