0
votes

I am having a trouble with Microsoft Dynamics CRM 2011. I would like to get a first connection in C#. I have all information to connect the CRM. I can do this on the browser.

Also I should add/remove a new record (if user fill contact form and press the button, I should add him to the CRM successfully).

Is there any clear and understandable example? I found something that confused my mind.

2

2 Answers

4
votes

you can connect to CRM like this:

  1. put this in your app-config to the "connectionStrings"-Tag:

    <add name="MyAppConfigString" connectionString="Url=http://myserver:5555/myorg;Domain=mydomain; Username=myuser; Password=mypassword"/>
    
  2. this is how to add a contact to CRM 2011/2013

var connection = new CrmConnection("MyAppConfigString");

using (var service = new OrganizationService(connection))
using (var context = new OrganizationServiceContext(service))
{
    var contactRecord = new Entity("contact");
    contactRecord.Attributes.Add("firstname", "Peter");
    contactRecord.Attributes.Add("lastname", "Jackson");

    context.AddObject(contactRecord);
    context.SaveChanges();
}

to delete a record, simple use this:

service.Delete("contact", myRecordId);

to retrieve a record you could use linq:

var query = context.CreateQuery("contact");

var result = query.FirstOrDefault(r => ((string) r["lastname"]) == "Jackson");

if(result != null)
{
    var recordId = result.Id;
}
3
votes

I would have commented on Tobias Koller's answer, but my low reputation prevent me to do so.

His solution is right, although, it's good to know that in order to test the connection to the CRM without creating any new record you can perform a WhoAmIRequest:

WhoAmIRequest userRequest = new WhoAmIRequest();
WhoAmIResponse user = (WhoAmIResponse)service.Execute(userRequest);

The returned value should be the user you used for the request.