Question Status

Suggested Answer
Thomas Peschat asked a question on 19 Mar 2015 2:08 PM

Hi,

I have been searching for a way to filter birthdays in CRM and found a plugin from CRM MVP Darren Liu, which would perfectly fit to our needs:

http://blogs.msdn.com/b/crm/archive/2009/02/27/creating-a-birthday-contact-list.aspx

We'll I tried to build it in Visual Studio but suddenly recognized that the code is for CRM 4, so I need to rewrite parts of the plugin, because e.g. the data types changed from CRM 4 to CRM 2011 (to the .NET data types).

Then I registered the plugin for create and update, entity contact as pre-operation steps.

The plugin works fine. It writes the birthdate to the three new fields when creating a new contact, or when updating the birthdate for a contact.

BUT: I need to restrict the plugin that it doesn't run for contacts with a certain ownerid. Unfortunately I didn't manage to write that code, because I just started writing plugins (based on SDK samples) and I didn't study development.

 

The plugin shall not run, if the owner of the contact is = "04700952-321B-E111-B232-005056830021" (-> that's the GUID of the owner).

 

I tried it like that:

Entity current = service.Retrieve("entityname", context.PrimaryEntityId, new ColumnSet("ownerid"));

EntityReference OwnerId = (EntityReference)current["ownerid"];

if (entity.Attributes.Contains("birthdate") && OwnerId.ToString() != "04700952-321B-E111-B232-005056830021") 

--> but that didn't work out and threw an exception

 

It would be really great if somebody could help me out with that issue :)

 

thx a lot in advance

Thomas

 

 

 

That's my current source code (without the restriction):

using System;

using System.Diagnostics;

using System.Linq;

using System.ServiceModel;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Query;

 

namespace BirthdayPlugin

{

    public class BirthdayField : IPlugin

    {

        public void Execute(IServiceProvider serviceProvider)

        {

        IPluginExecutionContext context = (IPluginExecutionContext)

        serviceProvider.GetService(typeof(IPluginExecutionContext));

 

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

        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

        ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

 

        try

            {

                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)

                {

                    Entity entity = (Entity)context.InputParameters["Target"];

                    tracingService.Trace("EntityName:" + entity.LogicalName);

 

                     // Verify that the target entity represents a contact.

                     // If not, this plug-in was not registered correctly.

                   

                    if (entity.LogicalName == "contact")

                        {

                       

                        //Check if birthdate is filled in CRM and if new birthday fields are empty. If yes --> copy to new birthday/month/year fields

 

                           if (entity.Attributes.Contains("birthdate"))

                             {

                             //Neue Variable die den Geburtstag eines Contacts enthält

                             DateTime birthday = (DateTime) entity["birthdate"];

                             //Update bzw. Befüllung der 3 neuen Geburtstagsfelder am Contact

                             entity ["new_birthday"] = birthday.ToLocalTime().Day;

                             entity ["new_birthmonth"] = new OptionSetValue (birthday.ToLocalTime().Month);

                             entity["new_birthyear"] = birthday.ToLocalTime().Year;

                            }                                          

                        }

                }

            }

        catch (FaultException<OrganizationServiceFault> ex)

        {

            throw new InvalidPluginExecutionException("An error occurred in Birthday plugin", ex);

        }

        }

    }

}

Reply
Suggested Answer
Mahadeo Matre responded on 19 Mar 2015 2:21 PM

try this way..

 if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {

                    Entity entity = (Entity)context.InputParameters["Target"];

                    tracingService.Trace("EntityName:" + entity.LogicalName);

                     // Verify that the target entity represents a contact.

                     // If not, this plug-in was not registered correctly.

                   Guid skipOwner=new Guid("04700952-321B-E111-B232-005056830021");

                    if (entity.LogicalName == "contact")
                        {
//Get OwnerId from Target Entity EntityReference owner = (EntityReference)entity.Attributes["ownerid"].value; //check owner is not skip owner.. if(owner.Id !=skipOwner) { if (entity.Attributes.Contains("birthdate")) { //Neue Variable die den Geburtstag eines Contacts enthält DateTime birthday = (DateTime) entity["birthdate"]; //Update bzw. Befüllung der 3 neuen Geburtstagsfelder am Contact entity ["new_birthday"] = birthday.ToLocalTime().Day; entity ["new_birthmonth"] = new OptionSetValue (birthday.ToLocalTime().Month); entity["new_birthyear"] = birthday.ToLocalTime().Year; } } } }

Reply
Thomas Peschat responded on 19 Mar 2015 2:42 PM

Thx a lot for your quick response. I'll try it out tomorrow morning and let you know if it solved my problem ;)

;) Thomas

Reply
Thomas Peschat responded on 20 Mar 2015 3:38 AM

Hi,

the following part throws an error:

//Get OwnerId from Target Entity

EntityReference owner = (EntityReference)entity.Attributes["ownerid"].value;

Error 1 'object' does not contain a definition for 'value' and no extension method 'value' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) \\p1at.s-group.cc\0188\users\s81na\daten\visual studio 2010\Projects\BirthdayPlugin\BirthdayPlugin\Class1.cs 38 95 BirthdayPlugin

Please help

thx Thomas

Reply
Mahendar Pal MVP responded on 20 Mar 2015 3:44 AM

Hello,

Try this

EntityReference owner = entity.GetAttributeValue<EntityReference>("ownerid");


Need help in CRM Contact US | Our Blog | Follow US | Like our Facebook Page | Our Book

Make sure to Vote as Helpful and  Mark As Answer ,if you get answer of your question.

Reply
Mithilesh Kumar responded on 20 Mar 2015 3:45 AM

Thomas,

It should be

EntityReference owner = ((EntityReference)(entity.Attributes[“ownerid”])).Value;

"value" with capital "V".

Thanks

Reply
Thomas Peschat responded on 20 Mar 2015 4:29 AM

Hi Mithilesh,

thx for your response.

It throws the same error with a capital V.

Actually the method "Value" isn't offered for entity.Attributes (see attached screenshot)

br Thomas

Reply
Mithilesh Kumar responded on 20 Mar 2015 4:37 AM

Hi Thomas,

You will have to make use of Id properties of Entity Reference.

Once you get the Id, make use of LINQ Query to get the value from SystemUser Entity with the ID you fetched.

You can make use of EarlyBound Classes for LINQ Queries.

Thanks

Reply
Thomas Peschat responded on 20 Mar 2015 4:45 AM

Hi,

I now changed it to the suggestion of Mahendar Pal and now when rebuiliding the solution it doesn't throw an execption.

The plugin still works, but it also runs for the user wit the GUID I want to ignore ...

I assume there is an issue with comparing:

  Guid skipOwner = new Guid("04700952-321B-E111-B232-005056830021");

with the value returned by:

 EntityReference owner = entity.GetAttributeValue<EntityReference>("ownerid");

thx a lot for your support

br Thomas

That's my current source code:

using System;

using System.Diagnostics;

using System.Linq;

using System.ServiceModel;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Query;

namespace BirthdayPlugin

{

   public class BirthdayField : IPlugin

   {

       public void Execute(IServiceProvider serviceProvider)

       {

       IPluginExecutionContext context = (IPluginExecutionContext)

       serviceProvider.GetService(typeof(IPluginExecutionContext));

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

       IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

       ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

       try

           {

               if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)

               {

                   Entity entity = (Entity)context.InputParameters["Target"];

                   tracingService.Trace("EntityName:" + entity.LogicalName);

                    // Verify that the target entity represents a contact.

                    // If not, this plug-in was not registered correctly.

                   if (entity.LogicalName == "contact")

                       {

                       //Variable skipOwner = "CZ_OWNER" --> damit Plugin nicht für CZ läuft

                       Guid skipOwner = new Guid("04700952-321B-E111-B232-005056830021");

                       //Get OwnerId from Target Entity

                          //EntityReference owner = (EntityReference)entity.Attributes["ownerid"];

                       EntityReference owner = entity.GetAttributeValue<EntityReference>("ownerid");

                       //Check if owner isn't skipOwner

                       if (owner.Id != skipOwner)

                       {

                           //Check if the plugin context contains the attribute birthday (=create or update of birthdate in CRM). If yes --> copy to new birthday/month/year fields                          

                           if (entity.Attributes.Contains("birthdate"))

                           {

                               //Neue Variable die den Geburtstag eines Contacts enthält

                               DateTime birthday = (DateTime)entity["birthdate"];

                               //Update bzw. Befüllung der 3 neuen Geburtstagsfelder am Contact

                               entity["new_birthday"] = birthday.ToLocalTime().Day;

                               entity["new_birthmonth"] = new OptionSetValue(birthday.ToLocalTime().Month);

                               entity["new_birthyear"] = birthday.ToLocalTime().Year;

                           }

                       }              

                       }

               }

           }

       catch (FaultException<OrganizationServiceFault> ex)

       {

           throw new InvalidPluginExecutionException("An error occurred in Birthday plugin", ex);

       }

       }

   }

}

Reply
Suggested Answer
Guido Preite responded on 20 Mar 2015 4:55 AM

the problem you are facing is related to the event.

the plugin is registered (if you followed the tutorial) to the Create and the Update event.

In the Create event the Target contains the ownerid attribute (because the Create always pass all the attributes inside the plugin)

In the Update event the Target contains only the updated attributes (so when you retrieve the ownerid using GetAttributeValue it returns an empty guid because that field is missing causing your code to be always executed)

To solve you have two ways:

1) adding a pre-image to your plugin in order to have always the ownerid attribute

(crmbook.powerobjects.com/.../plug-in-images-pre-vs-post)

or

2) do a service.Retrieve in order to retrieve the ownerid field

Reply
Thomas Peschat responded on 20 Mar 2015 6:53 AM

Hi,

but it also doesn't work in the create event and what I read at your link there is no way to create a pre or post image for a pre-operation step for a create message.

br Thomas

Reply
Suggested Answer
Mahadeo Matre responded on 19 Mar 2015 2:21 PM

try this way..

 if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {

                    Entity entity = (Entity)context.InputParameters["Target"];

                    tracingService.Trace("EntityName:" + entity.LogicalName);

                     // Verify that the target entity represents a contact.

                     // If not, this plug-in was not registered correctly.

                   Guid skipOwner=new Guid("04700952-321B-E111-B232-005056830021");

                    if (entity.LogicalName == "contact")
                        {
//Get OwnerId from Target Entity EntityReference owner = (EntityReference)entity.Attributes["ownerid"].value; //check owner is not skip owner.. if(owner.Id !=skipOwner) { if (entity.Attributes.Contains("birthdate")) { //Neue Variable die den Geburtstag eines Contacts enthält DateTime birthday = (DateTime) entity["birthdate"]; //Update bzw. Befüllung der 3 neuen Geburtstagsfelder am Contact entity ["new_birthday"] = birthday.ToLocalTime().Day; entity ["new_birthmonth"] = new OptionSetValue (birthday.ToLocalTime().Month); entity["new_birthyear"] = birthday.ToLocalTime().Year; } } } }

Reply
Suggested Answer
Guido Preite responded on 20 Mar 2015 4:55 AM

the problem you are facing is related to the event.

the plugin is registered (if you followed the tutorial) to the Create and the Update event.

In the Create event the Target contains the ownerid attribute (because the Create always pass all the attributes inside the plugin)

In the Update event the Target contains only the updated attributes (so when you retrieve the ownerid using GetAttributeValue it returns an empty guid because that field is missing causing your code to be always executed)

To solve you have two ways:

1) adding a pre-image to your plugin in order to have always the ownerid attribute

(crmbook.powerobjects.com/.../plug-in-images-pre-vs-post)

or

2) do a service.Retrieve in order to retrieve the ownerid field

Reply