Microsoft Graph

Enables integration with Microsoft Graph.

The component handles authentication and HTTP requests, but you will need to refer to the the Graph API documentation to learn how each API is used. The Graph Explorer is also a valuable tool for experimenting with Graph APIs.

The system settings GraphDefaultTenantId and GraphDefaultCredentials may be used to set defaults for the credentials used to access Graph.

SQL

SQL Call: Init (mandatory)

Used to dynamically overwrite the default authorization settings and credentials and to set a batch id.

May modify database: No

Parameters

@Action string
Will be set to "Init".

Resultset: Init data (optional)

Table count: repeated zero or one time
Row count: zero or one row
Columns
BatchId optional string
BatchId to send to all remaining calls to the component.
Credentials optional string
Used to dynamically overwrite the GraphDefaultCredentials system setting.

The credentials should be of type Name and Password and use ClientId as name and Secret as password. ClientId and Secret are fetched from the Azure portal.
TenantId optional string
Used to dynamically overwrite the GraphDefaultTenantId setting.
AuthorizationUrl optional string
Used to dynamically overwrite the GraphAuthorizationUrl setting. May contain {TenantId} to be replaced.

SQL Call: Initial commands (mandatory)

Gets the initial commands to be performed by the component.

May modify database: Yes

Parameters

@Action string
Will be set to "Commands".

Resultset: Commands (optional)

Table count: repeated zero or one time
Row count: zero or more rows
Columns
HttpMethod mandatory string
Http method to use.
Possible value Description
DELETE
GET
PATCH
POST
PUT
ApiVersion optional string
Version of the API to use.
Possible value Description
beta
v1.0
Path optional string
The path to append to the base graph address.
Url optional string
The full Url to call, use when Microsoft Graph is returning a full URL to call, for example when using paging. Not used with Path or ApiVersion.
ReceiveResponseHeaders optional bit
Determines whether headers should be read in the response and available in the "StoreResponse" command. Default is 0.
SendCustomRequestHeaders optional bit
Determines whether the "GetHeaders" call should be made to the procedure to add custom headers to the request. Default is 0.
ResponseIsBinary optional bit
Determine whether response should be read as binary data.
BeginExtraParams optional any
Marker that indicates that all columns with a higher ordinal than this column will be passed as parameters to the procedure for all actions created by this command. This column must only contain NULL.
<XXX> optional any
Values in columns to the right of the BeginExtraParams column are passed as parameters to the procedure for the calls created by the command.

SQL Call: Request data (mandatory)

May modify database: No

Parameters

@Action string
Will be set to "RequestData".

Resultset: Request body (optional)

Table count: repeated zero or one time
Row count: zero or one row
Columns
RequestJson optional string
The request as JSON.
RequestBinary optional binary
The request data to send as binary data. Mutually exclusive with
RequestJson.

This column must be the last column of the table.
ContentLength optional bigint
Sets the Content-Length header. You should only use this for calls where the API documentation specifies that this header is used.

You can only specify Content-Length when using the RequestBinary column.
ContentRange optional string
Sets the Content-Range header. You should only use this for calls where the API documentation specifies that this header is used.

You can only specify Content-Range when using the RequestBinary column.
ContentType optional string
Sets the Content-Type header. You should only use this for calls where the API documentation specifies that this header is used.

You can only specify Content-Type when using the RequestBinary column. RequestJson will always use application/json.

SQL Call: Request headers (mandatory)

Specifies custom request headers to send with the call. See the API documentation for each individual call to determine which, if any, headers it accepts. The Authorization header is automatically set by the component.

You can not specify any Content-* headers in this call. Those are specified by the Request data call instead.

May modify database: No

Parameters

@Action string
Will be set to "RequestHeaders".

Resultset: Custom headers (optional)

A key-value list of the custom headers.
Table count: repeated zero or one time
Row count: zero or more rows
Columns
HttpHeaderName mandatory string
Name of the header.
HttpHeaderValue mandatory string
Value of the header.

SQL Call: Store response (mandatory)

Called once for each command. This call can optionally emit new commands to perform.

May modify database: Yes

Parameters

@Action string
Will be set to "StoreResponse".
@ErrorCode binary
Error code if an error occured.
Possible value Description
<XXX> Any error code from Microsoft Graph
Softadmin_ApplicationThrottled The component tried to make a call disregarding previous returned @RetryAfter. The call has been ignored.
@ErrorMessage string
@HttpStatusCode int
@ResponseBinary binary
The response as binary if requested in the commands call.
@ResponseJson string
The result as Json string if if the response isnt read as a binary.
@RetryAfterUtc datetime
A datetime indicating when the next call is allowed. NULL if more calls are allowed straight away.

Resultset: #ResponseHeaders

If requested in the commands call this tables contains all headers from the response.
Table count:
Row count:
Columns
HttpHeaderName mandatory string
Name of the HTTP header.
HttpHeaderValue mandatory string
Value of the HTTP header.

Resultset: Store response (optional)

Commands to be added to the end of the call queue.
Table count: repeated zero or one time
Row count: zero or one row
Columns
HttpMethod mandatory string
Http method to use.
Possible value Description
DELETE
GET
PATCH
POST
PUT
ApiVersion optional string
Version of the API to use.
Possible value Description
beta
v1.0
Path optional string
The path to append to the base graph address.
Url optional string
The full Url to call, use when Microsoft Graph is returning a full URL to call, for example when using paging. Not used with Path or ApiVersion.
ReceiveResponseHeaders optional bit
Determines whether headers should be read in the response and available in the "StoreResponse" command. Default is 0.
SendCustomRequestHeaders optional bit
Determines whether the "GetHeaders" call should be made to the procedure to add custom headers to the request. Default is 0.
ResponseIsBinary optional bit
Determine whether response should be read as binary data.
BeginExtraParams optional any
Marker that indicates that all columns with a higher ordinal than this column will be passed as parameters to the procedure for all actions created by this command. This column must only contain NULL.
<XXX> optional any
Values in columns to the right of the BeginExtraParams column are passed as parameters to the procedure for the calls created by the command.

SQL Call: Finished (mandatory)

Call made when all commands have finished.

Supports custom errors: Yes
May modify database: Yes

Parameters

@Action string
Will be set to "Finished".

Resultset: Forwardning definitions (optional)

Table count: repeated zero or more times
Row count: exactly one row
Columns
ADMIN_ErrorMessage optional string

Displays a user friendly error message to the user. This blocks any forwarding for the user.

ADMIN_ConfirmDelete optional string

Displays a user friendly confirmation message to the user with a delete button as the confirm button. If the user chooses OK the SQL call will be rerun with the parameter @ButtonAction set to 'Delete'.

ADMIN_ConfirmQuestion optional string

Displays a user friendly confirmation message to the user with a question style. If the user chooses OK the SQL call will be rerun with the parameter @ButtonAction set to 'Confirm'.

ADMIN_ConfirmWarning optional string

Displays a user friendly confirmation message to the user with a warning style. If the user chooses OK the SQL call will be rerun with the parameter @ButtonAction set to 'Confirm'.

ADMIN_InfoMessage optional string

Displays a user friendly info message to the user. When the user clicks OK the user is forwarded.

ADMIN_SuccessMessage optional string

Displays a user friendly success message to the user. When the user clicks OK the user is forwarded.

ADMIN_Dialog optional string

The dialog alias of a predefined dialog to show the user. Must be the first column in the result set table. Use multiple result set tables to combine with other forwarding.

Use the menu item "Admin > Dialogs" to register new dialogs or find aliases for existing ones.

<xxx> (for ADMIN_Dialog) optional any

Any column without special meaning in the result set with the first column ADMIN_Dialog will be used to make replacements of placeholders in the message and title text.

ADMIN_DebugInfo optional string

Additional information to show the developer when using ADMIN_Dialog.

<passing_field> optional string
Any column with no other specific meaning will pe passed along to the menu item you are forwarding to.
ADMIN_CancelCidStepsBack optional int
Number of steps in the page history to jump back if the user clicks Cancel in an ADMIN_FORCE dialog (the default being none). This value overrides cancelcidstepsback specified in the query string.
ADMIN_CancelReturnToMenuItem optional string
Jumps back to the menu item with this alias if the user clicks Cancel in an ADMIN_FORCE dialog (the default being none). If no prior menu item is found with the given alias, then an error is thrown.
ADMIN_CancelMenuItem optional string
Alias of the menu item to execute if the user clicks Cancel in an ADMIN_FORCE dialog (the default being none). This value overrides cancelmenuitemid specified in the query string.
ADMIN_CancelMenuItemId optional int

Deprecated. Use ADMIN_CancelMenuItem instead.

Id of the menuitem to execute if the user clicks Cancel in an ADMIN_FORCE dialog (the default being none). This value overrides cancelmenuitemid specified in the query string.

ADMIN_CidStepsBack optional int
Number of steps in the page history to jump back after execution (the default being one step back). This value overrides any destination specified by the query string.
ADMIN_ReturnToMenuItem optional string
Jumps back to the menu item with this alias after execution. This value overrides any destination specified by the query string. If no prior menu item is found with the given alias, then an error is thrown.
ADMIN_Force optional string
Prompts the user with the specified text and the user may answer OK or cancel. If the user chooses OK the sql call will be rerun with the parameter @force set to 1.
ADMIN_Forward optional string
Displays a user friendly message and then forwards to the next menu item.
ADMIN_ForwardLink optional string
Alias of the link to forward to.
ADMIN_ForwardMenuGroup optional string

Alias of the menu group to show after execution (instead of former menu item). This value overrides any destination specified by the query string.

ADMIN_ForwardMenuGroupId optional int

Deprecated. Use ADMIN_ForwardMenuGroup instead.

Id of the menu group to show after execution (instead of former menu item). This value overrides any destination specified by the query string.

ADMIN_ForwardMenuItem optional string
Alias of the menu item to execute after execution (instead of former menu item). This value overrides any destination specified by the query string.
ADMIN_ForwardMenuItemId optional int

Deprecated. Use ADMIN_ForwardMenuItem instead.

Id of the menu item to execute after execution (instead of former menu item). This value overrides any destination specified by the query string.

ADMIN_Message optional string

Displays a user friendly error message to the user.

ADMIN_PasteHtmlFromPopup optional string
Pastes HTML into an HTML editor. See ADMIN_SetFieldValueFromPopup.
ADMIN_SetFieldValueFromPopup optional string
Sets the value of the field specified in the menuitempopup call. Only select this column if menu item is opened in a popup.
ADMIN_ClosePopup optional bit
If this column is anything but NULL the popup will be closed. Only select this column if the menu item is opened in a popup.
Default: The default behavior is to step back inside the popup window and close it if there is nothing to step back to.
ADMIN_ClosePopupAndReloadOpener optional bit

If this column is anything but NULL the popup will be closed and the parent will be reloaded. Only select this column if the menu item is opened in a popup. Avoid using this feature if the opener is a newEdit as that may interrupt the user's ongoing input.

ADMIN_ClearHistory optional any
When the value is not NULL all navigation history is cleared and the user can't navigate back. This is only supported when forwarding to another menu item.
ADMIN_RefreshMenu optional bit
Will trigger a reload of the sidebar if the column is anything but NULL.
Cache optional string
Cache key to be cleared. Supports wildcards.
CacheUserId optional string
Either a user id or '%'.

Clears all caches (e.g. access permissions) related to the specified user id.

Use '%' to clear caches for all users.
CancelButtonText optional string

Changes the text of the Cancel button when used with ADMIN_Force, ADMIN_ConfirmWarning, ADMIN_ConfirmQuestion, ADMIN_ConfirmDelete.

OkButtonText optional string

Changes the text of the OK button when used with ADMIN_ErrorMessage, ADMIN_ConfirmWarning, ADMIN_ConfirmQuestion, ADMIN_ConfirmDelete, ADMIN_InfoMessage, ADMIN_SuccessMessage, ADMIN_Message, ADMIN_Force, or ADMIN_Forward. ADMIN_Force,

SQL Call: Validate parameters

Allows you to validate the parameters supplied by the user before any other SQL is run in the component. This call is only made if the component has visible parameters, the SQL is a stored procedure, and Validate parameters is checked.

May modify database: No

Parameters

@Force bit
Set to 1 if the last call to validate parameters used admin_force and the user clicked OK in the OK/Cancel dialog.
@ValidateParams bit
Set to 1 when this call is made.

Resultset: Messages (optional)

Table count: repeated zero or one time
Row count: zero or one row
Columns
ADMIN_Force optional string
Message asking the end user to confirm their parameters.
ADMIN_Message optional string
Message explaining why the parameters are rejected.

Custom access control and logging

SQL Call: Custom access control and logging

Use this call to restrict which entries a user is allowed to view and edit, and to log which entries a user views.

Access to a menu item is normally controlled through functions and roles alone but some entities need more fine grained control. For example, a user may have access to the View Member menu item for normal members but not for members with a protected identity.

The menu items a user visits are always logged (in ADMINLogMenuItem) but for sensitive data you may need to log exactly what entries are viewed. Do the logging in this call as the common ways of viewing data (grid and InfoSQL) are not allowed to modify the database.

If you bind a scalar function instead of a stored procedure to this call then its name must end with '_GrantAccess'.

May modify database: Yes

Resultset: Access permissions

Return whether the user is allowed to visit the menu item with the current parameters.
Table count: repeated exactly once
Row count: exactly one row
Columns
GrantAccess mandatory bit
1 if the user is allowed to view the menu item, 0 if the user should not be allowed to view the menu item.

If 0 then an error will be logged as the user should not have been able to reach the menu item with the given parameters in the first place.

Examples

Graph example

CREATE OR ALTER PROCEDURE [Example].[Graph]
	@Action varchar(max) = NULL,
	@Id varchar(max) = NULL,
	@ResponseJson nvarchar(max) = NULL,
	@HttpStatusCode int = NULL,
	@ErrorMessage varchar(max) = NULL,
	@ErrorCode varchar(max) = NULL,
	@RetryAfterUtc datetime2(2) = NULL
AS
BEGIN
	SET XACT_ABORT ON;

	IF @Action = 'Init'
	BEGIN
		RETURN;
	END;
	
	IF @Action = 'Commands'
	BEGIN
		SELECT
			GC.Path AS Path,
			'v1.0' AS ApiVersion,
			GC.HttpMethod AS HttpMethod,
			NULL AS BeginExtraParams,
			GC.GraphCommandQueueId AS Id
		FROM
			dbo.GraphCommandQueue GC
			LEFT JOIN (SELECT MAX(GS.RetryAfter) AS RetryAfter FROM dbo.GraphState GS) S ON 1 = 1
		WHERE
			SYSDATETIME() > ISNULL(S.RetryAfter, '1900');
		RETURN;
	END;

	IF @Action = 'RequestData'
	BEGIN
		SELECT
			GC.RequestJson
		FROM
			dbo.GraphCommandQueue GC
		WHERE
			GC.GraphCommandQueueId = @Id;
		RETURN;
	END;

	IF @Action = 'StoreResponse'
	BEGIN
		BEGIN TRAN;

		DELETE dbo.GraphState;

		IF @RetryAfter IS NOT NULL
		BEGIN
			INSERT INTO dbo.GraphState
			(
				RetryAfter
			)
			VALUES
			(
				@RetryAfter
			);
		END;

		COMMIT;
		BEGIN TRAN;

		IF @HttpStatusCode = 2XX
		BEGIN
			DELETE dbo.GraphCommandQueue
			WHERE
				GraphCommandQueueId = @Id;
		END;
		ELSE
		BEGIN
			UPDATE dbo.GraphCommandQueue SET
				ResponseJson = @ResponseJson,
				ErrorCode = @ErrorCode,
				ErrorMessage = @ErrorMessage,
				HttpStatusCode = @HttpStatusCode
			WHERE
				GraphCommandQueueId = @Id;

			DECLARE @LogMessage varchar(max) = 
				CONCAT('Error occured when performing Action for dbo.GraphCommandQueue: GraphCommandQueueId:', @Id);
			EXEC SoftadminApi.Log_LogError
				@LogMessage = @LogMessage;
		END;

		COMMIT;

		RETURN;
	END;

	IF @Action = 'Finished'
	BEGIN
		RETURN;
	END;
END;

Importing profile pictures from graph

This demonstrates how you can use the 64x64 URL segment to download resized photos, and use ETags to only download updated photos.

CREATE OR ALTER PROCEDURE Example.SyncPhotosFromGraph
	@Action			varchar(50),
	@UserId			int = NULL,
	@HttpStatusCode	int = NULL,
	@ResponseJson	varchar(max) = NULL,
	@ResponseBinary	varbinary(max) = NULL,
	@ErrorCode		varchar(300) = NULL,
	@ErrorMessage	varchar(max) = NULL,
	@RetryAfterUtc	datetime2(0) = NULL
AS
BEGIN
	IF @Action = 'Init'
	BEGIN
		RETURN;
	END;

	IF @Action = 'Commands'
	BEGIN
		SELECT
			'GET' AS HttpMethod,
			CONCAT(
				'/users/',
				U.Username,
				'/photos/64x64/$value'
			) AS Path,
			'/v1.0' AS ApiVersion,
			1 AS SendCustomRequestHeaders, -- We want to send ETag.
			1 AS ReceiveResponseHeaders, -- We want to receive ETag.
			1 AS ResponseIsBinary, -- We're downloading photos, not JSON.
			NULL AS BeginExtraParams,
			U.UserId -- Pass the user ID to RequestHeaders and StoreResponse.
		FROM
			SoftadminApi.[User] U
		WHERE
			U.IsEnabled = 1 AND
			U.Username LIKE '%@%' AND
			1=1; -- Add your own logic for deciding which users to sync here.

		RETURN;
	END;

	IF @Action = 'RequestData'
	BEGIN
		-- All requests are GET-request, meaning they don't have a body,
		-- so this Action will never get called.
		RETURN;
	END;

	IF @Action = 'RequestHeaders'
	BEGIN
		-- Use the If-None-Match header to only fetch changed profile pictures.
		SELECT
			'If-None-Match' AS HttpHeaderName,
			ETag AS HttpHeaderValue
		FROM
			SoftadminApi.UserPhoto
		WHERE
			UserId = @UserId;

		RETURN;
	END;

	IF @Action = 'StoreResponse'
	BEGIN
		IF @HttpStatusCode = 304
		BEGIN
			-- The photo is unchanged since previous sync.
			RETURN;
		END;

		IF @HttpStatusCode = 200
		BEGIN
			DECLARE
				@ResponseContentType varchar(300) = (
					SELECT HttpHeaderValue
					FROM #ResponseHeaders
					WHERE HttpHeaderName = 'content-type'),
				@ResponseETag varchar(300) = (
					SELECT HttpHeaderValue
					FROM #ResponseHeaders
					WHERE HttpHeaderName = 'etag');

			BEGIN TRANSACTION;

				-- Remove the existing user photo and generate a new one with a new ID.
				-- User photos remain cached for a year, reusing the same UserPhotoId would
				-- result in all browsers retaining the previous photo.
				DELETE SoftadminApi.UserPhoto WHERE UserId = @UserId;

				INSERT SoftadminApi.UserPhoto
				(
					UserId,
					UserPhoto,
					UserPhotoContentType,
					ETag,
					UpdateDatetime
				)
				VALUES
				(
					@UserId,
					@ResponseBinary,
					@ResponseContentType,
					@ResponseETag,
					SYSDATETIMEOFFSET()
				);

			COMMIT TRANSACTION;

			RETURN;
		END;

		IF @HttpStatusCode = 404
		BEGIN
			-- The user does not exist or does not have a photo.
			RETURN;
		END;

		IF @HttpStatusCode BETWEEN 400 AND 599
		BEGIN
			-- Log unexpected errors.
			DECLARE @LogMessage varchar(MAX) = CONCAT('Graph returned an error when fetching photo: ', @ErrorCode);
			EXEC SoftadminApi.Log_LogError
				@LogMessage	= @LogMessage,
				@LogTrace	= @ErrorMessage,
				@MenuItemId	= 123; -- Use your own menu item ID.
		END;

		RETURN;
	END;

	IF @ErrorCode IS NOT NULL OR @ErrorMessage IS NOT NULL
	BEGIN
		RAISERROR('%s %s', 16, 1,@ErrorCode, @ErrorMessage);
	END;
END;