Wednesday, July 8, 2020

Microsoft Flow - Avoid Infinite Loop on Sharepoint Lists

In Flow triggers on a Sharepoint list, we have either to trigger on Create or Create and Modify. When we use triggers on Modify and if the flow logic has functionality to Update Current Item, then upon running this action, it triggers the flow again and thus leads to infinite internal loop.

The reason is all update actions, could be our own HTTP Rest API or the Update Item action, both would go though standard process and these updates would trigger any flows configured to run on modify. 

Till Microsoft  comes up with different actions to update, we can leverage Trigger Conditions, available in Trigger Settings.

Trigger conditions are basically, extra conditions we can configure to make sure the flow executes only if they are met. Like, run only if Status is Complete. 

And, to avoid this infinite looping, I follow below 2 approaches, based on the situation.

Approach 1: If we are using any System Account for all the connections, this would say any updates happened through a Flow would set the Modified By to the System Account. So, in this case, I use the trigger condition as to run only if the Modified by is no the System Account. 

In this way, even if the record is updated through different flow, no flow would be triggered. 

And the trigger condition is
                    @not(contains(triggerBody()['Editor']?['Claims'],'adminaccount@company.com'))

Here I used Claims property. we can use any other property like Display Name, email etc.


Approach 2: If we are not using dedicated Accounts, then we create a new DateTime column named FlowRunDate. And, in every update action, we make sure to set this column value to UtcNow().

Thus, if any update happened through flow, we would have FlowRunDate and Modified as same values. 
If its updated manually, Modified date changes, but not FlowRunDate. 

We use this condition to control the flow execution. And, the conditions is,

@or(
          empty(triggerBody()?['FlowRunDate']),
          greaterOrEquals(
                    ticks(triggerBody()?['Modified']),
                    ticks(addSeconds(triggerBody()?['FlowRunDate'],10))
              )
       )

Here the first condition to check if the field value is empty, i.e. for already existing records, it will be helpful. And, the section condition is we add 10 seconds to the FlowRunDate field value and compare with Modified field. If the difference is more than it, then the update is happened by external person ad thus trigger the flow.

We can have 5 seconds or soem other value, but some time is needed as there are chances that there could some fraction of seconds difference from Modified Date field from other fields in update event.




No comments:

Post a Comment