Friday, January 18, 2013

Adding/updating records to CRM using dynamic entities

This example shows how to use WCF to add records to an existing CRM entity.
  1. Create a windows application project, and add the following references:

    Review MSDN:
    In order to work with the classes you also need to add references to the following Microsoft Dynamics CRM and .NET assemblies:


    C:\CRM\sdk\bin\microsoft.crm.sdk.proxy.dll
    C:\CRM\sdk\bin\microsoft.xrm.client.dll
    C:\CRM\sdk\bin\microsoft.xrm.portal.dll
    C:\CRM\sdk\bin\microsoft.xrm.portal.files.dll
    C:\CRM\sdk\bin\microsoft.xrm.sdk.dll


    NOTE: YOU HAVE TO USE THE .NET FRAMEWORK 4 AS THE TARGET FRAMEWORK, AND NOT THE .NET FRAMEWORK 4 CLIENT PROFILE

  2. Create a windows form and add the following Usings:

    using System;
    using System.ServiceModel.Description;
    using System.Windows.Forms;
    using Microsoft.Crm.Sdk.Messages;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Xrm.Sdk.Query;
     
  3. Add the following labels and textboxes to the form:
    • Server URL: textBoxServerUrl
    • Org: textBoxOrg
    • Domain: textBoxDomain
    • UserName: textBoxName
    • Password: textBoxPassword
  4. Add another label and textbox, with an Add button:

    • Account name: textboxAccountName
    • buttonAdd: Add account
  5. You should have something that looks like this: 
  6. Embed this code in the click event of the AddNewRecord button:
    //SET UP CREDENTIALS
    Uri OrganizationUri = new Uri(textBoxServerUrl.Text + "/" + textBoxOrg.Text + "/XRMServices/2011/Organization.svc");
    ClientCredentials Credentials = new ClientCredentials();
    Credentials.Windows.ClientCredential = new System.Net.NetworkCredential(textBoxName.Text, textBoxPassword.Text, textBoxDomain.Text);

    //INITIALIZE PIPELINE SERVICE
    OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, Credentials, null);
    serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
    IOrganizationService service = (IOrganizationService)serviceProxy;

    Entity a = new Entity("account");
    a["name"] = textBoxAccountName.Text;
    service.Create(a); 
  7.  Run the code, and fill in a value in the account name, then click the Add new record button. Go to CRM and refresh the account list, there will be your new account.

The following code UPDATES records on CRM:

using System;
using System.ServiceModel.Description;
using Applications.LoanAccounting.BillsAndStatements.Properties;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;

namespace Applications.LoanAccounting.BillsAndStatements
{
    public class XRMWriter
    {
 
 
        #region Private members
 
        private string _server;
        private string _login;
        private string _password;
        private string _domain;
        private ClientCredentials _credentials;
 
        #endregion
 
 
        #region Constructor
        public XRMWriter()
        {
            try
            {
                _login = (string)Settings.Default["CRMUserLoginId"];
                _password = (string)Settings.Default["CRMUserPassword"];
                _domain = (string)Settings.Default["CRMUserDomainName"];
                _server = (string)Settings.Default["CRMServerUrl"];
 
                _credentials = new ClientCredentials();
                _credentials.Windows.ClientCredential = new System.Net.NetworkCredential(_login, _password, _domain);
 
            }
            catch (Exception ex)
            {
               
                throw;
            }
        }
        #endregion
 
 
        #region General private methods
 
        /// <summary>
        /// Gets a CRM service
        /// </summary>
        /// <param name="org">Name of the Org that writing to</param>
        /// <returns>Instance of IOrganizationService</returns>
        private IOrganizationService GetXrmService(string org)
        {
 
            try
            {
                Uri OrganizationUri = new Uri(String.Format("{0}/{1}/XRMServices/2011/Organization.svc", _server, org));
 
                ////INITIALIZE PIPELINE SERVICE
                using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, _credentials, null))
                {
                    serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                    return (IOrganizationService)serviceProxy;
                }
 
 
            }
            catch (Exception ex)
            {
               
                throw;
            }
        }
 
        #endregion
 
 
        #region General public methods
        /// <summary>
        /// Updates the specified XRM BillHeader with the name of the PDF document
        /// </summary>
        /// <param name="org">The name of the org that coontains the bill header</param>
        /// <param name="billHeaderId">The unique identifier for this bill header instance</param>
        /// <param name="pdfUrl">The fully qualified location where this PDF got saved.</param>
        public void SaveBillFileNameToXRM(string org, Guid billHeaderId, string pdfUrl)
        {
 
            IOrganizationService xrmService = GetXrmService(org);
 
 
 
            // the ConditionExpression generates a where-clause:
            // (fcbt_billheaderid = billHeaderId)
            ConditionExpression condition = new ConditionExpression();
            condition.AttributeName = "fcbt_billheaderid";
            condition.Operator = ConditionOperator.Equal;
            condition.Values.Add(billHeaderId);
 
 
           
            //Now add the the condition(where-clause) to the filter expression:
            // (WHERE fcbt_billheaderid = billHeaderId)
            FilterExpression filter = new FilterExpression();
            filter.FilterOperator = LogicalOperator.And;
            filter.Conditions.Add(condition);
 
 
            //Now use the filter expression in a query:
            //(SELECT * from [fcbt_billheader] WHERE fcbt_billheaderid = billHeaderId
            QueryExpression query = new QueryExpression();
            query.EntityName = "fcbt_billheader";
 
            ColumnSet columnSet = new ColumnSet();       // new ColumnSet(true) -> will retreive all properties.
            columnSet.Columns.Add("fcbt_pdfurl");
            columnSet.Columns.Add("fcbt_lastrendereddate");
 
            query.ColumnSet = columnSet;
            query.Criteria = filter;
 
 
            EntityCollection entityCollection = xrmService.RetrieveMultiple(query);
 
            Entity BillHeaderEntity = entityCollection[0];
 
            BillHeaderEntity.Attributes["fcbt_pdfurl"] = pdfUrl;
            BillHeaderEntity.Attributes["fcbt_lastrendereddate"] = DateTime.Now;
            xrmService.Update(BillHeaderEntity);
 
        }
 
        #endregion
 
    }
}

No comments:

Post a Comment