CRM 2011 connect to organization.svc using C#

Greg Oks picture Greg Oks · Aug 7, 2012 · Viewed 21.3k times · Source

The CRM 2011 is setup with ADFS and HTTPS. I'm trying to connect to organization.svc from custom web page which sits on the same IIS with CRM 2011 but as a different web site using this code:

OrganizationServiceProxy serviceProxy;
ClientCredentials clientCredentials = new ClientCredentials();
clientCredentials.UserName.UserName = "admin";
clientCredentials.UserName.Password = "pass";

Guid contactId = Guid.Empty;

Uri OrganizationUri = new Uri(String.Format("https://organization.crmdev.com:port/XRMServices/2011/Organization.svc"));

Uri HomeRealmUri = new Uri(String.Format("https://organization.crmdev.com:port/XRMServices/2011/Discovery.svc"));

using (serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, clientCredentials, null))
{
    serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
    IOrganizationService service = (IOrganizationService)serviceProxy; 
    Entity contact = new Entity("contact");
    contact.Attributes["lastname"] = "oi oi";
    contactId = service.Create(contact);
}

It returns error message:

An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.ID3242: The security token could not be authenticated or authorized.

and in the event viewer I see error:

Account For Which Logon Failed:
    Security ID:        NULL SID
    Account Name:       admin
    Account Domain: 
Failure Reason:     Unknown user name or bad password.

although I give the correct user name and password..

and if I try to replace:

using (serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, clientCredentials, null))

with:

using (serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealUri, clientCredentials, null))

it returns:

Object reference not set to an instance of an object.

because serviceProxy is null.

Answer

James Wood picture James Wood · Aug 7, 2012

So, I'm just starting to use ADFS myself, I would suggest having a read of Active Directory and Claims-Based Authentication if you havnt already.

Also from looking at your code I don't think your HomeRealmUri is correct. You appear to have given it the address of the CRM Discovery Service. I think you are okay to leave it as null if you only have the single ADFS in play. As described in the MSDN here.

I would have expected it to look more like this: urn:federation:contoso

For the user name I believe you need to specify the domain, which you usually have to do in this format: username@domain

You might also want to look at this example its a single sign on web page that talks to Crm, which sounds a lot like what your trying to achieve.

Good luck.