An interesting scenario came by my desk, where someone wanted to take attachments from the current item, move them to a document library in SharePoint, and then delete those attachments, so that there weren't duplicate files. A great scenario that Nintex Workflow is perfect for.
This is scenario that I think many of you have come across, or may in the future. The actual deletion of the attachments is something I found I could put into a User Defined Action, because it makes it that much easier to reuse in other workflows. It also makes it very easy to share with everyone.
As you can see, there isn't that much to this UDA. SharePoint comes with the Lists.asmx web service. Essentially, we are using two of the web methods it provide. The GetAttachmentCollection and the DeleteAttachment.
The GetAttachmentCollection web method will return XML, which we can get data out of, using the Query XML action. This pulls out each attachment URL and stores it in a Nintex Workflow collection variable.
Then, we iterate through each URL and we call the DeleteAttachment web method, to delete that off of the current item.
In the screenshot above, you can see that I'm utilizing some common properties, like the Web URL, List Name and the item property ID. This makes the UDA dynamic, so that it works on the item I'm currently running my workflow on. If you want to extend this UDA, you could add some parameters to specify the List Name and the Item ID, and that way, it could be made to delete attachments from items anywhere in the site.
The result is stored in a Text variable, so that we can parse it.
The Query XML action is using a very simple XPath expression, //defaultNS:Attachment, to pull out all the attachment URLs from the XML and store them in the collection variable.
Now that we have all the Attachment URLs in a collection variable, we can use the For Each action to iterate through each of the URLs. One of the great features of the For Each, is that although it is a loop, it isn't affected by Safe Looping. So there is no delay between each iteration of the For Each.
The final action in the UDA, is the Call Web Service action that calls the DeleteAttachment web method. Again, we are using common properties like Web URL, ListName and the Item property ID. We are also passing in the URL that we have within the For Each.
As I mentioned above, this UDA is limited to the current item the workflow is running on. But you could enhance this UDA with these options:
1. add parameters to handle List Name, Item ID and even a Site URL so that the UDA can delete attachments from any item in any site.
2. add error handling to the Call Web Service. This is always a good preventative option so that if any issue occur, you can capture the error and do something with it.
3. add logic to the For Each action, so that only a subset of the attachments are removed. eg. you may want to keep PDFs attached, and everything else removed.