Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Deactivate a record using c# error

(0) ShareShare
ReportReport
Posted on by Microsoft Employee

Hi everyone, I'm trying to deactivate an account but it seems I'm missing something related to id. It's giving me an error

I need your help.

thank you

//------------ Start of function: Deactivate the created account------------------------------------------------------

public static void getDeactivatedbyaccount(string entityName, Guid accountid, IOrganizationService _service)
{

// Attributes I want to Deactivate: statecode, statuscode.
var cols = new ColumnSet(new string[] {"statecode", "statuscode", "accountid"});

//Check if it is Active or not active
// Entity account =_service.Retrieve("account", accountid, cols);
//Guid = ((EntityReference)account["account"]).Id;
var entity_parent = new EntityReference("account", accountid);
Entity account = _service.Retrieve("account",accountid, new ColumnSet(true));

if (account != null && account.GetAttributeValue<OptionSetValue>("statecode").Value == 0)
{
//StateCode = 1 and StatusCode = 2 for deactivating Account or Contact
SetStateRequest setStateRequest = new SetStateRequest()
{
EntityMoniker = new EntityReference
{
Id = accountid,
LogicalName = "account",
},
State = new OptionSetValue(1),
Status = new OptionSetValue(2)
};
_service.Execute(setStateRequest);
}
}

*This post is locked for comments

  • Suggested answer
    Gopalan Bhuvanesh Profile Picture
    Gopalan Bhuvanesh 11,399 on at
    RE: Deactivate a record using c# error

    Hi Goutham

    You can choose a specific random Guid for your newly created record. This is allowed through coding.

    The code by me has been tested and it works (I did not check the GetService method as I used my own method to get the service).

    But Create and Deactivate methods are working, I tested it with my organization. It needs refactoring, but left it as such to go along with the existing code.

  • Suggested answer
    Goutham A Profile Picture
    Goutham A on at
    RE: Deactivate a record using c# error

    Hi Faith,

    The error is bcause Account with that id does not exist. If you are using 2016 and above, please use web api to cretrive accounts and check if id is present

     "https://contosso.myorg.com/api/data/v8.0/accounts"
    "https://contosso.myorg.com/api/data/v8.0/accounts(59e61c6d-3015-e711-80dc-00155d004f8b)"

    ps : You can't create a GUID . Its generated by system

  • Suggested answer
    Gopalan Bhuvanesh Profile Picture
    Gopalan Bhuvanesh 11,399 on at
    RE: Deactivate a record using c# error

    The modified code works?

    Modifications are as follow:

    1. uncommented this

     public Guid g;

    2. Different Guid for Contact and Account

           public Guid contactid = new Guid("59E61C6D-3015-E711-80DC-00155D004F8B");//

           //public Guid accountId = new Guid("59E61C6D-3015-E711-80DC-00155D004F8B");

           public Guid accountId = new Guid("9f824a38-ba8f-41cd-97c0-5b16c7c5269c");

    3. Added the following

     contact.Id = contactid;

    account.Id = accountId;

    4. Added the following

     _service = GetService();

     _service = GetService();

    You need to delete the Account and Contact (delete manually by using the Browser client) created by this, to re-run this again. Otherwise it would throw error (Duplicate key ....), as Account/Contact with the same Guid is already in CRM.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Deactivate a record using c# error

    thank you so much Yes I have the correct org uri but it didnt work what did you changed ?

  • Suggested answer
    Gopalan Bhuvanesh Profile Picture
    Gopalan Bhuvanesh 11,399 on at
    RE: Deactivate a record using c# error

    HI

    Please find the fixed code.

     public partial class Form1 : Form

       {

           //Setting Organization Service name

           private OrganizationServiceProxy _serviceProxy;

           private IOrganizationService _service;

           // Calling the entity by name

           // private Entity new_Child = new Entity("new_child");

           // setting the id

           public Guid g;

           public Guid contactid = new Guid("59E61C6D-3015-E711-80DC-00155D004F8B");

           //public Guid accountId = new Guid("59E61C6D-3015-E711-80DC-00155D004F8B");

           public Guid accountId = new Guid("9f824a38-ba8f-41cd-97c0-5b16c7c5269c");

           public Form1()

           {

               InitializeComponent();

           }

           //----------- Connect to the organization and  create the crm service----------------

           private IOrganizationService GetService()

           {

               // URI Of the project

               String uri = "bpscrm2016/.../Organization.svc";

        int retries = 3;

               OrganizationServiceProxy orgProxy = null;

               int reconnectretries = 0;

               do

               {

                   try

                   {

                       reconnectretries++;

                       var organizationUri = new Uri(uri);

                       ClientCredentials credentials = new ClientCredentials();

                       // Early Bound

                       // credentials.Windows.ClientCredential = new NetworkCredential("Login", "Password", "Domain");

                       credentials.Windows.ClientCredential = new NetworkCredential("administrator", "@dmin2016", "testbps");

                       orgProxy = new OrganizationServiceProxy(organizationUri, null, credentials, null);

                   }

                   catch (Exception ex)

                   {

                   }

               } while (reconnectretries < retries && (orgProxy == null));

               return orgProxy;

           }

           //------------ Start of function: Create New Contact----------------------------------------------------------------------------

           private void button9_Click(object sender, EventArgs e)

           {

               //create new contact

               Entity contact = new Entity("contact");

               //attributes names and values

               contact.Attributes["firstname"] = "Joy";

               contact.Attributes["lastname"] = "Abi Rachid";

               contact.Attributes["fullname"] = "Joy Abi Rachid";

               OptionSetValue picklist = new OptionSetValue(3); // the index no of the option you want to set on OptionSet

               contact.Attributes.Add("preferredcontactmethodcode", picklist);

               OptionSetValue pickcode = new OptionSetValue(2);

               contact.Attributes.Add("familystatuscode", pickcode);

               contact.Attributes["anniversary"] = new DateTime(2014, 06, 04);

               contact.Id = contactid;

               // GetService() function

               _service = GetService();

               g = _service.Create(contact);

           }

           //------------ Start of function: Create New account--------------------------------------------------------------------

           private void button13_Click(object sender, EventArgs e)

           {

               //creates a new instance of EntityReference for a specific contact id; lookup primary contact

               EntityReference contactId = new EntityReference("contact", new Guid("59E61C6D-3015-E711-80DC-00155D004F8B"));

               //create new account

               Entity account = new Entity("account");

               account.Attributes["name"] = "Test";

               account.Attributes["telephone1"] = "71046800";

               account.Attributes["fax"] = "789654123";

               account.Attributes["numberofemployees"] = 100;

               OptionSetValue picklist2 = new OptionSetValue(6); // the index no of the option you want to set on OptionSet

               account.Attributes.Add("industrycode", picklist2);

               account.Attributes["creditlimit"] = new Money(6000);

               account.Attributes["creditonhold"] = true;

               //Primary Contact is a lookup field on account;

               //entity parent refer contact with the mentioned Guid is the primary contact.

               var entity_parentcontact = new EntityReference("account", contactId.Id);

               account.Attributes["primarycontactid"] = entity_parentcontact;

               // GetService() function

               account.Id = accountId;

               _service = GetService();

               // Create

               g = _service.Create(account);

           }

           //------------ Start of function: Deactivate the created account------------------------------------------------------

           public static void getDeactivatedbyaccount(string entityName, Guid accountId, IOrganizationService _service)

           {

               // Attributes I want to Deactivate: statecode, statuscode.

               var cols = new ColumnSet(new[] { "statecode", "statuscode" });

               //Check if it is Active or not active

               Entity account = _service.Retrieve("account", accountId, cols);

               try

               {

                   if (account != null && account.GetAttributeValue<OptionSetValue>("statecode").Value == 0)

                   {

                       //StateCode = 1 and StatusCode = 2 for deactivating Account or Contact

                       SetStateRequest setStateRequest = new SetStateRequest()

                       {

                           EntityMoniker = new EntityReference

                           {

                               Id = accountId,

                               LogicalName = "account",

                           },

                           State = new OptionSetValue(1),

                           Status = new OptionSetValue(2)

                       };

                       _service.Execute(setStateRequest);

                   }

               }

               catch (TimeoutException ex)

               {

                   //Exception Code

               }

           }

           //------------ Start of function: Deactivate the created contact-------------------------------------------------------

           public static void getDeactivatedbycontact(string entityName, Guid contactid, IOrganizationService _service)

           {

               // Attributes I want to Deactivate: statecode, statuscode.

               var cols = new ColumnSet(new[] { "statecode", "statuscode", "contactid" });

               //Check if it is Active or not active

               var contact = _service.Retrieve("contact", contactid, cols);

               if (contact != null && contact.GetAttributeValue<OptionSetValue>("statecode").Value == 0)

               {

                   //StateCode = 1 and StatusCode = 2 for deactivating Account or Contact

                   SetStateRequest setStateRequest = new SetStateRequest()

                   {

                       EntityMoniker = new EntityReference

                       {

                           Id = contactid,

                           LogicalName = "contact",

                       },

                       State = new OptionSetValue(1),

                       Status = new OptionSetValue(2)

                   };

                   _service.Execute(setStateRequest);

               }

           }

           private void button10_Click(object sender, EventArgs e)

           {

               _service = GetService();

               // Calling getDeactivatedbyaccount function to deactivate the record

               getDeactivatedbyaccount("account", accountId, _service);

           }

           private void button11_Click(object sender, EventArgs e)

           {

               _service = GetService();

               // Calling getDeactivatedbycontact function to deactivate the record

               getDeactivatedbycontact("contact", contactid, _service);

           }

       }

    This must work as long as you have the correct organization uri and GetService() method returns the service reference. (check it is not returning null object because of the wrong environment variables)

  • Verified answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Deactivate a record using c# error

    Are you sure that both contact and account have the same GUID? Please confirm the GUID of account by going into CRM, opening the account record, popout the window, copy the URL and get the GUID from the URL.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Deactivate a record using c# error

    This is my whole code:

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Net;

    using System.Net.NetworkInformation;

    using System.Runtime.InteropServices;

    using System.ServiceModel.Description;

    using System.Text;

    using System.Threading.Tasks;

    using System.Windows.Forms;

    using System.Windows.Forms.VisualStyles;

    using Microsoft.Crm.Sdk.Messages;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Client;

    using Microsoft.Xrm.Sdk.Messages;

    using Microsoft.Xrm.Sdk.Metadata;

    using Microsoft.Xrm.Sdk.Query;

    namespace Exercise1

    {

       public partial class Form1 : Form

       {

           //Setting Organization Service name

           private OrganizationServiceProxy _serviceProxy;

           private IOrganizationService _service;

           public Guid contactid = new Guid("59E61C6D-3015-E711-80DC-00155D004F8B");

           public Guid accountId = new Guid("59E61C6D-3015-E711-80DC-00155D004F8B");

           public Form1()

           {

               InitializeComponent();

           }

           //----------- Connect to the organization and  create the crm service----------------

           private IOrganizationService GetService()

           {

               // URI Of the project

      

               int retries = 3;

               OrganizationServiceProxy orgProxy = null;

               int reconnectretries = 0;

               do

               {

                   try

                   {

                       reconnectretries++;

                       var organizationUri = new Uri(uri);

                       ClientCredentials credentials = new ClientCredentials();

                       // Early Bound

                       // credentials.Windows.ClientCredential = new NetworkCredential("Login", "Password", "Domain");

              

                       orgProxy = new OrganizationServiceProxy(organizationUri, null, credentials, null);

                   }

                   catch (Exception ex)

                   {

                   }

               } while (reconnectretries < retries && (orgProxy == null));

               return orgProxy;

           }

    //------------ Start of function: Create New Contact----------------------------------------------------------------------------

           private void button9_Click(object sender, EventArgs e)

           {

               //create new contact

               Entity contact = new Entity("contact");

               //attributes names and values

               contact.Attributes["firstname"] = "Joy";

               contact.Attributes["lastname"] = "";

               contact.Attributes["fullname"] = "Joy ";

               OptionSetValue picklist = new OptionSetValue(3); // the index no of the option you want to set on OptionSet

               contact.Attributes.Add("preferredcontactmethodcode", picklist);

               OptionSetValue pickcode= new OptionSetValue(2);

               contact.Attributes.Add("familystatuscode", pickcode);

               contact.Attributes["anniversary"] = new DateTime(2014, 06, 04);

               // GetService() function

               _service = GetService();

               g = _service.Create(contact);

            }

    //------------ Start of function: Create New account--------------------------------------------------------------------

           private void button13_Click(object sender, EventArgs e)

           {

               //creates a new instance of EntityReference for a specific contact id; lookup primary contact

               EntityReference contactId = new EntityReference("contact", new Guid("59E61C6D-3015-E711-80DC-00155D004F8B"));

               //create new account

               Entity account = new Entity("account");

               account.Attributes["name"] = "Test";

               account.Attributes["telephone1"] = "";

               account.Attributes["fax"] = "";

               account.Attributes["numberofemployees"] = 100;

               OptionSetValue picklist2 = new OptionSetValue(6); // the index no of the option you want to set on OptionSet

               account.Attributes.Add("industrycode", picklist2);

               account.Attributes["creditlimit"] = new Money(6000);

               account.Attributes["creditonhold"]=true;

               //Primary Contact is a lookup field on account;

               //entity parent refer contact with the mentioned Guid is the primary contact.

               var entity_parentcontact = new EntityReference("account", contactId.Id);

               account.Attributes["primarycontactid"] = entity_parentcontact;

               // GetService() function

               _service = GetService();

               // Create

               g = _service.Create(account);

           }

           //------------ Start of function: Deactivate the created account------------------------------------------------------

           public static void getDeactivatedbyaccount(string entityName, Guid accountId, IOrganizationService _service)

           {

               // Attributes I want to Deactivate: statecode, statuscode.

               var cols = new ColumnSet(new [] {"statecode", "statuscode"});

               //Check if it is Active or not active

              Entity account = _service.Retrieve("account", accountId, cols);

               try

               {

                   if (account != null && account.GetAttributeValue<OptionSetValue>("statecode").Value == 0)

                   {

                       //StateCode = 1 and StatusCode = 2 for deactivating Account or Contact

                       SetStateRequest setStateRequest = new SetStateRequest()

                       {

                           EntityMoniker = new EntityReference

                           {

                               Id = accountId,

                               LogicalName = "account",

                           },

                           State = new OptionSetValue(1),

                           Status = new OptionSetValue(2)

                       };

                       _service.Execute(setStateRequest);

                   }

               }

               catch (TimeoutException ex)

               {

                   //Exception Code

               }

           }

    //------------ Start of function: Deactivate the created contact-------------------------------------------------------

           public static void getDeactivatedbycontact(string entityName, Guid contactid, IOrganizationService _service)

           {

               // Attributes I want to Deactivate: statecode, statuscode.

               var cols = new ColumnSet(new[] { "statecode", "statuscode", "contactid" });

               //Check if it is Active or not active

               var contact = _service.Retrieve("contact", contactid, cols);

               if (contact != null && contact.GetAttributeValue<OptionSetValue>("statecode").Value == 0)

               {

                   //StateCode = 1 and StatusCode = 2 for deactivating Account or Contact

                   SetStateRequest setStateRequest = new SetStateRequest()

                   {

                       EntityMoniker = new EntityReference

                       {

                           Id = contactid,

                           LogicalName = "contact",

                       },

                       State = new OptionSetValue(1),

                       Status = new OptionSetValue(2)

                   };

                   _service.Execute(setStateRequest);

               }

           }

           private void button10_Click(object sender, EventArgs e)

           {

               // Calling getDeactivatedbyaccount function to deactivate the record

              getDeactivatedbyaccount("account",accountId , _service);

           }

           private void button11_Click(object sender, EventArgs e)

           {

               // Calling getDeactivatedbycontact function to deactivate the record

               getDeactivatedbycontact("contact", contactid, _service);

           }

       }

    }

  • Suggested answer
    Gopalan Bhuvanesh Profile Picture
    Gopalan Bhuvanesh 11,399 on at
    RE: Deactivate a record using c# error

    account With Id = 59e61c6d-3015-e711-80dc-00155d004f8b Does Not Exist

    In which line you are getting this error? Is it the following line in the above method?

    Entity account = _service.Retrieve("account",accountid, new ColumnSet(true));

    Means Id is passed to the method, but could not retrieve it from CRM (because it does not exist).

    How did you check this id exists in CRM?

    *I created an account and contact with this Id..

    You created using code?

    Please verify those records are created and exist in CRM (just a sanity check).

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Deactivate a record using c# error

    It is a windows app by the way

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Deactivate a record using c# error

    Guid accountId is global.

    the error is : account With Id = 59e61c6d-3015-e711-80dc-00155d004f8b Does Not Exist

    but Actually it does I created an account and contact with this Id..

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

Congratulations 2024 Spotlight Honorees

Kudos to all of our 2024 community stars! 🎉

Meet the Top 10 leaders for December

Congratulations to our December super stars! 🥳

Start Your Super User Journey

Join the ranks of our community heros! 🦹

Leaderboard

#1
André Arnaud de Calavon Profile Picture

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

#2
Martin Dráb Profile Picture

Martin Dráb 230,458 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans