Export (0) Print
Expand All

Custom Workflow Activity: Calculate Credit Score

banner art

[Applies to: Microsoft Dynamics CRM 4.0]

The following sample workflow activity calculates the credit score based on the Social Security Number (SSN) and name. Note that this uses dynamic entity rather than strong types as is recommended for workflows and plug-ins.

This sample code can be found in the following files in the SDK download:

Server\FullSample\CustomWorkflowActivity\CS\RetrieveCreditScore.cs
Server\FullSample\CustomWorkflowActivity\VB\RetrieveCreditScore.cs

Example

using System;
using System.Collections;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using System.Reflection;

using Microsoft.Crm.Workflow;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;

namespace SampleWorkflows
{
    /// <summary>
    /// Calculates the credit score based on the Social Security Number (SSN) and name. 
    /// </summary>
    /// <remarks>
    /// This depends on a custom entity called Loan Application and customizations to Contact.
    /// 
    /// Loan Application requires the following properties:
    /// <list>
    ///      <item>Schema Name: new_loanapplication</item>
    ///      <item>Attribute: new_loanapplicationid as the primary key</item>
    ///      <item>Attribute: new_creditscore of type int with min of 0 and max of 1000 (if it is to be updated)</item>
    ///      <item>Attribute: new_loanamount of type money with default min/max</item>
    ///      <item>Customize the form to include the attribute new_loanapplicantid</item>
    /// </list>
    /// 
    /// Contact requires the following customizations:
    /// <list>
    ///      <item>Attribute: new_ssn as nvarchar with max length of 15</item>
    ///      <item>One-To-Many Relationship with these properties:
    ///         <list>
    ///            <item>Relationship Definition Schema Name: new_loanapplicant</item>
    ///            <item>Relationship Definition Related Entity Name: Loan Application</item>
    ///            <item>Relationship Atttribute Schema Name: new_loanapplicantid</item>
    ///            <item>Relationship Behavior Type: Referential</item>
    ///         </list>
    ///      </item>
    /// </list>
    /// 
    /// The activity takes, as input, a lookup to the Loan Application and a Boolean indicating whether new_creditscore should be updated to the credit score.
    /// </remarks>
    /// <exception cref=">ArgumentNullException">Thrown when LoanApplication is null</exception>
    /// <exception cref=">ArgumentException">Thrown when LoanApplication is not a lookup to a LoanApplication entity</exception>
    [CrmWorkflowActivity("Calculate Credit Score", "Release Scenarios")]
    public partial class RetrieveCreditScore : SequenceActivity
    {
        private const string _customEntity = "new_loanapplication";

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            //Check to see if the lookup has been set.
            Lookup loanApplication = this.LoanApplication;
            if (loanApplication == null)
            {
                throw new InvalidPluginExecutionException("Loan Application has not been specified", new ArgumentNullException("Loan Application"));
            }
            else if (loanApplication.type != _customEntity)
            {
                throw new InvalidPluginExecutionException("Loan Application must reference a Loan Application entity",
                   new ArgumentException("Loan Application must be of type Loan Application", "Loan Application"));
            }

            //Retrieve the CrmService so that we can retrieve the loan application.
            IContextService contextService = (IContextService)executionContext.GetService(typeof(IContextService));
            IWorkflowContext context = contextService.Context;
            ICrmService service = context.CreateCrmService();

            //Retrieve the Loan Application entity.
            DynamicEntity loanEntity;
            {
                //Create the target.
                TargetRetrieveDynamic retrieveTarget = new TargetRetrieveDynamic();
                retrieveTarget.EntityId = loanApplication.Value;
                retrieveTarget.EntityName = loanApplication.type;

                //Create a request.
                RetrieveRequest retrieveRequest = new RetrieveRequest();
                retrieveRequest.ColumnSet = new ColumnSet(new string[] { "new_loanapplicationid", "new_loanapplicantid" });
                retrieveRequest.ReturnDynamicEntities = true;
                retrieveRequest.Target = retrieveTarget;

                //Execute the request.
                RetrieveResponse retrieveResponse = (RetrieveResponse)service.Execute(retrieveRequest);

                //Retrieve the Loan Application entity.
                loanEntity = retrieveResponse.BusinessEntity as DynamicEntity;
            }

            //Retrieve the Contact entity.
            DynamicEntity contactEntity;
            {
                //Create the target.
                TargetRetrieveDynamic retrieveTarget = new TargetRetrieveDynamic();
                retrieveTarget.EntityId = ((Lookup)loanEntity["new_loanapplicantid"]).Value;
                retrieveTarget.EntityName = EntityName.contact.ToString();

                //Create a request.
                RetrieveRequest retrieveRequest = new RetrieveRequest();
                retrieveRequest.ColumnSet = new ColumnSet(new string[] { "fullname", "new_ssn", "birthdate" });
                retrieveRequest.ReturnDynamicEntities = true;
                retrieveRequest.Target = retrieveTarget;

                //Execute the request.
                RetrieveResponse retrieveResponse = (RetrieveResponse)service.Execute(retrieveRequest);

                //Retrieve the Loan Application entity.
                contactEntity = retrieveResponse.BusinessEntity as DynamicEntity;
            }

            //Retrieve the needed properties.
            string ssn = (string)contactEntity["new_ssn"];
            string name = (string)contactEntity["fullname"];
            CrmDateTime birthdate = (CrmDateTime)contactEntity["birthdate"];
            int creditScore;

            //This is where the logic for retrieving the credit score would be inserted.
            //We are simply going to return a random number.
            creditScore = (new Random()).Next(0, 1000);

            //Set the credit score property.
            this.CreditScore = new CrmNumber(creditScore);

            //Check to see if the credit score should be saved to the entity.
            //If the value of the property has not been set or it is set to true
            if (this.UpdateEntity == null || this.UpdateEntity.Value)
            {
                //Create the entity.
                DynamicEntity updateEntity = new DynamicEntity(loanApplication.type);
                updateEntity["new_loanapplicationid"] = loanEntity["new_loanapplicationid"];
                updateEntity["new_creditscore"] = this.CreditScore;

                //Update the entity.
                service.Update(updateEntity);
            }

            //Give the execution to the base class.
            return base.Execute(executionContext);
        }

        //Define the variables.
        public static DependencyProperty LoanApplicationProperty = DependencyProperty.Register("LoanApplication", typeof(Lookup), typeof(RetrieveCreditScore));
        public static DependencyProperty UpdateEntityProperty = DependencyProperty.Register("UpdateEntity", typeof(CrmBoolean), typeof(RetrieveCreditScore));
        public static DependencyProperty CreditScoreProperty = DependencyProperty.Register("CreditScore", typeof(CrmNumber), typeof(RetrieveCreditScore));

        //Define the properties.
        [CrmInput("Loan Application")]
        [CrmReferenceTarget(_customEntity)]
        public Lookup LoanApplication
        {
            get
            {
                return (Lookup)base.GetValue(LoanApplicationProperty);
            }
            set
            {
                base.SetValue(LoanApplicationProperty, value);
            }
        }

        [CrmInput("Update Entity's Credit Score")]
        [CrmDefault("true")]
        public CrmBoolean UpdateEntity
        {
            get
            {
                return (CrmBoolean)base.GetValue(UpdateEntityProperty);
            }
            set
            {
                base.SetValue(UpdateEntityProperty, value);
            }
        }

        [CrmOutput("Credit Score")]
        [CrmAttributeTarget(_customEntity, "new_creditscore")]
        public CrmNumber CreditScore
        {
            get
            {
                return (CrmNumber)base.GetValue(CreditScoreProperty);
            }
            set
            {
                base.SetValue(CreditScoreProperty, value);
            }
        }
    }
}

See Also

Concepts


© 2010 Microsoft Corporation. All rights reserved.


Show:
© 2014 Microsoft