Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Error when retrievieng Entity C#

Posted on by Microsoft Employee

I want to create and retrieve custom entity  using application writen in C#, my code was based on example from this site: https://msdn.microsoft.com/en-us/library/hh675400(v=crm.6).aspx

Run method from example looks like:

public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig) )
                {
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // Display information about the logged on user.
                    Guid userid = ((WhoAmIResponse)_serviceProxy.Execute(new WhoAmIRequest())).UserId;
                    SystemUser systemUser = (SystemUser)_serviceProxy.Retrieve("systemuser", userid, 
                        new ColumnSet(new string[] {"firstname", "lastname"}));
                    Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName);
 
                    // Retrieve the version of Microsoft Dynamics CRM.
                    RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
                    RetrieveVersionResponse versionResponse =
                        (RetrieveVersionResponse)_serviceProxy.Execute(versionRequest);
                    Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);


                    // Instantiate an account object. Note the use of the option set enumerations defined in OptionSets.cs.
                    // See the Entity Metadata topic in the SDK documentation to determine 
                    // which attributes must be set for each entity.
                    Account account = new Account { Name = "Fourth Coffee" };
                    account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
                    account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor);

                    // Create an account record named Fourth Coffee.
                    _accountId = _serviceProxy.Create(account);

                    Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

                    // Retrieve the account containing several of its attributes.
                    ColumnSet cols = new ColumnSet(
                        new String[] { "name", "address1_postalcode", "lastusedincampaign" });

                    Account retrievedAccount = (Account)_serviceProxy.Retrieve("account", _accountId, cols);
                    Console.Write("retrieved, ");

                    // Update the postal code attribute.
                    retrievedAccount.Address1_PostalCode = "98052";

                    // The address 2 postal code was set accidentally, so set it to null.
                    retrievedAccount.Address2_PostalCode = null;

                    // Shows use of a Money value.
                    retrievedAccount.Revenue = new Money(5000000);

                    // Shows use of a Boolean value.
                    retrievedAccount.CreditOnHold = false;

                    // Update the account record.
                    _serviceProxy.Update(retrievedAccount);
                    Console.WriteLine("and updated.");

                    DeleteRequiredRecords(promptforDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }


And my Run method:

public void Run(ServerConnection.Configuration serverConnect, bool promptForDelete)
        {
            try
            {
                //Connect to the organization service.
                //Using statement assures that the service proxy will be properly disposed
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConnect))
                {
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredMethod();

                    //Display information about the logged user
                    Guid userId = ((WhoAmIResponse)_serviceProxy.Execute(new WhoAmIRequest())).UserId;
                    // TODO:  manually enter user ID

                    SystemUser systemUser = (SystemUser)_serviceProxy.Retrieve("systemuser", userId, new ColumnSet(new string[] { "firstname", "lastname" }));
                    //Console.WriteLine("FirstName: {0}\t LastName: {1}\t id: {2}",systemUser.FirstName,systemUser.LastName, systemUser.Id);

                    //Retrieve the version of Microsoft Dynamics CRM.
                    RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
                    RetrieveVersionResponse versionResponse = (RetrieveVersionResponse)_serviceProxy.Execute(versionRequest);
                    Console.WriteLine("Microsoft Dynamics CRM Version:  {0}",versionResponse.Version);

                    //USING CODE GENERATED BY CrmSvcUtil.exe RATHER THAN MyOrganizationCrmSdkTypes
                    
                    Account account = new Account { Name = "Called from Desktop App " + DateTime.Now};
                    account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
                    account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Influencer);
                    //Create new account
                    _accountId = _serviceProxy.Create(account);

                    mb_entitytotestsimplesoap customEntity = new mb_entitytotestsimplesoap { mb_name = "Called from Desktop App " + DateTime.Now, mb_Numer=36 };
                    customEntity.mb_Numer = 36;
                    _customEntityId = _serviceProxy.Create(customEntity);
                    Console.WriteLine("Created custom entity with Id= " + _customEntityId);

                    Contact contact = new Contact {FirstName = "Called from Desktop App " + DateTime.Now,LastName = "AAA" };
                    contact.MobilePhone="4561237890";
                    contact.Address1_PrimaryContactName = "AAAAA";
                    _contactId = _serviceProxy.Create(contact);

                    //Retrieve account and custom entity containing several of its attributes
                    ColumnSet colsAcc = new ColumnSet(new String[] { "name", "address1_postalcode", "lastusedincampaign" });
                    ColumnSet colCus = new ColumnSet(new String[] { "mb_name" });
                    ColumnSet colCon = new ColumnSet(new String[] { "firstname","lastname" });

                    Account retrievedAccount = (Account)_serviceProxy.Retrieve("account", _accountId, colsAcc);
                    Contact retrievedContact = (Contact)_serviceProxy.Retrieve("contact", _contactId, colCon);
                    mb_developmententity retrievedEntity = (mb_developmententity)_serviceProxy.Retrieve("mb_developmententity", _customEntityId, colCus);

                                       
                }

            }
            catch (FormatException fExc)
            {
                Console.WriteLine("Format exception: " + fExc.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {

            }
        }


I got an error:
"mb_developmententity With Id = {id of entity} Does Not Exist"

Console prints:
0572.Capture.PNG
but I'm pretty sure, that these entities are created (they are because i cen view them in crm)

*This post is locked for comments

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,269 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,198 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans