5 Mei 2022

Implementing Spider Workflow in Power Automate

There are many patterns to implement different types of workflow using Power Automate. But one that strikes me a lot in terms of the dynamicity, is the spider workflow. There are not much of reference out there, it was (in my work history) implemented in a project in one of the prestigious client in Singapore, sparked by my technical architect.

Drawing1

It’s called spider because… of course it looks like a spider. This pattern can be repeated in many projects and even one can implement the template for it in Power Automate. This pattern mainly to overcome a problem when the workflow is not well-defined, prone to change, or to provide dynamic ever-changing workflow without re-work of the entire workflow.

Implementing Spider Workflow

The main concept of this workflow is to loop the process back to the controller after the decision of the next path. The first step to work this out, is to define how many distinctive tasks that a process can do. In the sample diagram above, there are 5 paths that goes everywhere with one of them proceed to end the workflow. The other four, goes back to the controller to decide what’s the next path after an outcome is reached. In the real-world, it can spawn more than 5 or less, depending on the requirement.

The second step, you need to run your thought process to link up between an outcome with the next path. To give you an example, if say the initial flow goes to Approval first (Path 1), definitely it will have 2 outcomes whether it’s Approve or Reject. You could make a story where after the first approval, it will go to another level of approval if the outcome is Approve (Path 1). Otherwise if it’s Reject, you then decide to flow it to End the workflow (Path 3). If you get the feel of your own thought process thoroughly, you could end up having the exact same flow like in the diagram below.

Drawing2

Now, how do we take care of the workflow’s most important mechanism such as notifying the requestor or setting the workflow status once it’s completing one stage? These mechanism you actually can put under the controller itself since it’s executed every time it passes with another path decision.

Be very careful when you run your thought process, do avoid any process that potentially goes into an endless loop (because it can happen). The design itself is perfect, this endless loop can happen due to misconfiguration. Wait, there’s configuration?

Spider Workflow Configuration

There is a configuration to accompany this flow. You could actually leverage on anything to store, literally. Back in my old days, all workflow data are stored as a row in a SQL Server database. Nowadays, you can just work out the JSON configuration and let the configuration be parsed by the flow. Let’s take a sample on how you can define the JSON structure for just one single stage.


{
	"Index": 2,
	"Stage": "Approval 1",
	"Status": "Pending Approver 1",
	"Type": "BasicApproval",
	"SendAttachment": true,
	"AssignedTo": "Dynamic",
	"Outcomes": [
		{
			"Outcome": "Approve",
			"Next Index": 3
		},
		{
			"Outcome": "Reject",
			"Next Index": 6
		}
	]
}

As above is just a simple sample, you could define your own JSON that depicts the flow process. To summarize,

  • Index – defines the index of this current path.
  • Stage – defines the current stage name (or whatever you want to define as the state of the current flow).
  • Status – defines the workflow status for the current path.
  • Type – defines the path where to go. If you could link this up with the first diagram above, it’s the Path 1.
  • SendAttachment – typically the current controller’s configuration to send attachment to the approver. You can also add your own other configuration.
  • AssignedTo – is also the current controller’s configuration to take the approver list dynamically from a table or database. The other values can also be “Requestor” where it will assign to the initiator of the flow.
  • Outcomes – defines the routing! You can read it simply by say if the outcome is “Approve”, go to the object that the index is 3. Else if it’s “Reject”, go to index 6.

Now, if you run your thought process, you could define a JSON configuration for the entire process just like below.


[
  {
    "Index": 0,
    "Stage": "Resubmission",
    "Status": "Pending Resubmission",
    "Type": "Closure",
    "SendAttachment": true,
    "AssignedTo": "Requestor"
  },
  {
    "Index": 1,
    "Stage": "Review",
    "Status": "Pending Project Admin Review",
    "Type": "CustomApproval",
    "SendAttachment": true,
    "Actions": [
      "Checked",
      "Return"
    ],
    "AssignedTo": "Dynamic",
    "Outcomes": [
      {
        "Outcome": "Checked",
        "Next Index": 2
      },
      {
        "Outcome": "Return",
        "Next Index": 0
      }
    ]
  },
  {
    "Index": 2,
    "Stage": "Approval 1",
    "Status": "Pending Approver 1",
    "Type": "BasicApproval",
    "SendAttachment": true,
    "AssignedTo": "Dynamic",
    "Outcomes": [
      {
        "Outcome": "Approve",
        "Next Index": 3
      },
      {
        "Outcome": "Reject",
        "Next Index": 6
      }
    ]
  },
  {
    "Index": 3,
    "Stage": "Approval 2",
    "Status": "Pending Approver 2",
    "Type": "BasicApproval",
    "SendAttachment": true,
    "AssignedTo": "Dynamic",
    "Outcomes": [
      {
        "Outcome": "Approve",
        "Next Index": 4
      },
      {
        "Outcome": "Reject",
        "Next Index": 6
      }
    ]
  },
  {
    "Index": 4,
    "Stage": "Super Admin",
    "Status": "Pending Super Admin",
    "Type": "CustomApproval",
    "SendAttachment": true,
    "Actions": [
      "Complete Request"
    ],
    "AssignedTo": "Dynamic",
    "Outcomes": [
      {
        "Outcome": "Complete Request",
        "Next Index": 5
      }
    ]
  },
  {
    "Index": 5,
    "Stage": "Closed",
    "Status": "Completed",
    "Type": "Closure"
  },
  {
    "Index": 6,
    "Stage": "Closed",
    "Status": "Rejected",
    "Type": "Closure"
  }
]


Lastly, this blog is just a conceptual idea that you can implement in each project you go on either with Nintex, Power Automate, K2, or any other cloud workflow out there.

16 Nov 2018

Add PowerShell Context Menu to Windows Explorer

Do you want to get this in your laptop?

image

Here is what you should do. Open regedit.

image

Navigate to HKEY_CLASSES_ROOT\Directory. You will need to focus on 2 keys, Background\shell and shell alone.

image

Background\shell basically to control when you are right-clicking at nothing inside a folder.

D1AF38B4-E1D5-41E8-8E0D-32837C4AE45A

Lastly, you can copy the code below and save it with .reg extension.


Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\Background\shell\PowerShellHere]
@="Open PowerShell Here"
"Icon"="%SystemRoot%\\system32\\WindowsPowerShell\\v1.0\\powershell.exe"

[HKEY_CLASSES_ROOT\Directory\Background\shell\PowerShellHere\command]
@="powershell.exe -noexit"

[HKEY_CLASSES_ROOT\Directory\shell\PowerShellHere]
@="Open PowerShell Here"
"Icon"="%SystemRoot%\\system32\\WindowsPowerShell\\v1.0\\powershell.exe"

[HKEY_CLASSES_ROOT\Directory\shell\PowerShellHere\command]
@="powershell.exe -noexit -command Set-Location '%V'"

10 Apr 2018

Connecting to Microsoft OAuth 2.0

Connecting to OAuth 2.0 authentication might be a common and critical task to do for many developers, especially in Microsoft Office 365 environment. It could be a connection to OneDrive, Excel, SharePoint, OneNote, even the big developer platform such as Microsoft Graph. It could be connecting to any other cloud app services such as twitter, facebook, google, pinterest, or any other cloud services in this world.

You can take a look to find out how we deal with Microsoft OAuth 2.0 authorization code is retrieved and how the flow works for you at: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols-oauth-code.

In practical way, you can follow my step-by-step below if you find the article is not clear enough or lack of examples. This article will be focusing on Microsoft Online credential which can be used with Azure Active Directory or Microsoft Online account.

finger-769300_640


Registering Your App

Before you can make connection to any cloud services using OAuth 2.0, you would need 2 things, Client ID and Client Secret. Anything that connects using OAuth 2.0 is considered an app, and you need to register that before proceeding. This will usually generates you a Client ID and commonly with Client Secret, which acts same like your own username and password.

15 Agu 2017

PowerShell Script: List Files and Sub-Folders in a SharePoint Document Library

Just want to share to you guys for today, which I hope it will help you out when you need it. I’ve been writing a few about PowerShell before, PowerShell Script upload large file. Here is the script to list all files and sub-folders in a SharePoint Document Library.

Syntax:
.\SPDocContent.ps1 [[-Credential] <PSCredential>] [-URL] <String> [-DocumentLibrary] <String> [[-BaseFolderPath] <String>] [[-CSVPath] <String>] [<CommonParameters>]



##############################################################################
#.SYNOPSIS
# Gets a list of files, folders and sub-folders in a SharePoint Online Document Library.
#
#.DESCRIPTION
# Gets a list of files, folders and sub-folders in a SharePoint Online Document Library.
#
#.PARAMETER Credential
# The credential to access with SharePoint Online.
#
#.PARAMETER URL
# The URL of the SharePoint site (can be a sub-site or root site).
#
#.PARAMETER Document Library
# The Document Library name to connect to.
#
#.PARAMETER BaseFolderPath
# Start from particular sub-folder (optional).
#
#.PARAMETER CSVPath
# The path of the CSV file to export the result.
#
#.EXAMPLE
# $Crd = Get-Credential
# .\SPDocContent.ps1 -URL "https://rdz.sharepoint.com" -DocumentLibrary "Documents" -CSVPath "D:\Documents.csv"
##############################################################################

[Cmdletbinding()]
param (
	[Parameter(Mandatory = $false)]
    [System.Management.Automation.PSCredential]$Credential = $null,
    [Parameter(Mandatory=$true)]
    [string]$URL,
    [Parameter(Mandatory=$true)]
    [string]$DocumentLibrary,
    [Parameter(Mandatory=$false)]
    [string]$BaseFolderPath,
	[Parameter(Mandatory = $false)]
    [string]$CSVPath = ""
)

Function ListContent(
    [Parameter(Mandatory=$true)]
    [Microsoft.SharePoint.Client.Folder]$BaseFolder,
    [Parameter(Mandatory=$false)]
    [switch]$Recursive = $false,
    [Parameter(Mandatory=$false)]
    [Microsoft.SharePoint.Client.Folder]$RootFolder,
    [Parameter(Mandatory=$false)]
    [int]$Level = 0
)
{
    $ContentInfo = @()

    $RootLevel = $false;
    $ctx.Load($BaseFolder.Folders)
    $ctx.Load($BaseFolder.Files)
    $ctx.Load($BaseFolder.ParentFolder)
    $ctx.ExecuteQuery()

    if ($RootFolder -eq $null) { $RootLevel = $true; $RootFolder = $BaseFolder; }
    $tabsRepeat = New-Object System.String("`t", ($Level + 1))

    if ($BaseFolder.Folders.Count -gt 0)
    {
        Write-Host "$($tabsRepeat)$($BaseFolder.Folders.Count) sub-folders for $($BaseFolder.ServerRelativeUrl.Replace($RootFolder.ServerRelativeUrl + "/", [System.String]::Empty))" -ForegroundColor Yellow
        for ($i = 0; $i -lt $BaseFolder.Folders.Count; $i++)
        {
            $ctx.Load($BaseFolder.Folders[$i])
            $ctx.ExecuteQuery()
            if ($BaseFolder.Folders[$i])
            {
                if (($RootLevel -and $BaseFolder.Folders[$i].Name -ne "Forms") -or -not $RootLevel)
                {
                    Write-Host "$($tabsRepeat)$($BaseFolder.Folders[$i].ServerRelativeUrl.Replace($RootFolder.ServerRelativeUrl + "/", [System.String]::Empty))"
                    $ContentInfo += [pscustomobject]@{
                        RelativePath = "$($BaseFolder.Folders[$i].ServerRelativeUrl.Replace($RootFolder.ServerRelativeUrl + "/", [System.String]::Empty))";
                        Type = "Folder";
                        Name = "$($BaseFolder.Folders[$i].Name)";
                        Level = $Level;
                    };

                    if ($Recursive -eq $true)
                    {
                        $ContentInfo += (ListContent -BaseFolder $BaseFolder.Folders[$i] -RootFolder $RootFolder -Recursive:$Recursive -Level ($Level + 1))
                    }
                }
            }
        }
    }
    if ($BaseFolder.Files.Count -gt 0)
    {
        Write-Host "$($tabsRepeat)$($BaseFolder.Files.Count) sub-files for $($BaseFolder.ServerRelativeUrl.Replace($RootFolder.ServerRelativeUrl + "/", [System.String]::Empty))" -ForegroundColor Yellow
        for ($i = 0; $i -lt $BaseFolder.Files.Count; $i++)
        {
            $ctx.Load($BaseFolder.Files[$i])
            $ctx.ExecuteQuery()
            if ($BaseFolder.Files[$i])
            {
                $ContentInfo += [pscustomobject]@{
                    RelativePath = "$($BaseFolder.Files[$i].ServerRelativeUrl.Replace($RootFolder.ServerRelativeUrl + "/", [System.String]::Empty))";
                    Type = "File";
                    Name = "$($BaseFolder.Files[$i].Name)";
                    Level = $Level;
                };
                Write-Host "$($tabsRepeat)$($BaseFolder.Files[$i].ServerRelativeUrl.Replace($RootFolder.ServerRelativeUrl + "/", [System.String]::Empty))"
            }
        }
    }
    return $ContentInfo;
}

$ContentInfo = @()
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($URL)
Try
{
    if ($Credential)
    {
        if ($Credential.GetType().FullName -eq "Microsoft.SharePoint.Client.SharePointOnlineCredentials")
        {
            $ctx.Credentials = $Credential
        } elseif ($Credential.GetType().FullName -eq "System.Management.Automation.PSCredential")
        {
            $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Credential.Username,$Credential.Password)
        }
    }
    elseif ($PSCrd)
    {
        Write-Host "No credential set, retrieving from `$PSCrd." -ForegroundColor Yellow
        $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($PSCrd.Username,$PSCrd.Password)
    }
    elseif ($SPCrd)
    {
        Write-Host "No credential set, retrieving from `$SPCrd." -ForegroundColor Yellow
        $ctx.Credentials = $SPCrd
    }
    else
    {
        Write-Host "No credential set, none retrieved." -ForegroundColor Red -BackgroundColor Black
        exit
    }

    $Site = $ctx.Site
    $Web = $ctx.Web
    $ctx.Load($Site)
    $ctx.Load($Web)
    $ctx.Load($Web.Lists)
    $ctx.Load($Web.Webs)
    $ctx.ExecuteQuery()

    $DL = $Web.Lists.GetByTitle($DocumentLibrary)
    $ctx.ExecuteQuery()

    $ctx.Load($DL.RootFolder)
    $ctx.ExecuteQuery()

    if ($BaseFolderPath)
    {
        $RootFolderPath = "$($DL.RootFolder.ServerRelativeUrl)/$($BaseFolderPath)"
        $RootFolder = $DL.RootFolder.Folders.GetByUrl($BaseFolderPath)
        $ctx.Load($RootFolder)
        $ctx.ExecuteQuery()
        $ContentInfo += (ListContent -BaseFolder $RootFolder -Recursive)
    }
    else
    {
        $ContentInfo += (ListContent -BaseFolder $DL.RootFolder -Recursive)
    }

    if ($CSVPath)
    {
        if (Test-Path $CSVPath) { Remove-Item $CSVPath }
        $ContentInfo | Export-Csv $CSVPath -NoTypeInformation
    }
}
Catch
{
    Throw
}
Finally
{
    if ($ctx -ne $null) { $ctx.Dispose(); }
}

Note: this script is only meant for SharePoint Online.

13 Jun 2017

PowerShell Script: Upload Large File to SharePoint in Chunks

Get back to the business again! Just wanted to share another great things in SharePoint (although to user is not fun at all).

According to MSDN, there are a few options to upload files to SharePoint.

3 Apr 2017

SharePoint CAML Query through jQuery

I was just digging into my code snippet, and I thought this worth to share. I got the sample code where we can query using CAML in jQuery.

After a few tests, it’s still valid to be used. Here it is!


var DocLibName = "Shared Documents";
var camlQry = 
	"<View Scope='RecursiveAll'>" +
		"<Query>" +
			"<Where>" +
				"<And>" +
					"<Leq>" +
						"<FieldRef Name='Created'/>" +
						"<Value Type='DateTime'><Today /></Value>" +
					"</Leq>" +
					"<Eq>" +
						"<FieldRef Name='FSObjType'/>" +
						"<Value Type='Integer'>0</Value>" +
					"</Eq>" +
				"</And>" + 
			"</Where>" +
		"</Query>" +
	"</View>";
var requestData = { "query" :
	{ "__metadata" :
		{ "type" : "SP.CamlQuery" },
		"ViewXml" : camlQry
	}
};
$.ajax({
	url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + DocLibName + "')/GetItems?$expand=FieldValuesAsText",
	method: "POST",
	async: false,
	data: JSON.stringify(requestData),
	headers: {
		"X-RequestDigest": $("#__REQUESTDIGEST").val(),
		"Accept": "application/json; odata=verbose",
		"Content-Type": "application/json; odata=verbose"
	},
	success : function(d) {
		$.each(d.d.results, function (iRow, vRow) {
			//do your own processing here
		});
	}, error : function(a, b, c) {
		console.log(a);
		console.log(b);
		console.log(c);
	}
});

Enjoy!

29 Mar 2017

PowerShell: Remove Site Collection Administrator Account

This time, I’m going to share you on the script to remove Site Collection Administrator of ALL site collections at one go.

12_13_47-000117


[Cmdletbinding()]
param (
    [string]$UserName = "",
    [string]$Tenant = "",
	[Parameter(Mandatory=$true)]
    [string]$AccountToRemove = "",
    [string]$RelativeSiteUrl = ""
)

Connect-SPOService -Url "https://$($Tenant)-admin.sharepoint.com" -Credential $UserName

if ($RelativeSiteUrl)
{
    $siteUrl = "https://$($Tenant).sharepoint.com$($RelativeSiteUrl)"
    Write-Host "Removing $AccountToRemove from $siteUrl..." -Fore Yellow -NoNewline
    Set-SPOUser -Site $site.Url -LoginName $AccountToRemove -IsSiteCollectionAdmin $false
    Write-Host "REMOVED" -Fore Green
}
else
{
    $SiteColl = Get-SPOSite
    Write-Host "Removing $AccountToRemove from:" -Fore Green
    foreach ($site in $SiteColl)
    {
        Write-Host "`t$($site.Url)..." -Fore Yellow -NoNewline
        Set-SPOUser -Site $site.Url -LoginName $AccountToRemove -IsSiteCollectionAdmin $false
        Write-Host "REMOVED" -Fore Green
    }
}

Disconnect-SPOService

Enjoy!

22 Mar 2017

PowerShell Script to Iterate All Documents (including sub-folders)

Seems like I want to dump again an old script to you. This PowerShell Script is commonly used to list down all documents in the Document Library regardless of their location, whether it’s in the root or sub-folders.

No need to explain in detail again, here’s the script.

Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.WorkflowServices.dll"
$Siteurl = "https://consotoayam.com/sites/EPRG" #you can replace this url with your own
$ListName = "Shared Documents" #replace this with your own Document Library name
$credential = Get-Credential #to prompt for credential

if ($SiteUrl -ne $null)
{
    $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
    if ($ctx -ne $null)
    {
        $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($credential.UserName, $credential.Password)

        $st = $ctx.Site
        $wb = $ctx.Web
        $DocsLib = $wb.Lists.GetByTitle($ListName)

        $q = New-Object Microsoft.SharePoint.Client.CamlQuery
        $q.ViewXml = '0'

        $items = $DocsLib.GetItems($q)
        $ctx.Load($st)
        $ctx.Load($wb)
        $ctx.Load($DocsLib)
        $ctx.Load($items)
        $ctx.ExecuteQuery()
        foreach($item in $items)
        {
	    #if necessary, you can load the item
            $ctx.Load($item)
            $ctx.ExecuteQuery()
        }
    }
}

Enjoy!


19 Agu 2016

Simple Workaround for Content Editor Webpart in Another Site Collection

Guess what? You have created a HTML script stored somewhere in SharePoint, and you want to use it somewhere in another Site Collection. But you are stuck with this error, “Cannot retrieve the URL specified in the Content Link property. For more assistance, contact your site administrator”.

image

There are a few workarounds you can try.

Using Page Viewer or IFRAME

To use the page viewer, the solution is quite straight-forward and can be described in a few sentences.

Firstly, you know that you have created the HTML script, now create a page in the same Site Collection, then add Content Editor Webpart that links to the HTML script.

Then you can go to the other Site Collection, create a page with Page Viewer, or direct HTML with IFRAME which links to the page created in previous step. Remember, the SharePoint top links bar and left navigation will still be displayed. To overcome that, you can add query string “IsDlg=1” at the end of the URL.

If your URL is like: http://contoso.com/Pages/cewp.aspx, then it should be like http://contoso.com/Pages/cewp.aspx?IsDlg=1.

Using jQuery

If your masterpage is attached with jQuery, you can re-use the following code.

<div class="pp-container">
</div>
<script type="text/javascript">
 $.ajax({
  url: "/SiteAssets/common/thescripts.txt",
  method: "GET",
  success: function (data) {
   $('div.pp-container').append(data);
  },
  error: function (data) {
   console.log("Error:");
   console.log(data);
  }
 });
</script>

Where "/SiteAssets/common/thescripts.txt" is the URL of your HTML script.

8 Agu 2016

Tips: Open Office Document Online (Web Version) in SharePoint

In SharePoint, there are 2 ways of setting a link to an Office Document. The most common way we’ve always seen is by direct link, which will download the Office document to your local storage.

Now, there’s another way to link to an Office document and force it to open in Online viewer such as Excel Online, PowerPoint Online, or Word Online. The most possible way is to copy the URL by clicking on the ellipsis next to the filename.

image

Now, you’ll see something similar to this, which will force-open the file in Excel Online:
https://www.contoso.com/Shared%20Documents/Essential%20Regulatory%20Documents%20Inventory%20List%20Template.xlsx?d=we035ad79215c4e82ba32d989b66bacfd

Or at any point of time if you know the direct URL to the file but unsure what is the number or code next to d=, you can just put the link as below.

https://www.contoso.com/Shared%20Documents/Essential%20Regulatory%20Documents%20Inventory%20List%20Template.xlsx?web=1

This way, it will forcefully open the excel (or essentially any Office document) in Online Viewer.

 

WAIT, there’s more! I know that you’re going to complain!