I have found that I needed to delete custom SObject records in bulk on the Force.com platform. If you are like me, you have done it before and just need to remember what is the best way to do it again. You also wished you documented it so that you do not have to dig around. In addition, if you are like me you want to make sure it is as efficient as possible. Some people might not like how I have implemented this and would provide suggestions to make it better. I welcome that, but if you do not have a clue how to do it, I hope to help. First, make sure you have a reference to the Salesforce API in your C# project. If you do not know how to do that, then send me a comment to add that post. I use the standard web reference in my .NET 3.5 windows application. It points to a local copy of the WSDL I generated from the force.com platform. Next, I made my own Salesforce Data Service class that handles the login and initialization of the SFBinding object that would allow me to make SOAP calls to the platform and handle the much needed action
Please note, I have decided to take advantage of the System.Linq and Microsoft.Practices.EnterpriseLibrary.ExceptionHandling namespaces in my code snippet. Make sure you have references to them when attempting to test this on your own. Thanks.
1: private SforceService SalesforceBinding
2: {
3: get
4: {
5: if ( _SfBinding == null || _SfBinding.SessionHeaderValue == null || _lastSForceLoginTime == null )
6: {
7: Login();
8: }
9: System.TimeSpan timeDif = System.DateTime.Now - _lastSForceLoginTime;
10: if ( timeDif.TotalMinutes > 30 )
11: {
12: Login();
13: }
14: return _SfBinding;
15: }
16: }
1: internal void DeleteExistingNodes()
2: {
3: QueryResult qr = this.SalesforceBinding.queryAll( "select Id from MyCustomObject__c where isdeleted=false" );
4: if ( qr.done )
5: {
6: if ( qr.size > 0 )
7: {
8:
9: var tsIds = (from q in qr.records
10: select q.Id).ToArray();
11:
12: int iRecordCount = 200;
13: DeleteResult[] ds = null;
14: for ( int t = 0 ; t < (System.Math.Abs(tsIds.Length/200)+1) ; t++)
15: {
16: if (t==0)
17: ds = this.SalesforceBinding.delete( tsIds.Take( iRecordCount ).ToArray() );
18: else
19: ds = this.SalesforceBinding.delete( tsIds.Skip((iRecordCount*t)).Take( iRecordCount ).ToArray() );
20:
21: if ( ds is DeleteResult[] )
22: {
23: for ( int i = 0 ; i < ds.Length ; i++ )
24: {
25: if ( !ds[ i ].success )
26: {
27: foreach ( Error err in ds[ i ].errors )
28: {
29: ExceptionPolicy.HandleException( new SalesforceException( err.message ) , "Global Policy" );
30: }
31: }
32: }
33: }
34: }
35: }
36: }
37: }
Comments