How can we help?

Out of the box CRM has activities for Phone Calls, Emails, Tasks, Appointments, Letters or with custom activity entities anything you can imagine. In this example I’ll show you step by step how to create a simple application in C# that creates a task in CRM and associates it with a contact in the system using only the Organization Service endpoint.

First, login to your CRM Organization and Navigate to Settings -> Customizations

cobalt-customize
Next, click Developer Resources and copy the URL for the Organization Service (SOAP).
cobalt-developer-resources
Now, create a new project of your choosing in Visual Studio. For this example I will be creating a console application named CreateTaskCrm2013. Right Click the project in the Solution Explorer and choose “Add Service Reference”. Paste the Organization Service Url you copied above into the Address and Click Go. Set the namespace to CrmServices and Click OK.
cobalt-crm-services

In order to fix an issue in the generated proxy classes (VS 2010) pasted the following into a new .cs file or directly in the Program.cs outside the namespace  CreateTaskCrm2013 declaration.

 namespace CreateTaskCrm2013.CrmServices
{
    //These are here to fix an issue with serialization in the generated proxy
    [System.Runtime.Serialization.KnownTypeAttribute(typeof(OptionSetValue))]
    [System.Runtime.Serialization.KnownTypeAttribute(typeof(EntityReference))]
    public partial class Entity { }


    [System.Runtime.Serialization.KnownTypeAttribute(typeof(OptionSetValue))]
    [System.Runtime.Serialization.KnownTypeAttribute(typeof(EntityReference))]
    public partial class EntityCollection { }


    [System.Runtime.Serialization.KnownTypeAttribute(typeof(EntityReference))]
    [System.Runtime.Serialization.KnownTypeAttribute(typeof(PrincipalAccess))]
    [System.Runtime.Serialization.KnownTypeAttribute(typeof(OptionSetValue))]
    public partial class OrganizationRequest { }
}

 

Now add the following using statements.

 

 using System.ServiceModel.Channels;
using System.ServiceModel.Security.Tokens;
using System.ServiceModel;
using System.Net;
using CreateTaskCrm2013.CrmServices;

In order to create an instance of the Organization Service for CRUD operations add the following to the applications Program class.

 

 public static IOrganizationService OrgService { get; set; }

        public static void CreateCRMService(string serverHost, string organizationName, string userName, string domain, string password)
        {
            Uri OrgUri = new Uri(string.Format("{0}/{1}/XRMServices/2011/Organization.svc", serverHost, organizationName));

            SymmetricSecurityBindingElement symmetricSecurityBindingElement = new SymmetricSecurityBindingElement();
            symmetricSecurityBindingElement.ProtectionTokenParameters = new SspiSecurityTokenParameters();

            HttpTransportBindingElement httpTransportBindingElement = new HttpTransportBindingElement();
            httpTransportBindingElement.MaxReceivedMessageSize = 1000000000;

            CustomBinding customBinding = new CustomBinding();
            customBinding.Elements.Add(symmetricSecurityBindingElement);

            TextMessageEncodingBindingElement textMessageEncodingBindingElement = new TextMessageEncodingBindingElement(
                MessageVersion.Soap12WSAddressing10, Encoding.UTF8);
            customBinding.Elements.Add(textMessageEncodingBindingElement);
            customBinding.Elements.Add(httpTransportBindingElement);

            EndpointAddress endpointAddress = new EndpointAddress(OrgUri);

            OrganizationServiceClient organizationServiceClient = new OrganizationServiceClient(customBinding, endpointAddress);
            organizationServiceClient.ClientCredentials.Windows.ClientCredential = new NetworkCredential(userName, password, domain);

            OrgService = (IOrganizationService)organizationServiceClient;
        }

 

and finally inside the Main method of the Program class add the following code, substituting the url, organization name, user name, domain and password for your CRM Organization.

            CreateCRMService("http://[YOUR_CRM_ADDRESS]", 
                             "[YOUR_CRM_ORG_NAME]", 
                             "[YOUR_CRM_USERNAME]", 
                             "[YOUR_CRM_USER_DOMAIN]", 
                             "[YOUR_CRM_USER_PASSWORD]");
            //Select the first contact from CRM named Emaline Ochs to assign a task to.
            QueryExpression query = new QueryExpression();
            query.EntityName = "contact";

            FilterExpression expression = new FilterExpression();
            expression.FilterOperator = LogicalOperator.And;
            expression.Conditions = new ConditionExpression[] { new ConditionExpression(), new ConditionExpression() };
            expression.Conditions[0].AttributeName = "lastname";
            expression.Conditions[0].Operator = ConditionOperator.Equal;
            expression.Conditions[0].Values = new string[] { "Ochs" };

            expression.Conditions[1].AttributeName = "firstname";
            expression.Conditions[1].Operator = ConditionOperator.Equal;
            expression.Conditions[1].Values = new string[] { "Michael" };
            
            query.Criteria = expression;
            query.PageInfo = new PagingInfo();
            query.PageInfo.Count = 1;
            query.PageInfo.PageNumber = 1;
            query.ColumnSet = new ColumnSet();
            query.ColumnSet.Columns = new string[] { "contactid" };
            EntityCollection collection = OrgService.RetrieveMultiple(query);
            Entity contact = null;
            if (collection.Entities != null && collection.Entities.Length > 0)
            {
                //Found the contact we're looking for
                contact = collection.Entities[0];
            }
            else
            {
                //No contact found. Create a new contact.
                contact = new Entity();
                contact.LogicalName = "contact";
                AttributeCollection contactAttCollection = new AttributeCollection();
                //Assign an id to this contact. If not id is assigned the system will assign the id on create.
                contactAttCollection.Add(new KeyValuePair<string, object>("contactid", Guid.NewGuid()));
                contactAttCollection.Add(new KeyValuePair<string, object>("firstname", "Michael"));
                contactAttCollection.Add(new KeyValuePair<string, object>("lastname", "Ochs"));
                contact.Attributes = contactAttCollection;
                //Create the contact
                OrgService.Create(contact);
            }
            //Retrieve the contact id either retrieved or created above
            Guid contactId = (Guid)contact.Attributes[0].Value;
            Entity task = new Entity();
            //Set the logical name of the CRM Entity
            task.LogicalName = "task";

            AttributeCollection attCollection = new AttributeCollection();
            attCollection.Add(new KeyValuePair<string, object>("subject", "Testing Create with no SDK"));
            //Set the regarding to the contact using an EntityReference object.
            attCollection.Add(new KeyValuePair<string, object>("regardingobjectid", new EntityReference() 
                { Id = contactId, LogicalName = "contact" }));
            task.Attributes = attCollection;
            //Create the task
            OrgService.Create(task);

That’s it. Run the application and log back into CRM and search for the newly created “Michael Ochs” contact. Navigate to the contact’s activities and behold the associated activity record. Note: You may need to change the Filter in the Activities view from Next 30 Days to All.

Activities-crm

You can download the full source code and VS 2010 project here.  All code is provided “AS IS,” without express or implied warranty of any kind.

Request A Demo

Your time & resources are valuable.

Let's get started.