Get OrganizationServiceProxy from CrmOrganizationServiceContext in external MVC app

Viewed 3298

I'm want to be able to set the caller ID on my

XrmServiceContext : Microsoft.Xrm.Client.CrmOrganizationServiceContext

Context that has been generated for crm using svcutil.exe.

As far as I can tell I cant do this on an existing connection and I need to first create an instance of OrganizationServiceProxy set the CallerID and then pass it as a paramater to a new XrmServiceContext which I can then use instead.

However I'm kind of stuck on how I go from a CrmOrganizationServiceContext to having a OrganizationServiceProxy

The program is a separate .Net4.5 application

Any helpful tips or links?


Edit: Found this page just after posting this: http://msdn.microsoft.com/en-us/library/gg695810.aspx

So it may be as simple as:

    var connection = new CrmConnection("Xrm");
    connection.CallerId = uide;
    _serviceContext = new XrmServiceContext(connection);

Edit 2: It was not as simple as that. Doing this resulted in no change of what data I received.

    CrmConnection connection = new CrmConnection("Xrm");
    connection.CallerId = Guid.NewGuid();//u.Id;

    _serviceContext = new XrmServiceContext(connection);

It compiles and dosen't crash but I was suspicious when I used the id of a user with very low privledges but still got all data back, I then tried generating a new Guid for every instance of the XrmServiceContext but I am still getting everything back. So I am guessing it is not being used.. or I am missing something else.

Edit 3 Doing a WhoAmIRequest after the CallerID has been set still returns the same user that is set in the connection string.

Edit 4 Seems my problems are Cache related. In my implementation I need to first make a call to the service context to figure out the Guid of the user I want to impersonate. This call is made without CallerID set. If I skip this initial query and just set a specific Guid from the beginning the CallerID works. I'm guessing this is because the service context has cached my original CallerId or something similar.

Now I just have to figure out how to clear the cache in CRM 2013 SDK.

Edit 5 By turning of the cache completly using this guide: http://msdn.microsoft.com/en-us/library/gg695805.aspx I have gotten it to work. I would however prefer if I could just clear it out at the one point I need to instead of disabling it completly.

If someone can show me how to empty the service context cache using code I will mark that as the correct solution

2 Answers
Related