public void Execute(IPluginExecutionContext context)
{
   
try
   
{
        DynamicEntity entity = null;
        // checks; are we at the right place
       
if (context.InputParameters.Properties.Contains("Target") && context.InputParameters.Properties["Target"] is DynamicEntity)
        {   // nearly
           
entity = (DynamicEntity)context.InputParameters.Properties["Target"];
            if (entity.Name != EntityName.email.ToString())
            {   // missed!
               
return;
            }

        }
        else
       
{   // missed
           
return;
        }
        // running stage?
       
if (context.Stage != (int)MessageProcessingStage.AfterMainOperationOutsideTransaction)
        {   // post please
           
throw new InvalidPluginExecutionException("Need to run this plugin post stage");
        }
        // service from context
       
ICrmService service = context.CreateCrmService(false);
        // local variables:
       
Guid EmailID = Guid.Empty;
        Guid SalesLiteratureID = Guid.Empty;
        CrmNumber attachNo = new CrmNumber(1);
        // Email Guid, attachment number and sales literature guid
        if
(entity.Properties.Contains("activityid"))
        {   // update should come here
           
Microsoft.Crm.Sdk.Key acid = (Microsoft.Crm.Sdk.Key)entity.Properties["activityid"];
            EmailID = acid.Value;
            // sales literature id
           
SalesLiteratureID = this.GetAndClearSalesLiteratureID(service, EmailID);
            // number of attachments
           
attachNo = this.GetNextAttachmentNo(service, EmailID);
        }
        else
if (context.OutputParameters.Properties.Contains("id"))
        {   // create should come here (annoying, different name!)
           
EmailID = new Guid(context.OutputParameters.Properties["id"].ToString());
            // sales literature id
           
if (entity.Properties.Contains("new_salesliteratureid"))
            {   // found it
               
Microsoft.Crm.Sdk.Lookup lkup = (Microsoft.Crm.Sdk.Lookup)entity.Properties["new_salesliteratureid"];
                SalesLiteratureID = lkup.Value;
            }
            // attachments; assume none!!!
       
}
        if
(EmailID == Guid.Empty)
        {   // failed
            return
;
        }
        if
(SalesLiteratureID == Guid.Empty)
        {   // another failure
           
return;
        }
        // attach items to the email
       
this.AttachSalesLiteratureItemsToEmail(service, SalesLiteratureID, EmailID, ref attachNo);
        // all done

    }
    catch
(System.Web.Services.Protocols.SoapException ex)
    {
        throw new InvalidPluginExecutionException(this.GenerateErrorLog("An error occurred in the AttachSalesLiterature plugin: ", ex), ex);
    }
}