Bvrce
Bvrce

Reputation: 2170

Is OrganizationServiceProxy Connected?

What is the best way to tell if an OrganizationServiceProxy has successfully connected to CRM?

I am using GetEnumerator() on AccountSet as this fails if not connected.

/* Tries to connect to CRM and return false if failure - credentials arguments */
public bool Connect(string username, string password, string uri)
{
    try
    {
        var cred = new ClientCredentials();
        cred.UserName.UserName = username;
        cred.UserName.Password = password;
        service = new OrganizationServiceProxy(new Uri(uri), null, cred, null);
        service.EnableProxyTypes(); // Allow LINQ early bound queries
        linq = new Context(service);
        /* This is where I need help */
        var e = linq.AccountSet.GetEnumerator(); // this fails if not connected
    }
    catch
    {
        return false;
    }
    return true;        
}   


Service and Linq are private fields.
Context is the serviceContextName in crmsvcutil.exe.
I am in the habit of using the name "linq" for the Context object.

There must be a better way.

Upvotes: 1

Views: 987

Answers (1)

Guido Preite
Guido Preite

Reputation: 15128

The simplest way is to execute a WhoAmIRequest, this because when you connect to CRM you need to provide valid credentials.

If the credentials are correct the WhoAmIRequest will return the current user GUID, if are not correct the request will fail.

So your code can be:

public bool Connect(string username, string password, string uri)
{
    try
    {
        var cred = new ClientCredentials();
        cred.UserName.UserName = username;
        cred.UserName.Password = password;
        service = new OrganizationServiceProxy(new Uri(uri), null, cred, null);
        WhoAmIRequest request = new WhoAmIRequest();
        WhoAmIResponse response = (WhoAmIResponse)service.Execute(request);
        Guid userId = response.UserId;
    }
    catch
    {
        return false;
    }
    return true;        
}  

Upvotes: 3

Related Questions