17/12/2012

Error CRM Dynamics: Unable to cast object of type 'Microsoft.Xrm.Sdk.Entity' to type

Here is when I have experienced this problem:

I have created a console app in VS 2012 added references and created my organization service as following:
  
            ClientCredentials clientCredentials = new ClientCredentials();
            clientCredentials.UserName.UserName = "YourAdminUserName";
            clientCredentials.UserName.Password = "YourPassword";


            OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(
                new Uri("https://OnlineCRMSample.api.crm5.dynamics.com/XRMServices/2011/Organization.svc"),
                null,
                clientCredentials, null);
            
              orgProxy.Authenticate();

            var _service = (IOrganizationService)orgProxy;
Up to here you have created your Organization service and you can simple use organization service to create/retrieve and update objects from CRM. for instance this will add an account:
 
            Entity account = new Entity("account");
            account.Attributes["name"] = "MySoopaDoopaAccount";

            _service.Create(account);
However I wanted to use early binding classes instead of using late-bound. Hence, first I've generated the classes using CrmSvcUtil.exe shipped in the Bin folder of the SDK:
C:\SDK\sdk\bin>crmsvcutil.exe /url:https://YouronlineCRM.api.crm5.dynamics.com/XRMSe
rvices/2011/Organization.svc /username:youruserName /passwor
d:YourPassword /serviceContextName:HoomanContext /namespace:Hooman /out:Generat
edCode.cs
This generated a cs file calls "GeneratedCode" which I have added to my console app and used the following line to extract the list of active contacts:
            //--- Creating Service Context --//
            var context = new HoomanContext(_service);

            //----------- Extract the list of active contacts --------------//
            var contacts = context.ContactSet.Where(c => c.StateCode == ContactState.Active).ToList();

            foreach (var c in contacts)
            {
                Console.WriteLine(c.FirstName + " " + c.LastName);
            }

            Console.WriteLine("Done!");
            Console.ReadKey(true);
But I have received this following error message: Unable to cast object of type 'Microsoft.Xrm.Sdk.Entity' to type 'Hooman.Contact'.

How to Solve it?

Use enableProxyTypes method on your Organization Service proxy to fix it, here is the sample for generating organization service proxy properly:

 
            orgProxy.EnableProxyTypes();

            orgProxy.Authenticate();

            var _service = (IOrganizationService)orgProxy;

1 comment:

  1. Thanks a lot for your post. Just one line 'orgProxy.EnableProxyTypes' saved my hours.

    ReplyDelete