Thursday, January 5, 2012

CRM 2011 Create a new Case (incident) using C#

using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using System.Runtime.Serialization;
namespace CreateIncident
{
    class Program
    {
        static void Main (string[] args)
        {
            try
            {
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = new System.Net.NetworkCredential
("username", "passw", "domain");

Uri organizationUri = new Uri("http://crmservername:port/orgname/XRMServices/2011/Organization.svc");
 
Uri homeRealmUri = null;
OrganizationServiceProxy orgService = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null); 
IOrganizationService _service = (IOrganizationService)orgService;
                              
Entity incident = new Entity(); 
incident.LogicalName = "incident";
 
incident["title"] = "Case subject..";
 
// Set customerid with some existing contact guid 
Guid customerid = new Guid("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}");
 
// Set customerid as contact to field "customerid" 
EntityReference CustomerId = new EntityReference("contact", customerid); 
incident["customerid"] = CustomerId;
 
// Set contactid with some existing contact guid 
Guid contactid = new Guid("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}");
 
// Set contactid as contact to field "casecontactid" 
EntityReference primaryContactId = new EntityReference("contact", contactid); 
incident["casecontactid"] = primaryContactId;
                                                      
_service.Create(incident);

            }
            catch (Exception e)
            {
                Console.Write(e.ToString());
            }
        }
    }
}

6 comments:

  1. Very Helpful .Thanks A lot !
    Is there a way to immediately get the id for the created incident (For example the service to return a guid) ? I would like to automatically add a phonecall under that case .
    Thanks anyway.

    ReplyDelete
  2. i'm glad that my article helped you! In this case i assume "incident.Id" would be right

    ReplyDelete
  3. Thanks A lot again for the fast reply. The Whole thing worked perfect . I am getting the id after calling the service like this
    var incidentId= service.Create(incident);

    ReplyDelete
  4. which tables are affected ?

    ReplyDelete