Showing posts with label plugin. Show all posts
Showing posts with label plugin. Show all posts

Friday, April 27, 2012

How to update the parent record when children records are created or updated

Few months ago, I wrote a blog on “How to update the children records when parent record is updated”. Here is link to that blog. In this blog I am posting a code on “How to update the parent record when child record is created or updated”. The scenario is that I want to display the sum of total of "Estimated Revenue” of the opportunities on the parent account record. Here are the steps
  • Create a new attribute named “new_oppamount” on the account entity and place it on the account entity form.
  • Publish the account entity
  • Create the plugin
  • Register this plugin on postcreate, postupdate , postsetstate and postsetstatedynamic  events of opportunity entity.
Here is the code. The code is using the fetch xml to get the sum of “Estimated Revenue” field of the open opportunities. Follow the steps mentioned in here and replace the ExecutePostAccountUpdateContacts method with follwing method
protected void ExecutePostOpportunityCreate(LocalPluginContext localContext)
{
    if (localContext == null)
    {
        throw new ArgumentNullException("localContext");
    }
            

    IPluginExecutionContext context = localContext.PluginExecutionContext;

    //Get a IOrganizationService
    IOrganizationService service = localContext.OrganizationService;

    //create a service context
    var ServiceContext = new OrganizationServiceContext(service);
    //ITracingService tracingService = localContext.TracingService;

    // The InputParameters collection contains all the data passed in the message request.
    if (context.InputParameters.Contains("Target") &&
    context.InputParameters["Target"] is Entity)
    {
        // Obtain the target entity from the input parmameters.
        Entity entity = (Entity)context.InputParameters["Target"];

        //get the customerid
        EntityReference a = (EntityReference)entity.Attributes["customerid"];
                
        decimal totalAmount=0;
                
        try
        {   
            //fetchxml to get the sum total of estimatedvalue
            string estimatedvalue_sum = string.Format(@" 
            <fetch distinct='false' mapping='logical' aggregate='true'> 
                <entity name='opportunity'> 
                    <attribute name='estimatedvalue' alias='estimatedvalue_sum' aggregate='sum' /> 
                    <filter type='and'>
                        <condition attribute='statecode' operator='eq' value='Open' />
                            <condition attribute='customerid' operator='eq' value='{0}' uiname='' uitype='' />
                    </filter>
                </entity>
            </fetch>", a.Id);
            EntityCollection estimatedvalue_sum_result = service.RetrieveMultiple(new FetchExpression(estimatedvalue_sum));

            foreach (var c in estimatedvalue_sum_result.Entities)
            {
                totalAmount = ((Money)((AliasedValue)c["estimatedvalue_sum"]).Value).Value;
            }
                    
            //updating the field on the account
            Entity acc = new Entity("account");
            acc.Id = a.Id;
            acc.Attributes.Add("new_oppamount", new Money(totalAmount));
            service.Update(acc);
                    
                    
        }
        catch (FaultException ex)
        {
                throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
        }
    }

}
Good Luck…

Tuesday, October 26, 2010

Step by step plugin tutorial for CRM 2011

This is a step by step guide to create a plug-in in CRM 2011.

1. Create a class library project in vs2010.
2. Sign the assembly by using the Signing tab of the project's properties sheet.
3. Add references to microsoft.crm.sdk.proxy , Microsoft.xrm.sdk ,
System.ServiceModel and System.Runtime.Serialization.
4. Here is code for this tutorial. This plugin will check if the account number
field is empty, create a task for the user to fill this up.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// Microsoft Dynamics CRM namespace(s)
using Microsoft.Xrm.Sdk;
using System.ServiceModel;

namespace CRMPlugin1
{
public class createNote:IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{

// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));


// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parmameters.
Entity entity = (Entity)context.InputParameters["Target"];



try
{
//check if the account number exist

if (entity.Attributes.Contains("account number") == false)
{

//create a task
Entity task = new Entity("task");
task["subject"] = "Account number is missing";
task["regardingobjectid"] = new EntityReference("account",new Guid(context.OutputParameters["id"].ToString()));

//adding attribute using the add function
// task["description"] = "Account number is missng for the following account. Please enter the account number";
task.Attributes.Add("description", "Account number is missng for the following account. Please enter the account number");



// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);


// Create the task in Microsoft Dynamics CRM.
service.Create(task);


}
}

catch (FaultException ex)
{
throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
}

}

}
}//end class
}//end name space


5. Compile the code and register it on the registration tool provided with sdk.
6. Register it on the post create event of account entity.
Note :check the sdk for instructions to register a plugin

Thanks

Saturday, June 21, 2008

Opportunity setstate plugin problems

Few months ago, I was writing a plugin on opportunity setstate. I registered the plugin using registeration tool. My plugin never get triggered. After messing around for few hours, I registered the plugin on SetStateDynamicEntity message. Even then when I closed the opportunity, the plugin did not trigger, did not matter if it's won or lost opportunity, But plugin did trigger when I reopened the closed opportunity. I tried a lot of different things and at the end I registerfed my pluggin for win and lose message instead of setstate or setstatedynamicentity message. It worked this time.
I hope this will help some of you guys facing the same problem.

Have a nice weekend.