Created
August 30, 2023 20:32
-
-
Save MitchMilam/e113eb0a76c077e29f6d45d26a5535fb to your computer and use it in GitHub Desktop.
Dynamics 365: Delete Attachments from email messages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static void DeleteAttachments(CrmServiceClient crmService) | |
{ | |
const bool testing = true; | |
const int filesize = 0; | |
const string actualend = "2023-12-31T00:00:00-06:00"; | |
const string operationDescription = testing ? "Retrieved" : "Deleting"; | |
var query = new QueryExpression("email") | |
{ | |
Distinct = true, | |
}; | |
// ReSharper disable once ConditionIsAlwaysTrueOrFalse | |
if (testing) | |
{ | |
query.TopCount = 25; | |
} | |
query.ColumnSet.AddColumns( | |
"subject", | |
"activityid"); | |
query.Criteria.AddCondition("actualend", ConditionOperator.OnOrBefore, actualend); | |
var linkEntity = query.AddLink("activitymimeattachment", "activityid", "objectid"); | |
linkEntity.EntityAlias = "ag"; | |
linkEntity.Columns.AddColumn("activitymimeattachmentid"); | |
linkEntity.LinkCriteria.AddCondition("filesize", ConditionOperator.GreaterThan, filesize); | |
var results = crmService.RetrieveMultiple(query); | |
Console.WriteLine(); | |
Console.WriteLine("ATTACHMENT REMOVAL"); | |
Console.WriteLine($"\tFilesize greater than: {filesize}"); | |
Console.WriteLine($"\tOn or Before: {actualend}."); | |
Console.WriteLine(); | |
if (results.Entities == null || results.Entities.Count == 0) | |
{ | |
Console.WriteLine(); | |
Console.WriteLine("No attachment records were found using the above criteria."); | |
Console.WriteLine(); | |
Console.Write("Press any key..."); | |
Console.ReadKey(); | |
return; | |
} | |
for (var index = 0; index < results.Entities.Count; index++) | |
{ | |
var entity = results.Entities[index]; | |
var id = entity.GetAliasedAttributeValue<Guid>("ag.activitymimeattachmentid"); | |
Console.WriteLine($"{operationDescription}: {index + 1} of {results.Entities.Count}. ID: {id}"); | |
// ReSharper disable once ConditionIsAlwaysTrueOrFalse | |
if (!testing) | |
{ | |
crmService.Delete(ActivityMimeAttachment.EntityLogicalName, id); | |
} | |
} | |
Console.WriteLine(); | |
Console.WriteLine(); | |
Console.Write("Processing complete. Press any key..."); | |
Console.ReadKey(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment