locked
Plugin for appointment not firing RRS feed

  • Question

  • Ok, so I've been searching and I've tried all the options I can find in the SDK on this one and a little help would be appreciated.  So I'm hoping the CRM gods can help me a little.  I've been getting more and more advanced in crm customizing and development, but this one is really messing me up.

    So I got this custom entity, and every activity has a N:1 relationship to this custom entity (Custom).  There are a bunch of parts of the plugin that need to go off but its not firing. 

    I have this plugin registered and working for the task, phone call, fax, and email activities.  But for the appointment it just won't run.  When I attempt to attach to the process and debug I discovered it is not launching it at all.  I have this registered as the following:

    Message: Create
    Primary Entity: appointment
    Execution Order: 1
    Post Stage
    Parent Pipeline
    Synchronous

    I have tired running this on both the "Create" and "Book" messages.  I read in my research that I should try the "Child pipeline" but that's a new problem.

    Under the child pipeline the plugin executes but fails on one of the first actions.  One of the first steps of this plugin is to put the text "GCustom" into the activities category field, and then update the entity using the UpdateRequest service.  In the child pipeline I receive an error saying that I cannot create the CRM service because it could create an infinite loop.

    So I am stumped, any thoughts?

    Monday, March 22, 2010 7:07 PM

Answers

  • Kmack,

    Sorry I didn't recognize this earlier, but I know what's going on:

    Performing "Updates" in the child pipeline don't work because there is a lock on the SQL table because the whole transaction around the "Create" isn't yet completed.  You're basically trying to "Update" a row that hasn't yet been written to the database.  When the transaction is finished, (in other words: at the end of the message execution), then will the row exist in the SQL table, and only then can you "Update" it without giving SQL an aneurysm.

    The best thing to do, is to modify the entity in the Pre-stage, before the database "insert" is ever made.  I do this all the time.  For this, you'll never need the entity's Id--not that it matters, because in the Pre-stage it hasn't been assigned by SQL yet.  Simply alter the attributes from the Properties collection of the entity referenced by the "Target" input-parameter.

    For example:

    public override void Execute(IPluginExecutionContext context) {
      // Cast the "Target" as a DynamicEntity called someNewRecord
      DynamicEntity someNewRecord = (DynamicEntity)context.InputParameters.Properties["Target"];
    
      // Establish a new StringProperty for inclusion to the new record
      StringProperty newStringProp = new StringProperty("stringattribute", "I'm a new string value");
    
      // Push newStingProp into someNewRecord
      someNewRecord.Properties.Add(newStringProp);
    }
    That's it.  That's all you have to do.  Whatever you modify on the "Target" will ultimately be what is written by the "insert" statement to SQL.  No need to make any other SOAP/WebService calls.


    Dave Berry
    • Marked as answer by KmackGFNet Thursday, March 25, 2010 11:39 AM
    Wednesday, March 24, 2010 6:14 PM
    Moderator

All replies

  • Hi.

    You definitely should use Child Pipeline. It seems that you've created following code to create crmservice instance:

    ICrmService crmservice = context.CreateCrmService(true);

    Replace this code with:

                CrmAuthenticationToken token = new CrmAuthenticationToken();
                token.AuthenticationType = AuthenticationType.AD;
                token.OrganizationName = <your organization name>;

                CrmService crmService = new CrmService();
                crmService.UseDefaultCredentials = true;
                crmService.Url = (string)(Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\MSCRM").GetValue("ServerUrl")) + "/2007/crmservice.asmx";
                crmService.CrmAuthenticationTokenValue = token;


    Truth is opened the prepared mind

    My blog (english)
    Мой блог (русскоязычный)
    Monday, March 22, 2010 7:20 PM
    Moderator
  • Ok, well I tried that and i'm getting that generatic, Server is unable to process request.  I also notice that while this plugin works for Email, Fax, Phone call, and task, it will not work for letter either.

    I added your suggestion as a static method in my utility class, and it was able to get the service fine, but it was able to process the request. 

    I am using DynamicEntities for this, could this be the problem, do letter and appointment allow for dynamic entities in plugins?

    Thanks

    Tuesday, March 23, 2010 1:23 PM
  • When you have this generic error message do the follwoing

    try
    
    {
    
    //your code
    
    }
    
    catch(SoapException error)
    
    {
    
    throw new Exception(error.Detail.SelectSingleNode("//description").InnerText;
    
    }
    
    

    You will have the true error message


    My blog : http://mscrmtools.blogspot.com
    You will find:
    Bulk Delete LauncherView Layout replicator
    ISV.Config Manager Form Javascript Manager
    Assembly RecoveryAnd others (use tool tag on my blog)
    Tuesday, March 23, 2010 1:26 PM
    Moderator
  • Hi,

    "I am using DynamicEntities for this, could this be the problem, do letter and appointment allow for dynamic entities in plugins?"

    You can access any entity using dynamic entity.

     


    Mahain
    Tuesday, March 23, 2010 1:48 PM
    Moderator
  • That's a great point, and I've updated everywhere I make a service.execute request in the plugin to have that try-catch blog, I've been trying to find a way to better show errors.

    But in this case I didn't get much better information as the error message it throws says "Generic SQL error".  So obviously i went to the event log to see what it says and it says the generic error but soon after I see a Communicator error.

    Here's a question, i am doing my development on a VPC, and obviously it doesn't connect to our network.  Could this problem be caused by that fact.  Could the scheduling engine be trying to hit the network and failing.

    Thanks

    Tuesday, March 23, 2010 2:14 PM
  • The Generic SQL Error can be interpreted only using CRM trace as you would have the true SQL message...


    My blog : http://mscrmtools.blogspot.com
    You will find:
    Bulk Delete LauncherView Layout replicator
    ISV.Config Manager Form Javascript Manager
    Assembly RecoveryAnd others (use tool tag on my blog)
    Tuesday, March 23, 2010 2:17 PM
    Moderator
  • I configured my VM to have Dev Errors on and with the registry keys for CRM Trace Logging.  WHen I try to add a letter, where before I got "An unexpected error has occurred" I get this in the event log viewer from stunnware.

    at ErrorInformation.LogError()
    at ErrorInformation..ctor(Exception exception, Uri requestUrl, Boolean logError)
    at ErrorInformation..ctor(Exception exception, Uri requestUrl)
    at AppForm.HandleSaveEntityException(Exception exception, FormEventId eventType, String url)
    at AppForm.SaveEntity(EntityProxy entity, FormEventId eventType, String redirectPath, Boolean performDuplicateCheck)
    at AppForm.RaiseDataEvent(FormEventId eventId)
    at EndUserForm.Initialize(Entity entity)
    at CustomizableForm.Execute(Entity entity, String formType)
    at CustomizableForm.Execute(Entity entity)
    at BasicActivityPage.ConfigureForm()
    at LetterDetailPage.ConfigureForm()
    at AppUIPage.OnPreRender(EventArgs e)
    at Control.PreRenderRecursiveInternal()
    at Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
    at Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
    at Page.ProcessRequest()
    at Page.ProcessRequestWithNoAssert(HttpContext context)
    at Page.ProcessRequest(HttpContext context)
    at microsoftcrm_activities_letter_edit_aspx.ProcessRequest(HttpContext context)
    at CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
    at HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
    at ApplicationStepManager.ResumeSteps(Exception error)
    at HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
    at HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)
    at HttpRuntime.ProcessRequestNoDemand(HttpWorkerRequest wr)
    at ISAPIRuntime.ProcessRequest(IntPtr ecb, Int32 iWRType)
    >MSCRM Error Report:
    --------------------------------------------------------------------------------------------------------
    Error: An unexpected error occurred.
    Error Number: 0x80040265
    Error Message: An unexpected error occurred.
    Error Details: An unexpected error occurred.
    Source File: Not available
    Line Number: Not available
    Request URL: http://localhost:5555/MicrosoftCRM/activities/letter/edit.aspx?pId={9020590A-37D0-DC11-AA32-0003FF33509E}&pType=2&pName=Alexander Eggerer&partyid={9020590A-37D0-DC11-AA32-0003FF33509E}&partytype=2&partyname=Alexander Eggerer&partyaddressused=&contactInfo=
    Stack Trace Info: [Exception: An unexpected error occurred.]
    at GFConference.PluginUtils.UpdateEntity(CrmService service, DynamicEntity _dentity) in C:\VPC Drive\Projects\GFCaptureConference\GFCaptureConference\PluginUtils.cs:line 78
    at GFConference.GFConferencePlugin.PluginMain(IPluginExecutionContext context) in C:\VPC Drive\Projects\GFCaptureConference\GFCaptureConference\GFConferencePlugin.cs:line 104
    at GFConference.GFConferencePlugin.Execute(IPluginExecutionContext context) in C:\VPC Drive\Projects\GFCaptureConference\GFCaptureConference\GFConferencePlugin.cs:line 80
    at Microsoft.Crm.Extensibility.PluginStep.Execute(PipelineExecutionContext context)
    [InvalidPluginExecutionException: An unexpected error occurred.]
    at Microsoft.Crm.Extensibility.PluginStep.Execute(PipelineExecutionContext context)
    at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
    at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
    at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
    at Microsoft.Crm.Extensibility.ExternalMessageDispatcher.Execute(String messageName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, PropertyBag fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
    at Microsoft.Crm.Sdk.RequestBase.Process(Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
    at Microsoft.Crm.Sdk.RequestBase.Process(CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
    at Microsoft.Crm.Sdk.CrmServiceInternal.Execute(RequestBase request, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
    at Microsoft.Crm.Sdk.InProcessCrmService.Execute(Object request)
    at Microsoft.Crm.Application.Platform.ServiceCommands.PlatformCommand.ExecuteInternal()
    at Microsoft.Crm.Application.Platform.ServiceCommands.CreateCommand.Execute()
    at Microsoft.Crm.Application.Platform.DataSource.Create(Entity entity, Boolean performDuplicateCheck)
    at Microsoft.Crm.Application.Platform.EntityProxy.Create(Boolean performDuplicateCheck)
    at Microsoft.Crm.Application.Forms.AppForm.SaveEntity(EntityProxy entity, FormEventId eventType, String redirectPath, Boolean performDuplicateCheck)

    And for the Appointment, that started this whole thing I get the following.  I'm getting an exception saying that :

    "Crm Exception: Message: , ErrorCode: -2147204784, InnerException: System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding."

    Or

    ">Exception when executing query: select appointment0.StateCode as 'statecode', appointment0.ScheduledStart as 'scheduledstart', appointment0.ScheduledEnd as 'scheduledend', appointment0.ActivityId as 'activityid', appointment0.OwningBusinessUnit as 'owningbusinessunit', appointment0.OwningUser as 'owninguser' from Appointment as appointment0 where ((appointment0.DeletionStateCode in (0)) and appointment0.ActivityId = 'a030cc71-8f36-df11-8f7b-0003ff34d0f8') Exception: System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)"

    Any thoughts?  This goes back to my thoughts on could this becaused by the scheduler.  After I get my error in the plugin, I get prompted with a CRM message box, asking me to ignore or save and says "General Failure in scheduling engine", could it be that the plugin is executing the scheduling engine is still running and attempting to create the activity? 

    Tuesday, March 23, 2010 3:27 PM
  • A timeout error could have many reasons...

    Maybe you could had a registry key (DWORD) in the HKLM\Software\Microsoft\MSCRM folder named OLEDBTimeout and put a value of 86400

    restart IIS and retry...

    I'm not sure that will help but you can give it a try


    My blog : http://mscrmtools.blogspot.com
    You will find:
    Bulk Delete Launcher View Layout replicator
    ISV.Config Manager Form Javascript Manager
    Assembly Recovery And others (use tool tag on my blog)
    Tuesday, March 23, 2010 3:32 PM
    Moderator
  • Its still timing out.  I've looked through the event logs, trace logs, sql server logs.  The other entity, Letter, I am still getting an error showing below:

    >MSCRM Error Report:
    --------------------------------------------------------------------------------------------------------
    Error: An unexpected error occurred.
    Error Number: 0x80040265
    Error Message: An unexpected error occurred.
    Error Details: An unexpected error occurred.
    Source File: Not available
    Line Number: Not available
    Request URL: http://localhost:5555/MicrosoftCRM/activities/letter/edit.aspx?pId={0820590A-37D0-DC11-AA32-0003FF33509E}&pType=2&pName=Abhijit Thakur&partyid={0820590A-37D0-DC11-AA32-0003FF33509E}&partytype=2&partyname=Abhijit Thakur&partyaddressused=&contactInfo=test
    Stack Trace Info: [Exception: An unexpected error occurred.]
    at GFConference.PluginUtils.UpdateEntity(CrmService service, DynamicEntity _dentity) in C:\VPC Drive\Projects\GFCaptureConference\GFCaptureConference\PluginUtils.cs:line 78
    at GFConference.GFConferencePluginCreate.PluginMain(IPluginExecutionContext context) in C:\VPC Drive\Projects\GFCaptureConference\GFCaptureConference\GFConferencePluginCreate.cs:line 155
    at GFConference.GFConferencePluginCreate.ExecuteProcess(IPluginExecutionContext context) in C:\VPC Drive\Projects\GFCaptureConference\GFCaptureConference\GFConferencePluginCreate.cs:line 102
    at GFConference.GFConferencePluginCreate.Execute(IPluginExecutionContext context) in C:\VPC Drive\Projects\GFCaptureConference\GFCaptureConference\GFConferencePluginCreate.cs:line 82
    at Microsoft.Crm.Extensibility.PluginStep.Execute(PipelineExecutionContext context)
    [InvalidPluginExecutionException: An unexpected error occurred.]
    at Microsoft.Crm.Extensibility.PluginStep.Execute(PipelineExecutionContext context)
    at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
    at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
    at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
    at Microsoft.Crm.Extensibility.ExternalMessageDispatcher.Execute(String messageName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, PropertyBag fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
    at Microsoft.Crm.Sdk.RequestBase.Process(Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
    at Microsoft.Crm.Sdk.RequestBase.Process(CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
    at Microsoft.Crm.Sdk.CrmServiceInternal.Execute(RequestBase request, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
    at Microsoft.Crm.Sdk.InProcessCrmService.Execute(Object request)
    at Microsoft.Crm.Application.Platform.ServiceCommands.PlatformCommand.ExecuteInternal()
    at Microsoft.Crm.Application.Platform.ServiceCommands.CreateCommand.Execute()
    at Microsoft.Crm.Application.Platform.DataSource.Create(Entity entity, Boolean performDuplicateCheck)
    at Microsoft.Crm.Application.Platform.EntityProxy.Create(Boolean performDuplicateCheck)
    at Microsoft.Crm.Application.Forms.AppForm.SaveEntity(EntityProxy entity, FormEventId eventType, String redirectPath, Boolean performDuplicateCheck)

    This makes no sense to me cause I literally stripped down the code to be the following:

    DynamicEntity _dentity = (DynamicEntity)context.InputParameters[ParameterName.Target];

    if (_dentity.Properties.Contains(_conferenceIDField))
                {
                    if (_dentity.Properties[_conferenceIDField] != null)
                    {
    CrmService service = PluginUtils.GetCRMService(context);

    TargetUpdateDynamic targetUpdate = new TargetUpdateDynamic();
                targetUpdate.Entity = _dentity;

                UpdateRequest update = new UpdateRequest();
                update.Target = targetUpdate;
               
                try
                {
                    UpdateResponse updated = (UpdateResponse)service.Execute(update);
                }
                catch (SoapException error)
                {
                    throw new Exception(error.Detail.SelectSingleNode("//description").InnerText);
                }
                service.Dispose();

               }

           }

     

    public static CrmService GetCRMService(IPluginExecutionContext context)
            {
                CrmAuthenticationToken token = new CrmAuthenticationToken();
                token.AuthenticationType = AuthenticationType.AD;
                token.OrganizationName = context.OrganizationName;

                CrmService service = new CrmService();
                service.UseDefaultCredentials = true;
                service.Url = (string)(Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\MSCRM").GetValue("ServerUrl") + "/2007/crmservice.asmx");
                service.CrmAuthenticationTokenValue = token;
                return service;
            }

    Tuesday, March 23, 2010 5:51 PM
  • You definitely make infinite loop. Don't you see this? What is the purpose of your code?
    Truth is opened the prepared mind

    My blog (english)
    Мой блог (русскоязычный)
    Tuesday, March 23, 2010 8:20 PM
    Moderator
  • As Andriy states, you're most likely tied up in an infinite loop.  However, since you state that the code above is registered to the "Create" message, this would mean that you have the same solution inadvertently tied also to the "Update" message (or some other piece of code is tied to this message which remains culpable).  Please check for that.  It can be easy to do when you try to approach a solution one way, but end up taking another course because of unforeseen circumstances, but accidentally leave portions of the first approach lingering in your code.
    Dave Berry
    Tuesday, March 23, 2010 8:56 PM
    Moderator
  • I will definitely look into that, and I may just have to put the code up here.  But essentially these are the steps my code is doing:

    • Add "GFCustom" to the category of the activity
    • If there is anything in the category, move it to the sub category
    • Update the activity entity
    • Get the contents of the regardingobjectid field
    • If that is a contact, check two fields
    • Check if FirstCustom(N:1 relationship with custom) is populated, if not do so
    • Populate LatestCustom(N:1 relationship with custom)
    • Check if there  is an existing relation between this contact and instance of Custom (N:N)
    • If not, create the relationship

    I'm curious though because it works fine for 4 other activities, in the case of the appointment could this be because I'm already in the child pipeline and trying to do an update.  And due to the fact that I'm already in that pipeline, it refuses to execute the update?  That would make sense to me at least, I'm grasping at straws.

    Also if I'm right in that theory, is there any message in the parent pipeline I could attach this to and have it work.  I guess my question is, and I've been searching for this, what order are the messages executed for an appointment when it is first created?

    Also I'm curious as to how I can have that Unexpected error when I try to run this for the parent pipeline for a letter.  Is a letter activity in any way different from an email, phone call, task, or fax?

    Wednesday, March 24, 2010 11:59 AM
  • Ok, so it looks to me like you can't really do anything inside a plugin to the Appointment entity.  To test this theory I altered the plugin to skip the first 3 of the steps above. So when it runs for the Create message in the child pipeline, it doess the following:

    • Get the contents of the regardingobjectid field
    • If that is a contact, check two fields
    • Check if FirstCustom(N:1 relationship with custom) is populated, if not do so
    • Populate LatestCustom(N:1 relationship with custom)
    • Check if there  is an existing relation between this contact and instance of Custom (N:N)
    • If not, create the relationship

    I developed javascript to handle most of the first part, as far as loading the field, and that's fine.  My problem now is that I still have to close the activity if a field is marked as a switch.  As of right now, cause of a time crunch I'm going to set a workflow to handle that.  But any ideas on how it might be possible to update an appointment during post create in the child pipeline?

    Wednesday, March 24, 2010 1:03 PM
  • Kmack,

    Sorry I didn't recognize this earlier, but I know what's going on:

    Performing "Updates" in the child pipeline don't work because there is a lock on the SQL table because the whole transaction around the "Create" isn't yet completed.  You're basically trying to "Update" a row that hasn't yet been written to the database.  When the transaction is finished, (in other words: at the end of the message execution), then will the row exist in the SQL table, and only then can you "Update" it without giving SQL an aneurysm.

    The best thing to do, is to modify the entity in the Pre-stage, before the database "insert" is ever made.  I do this all the time.  For this, you'll never need the entity's Id--not that it matters, because in the Pre-stage it hasn't been assigned by SQL yet.  Simply alter the attributes from the Properties collection of the entity referenced by the "Target" input-parameter.

    For example:

    public override void Execute(IPluginExecutionContext context) {
      // Cast the "Target" as a DynamicEntity called someNewRecord
      DynamicEntity someNewRecord = (DynamicEntity)context.InputParameters.Properties["Target"];
    
      // Establish a new StringProperty for inclusion to the new record
      StringProperty newStringProp = new StringProperty("stringattribute", "I'm a new string value");
    
      // Push newStingProp into someNewRecord
      someNewRecord.Properties.Add(newStringProp);
    }
    That's it.  That's all you have to do.  Whatever you modify on the "Target" will ultimately be what is written by the "insert" statement to SQL.  No need to make any other SOAP/WebService calls.


    Dave Berry
    Wednesday, March 24, 2010 6:13 PM
    Moderator
  • Kmack,

    Sorry I didn't recognize this earlier, but I know what's going on:

    Performing "Updates" in the child pipeline don't work because there is a lock on the SQL table because the whole transaction around the "Create" isn't yet completed.  You're basically trying to "Update" a row that hasn't yet been written to the database.  When the transaction is finished, (in other words: at the end of the message execution), then will the row exist in the SQL table, and only then can you "Update" it without giving SQL an aneurysm.

    The best thing to do, is to modify the entity in the Pre-stage, before the database "insert" is ever made.  I do this all the time.  For this, you'll never need the entity's Id--not that it matters, because in the Pre-stage it hasn't been assigned by SQL yet.  Simply alter the attributes from the Properties collection of the entity referenced by the "Target" input-parameter.

    For example:

    public override void Execute(IPluginExecutionContext context) {
      // Cast the "Target" as a DynamicEntity called someNewRecord
      DynamicEntity someNewRecord = (DynamicEntity)context.InputParameters.Properties["Target"];
    
      // Establish a new StringProperty for inclusion to the new record
      StringProperty newStringProp = new StringProperty("stringattribute", "I'm a new string value");
    
      // Push newStingProp into someNewRecord
      someNewRecord.Properties.Add(newStringProp);
    }
    That's it.  That's all you have to do.  Whatever you modify on the "Target" will ultimately be what is written by the "insert" statement to SQL.  No need to make any other SOAP/WebService calls.


    Dave Berry
    • Marked as answer by KmackGFNet Thursday, March 25, 2010 11:39 AM
    Wednesday, March 24, 2010 6:14 PM
    Moderator
  • Ok that makes perfect sense thanks.  So how using this method would I go about setting the state in the Pre-Stage event?  The only update I need to do now is to have it set the state to complete if a specific attribute(bit field) is set to true.  I'm going to be playing around with this, if I find it on my own I'll post it here.  But if you know of an easy way let me know.
    Thursday, March 25, 2010 11:41 AM
  • Indeed, the "Target" should contain your bit property, and you can override the statecode/statuscode property in the "Target" directly based on its value using a method similar to the one I posted above.  The only difference, however, is that you may have to "Remove" the existing statecode/statuscode property before you can add a new one containing your desired value.

    public override void Execute(IPluginExecutionContext context) {
      // Cast the "Target" as a DynamicEntity called someNewRecord
      DynamicEntity someNewRecord = (DynamicEntity)context.InputParameters.Properties["Target"];
    
      // Grab the value of the "someBoolean" attribute, if present
      if (someNewRecord.Properties.Contains("someBoolean")) {
        CrmBoolean someBoolean = (CrmBoolean)someNewRecord.Properties["someBoolean"];
    
        // If "someBoolean" is true, change the statecode
        if (someBoolean.Value == true) {
          // Remove any existing statecode value
          if (someNewRecord.Properties.Contains("statecode")) {
            someNewRecord.Properties.Remove("statecode");
          }
    
          // Set the statecode value to "Inactive"
          StateProperty newStateProp = new StateProperty("statecode", "Inactive");
    
          // Push the newStateProp into someNewRecord
          someNewRecord.Properties.Add(newStateProp);
        }
      }
    }
    

    Dave Berry
    Tuesday, March 30, 2010 12:10 AM
    Moderator