7.3 CRM Methods

The earlier post on handling Tax Codes is dependent on a number of methods that call the MSCRM Web Service to read data back from, or update or insert data into the MSCRM Database.

The following list of methods illustrates how these methods are used within the Tax Code Handling code, with the subsequent section listing the source code itself:

GetTaxCodeFromProduct Get the Tax Code associated to a particular Product in MSCRM
GetTaxCodeFromInvoice Get the Tax Code associated to a particular Invoice in MSCRM
GetAccountFromContact Get the Parent Account from a Contact record in MSCRM
GetDefaultTaxCodeFromAccount Get the Default Tax Code associated to a particular Account in MSCRM
GetDefaultTaxCode Gets the Tax Code flagged as the Default within MSCRM
GetTaxRateFromTaxCode Get Tax Rate (%) from a particular Tax Code in MSCRM
UpdateTaxAmount Updates an Invoice Line with the specified amount of Tax
Invoice_UpdateTaxCode Updates an Invoice record in MSCRM to associate the Invoice with the Tax Code indicated
InvoiceLine_UpdateTaxCode Updates a Invoice Line in MSCRM to associate the line with a Tax Code and Tax Rate

The following sourcecode then lists how these methods may be developed, using a pattern of encapsulating the CRM Webservice reference within a class containing a number of methods that invoke the Webservice to provide methods to the wider Business Logic.


public class PluginCRMMethods
{
    bool _useCrmService = false;
    ICrmService _service = null;
    CrmService _crmService = null;

    public PluginCRMMethods(ICrmService service)
    {
        _service = service;
        _useCrmService = false;
    }

    /// <param name="context">The execution context that was passed to the plug-in's Execute method.</param>
    /// <param name="flag">Set to True to use impersonation.</param>
    /// <returns>A CrmServce instance.</returns>
    public PluginCRMMethods(IPluginExecutionContext context, Boolean flag)
    {
        CrmAuthenticationToken authToken = new CrmAuthenticationToken();
        authToken.AuthenticationType = 0;
        authToken.OrganizationName = context.OrganizationName;

        // Include support for impersonation.
        if (flag)
            authToken.CallerId = context.UserId;
        else
            authToken.CallerId = context.InitiatingUserId;

        _crmService = new CrmService();
        _crmService.CrmAuthenticationTokenValue = authToken;
        _crmService.UseDefaultCredentials = true;

        // Include support for infinite loop detection.
        CorrelationToken corToken = new CorrelationToken();
        corToken.CorrelationId = context.CorrelationId;
        corToken.CorrelationUpdatedTime = context.CorrelationUpdatedTime;
        corToken.Depth = context.Depth;

        Microsoft.Win32.RegistryKey regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");

        _crmService.Url = String.Concat(regkey.GetValue("ServerUrl").ToString(), "/2007/crmservice.asmx");
        _crmService.CorrelationTokenValue = corToken;
        _useCrmService = true;
    }

    /// <summary>
    /// Get the Tax Code associated to a particular Product in MSCRM
    /// </summary>
    /// <param name="productId">The GUID Id of the Product record in MSCRM</param>
    /// <returns>The GUID Id of the associated Tax Code</returns>
    public Guid GetTaxCodeFromProduct(Guid productId)
    {
        try
        {
            ColumnSet cs = new ColumnSet(new string[] { "productid", "new_taxcodeid" });

            TargetRetrieveDynamic target = new TargetRetrieveDynamic();
            target.EntityName = "product";
            target.EntityId = productId;

            RetrieveRequest request = new RetrieveRequest();
            request.ColumnSet = cs;
            request.ReturnDynamicEntities = true;
            request.Target = target;

            RetrieveResponse response;

            if (_useCrmService == false)
            {
                response = (RetrieveResponse)_service.Execute(request);
            }
            else
            {
                response = (RetrieveResponse)_crmService.Execute(request);
            }

            if (response != null)
            {
                if (response.BusinessEntity != null)
                {
                    DynamicEntity product = (DynamicEntity)response.BusinessEntity;

                    if (product.Properties.Contains("new_taxcodeid") == true)
                    {
                        Microsoft.Crm.Sdk.Lookup new_taxcodeid = (Microsoft.Crm.Sdk.Lookup)product.Properties["new_taxcodeid"];

                        return new_taxcodeid.Value;
                    }
                    else
                    {
                        return Guid.Empty;
                    }
                }
                else
                {
                    return Guid.Empty;
                }
            }
            else
            {
                throw new Exception("Response from Webservice returned NULL");
            }
        }
        catch (System.Web.Services.Protocols.SoapException wex)
        {
            throw new Exception("PluginCRMMethods --> GetTaxCodeFromProduct (SOAP Exception : " + wex.Detail.InnerText + ")");
        }
        catch (Exception ex)
        {
            throw new Exception("PluginCRMMethods --> GetTaxCodeFromProduct (General Exception : " + ex.Message + ")");
        }
        finally
        {
            // 
        }            
    }

    /// <summary>
    /// Get the Tax Code associated to a particular Invoice in MSCRM
    /// </summary>
    /// <param name="productId">The GUID Id of the Invoice in MSCRM</param>
    /// <returns>The GUID Id of the associated Tax Code</returns>
    public Guid GetTaxCodeFromInvoice(Guid invoiceId)
    {
        try
        {
            ColumnSet cs = new ColumnSet(new string[] { "invoiceid", "new_taxcodeid" });

            TargetRetrieveDynamic target = new TargetRetrieveDynamic();
            target.EntityName = "invoice";
            target.EntityId = invoiceId;

            RetrieveRequest request = new RetrieveRequest();
            request.ColumnSet = cs;
            request.ReturnDynamicEntities = true;
            request.Target = target;

            RetrieveResponse response;

            if (_useCrmService == false)
            {
                response = (RetrieveResponse)_service.Execute(request);
            }
            else
            {
                response = (RetrieveResponse)_crmService.Execute(request);
            }

            DynamicEntity invoice = (DynamicEntity)response.BusinessEntity;

            if (invoice.Properties.Contains("new_taxcodeid") == true)
            {
                Microsoft.Crm.Sdk.Lookup new_taxcodeid = (Microsoft.Crm.Sdk.Lookup)invoice.Properties["new_taxcodeid"];

                return new_taxcodeid.Value;
            }
            else
            {
                return Guid.Empty;
            }
        }
        catch (System.Web.Services.Protocols.SoapException wex)
        {
            throw new Exception("PluginCRMMethods --> GetTaxCodeFromInvoice (SOAP Exception : " + wex.Detail.InnerText + ")");
        }

        catch (Exception ex)
        {
            throw new Exception("PluginCRMMethods --> GetTaxCodeFromInvoice (General Exception : " + ex.Message + ")");
        }
        finally
        {
            // 
        }
    }

    /// <summary>
    /// Get the Parent Account from a Contact record in MSCRM
    /// </summary>
    /// <param name="contactId">The GUID Id of the Contact in MSCRM</param>
    /// <param name="recursive">True/False flag determining whether to continue looking for a Parent Account if the Contact is associated to another Contact</param>
    /// <returns>The GUID Id of the associated Account</returns>
    public Guid GetAccountFromContact(Guid contactId, bool recursive)
    {
        try
        {
            ColumnSet cs = new ColumnSet(new string[] { "contactid", "parentcustomerid" });

            TargetRetrieveDynamic target = new TargetRetrieveDynamic();
            target.EntityName = "contact";
            target.EntityId = contactId;

            RetrieveRequest request = new RetrieveRequest();
            request.ColumnSet = cs;
            request.ReturnDynamicEntities = true;
            request.Target = target;

            RetrieveResponse response;

            if (_useCrmService == false)
            {
                response = (RetrieveResponse)_service.Execute(request);
            }
            else
            {
                response = (RetrieveResponse)_crmService.Execute(request);
            }

            DynamicEntity contact = (DynamicEntity)response.BusinessEntity;

            if (contact.Properties.Contains("parentcustomerid") == true)
            {
                Microsoft.Crm.Sdk.Customer parentcustomerid = (Microsoft.Crm.Sdk.Customer)contact.Properties["parentcustomerid"];

                if (parentcustomerid.type == "account")
                {
                    return parentcustomerid.Value;
                }
                else if (parentcustomerid.type == "contact")
                {
                    if (recursive == true)
                    {
                        return GetAccountFromContact(parentcustomerid.Value, true);
                    }
                }
            }

            return Guid.Empty;
        }
        catch (System.Web.Services.Protocols.SoapException wex)
        {
            throw new Exception("PluginCRMMethods --> GetAccountFromContact (SOAP Exception : " + wex.Detail.InnerText + ")");
        }
        catch (Exception ex)
        {
            throw new Exception("PluginCRMMethods --> GetAccountFromContact (General Exception : " + ex.Message + ")");
        }
        finally
        {
            // 
        }
    }

    /// <summary>
    /// Get the Default Tax Code associated to a particular Account in MSCRM
    /// </summary>
    /// <param name="accountId">The GUID Id of the Account in MSCRM</param>
    /// <returns>The GUID Id of the associated Tax Code</returns>
    public Guid GetDefaultTaxCodeFromAccount(Guid accountId)
    {
        try
        {
            ColumnSet cs = new ColumnSet(new string[] { "accountid", "new_taxcodeid" });

            TargetRetrieveDynamic target = new TargetRetrieveDynamic();
            target.EntityName = "account";
            target.EntityId = accountId;

            RetrieveRequest request = new RetrieveRequest();
            request.ColumnSet = cs;
            request.ReturnDynamicEntities = true;
            request.Target = target;

            RetrieveResponse response;

            if (_useCrmService == false)
            {
                response = (RetrieveResponse)_service.Execute(request);
            }
            else
            {
                response = (RetrieveResponse)_crmService.Execute(request);
            }

            DynamicEntity invoice = (DynamicEntity)response.BusinessEntity;

            if (invoice.Properties.Contains("new_taxcodeid") == true)
            {
                Microsoft.Crm.Sdk.Lookup new_taxcodeid = (Microsoft.Crm.Sdk.Lookup)invoice.Properties["new_taxcodeid"];

                return new_taxcodeid.Value;
            }
            else
            {
                return Guid.Empty;
            }
        }
        catch (System.Web.Services.Protocols.SoapException wex)
        {
            throw new Exception("PluginCRMMethods --> GetDefaultTaxCodeFromAccount (SOAP Exception : " + wex.Detail.InnerText + ")");
        }
        catch (Exception ex)
        {
            throw new Exception("PluginCRMMethods --> GetDefaultTaxCodeFromAccount (General Exception : " + ex.Message + ")");
        }
        finally
        {
            // 
        }
    }

    /// <summary>
    /// Gets the Tax Code flagged as the Default within MSCRM
    /// </summary>
    /// <returns>The GUID Id of the default Tax Code</returns>
    public Guid GetDefaultTaxCode()
    {
        try
        {
            ColumnSet cs = new ColumnSet(new string[] { "new_taxcodeid" });

            ConditionExpression ce = new ConditionExpression();
            ce.AttributeName = "new_isdefault";
            ce.Operator = ConditionOperator.Equal;
            ce.Values = new object[] { true };

            FilterExpression fe = new FilterExpression();
            fe.AddCondition(ce);

            QueryExpression query = new QueryExpression();
            query.ColumnSet = cs;
            query.Criteria = fe;
            query.EntityName = "new_taxcode";

            RetrieveMultipleRequest request = new RetrieveMultipleRequest();
            request.Query = query;
            request.ReturnDynamicEntities = true;

            RetrieveMultipleResponse response;

            if (_useCrmService == false)
            {
                response = (RetrieveMultipleResponse) _service.Execute(request);
            }
            else
            {
                response = (RetrieveMultipleResponse) _crmService.Execute(request);
            }

            if (response.BusinessEntityCollection != null)
            {
                if (response.BusinessEntityCollection.BusinessEntities.Count > 0)
                {
                    if (response.BusinessEntityCollection.BusinessEntities.Count == 1)
                    {
                        DynamicEntity de = (DynamicEntity)response.BusinessEntityCollection.BusinessEntities[0];

                        if (de.Properties.Contains("new_taxcodeid"))
                        {
                            Key new_taxcodeid = (Key) de.Properties["new_taxcodeid"];

                            return new_taxcodeid.Value;
                        }
                        else
                        {
                            throw new Exception("Default Tax Code found does not have Primary Key attribute?");
                        }
                    }
                    else
                    {
                        // multiple default Tax Codes
                        // throw as error for clarity
                        throw new Exception("Multiple Default Tax Codes defined for Organisation");
                    }
                }
            }

            return Guid.Empty;
        }
        catch (System.Web.Services.Protocols.SoapException wex)
        {
            throw new Exception("PluginCRMMethods --> GetDefaultTaxCode (SOAP Exception : " + wex.Detail.InnerText + ")");
        }
        catch (Exception ex)
        {
            throw new Exception("PluginCRMMethods --> GetDefaultTaxCode (General Exception : " + ex.Message + ")");
        }
        finally
        {
            // 
        }
    }

    /// <summary>
    /// Get Tax Rate (%) from a particular Tax Code in MSCRM
    /// </summary>
    /// <param name="taxCodeId">The GUID Id of the Tax Code record in MSCRM</param>
    /// <returns>The % Rate of Tax for the Tax Code</returns>
    public decimal GetTaxRateFromTaxCode(Guid taxCodeId)
    {
        try
        {
            ColumnSet cs = new ColumnSet(new string[] { "new_taxcodeid", "new_rate" });

            TargetRetrieveDynamic target = new TargetRetrieveDynamic();
            target.EntityName = "new_taxcode";
            target.EntityId = taxCodeId;

            RetrieveRequest request = new RetrieveRequest();
            request.ColumnSet = cs;
            request.ReturnDynamicEntities = true;
            request.Target = target;

            RetrieveResponse response;
            
            if ( _useCrmService == false )
            {
                response = (RetrieveResponse)_service.Execute(request);
            }
            else
            {
                response = (RetrieveResponse)_crmService.Execute(request);
            }

            if (response.BusinessEntity != null)
            {
                DynamicEntity taxcode = (DynamicEntity)response.BusinessEntity;

                if (taxcode.Properties.Contains("new_rate") == true)
                {
                    Microsoft.Crm.Sdk.CrmDecimal new_rate = (Microsoft.Crm.Sdk.CrmDecimal)taxcode.Properties["new_rate"];

                    return new_rate.Value;
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                return 0;
            }
        }
        catch (System.Web.Services.Protocols.SoapException wex)
        {
            throw new Exception("PluginCRMMethods --> GetTaxRateFromTaxCode (SOAP Exception : " + wex.Detail.InnerText + ")");
        }
        catch (Exception ex)
        {
            throw new Exception("PluginCRMMethods --> GetTaxRateFromTaxCode (General Exception : " + ex.Message + ")");
        }
        finally
        {
            // 
        }
    }

    /// <summary>
    /// Updates an Invoice Line with the specified amount of Tax
    /// </summary>
    /// <param name="invoiceDetailId">The GUID Id of the Invoice Detail Line in MSCRM</param>
    /// <param name="taxAmount">The amount of Tax calculated for the Invoice Detail Line</param>
    public void UpdateTaxAmount(Guid invoiceDetailId, decimal taxAmount)
    {
        try
        {
            KeyProperty invoicedetailid = new KeyProperty();
            invoicedetailid.Name = "invoicedetailid";
            invoicedetailid.Value = new Key();
            invoicedetailid.Value.Value = invoiceDetailId;

            CrmMoneyProperty tax = new CrmMoneyProperty();
            tax.Name = "tax";
            tax.Value = new CrmMoney();
            tax.Value.Value = taxAmount;

            DynamicEntity updateDe = new DynamicEntity();
            updateDe.Name = "invoicedetail";
            updateDe.Properties = new PropertyCollection();
            updateDe.Properties.Add(invoicedetailid);
            updateDe.Properties.Add(tax);

            TargetUpdateDynamic updateInvoiceLine = new TargetUpdateDynamic();
            updateInvoiceLine.Entity = updateDe;

            UpdateRequest request = new UpdateRequest();
            request.Target = updateInvoiceLine;

            UpdateResponse response;
            if (_useCrmService == false)
            {
                response = (UpdateResponse)_service.Execute(request);
            }
            else
            {
                response = (UpdateResponse)_crmService.Execute(request);
            }                
        }
        catch (System.Web.Services.Protocols.SoapException wex)
        {
            throw new Exception("PluginCRMMethods --> UpdateTaxAmount (SOAP Exception : " + wex.Detail.InnerText + ")");
        }
        catch (Exception ex)
        {
            throw new Exception("PluginCRMMethods --> UpdateTaxAmount (General Exception : " + ex.Message + ")");
        }
        finally
        {
            // 
        }
    }

    /// <summary>
    /// Updates an Invoice record in MSCRM to associate the Invoice with the Tax Code indicated
    /// </summary>
    /// <param name="invoiceDetailId">The GUID Id of the Invoice in MSCRM</param>
    /// <param name="taxCodeId">The Tax Code that is to be associated to the Invoice</param>
    public void Invoice_UpdateTaxCode(Guid invoiceId, Guid taxCodeId)
    {
        try
        {
            KeyProperty invoiceid = new KeyProperty();
            invoiceid.Name = "invoiceid";
            invoiceid.Value = new Key();
            invoiceid.Value.Value = invoiceId;

            LookupProperty new_taxcodeid = new LookupProperty();
            new_taxcodeid.Name = "new_taxcodeid";
            new_taxcodeid.Value = new Lookup();
            new_taxcodeid.Value.Value = taxCodeId;

            DynamicEntity updateDe = new DynamicEntity();
            updateDe.Name = "invoice";
            updateDe.Properties = new PropertyCollection();
            updateDe.Properties.Add(invoiceid);
            updateDe.Properties.Add(new_taxcodeid);

            TargetUpdateDynamic updateInvoiceLine = new TargetUpdateDynamic();
            updateInvoiceLine.Entity = updateDe;

            UpdateRequest request = new UpdateRequest();
            request.Target = updateInvoiceLine;

            UpdateResponse response;
            if (_useCrmService == false)
            {
                response = (UpdateResponse)_service.Execute(request);
            }
            else
            {
                response = (UpdateResponse)_crmService.Execute(request);
            }
        }
        catch (System.Web.Services.Protocols.SoapException wex)
        {
            throw new Exception("PluginCRMMethods --> Invoice_UpdateTaxCode (SOAP Exception : " + wex.Detail.InnerText + ")");
        }
        catch (Exception ex)
        {
            throw new Exception("PluginCRMMethods --> Invoice_UpdateTaxCode (General Exception : " + ex.Message + ")");
        }
        finally
        {
            // 
        }
    }

    /// <summary>
    /// Updates a Invoice Line in MSCRM to associate the line with a Tax Code and Tax Rate
    /// </summary>
    /// <param name="invoiceDetailId">The GUID Id of the Invoice Detail Line in MSCRM</param>
    /// <param name="taxCodeId">The Tax Code that is to be associated to the Invoice Line</param>
    /// <param name="taxRate">The Tax Rate that is to be used for the Invoice Line</param>
    public void InvoiceLine_UpdateTaxCode(Guid invoiceDetailId, Guid taxCodeId, decimal taxRate)
    {
        try
        {
            KeyProperty invoicedetailid = new KeyProperty();
            invoicedetailid.Name = "invoicedetailid";
            invoicedetailid.Value = new Key();
            invoicedetailid.Value.Value = invoiceDetailId;

            LookupProperty new_taxcodeid = new LookupProperty();
            new_taxcodeid.Name = "new_taxcodeid";
            new_taxcodeid.Value = new Lookup();
            new_taxcodeid.Value.Value = taxCodeId;

            CrmDecimalProperty new_taxrate = new CrmDecimalProperty();
            new_taxrate.Name = "new_taxrate";
            new_taxrate.Value = new CrmDecimal();
            new_taxrate.Value.Value = taxRate;

            DynamicEntity updateDe = new DynamicEntity();
            updateDe.Name = "invoicedetail";
            updateDe.Properties = new PropertyCollection();
            updateDe.Properties.Add(invoicedetailid);
            updateDe.Properties.Add(new_taxcodeid);
            updateDe.Properties.Add(new_taxrate);

            TargetUpdateDynamic updateInvoiceLine = new TargetUpdateDynamic();
            updateInvoiceLine.Entity = updateDe;

            UpdateRequest request = new UpdateRequest();
            request.Target = updateInvoiceLine;

            UpdateResponse response;
            if (_useCrmService == false)
            {
                response = (UpdateResponse)_service.Execute(request);
            }
            else
            {
                response = (UpdateResponse)_crmService.Execute(request);
            }
        }
        catch (System.Web.Services.Protocols.SoapException wex)
        {
            throw new Exception("PluginCRMMethods --> InvoiceLine_UpdateTaxCode (SOAP Exception : " + wex.Detail.InnerText + ")");
        }
        catch (Exception ex)
        {
            throw new Exception("PluginCRMMethods --> InvoiceLine_UpdateTaxCode (General Exception : " + ex.Message + ")");
        }
        finally
        {
            // 
        }
    }
}

For those following how to use these methods to incorporate the Tax Code functionality into their MSCRM Solution, this should give an idea of how these methods could be implemented for the earlier Plugins.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s