diff --git a/CHANGELOG.md b/CHANGELOG.md index b4f1f786f..5858eb9ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). - Added `Get-PnPTenantRestrictedSearchAllowedList` cmdlet to retrieve existing list of URLs in the allowed list. [#3997](https://github.com/pnp/powershell/pull/3997) - Added `-IsSharePointAddInsDisabled` to the `Set-PnPTenant` cmdlet which allows disabling SharePoint Add-ins [#4032](https://github.com/pnp/powershell/pull/4032) - Added `-RestrictContentOrgWideSearch`, `-ReadOnlyForUnmanagedDevices` and `-InheritVersionPolicyFromTenant` parameters to `Set-PnPTenantSite` cmdlet. [#4024](https://github.com/pnp/powershell/pull/4024) +- Added `Get-PnPPriviledgedIdentityManagementEligibleAssignment`, `Get-PnPPriviledgedIdentityManagementRole` and `Enable-PnPPriviledgedIdentityManagement` cmdlets to allow scripting of enabling Privileged Identity Management roles for a user [#4039](https://github.com/pnp/powershell/pull/4039) ### Fixed diff --git a/documentation/Enable-PnPPriviledgedIdentityManagement.md b/documentation/Enable-PnPPriviledgedIdentityManagement.md new file mode 100644 index 000000000..059ec8631 --- /dev/null +++ b/documentation/Enable-PnPPriviledgedIdentityManagement.md @@ -0,0 +1,183 @@ +--- +Module Name: PnP.PowerShell +schema: 2.0.0 +applicable: SharePoint Online +online version: https://pnp.github.io/powershell/cmdlets/Enable-PnPPriviledgedIdentityManagement.html +external help file: PnP.PowerShell.dll-Help.xml +title: Enable-PnPPriviledgedIdentityManagement +--- + +# Enable-PnPPriviledgedIdentityManagement + +## SYNOPSIS + +**Required Permissions** + +* Microsoft Graph: RoleAssignmentSchedule.ReadWrite.Directory + +Temporarily enables a Privileged Identity Management role for a user + +## SYNTAX + +### By Role Name And Principal + +```powershell +Enable-PnPPriviledgedIdentityManagement -Role [-PrincipalId ] [-Justification ] [-StartAt ] [-ExpireInHours ] [-Connection ] +``` + +### By Role Name And User + +```powershell +Enable-PnPPriviledgedIdentityManagement -Role -User [-Justification ] [-StartAt ] [-ExpireInHours ] [-Connection ] +``` + +### By Eligible Role Assignment + +```powershell +Enable-PnPPriviledgedIdentityManagement -EligibleAssignment [-Justification ] [-StartAt ] [-ExpireInHours ] [-Connection ] +``` + +## DESCRIPTION +Temporarily enables a Privileged Identity Management role for the provided allowing the user to perform actions that require the role. The role will be enabled starting at the specified date and time and will expire after the specified number of hours. The reason for the elevation of rights can be provided as justification. + +## EXAMPLES + +### Example 1 +```powershell +Enable-PnPPriviledgedIdentityManagement -Role "Global Administrator" +``` + +Enables the global administrator role for the current user through Privileged Identity Management starting immediately and expiring in 1 hour + +### Example 2 +```powershell +Enable-PnPPriviledgedIdentityManagement -Role "Global Administrator" -Justification "Just because" +``` + +Enables the global administrator role for the current user through Privileged Identity Management starting immediately and expiring in 1 hour, adding the justification provided to be logged as the reason for the elevation of rights + +### Example 3 +```powershell +Enable-PnPPriviledgedIdentityManagement -Role "Global Administrator" -Justification "Just because" -StartAt (Get-Date).AddHours(2) -ExpireInHours 2 +``` + +Enables the global administrator role for the current user through Privileged Identity Management starting in 2 hours from now and expiring 2 hours thereafter, adding the justification provided to be logged as the reason for the elevation of rights + +### Example 4 +```powershell +Enable-PnPPriviledgedIdentityManagement -Role "Global Administrator" -User "someone@contoso.onmicrosoft.com" +``` + +Enables the global administrator role for the provided user through Privileged Identity Management starting immediately and expiring in 1 hour + +## PARAMETERS + +### -Connection +Optional connection to be used by the cmdlet. +Retrieve the value for this parameter by either specifying -ReturnConnection on Connect-PnPOnline or by executing Get-PnPConnection. + +```yaml +Type: PnPConnection +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExpireInHours +Indication of after how many hours the elevation should expire. If omitted, the default value is 1 hour. + +```yaml +Type: short +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Justification +Text to be logged as the reason for the elevation of rights. If omitted, the default value is "Elevated by PnP PowerShell". + +```yaml +Type: string +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: "Elevated by PnP PowerShell" +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PrincipalId +The Id of of the principal to elevate. If omitted, the default value is the current user, if the connection has been made using a delegated identity. With an application identity, this parameter is required. + +```yaml +Type: Guid +Parameter Sets: By Role Name And Principal +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Role +The Id, name or instance of a role to elevate the current user to. Use `Get-PnPPriviledgedIdentityManagementRole` to retrieve the available roles. + +```yaml +Type: PriviledgedIdentityManagementRolePipeBind +Parameter Sets: By Role Name And Principal, By Role Name And User +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True +Accept wildcard characters: False +``` + +### -StartAt +Date and time at which to start the elevation. If omitted, the default value is the current date and time, meaning the activation will happen immediately. + +```yaml +Type: DateTime +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Get-Date +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -User +The Id, username or instance of a user which needs to be elevated + +```yaml +Type: AzureADUserPipeBind +Parameter Sets: By Role Name And User +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## RELATED LINKS + +[Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) \ No newline at end of file diff --git a/documentation/Get-PnPPriviledgedIdentityManagementEligibleAssignment.md b/documentation/Get-PnPPriviledgedIdentityManagementEligibleAssignment.md new file mode 100644 index 000000000..cea49dd36 --- /dev/null +++ b/documentation/Get-PnPPriviledgedIdentityManagementEligibleAssignment.md @@ -0,0 +1,80 @@ +--- +Module Name: PnP.PowerShell +schema: 2.0.0 +applicable: SharePoint Online +online version: https://pnp.github.io/powershell/cmdlets/Get-PnPPriviledgedIdentityManagementEligibleAssignment.html +external help file: PnP.PowerShell.dll-Help.xml +title: Get-PnPPriviledgedIdentityManagementEligibleAssignment +--- + +# Get-PnPPriviledgedIdentityManagementEligibleAssignment + +## SYNOPSIS + +**Required Permissions** + +* Microsoft Graph: RoleAssignmentSchedule.Read.Directory + +Retrieve the available Privileged Identity Management eligibility assignment roles that exist within the tenant + +## SYNTAX + +```powershell +Get-PnPPriviledgedIdentityManagementEligibleAssignment [-Identity ] [-Connection ] +``` + +## DESCRIPTION +Retrieve the available Privileged Identity Management eligibility assignment roles that exist within the tenant. These are the configured users with the configured roles they can be elevated to. + +## EXAMPLES + +### Example 1 +```powershell +Get-PnPPriviledgedIdentityManagementEligibleAssignment +``` + +Retrieves the available Privileged Identity Management eligibility assignment roles + +### Example 2 +```powershell +Get-PnPPriviledgedIdentityManagementEligibleAssignment -Identity 62e90394-69f5-4237-9190-012177145e10 +``` + +Retrieves the Privileged Identity Management eligibility assignment role with the provided id + +## PARAMETERS + +### -Connection +Optional connection to be used by the cmdlet. +Retrieve the value for this parameter by either specifying -ReturnConnection on Connect-PnPOnline or by executing Get-PnPConnection. + +```yaml +Type: PnPConnection +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Identity +The name, id or instance of a Priviledged Identity Management eligibility assignment role to retrieve the details of + +```yaml +Type: PriviledgedIdentityManagementRoleEligibilitySchedulePipeBind +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: True +Accept wildcard characters: False +``` + +## RELATED LINKS + +[Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) \ No newline at end of file diff --git a/documentation/Get-PnPPriviledgedIdentityManagementRole.md b/documentation/Get-PnPPriviledgedIdentityManagementRole.md new file mode 100644 index 000000000..b9b49ebba --- /dev/null +++ b/documentation/Get-PnPPriviledgedIdentityManagementRole.md @@ -0,0 +1,87 @@ +--- +Module Name: PnP.PowerShell +schema: 2.0.0 +applicable: SharePoint Online +online version: https://pnp.github.io/powershell/cmdlets/Get-PnPPriviledgedIdentityManagementRole.html +external help file: PnP.PowerShell.dll-Help.xml +title: Get-PnPPriviledgedIdentityManagementRole +--- + +# Get-PnPPriviledgedIdentityManagementRole + +## SYNOPSIS + +**Required Permissions** + +* Microsoft Graph: RoleManagement.Read.Directory + +Retrieve the available Privileged Identity Management roles that exist within the tenant + +## SYNTAX + +```powershell +Get-PnPPriviledgedIdentityManagementRole [-Identity ] [-Connection ] +``` + +## DESCRIPTION +Retrieve the available Privileged Identity Management roles that exist within the tenant. These are the roles to which elevation can take place. + +## EXAMPLES + +### Example 1 +```powershell +Get-PnPPriviledgedIdentityManagementRole +``` + +Retrieves the available Privileged Identity Management roles + +### Example 2 +```powershell +Get-PnPPriviledgedIdentityManagementRole -Identity "Global Administrator" +``` + +Retrieves the Privileged Identity Management with the provided name + +### Example 3 +```powershell +Get-PnPPriviledgedIdentityManagementRole -Identity 62e90394-69f5-4237-9190-012177145e10 +``` + +Retrieves the Privileged Identity Management role with the provided id + +## PARAMETERS + +### -Connection +Optional connection to be used by the cmdlet. +Retrieve the value for this parameter by either specifying -ReturnConnection on Connect-PnPOnline or by executing Get-PnPConnection. + +```yaml +Type: PnPConnection +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Identity +The name, id or instance of a Priviledged Identity Management role to retrieve the details of + +```yaml +Type: PriviledgedIdentityManagementRolePipeBind +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: True +Accept wildcard characters: False +``` + +## RELATED LINKS + +[Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) \ No newline at end of file diff --git a/resources/PnP.PowerShell.Format.ps1xml b/resources/PnP.PowerShell.Format.ps1xml index 0442495d1..314b9f3b9 100644 --- a/resources/PnP.PowerShell.Format.ps1xml +++ b/resources/PnP.PowerShell.Format.ps1xml @@ -2980,5 +2980,41 @@ + + RoleEligibilitySchedule + + PnP.PowerShell.Commands.Model.PriviledgedIdentityManagement.RoleEligibilitySchedule + + + + + left + + + 38 + left + + + + left + + + + + + + Id + + + DirectoryScopeId + + + $_.RoleDefinition.DisplayName + + + + + + \ No newline at end of file diff --git a/src/Commands/Admin/GetTenantInfo.cs b/src/Commands/Admin/GetTenantInfo.cs index eed560c45..fd60a6ce0 100644 --- a/src/Commands/Admin/GetTenantInfo.cs +++ b/src/Commands/Admin/GetTenantInfo.cs @@ -35,7 +35,7 @@ protected override void ExecuteCmdlet() var requestUrl = BuildRequestUrl(); WriteVerbose($"Making call to {requestUrl} to request tenant information"); - var results = RestHelper.GetAsync(Connection.HttpClient, requestUrl, graphAccessToken).GetAwaiter().GetResult(); + var results = RestHelper.Get(Connection.HttpClient, requestUrl, graphAccessToken); WriteObject(results, true); } diff --git a/src/Commands/Admin/PublishCompanyApp.cs b/src/Commands/Admin/PublishCompanyApp.cs index 51a765cef..9ca2e1b94 100644 --- a/src/Commands/Admin/PublishCompanyApp.cs +++ b/src/Commands/Admin/PublishCompanyApp.cs @@ -185,7 +185,7 @@ protected override void ExecuteCmdlet() if (!NoUpload) { var bytes = System.IO.File.ReadAllBytes(System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, $"{AppName}.zip")); - TeamsUtility.AddAppAsync(Connection, GraphAccessToken, bytes).GetAwaiter().GetResult(); + TeamsUtility.AddApp(this, Connection, GraphAccessToken, bytes); WriteObject($"Teams app uploaded to teams app Store."); } } diff --git a/src/Commands/Admin/RenameTenantSite.cs b/src/Commands/Admin/RenameTenantSite.cs index 93c4d8216..393a8f23d 100644 --- a/src/Commands/Admin/RenameTenantSite.cs +++ b/src/Commands/Admin/RenameTenantSite.cs @@ -68,7 +68,7 @@ protected override void ExecuteCmdlet() OperationId = Guid.Empty }; - var results = Utilities.REST.RestHelper.PostAsync(HttpClient, $"{AdminContext.Url.TrimEnd('/')}/_api/SiteRenameJobs?api-version=1.4.7", AdminContext, body, false).GetAwaiter().GetResult(); + var results = Utilities.REST.RestHelper.Post(HttpClient, $"{AdminContext.Url.TrimEnd('/')}/_api/SiteRenameJobs?api-version=1.4.7", AdminContext, body, false); if (!Wait.IsPresent) { if (results != null) diff --git a/src/Commands/Apps/AddAzureADServicePrincipalAppRole.cs b/src/Commands/Apps/AddAzureADServicePrincipalAppRole.cs index d0b7223c0..3a8b26bf6 100644 --- a/src/Commands/Apps/AddAzureADServicePrincipalAppRole.cs +++ b/src/Commands/Apps/AddAzureADServicePrincipalAppRole.cs @@ -34,7 +34,7 @@ public class AddAzureADServicePrincipalAppRole : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var principal = Principal.GetServicePrincipal(Connection, AccessToken); + var principal = Principal.GetServicePrincipal(this, Connection, AccessToken); if(principal == null) { @@ -47,7 +47,7 @@ protected override void ExecuteCmdlet() if (AppRole.AppRole == null) { - var resource = ParameterSetName == ParameterSet_BYBUILTINTYPE ? ServicePrincipalUtility.GetServicePrincipalByBuiltInType(Connection, AccessToken, BuiltInType) : Resource.GetServicePrincipal(Connection, AccessToken); + var resource = ParameterSetName == ParameterSet_BYBUILTINTYPE ? ServicePrincipalUtility.GetServicePrincipalByBuiltInType(this, Connection, AccessToken, BuiltInType) : Resource.GetServicePrincipal(this, Connection, AccessToken); if (resource == null) { @@ -67,7 +67,7 @@ protected override void ExecuteCmdlet() WriteVerbose($"Adding app role {appRole.Value}: {appRole.DisplayName}"); - var response = ServicePrincipalUtility.AddServicePrincipalRoleAssignment(Connection, AccessToken, principal, appRole); + var response = ServicePrincipalUtility.AddServicePrincipalRoleAssignment(this, Connection, AccessToken, principal, appRole); WriteObject(response, false); } } diff --git a/src/Commands/Apps/GetAzureADAppSitePermission.cs b/src/Commands/Apps/GetAzureADAppSitePermission.cs index 1d8fa3e9e..88980151e 100644 --- a/src/Commands/Apps/GetAzureADAppSitePermission.cs +++ b/src/Commands/Apps/GetAzureADAppSitePermission.cs @@ -52,14 +52,14 @@ protected override void ExecuteCmdlet() var accessToken = AccessToken; // All permissions, first fetch just the Ids as the API works in a weird way that requesting all permissions does not reveal their roles, so we will request all permissions and then request each permission individually so we will also have the roles - var permissions = GraphHelper.GetResultCollectionAsync(Connection, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}/permissions?$select=Id", accessToken).GetAwaiter().GetResult(); + var permissions = GraphHelper.GetResultCollection(this, Connection, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}/permissions?$select=Id", accessToken); if (permissions.Any()) { var results = new List(); foreach (var permission in permissions) { // Request the permission individually so it will include the roles - var detailedApp = GraphHelper.GetAsync(Connection, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}/permissions/{permission.Id}", accessToken).GetAwaiter().GetResult(); + var detailedApp = GraphHelper.Get(this, Connection, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}/permissions/{permission.Id}", accessToken); results.Add(detailedApp.Convert()); } @@ -76,7 +76,7 @@ protected override void ExecuteCmdlet() } else { - var results = GraphHelper.GetAsync(Connection, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}/permissions/{PermissionId}", AccessToken).GetAwaiter().GetResult(); + var results = GraphHelper.Get(this, Connection, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}/permissions/{PermissionId}", AccessToken); WriteObject(results.Convert()); } } diff --git a/src/Commands/Apps/GetAzureADServicePrincipal.cs b/src/Commands/Apps/GetAzureADServicePrincipal.cs index def1f5e0c..60673b766 100644 --- a/src/Commands/Apps/GetAzureADServicePrincipal.cs +++ b/src/Commands/Apps/GetAzureADServicePrincipal.cs @@ -42,19 +42,19 @@ protected override void ExecuteCmdlet() switch (ParameterSetName) { case ParameterSet_BYAPPID: - servicePrincipal = ServicePrincipalUtility.GetServicePrincipalByAppId(Connection, AccessToken, AppId); + servicePrincipal = ServicePrincipalUtility.GetServicePrincipalByAppId(this, Connection, AccessToken, AppId); break; case ParameterSet_BYOBJECTID: - servicePrincipal = ServicePrincipalUtility.GetServicePrincipalByObjectId(Connection, AccessToken, ObjectId); + servicePrincipal = ServicePrincipalUtility.GetServicePrincipalByObjectId(this, Connection, AccessToken, ObjectId); break; case ParameterSet_BYAPPNAME: - servicePrincipal = ServicePrincipalUtility.GetServicePrincipalByAppName(Connection, AccessToken, AppName); + servicePrincipal = ServicePrincipalUtility.GetServicePrincipalByAppName(this, Connection, AccessToken, AppName); break; case ParameterSet_BYBUILTINTYPE: - servicePrincipal = ServicePrincipalUtility.GetServicePrincipalByBuiltInType(Connection, AccessToken, BuiltInType); + servicePrincipal = ServicePrincipalUtility.GetServicePrincipalByBuiltInType(this, Connection, AccessToken, BuiltInType); break; case ParameterSet_ALL: - var servicePrincipals = ServicePrincipalUtility.GetServicePrincipals(Connection, AccessToken, Filter); + var servicePrincipals = ServicePrincipalUtility.GetServicePrincipals(this, Connection, AccessToken, Filter); WriteObject(servicePrincipals, true); return; } diff --git a/src/Commands/Apps/GetAzureADServicePrincipalAssignedAppRole.cs b/src/Commands/Apps/GetAzureADServicePrincipalAssignedAppRole.cs index 28507ba75..3aac860f8 100644 --- a/src/Commands/Apps/GetAzureADServicePrincipalAssignedAppRole.cs +++ b/src/Commands/Apps/GetAzureADServicePrincipalAssignedAppRole.cs @@ -22,7 +22,7 @@ public class GetAzureADServicePrincipalAssignedAppRole : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var principal = Principal.GetServicePrincipal(Connection, AccessToken); + var principal = Principal.GetServicePrincipal(this, Connection, AccessToken); if(principal == null) { @@ -31,7 +31,7 @@ protected override void ExecuteCmdlet() WriteVerbose($"Requesting currently assigned app roles to service principal {principal.DisplayName}"); - var appRoleAssignments = ServicePrincipalUtility.GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(Connection, AccessToken, principal.Id); + var appRoleAssignments = ServicePrincipalUtility.GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(this, Connection, AccessToken, principal.Id); if(ParameterSpecified(nameof(Identity))) { var appRole = Identity.GetAvailableAppRole(Connection, AccessToken, principal); diff --git a/src/Commands/Apps/GetAzureADServicePrincipalAvailableAppRole.cs b/src/Commands/Apps/GetAzureADServicePrincipalAvailableAppRole.cs index 238de01bb..cced88f9b 100644 --- a/src/Commands/Apps/GetAzureADServicePrincipalAvailableAppRole.cs +++ b/src/Commands/Apps/GetAzureADServicePrincipalAvailableAppRole.cs @@ -21,7 +21,7 @@ public class GetAzureADServicePrincipalAvailableAppRole : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var principal = Principal.GetServicePrincipal(Connection, AccessToken); + var principal = Principal.GetServicePrincipal(this, Connection, AccessToken); if(principal == null) { diff --git a/src/Commands/Apps/GrantAzureADAppSitePermission.cs b/src/Commands/Apps/GrantAzureADAppSitePermission.cs index 2372a84e7..234bac4e6 100644 --- a/src/Commands/Apps/GrantAzureADAppSitePermission.cs +++ b/src/Commands/Apps/GrantAzureADAppSitePermission.cs @@ -56,7 +56,7 @@ protected override void ExecuteCmdlet() // Adding a fix for multi-geo issue // https://github.com/pnp/powershell/issues/2801 - var multiGeoFix = Utilities.REST.RestHelper.GetAsync(Connection.HttpClient, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}", AccessToken).GetAwaiter().GetResult(); + var multiGeoFix = Utilities.REST.RestHelper.Get(Connection.HttpClient, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}", AccessToken); // Construct the payload of the Graph request var payload = new @@ -83,7 +83,7 @@ protected override void ExecuteCmdlet() WriteVerbose($"Granting App with Id {AppId} the permission{(payload.roles.Length != 1 ? "s" : "")} {string.Join(',', payload.roles)}"); // Make the Graph Grant request - var result = Utilities.REST.RestHelper.PostAsync(Connection.HttpClient, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}/permissions", AccessToken, payload).GetAwaiter().GetResult(); + var result = Utilities.REST.RestHelper.Post(Connection.HttpClient, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}/permissions", AccessToken, payload); WriteObject(result.Convert()); } } diff --git a/src/Commands/Apps/GrantTenantServicePrincipalPermission.cs b/src/Commands/Apps/GrantTenantServicePrincipalPermission.cs index 1742cedda..ae62a554f 100644 --- a/src/Commands/Apps/GrantTenantServicePrincipalPermission.cs +++ b/src/Commands/Apps/GrantTenantServicePrincipalPermission.cs @@ -26,7 +26,7 @@ protected override void ExecuteCmdlet() { var spoWebAppServicePrincipal = new SPOWebAppServicePrincipal(tenantContext); var appId = spoWebAppServicePrincipal.EnsureProperty(a => a.AppId); - var results = GraphHelper.GetAsync>(Connection, $"/v1.0/servicePrincipals?$filter=appId eq '{appId}'&$select=id", AccessToken).GetAwaiter().GetResult(); + var results = GraphHelper.Get>(this, Connection, $"/v1.0/servicePrincipals?$filter=appId eq '{appId}'&$select=id", AccessToken); if (results.Items.Any()) { var servicePrincipal = results.Items.First(); diff --git a/src/Commands/Apps/RemoveAzureADServicePrincipalAssignedAppRole.cs b/src/Commands/Apps/RemoveAzureADServicePrincipalAssignedAppRole.cs index 19ec31141..1fce57a90 100644 --- a/src/Commands/Apps/RemoveAzureADServicePrincipalAssignedAppRole.cs +++ b/src/Commands/Apps/RemoveAzureADServicePrincipalAssignedAppRole.cs @@ -33,7 +33,7 @@ protected override void ExecuteCmdlet() { if(ParameterSetName == ParameterSet_BYASSIGNEDAPPROLE || ParameterSetName == ParameterSet_BYAPPROLENAME) { - var principal = Principal.GetServicePrincipal(Connection, AccessToken); + var principal = Principal.GetServicePrincipal(this, Connection, AccessToken); if(principal == null) { @@ -46,23 +46,23 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Identity))) { - var appRoleAssignment = Identity.GetAssignedAppRole(Connection, AccessToken, principal.Id); - ServicePrincipalUtility.RemoveServicePrincipalRoleAssignment(Connection, AccessToken, appRoleAssignment); + var appRoleAssignment = Identity.GetAssignedAppRole(this, Connection, AccessToken, principal.Id); + ServicePrincipalUtility.RemoveServicePrincipalRoleAssignment(this, Connection, AccessToken, appRoleAssignment); } else { - ServicePrincipalUtility.RemoveServicePrincipalRoleAssignment(Connection, AccessToken, principal); + ServicePrincipalUtility.RemoveServicePrincipalRoleAssignment(this, Connection, AccessToken, principal); } } else { - ServicePrincipalUtility.RemoveServicePrincipalRoleAssignment(Connection, AccessToken, principal, AppRoleName); + ServicePrincipalUtility.RemoveServicePrincipalRoleAssignment(this, Connection, AccessToken, principal, AppRoleName); } } else { - var appRoleAssignment = Identity.GetAssignedAppRole(Connection, AccessToken); - ServicePrincipalUtility.RemoveServicePrincipalRoleAssignment(Connection, AccessToken, appRoleAssignment); + var appRoleAssignment = Identity.GetAssignedAppRole(this, Connection, AccessToken); + ServicePrincipalUtility.RemoveServicePrincipalRoleAssignment(this, Connection, AccessToken, appRoleAssignment); } } } diff --git a/src/Commands/Apps/RevokeAzureADAppSitePermission.cs b/src/Commands/Apps/RevokeAzureADAppSitePermission.cs index f1a1f3c0c..e4f56d87b 100644 --- a/src/Commands/Apps/RevokeAzureADAppSitePermission.cs +++ b/src/Commands/Apps/RevokeAzureADAppSitePermission.cs @@ -38,7 +38,7 @@ protected override void ExecuteCmdlet() { if (Force || ShouldContinue("Are you sure you want to revoke the permissions?", string.Empty)) { - var results = PnP.PowerShell.Commands.Utilities.REST.RestHelper.DeleteAsync(Connection.HttpClient, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}/permissions/{PermissionId}", AccessToken).GetAwaiter().GetResult(); + var results = PnP.PowerShell.Commands.Utilities.REST.RestHelper.Delete(Connection.HttpClient, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}/permissions/{PermissionId}", AccessToken); } } } diff --git a/src/Commands/Apps/RevokeTenantServicePrincipalPermission.cs b/src/Commands/Apps/RevokeTenantServicePrincipalPermission.cs index 97c167e91..17dece954 100644 --- a/src/Commands/Apps/RevokeTenantServicePrincipalPermission.cs +++ b/src/Commands/Apps/RevokeTenantServicePrincipalPermission.cs @@ -30,7 +30,7 @@ protected override void ExecuteCmdlet() { var spoWebAppServicePrincipal = new SPOWebAppServicePrincipal(tenantContext); var appId = spoWebAppServicePrincipal.EnsureProperty(a => a.AppId); - var results = GraphHelper.GetAsync>(Connection, $"/v1.0/servicePrincipals?$filter=appId eq '{appId}'&$select=id", AccessToken).GetAwaiter().GetResult(); + var results = GraphHelper.Get>(this, Connection, $"/v1.0/servicePrincipals?$filter=appId eq '{appId}'&$select=id", AccessToken); if (results.Items.Any()) { if (Force || ShouldContinue($"Revoke permission {Scope}?", "Continue")) diff --git a/src/Commands/Apps/SetAzureADAppSitePermission.cs b/src/Commands/Apps/SetAzureADAppSitePermission.cs index 4d8f055e4..335c102da 100644 --- a/src/Commands/Apps/SetAzureADAppSitePermission.cs +++ b/src/Commands/Apps/SetAzureADAppSitePermission.cs @@ -48,7 +48,7 @@ protected override void ExecuteCmdlet() roles = Permissions.Select(p => p.ToLower()).ToArray() }; - var results = Utilities.REST.RestHelper.PatchAsync(Connection.HttpClient, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}/permissions/{PermissionId}", AccessToken, payload).GetAwaiter().GetResult(); + var results = Utilities.REST.RestHelper.Patch(Connection.HttpClient, $"https://{Connection.GraphEndPoint}/v1.0/sites/{siteId}/permissions/{PermissionId}", AccessToken, payload); WriteObject(results.Convert()); } } diff --git a/src/Commands/AzureAD/AddAzureADGroupMember.cs b/src/Commands/AzureAD/AddAzureADGroupMember.cs index 5c7c33f20..53f169ae1 100644 --- a/src/Commands/AzureAD/AddAzureADGroupMember.cs +++ b/src/Commands/AzureAD/AddAzureADGroupMember.cs @@ -34,7 +34,7 @@ protected override void ExecuteCmdlet() if (Identity != null) { - group = Identity.GetGroup(Connection, AccessToken); + group = Identity.GetGroup(this, Connection, AccessToken); } if (group != null) { @@ -44,14 +44,14 @@ protected override void ExecuteCmdlet() if (userArray.Length > 0) { - Microsoft365GroupsUtility.AddMembersAsync(Connection, new System.Guid(group.Id), userArray, AccessToken, RemoveExisting.ToBool()).GetAwaiter().GetResult(); + ClearOwners.AddMembers(this, Connection, new Guid(group.Id), userArray, AccessToken, RemoveExisting.ToBool()); } var secGroups = Users.Where(x => Guid.TryParse(x, out emptyGuid)).Select(x => emptyGuid).ToArray(); if (secGroups.Length > 0) { - Microsoft365GroupsUtility.AddDirectoryMembersAsync(Connection, new System.Guid(group.Id), secGroups, AccessToken, RemoveExisting.ToBool()).GetAwaiter().GetResult(); + ClearOwners.AddDirectoryMembers(this, Connection, new Guid(group.Id), secGroups, AccessToken, RemoveExisting.ToBool()); } } } diff --git a/src/Commands/AzureAD/AddAzureADGroupOwner.cs b/src/Commands/AzureAD/AddAzureADGroupOwner.cs index 85c7d76d7..8fdd3a5df 100644 --- a/src/Commands/AzureAD/AddAzureADGroupOwner.cs +++ b/src/Commands/AzureAD/AddAzureADGroupOwner.cs @@ -29,7 +29,7 @@ protected override void ExecuteCmdlet() if (Identity != null) { - group = Identity.GetGroup(Connection, AccessToken); + group = Identity.GetGroup(this, Connection, AccessToken); } if (group != null) @@ -41,14 +41,14 @@ protected override void ExecuteCmdlet() if (userArray.Length > 0) { - Microsoft365GroupsUtility.AddOwnersAsync(Connection, new System.Guid(group.Id), userArray, AccessToken, RemoveExisting.ToBool()).GetAwaiter().GetResult(); + ClearOwners.AddOwners(this, Connection, new System.Guid(group.Id), userArray, AccessToken, RemoveExisting.ToBool()); } var secGroups = Users.Where(x => Guid.TryParse(x, out emptyGuid)).Select(x => emptyGuid).ToArray(); if (secGroups.Length > 0) { - Microsoft365GroupsUtility.AddDirectoryOwnersAsync(Connection, new System.Guid(group.Id), secGroups, AccessToken, RemoveExisting.ToBool()).GetAwaiter().GetResult(); + ClearOwners.AddDirectoryOwners(this, Connection, new System.Guid(group.Id), secGroups, AccessToken, RemoveExisting.ToBool()); } } } diff --git a/src/Commands/AzureAD/ClearAzureADGroupMember.cs b/src/Commands/AzureAD/ClearAzureADGroupMember.cs index 5fe5b3ff7..32eb75b8a 100644 --- a/src/Commands/AzureAD/ClearAzureADGroupMember.cs +++ b/src/Commands/AzureAD/ClearAzureADGroupMember.cs @@ -22,16 +22,16 @@ protected override void ExecuteCmdlet() if (Identity != null) { - group = Identity.GetGroup(Connection, AccessToken); + group = Identity.GetGroup(this, Connection, AccessToken); } if (group != null) { - var members = Microsoft365GroupsUtility.GetMembersAsync(Connection, new System.Guid(group.Id), AccessToken).GetAwaiter().GetResult(); + var members = ClearOwners.GetMembers(this, Connection, new System.Guid(group.Id), AccessToken); var membersToBeRemoved = members?.Select(p => p.UserPrincipalName).ToArray(); - Microsoft365GroupsUtility.RemoveMembersAsync(Connection, new System.Guid(group.Id), membersToBeRemoved, AccessToken).GetAwaiter().GetResult(); + ClearOwners.RemoveMembers(this, Connection, new System.Guid(group.Id), membersToBeRemoved, AccessToken); } } } diff --git a/src/Commands/AzureAD/ClearAzureADGroupOwner.cs b/src/Commands/AzureAD/ClearAzureADGroupOwner.cs index cb218e7d8..d542a8c85 100644 --- a/src/Commands/AzureAD/ClearAzureADGroupOwner.cs +++ b/src/Commands/AzureAD/ClearAzureADGroupOwner.cs @@ -22,16 +22,16 @@ protected override void ExecuteCmdlet() if (Identity != null) { - group = Identity.GetGroup(Connection, AccessToken); + group = Identity.GetGroup(this, Connection, AccessToken); } if (group != null) { - var owners = Microsoft365GroupsUtility.GetOwnersAsync(Connection, new System.Guid(group.Id), AccessToken).GetAwaiter().GetResult(); + var owners = ClearOwners.GetOwners(this, Connection, new System.Guid(group.Id), AccessToken); var ownersToBeRemoved = owners?.Select(p => p.UserPrincipalName).ToArray(); - Microsoft365GroupsUtility.RemoveOwnersAsync(Connection, new System.Guid(group.Id), ownersToBeRemoved, AccessToken).GetAwaiter().GetResult(); + ClearOwners.RemoveOwners(this, Connection, new System.Guid(group.Id), ownersToBeRemoved, AccessToken); } } } diff --git a/src/Commands/AzureAD/GetAzureADActivityReportDirectoryAudit.cs b/src/Commands/AzureAD/GetAzureADActivityReportDirectoryAudit.cs index d51fc781c..d13b2bf32 100644 --- a/src/Commands/AzureAD/GetAzureADActivityReportDirectoryAudit.cs +++ b/src/Commands/AzureAD/GetAzureADActivityReportDirectoryAudit.cs @@ -31,12 +31,12 @@ protected override void ExecuteCmdlet() if (ParameterSpecified(nameof(Identity))) { - var auditResults = GraphHelper.GetAsync(Connection, auditLogUrl, AccessToken).GetAwaiter().GetResult(); + var auditResults = GraphHelper.Get(this, Connection, auditLogUrl, AccessToken); WriteObject(auditResults, false); } else { - var auditResults = GraphHelper.GetResultCollectionAsync(Connection, auditLogUrl, AccessToken).GetAwaiter().GetResult(); + var auditResults = GraphHelper.GetResultCollection(this, Connection, auditLogUrl, AccessToken); WriteObject(auditResults, true); } } diff --git a/src/Commands/AzureAD/GetAzureADActivityReportSignIn.cs b/src/Commands/AzureAD/GetAzureADActivityReportSignIn.cs index ff12d4e0b..82387d54a 100644 --- a/src/Commands/AzureAD/GetAzureADActivityReportSignIn.cs +++ b/src/Commands/AzureAD/GetAzureADActivityReportSignIn.cs @@ -35,12 +35,12 @@ protected override void ExecuteCmdlet() if (ParameterSpecified(nameof(Identity))) { - var auditResults = GraphHelper.GetAsync(Connection, signInUrl, AccessToken).GetAwaiter().GetResult(); + var auditResults = GraphHelper.Get(this, Connection, signInUrl, AccessToken); WriteObject(auditResults, false); } else { - var auditResults = GraphHelper.GetResultCollectionAsync(Connection, signInUrl, AccessToken).GetAwaiter().GetResult(); + var auditResults = GraphHelper.GetResultCollection(this, Connection, signInUrl, AccessToken); WriteObject(auditResults, true); } } diff --git a/src/Commands/AzureAD/GetAzureADApp.cs b/src/Commands/AzureAD/GetAzureADApp.cs index 83d2bb701..a6c881a94 100644 --- a/src/Commands/AzureAD/GetAzureADApp.cs +++ b/src/Commands/AzureAD/GetAzureADApp.cs @@ -41,7 +41,7 @@ protected override void ExecuteCmdlet() { "ConsistencyLevel", "eventual" } }; } - var result = GraphHelper.GetResultCollectionAsync(Connection, requestUrl, AccessToken, additionalHeaders: additionalHeaders).GetAwaiter().GetResult(); + var result = GraphHelper.GetResultCollection(this, Connection, requestUrl, AccessToken, additionalHeaders: additionalHeaders); WriteObject(result, true); } } diff --git a/src/Commands/AzureAD/GetAzureADAppPermission.cs b/src/Commands/AzureAD/GetAzureADAppPermission.cs index 7335a966e..03c85d893 100644 --- a/src/Commands/AzureAD/GetAzureADAppPermission.cs +++ b/src/Commands/AzureAD/GetAzureADAppPermission.cs @@ -26,7 +26,7 @@ protected override void ExecuteCmdlet() else { List apps = new List(); - var result = GraphHelper.GetResultCollectionAsync(Connection, "/v1.0/applications", AccessToken).GetAwaiter().GetResult(); + var result = GraphHelper.GetResultCollection(this, Connection, "/v1.0/applications", AccessToken); if (result != null && result.Any()) { apps.AddRange(result.Select(p => ConvertToPSObject(p))); diff --git a/src/Commands/AzureAD/GetAzureADGroup.cs b/src/Commands/AzureAD/GetAzureADGroup.cs index bd754ffc4..fcea2760c 100644 --- a/src/Commands/AzureAD/GetAzureADGroup.cs +++ b/src/Commands/AzureAD/GetAzureADGroup.cs @@ -19,7 +19,7 @@ protected override void ExecuteCmdlet() { if (Identity != null) { - var group = Identity.GetGroup(Connection, AccessToken); + var group = Identity.GetGroup(this, Connection, AccessToken); if (group != null) { WriteObject(group); @@ -27,7 +27,7 @@ protected override void ExecuteCmdlet() } else { - var groups = AzureADGroupsUtility.GetGroupsAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var groups = AzureADGroupsUtility.GetGroups(this, Connection, AccessToken); if (groups != null) { WriteObject(groups?.OrderBy(m => m.DisplayName), true); diff --git a/src/Commands/AzureAD/GetAzureADGroupMember.cs b/src/Commands/AzureAD/GetAzureADGroupMember.cs index fcd6251a6..666cf15e1 100644 --- a/src/Commands/AzureAD/GetAzureADGroupMember.cs +++ b/src/Commands/AzureAD/GetAzureADGroupMember.cs @@ -23,13 +23,13 @@ protected override void ExecuteCmdlet() if (Identity != null) { - group = Identity.GetGroup(Connection, AccessToken); + group = Identity.GetGroup(this, Connection, AccessToken); } if (group != null) { // Get members of the group - var members = Microsoft365GroupsUtility.GetMembersAsync(Connection, new Guid(group.Id), AccessToken).GetAwaiter().GetResult(); + var members = ClearOwners.GetMembers(this, Connection, new Guid(group.Id), AccessToken); WriteObject(members?.OrderBy(m => m.DisplayName), true); } } diff --git a/src/Commands/AzureAD/GetAzureADGroupOwner.cs b/src/Commands/AzureAD/GetAzureADGroupOwner.cs index 2a29ce65e..e9ef15214 100644 --- a/src/Commands/AzureAD/GetAzureADGroupOwner.cs +++ b/src/Commands/AzureAD/GetAzureADGroupOwner.cs @@ -23,13 +23,13 @@ protected override void ExecuteCmdlet() if (Identity != null) { - group = Identity.GetGroup(Connection, AccessToken); + group = Identity.GetGroup(this, Connection, AccessToken); } if (group != null) { // Get Owners of the group - var owners = Microsoft365GroupsUtility.GetOwnersAsync(Connection, new Guid(group.Id), AccessToken).GetAwaiter().GetResult(); + var owners = ClearOwners.GetOwners(this, Connection, new Guid(group.Id), AccessToken); WriteObject(owners?.OrderBy(m => m.DisplayName), true); } } diff --git a/src/Commands/AzureAD/NewAzureADGroup.cs b/src/Commands/AzureAD/NewAzureADGroup.cs index 659bd65da..a4262c8e4 100644 --- a/src/Commands/AzureAD/NewAzureADGroup.cs +++ b/src/Commands/AzureAD/NewAzureADGroup.cs @@ -52,7 +52,7 @@ protected override void ExecuteCmdlet() if (!Force) { - var existingGroup = AzureADGroupsUtility.GetGroupAsync(Connection, MailNickname, AccessToken).GetAwaiter().GetResult(); + var existingGroup = AzureADGroupsUtility.GetGroup(this, Connection, MailNickname, AccessToken); forceCreation = existingGroup == null || ShouldContinue(string.Format(Resources.ForceCreationOfExistingGroup0, MailNickname), Resources.Confirm); } @@ -77,12 +77,12 @@ protected override void ExecuteCmdlet() if (Owners?.Length > 0) { - ownerData = Microsoft365GroupsUtility.GetUsersDataBindValueAsync(Connection, AccessToken, Owners).GetAwaiter().GetResult(); + ownerData = ClearOwners.GetUsersDataBindValue(this, Connection, AccessToken, Owners); postData.Add("owners@odata.bind", ownerData); } if (Members?.Length > 0) { - memberData = Microsoft365GroupsUtility.GetUsersDataBindValueAsync(Connection, AccessToken, Members).GetAwaiter().GetResult(); + memberData = ClearOwners.GetUsersDataBindValue(this, Connection, AccessToken, Members); postData.Add("members@odata.bind", memberData); } @@ -90,7 +90,7 @@ protected override void ExecuteCmdlet() var stringContent = new StringContent(data); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - var groupResult = GraphHelper.PostAsync(Connection, $"v1.0/groups", stringContent, AccessToken).GetAwaiter().GetResult(); + var groupResult = GraphHelper.Post(this, Connection, $"v1.0/groups", stringContent, AccessToken); WriteObject(groupResult); } diff --git a/src/Commands/AzureAD/RegisterAzureADApp.cs b/src/Commands/AzureAD/RegisterAzureADApp.cs index 612a609e3..80b26cea1 100644 --- a/src/Commands/AzureAD/RegisterAzureADApp.cs +++ b/src/Commands/AzureAD/RegisterAzureADApp.cs @@ -534,7 +534,7 @@ private bool AppExists(string appName, HttpClient httpClient, string token) graphEndpoint = Environment.GetEnvironmentVariable("MicrosoftGraphEndPoint", EnvironmentVariableTarget.Process); } - var azureApps = RestHelper.GetAsync>(httpClient, $"{graphEndpoint}/v1.0/applications?$filter=displayName eq '{appName}'&$select=Id", token).GetAwaiter().GetResult(); + var azureApps = RestHelper.Get>(httpClient, $"{graphEndpoint}/v1.0/applications?$filter=displayName eq '{appName}'&$select=Id", token); if (azureApps != null && azureApps.Items.Any()) { Host.UI.WriteLine(); @@ -584,7 +584,7 @@ private AzureADApp CreateApp(string loginEndPoint, HttpClient httpClient, string graphEndpoint = Environment.GetEnvironmentVariable("MicrosoftGraphEndPoint", EnvironmentVariableTarget.Process); } - var azureApp = RestHelper.PostAsync(httpClient, $"{graphEndpoint}/v1.0/applications", token, payload).GetAwaiter().GetResult(); + var azureApp = RestHelper.Post(httpClient, $"{graphEndpoint}/v1.0/applications", token, payload); if (azureApp != null) { Host.UI.WriteLine(ConsoleColor.Yellow, Host.UI.RawUI.BackgroundColor, $"App {azureApp.DisplayName} with id {azureApp.AppId} created."); @@ -714,7 +714,7 @@ private void SetLogo(AzureADApp azureApp, string token) { var byteArrayContent = new ByteArrayContent(bytes); byteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(mediaType); - GraphHelper.PutAsync(PnPConnection.Current, endpoint, token, byteArrayContent).GetAwaiter().GetResult(); + GraphHelper.Put(this, PnPConnection.Current, endpoint, token, byteArrayContent); WriteVerbose("Successfully set the logo for the Azure AD app"); } diff --git a/src/Commands/AzureAD/RemoveAzureADApp.cs b/src/Commands/AzureAD/RemoveAzureADApp.cs index fb72e00ee..0e47a25f1 100644 --- a/src/Commands/AzureAD/RemoveAzureADApp.cs +++ b/src/Commands/AzureAD/RemoveAzureADApp.cs @@ -22,7 +22,7 @@ protected override void ExecuteCmdlet() if (Force || ShouldContinue($"Remove app '{app.DisplayName}' with id '{app.Id}'", string.Empty)) { - Utilities.REST.GraphHelper.DeleteAsync(Connection, $"/v1.0/applications/{app.Id}", AccessToken).GetAwaiter().GetResult(); + Utilities.REST.GraphHelper.Delete(this, Connection, $"/v1.0/applications/{app.Id}", AccessToken); } } } diff --git a/src/Commands/AzureAD/RemoveAzureADGroup.cs b/src/Commands/AzureAD/RemoveAzureADGroup.cs index ef4702e46..ddf59589b 100644 --- a/src/Commands/AzureAD/RemoveAzureADGroup.cs +++ b/src/Commands/AzureAD/RemoveAzureADGroup.cs @@ -19,11 +19,11 @@ protected override void ExecuteCmdlet() { if (Identity != null) { - Group group = Identity.GetGroup(Connection, AccessToken); + Group group = Identity.GetGroup(this, Connection, AccessToken); if (group != null) { - Microsoft365GroupsUtility.RemoveGroupAsync(Connection, new System.Guid(group.Id), AccessToken).GetAwaiter().GetResult(); + ClearOwners.RemoveGroup(this, Connection, new System.Guid(group.Id), AccessToken); } } } diff --git a/src/Commands/AzureAD/RemoveAzureADGroupMember.cs b/src/Commands/AzureAD/RemoveAzureADGroupMember.cs index aeadf8f32..3dbf036fb 100644 --- a/src/Commands/AzureAD/RemoveAzureADGroupMember.cs +++ b/src/Commands/AzureAD/RemoveAzureADGroupMember.cs @@ -24,12 +24,12 @@ protected override void ExecuteCmdlet() if (Identity != null) { - group = Identity.GetGroup(Connection, AccessToken); + group = Identity.GetGroup(this, Connection, AccessToken); } if (group != null) { - Microsoft365GroupsUtility.RemoveMembersAsync(Connection, new System.Guid(group.Id), Users, AccessToken).GetAwaiter().GetResult(); + ClearOwners.RemoveMembers(this, Connection, new System.Guid(group.Id), Users, AccessToken); } } } diff --git a/src/Commands/AzureAD/RemoveAzureADGroupOwner.cs b/src/Commands/AzureAD/RemoveAzureADGroupOwner.cs index 552405356..871ec671e 100644 --- a/src/Commands/AzureAD/RemoveAzureADGroupOwner.cs +++ b/src/Commands/AzureAD/RemoveAzureADGroupOwner.cs @@ -24,12 +24,12 @@ protected override void ExecuteCmdlet() if (Identity != null) { - group = Identity.GetGroup(Connection, AccessToken); + group = Identity.GetGroup(this, Connection, AccessToken); } if (group != null) { - Microsoft365GroupsUtility.RemoveOwnersAsync(Connection, new System.Guid(group.Id), Users, AccessToken).GetAwaiter().GetResult(); + ClearOwners.RemoveOwners(this, Connection, new System.Guid(group.Id), Users, AccessToken); } } } diff --git a/src/Commands/AzureAD/SetAzureADGroup.cs b/src/Commands/AzureAD/SetAzureADGroup.cs index d7411d400..628284674 100644 --- a/src/Commands/AzureAD/SetAzureADGroup.cs +++ b/src/Commands/AzureAD/SetAzureADGroup.cs @@ -46,7 +46,7 @@ protected override void ExecuteCmdlet() if (Identity != null) { - group = Identity.GetGroup(Connection, AccessToken); + group = Identity.GetGroup(this, Connection, AccessToken); } if (group != null) @@ -77,22 +77,22 @@ protected override void ExecuteCmdlet() if (changed) { - AzureADGroupsUtility.UpdateAsync(Connection, AccessToken, group).GetAwaiter().GetResult(); + AzureADGroupsUtility.Update(this, Connection, AccessToken, group); } if (ParameterSpecified(nameof(Owners))) { - Microsoft365GroupsUtility.UpdateOwnersAsync(Connection, new Guid(group.Id), AccessToken, Owners).GetAwaiter().GetResult(); + ClearOwners.UpdateOwners(this, Connection, new Guid(group.Id), AccessToken, Owners); } if (ParameterSpecified(nameof(Members))) { - Microsoft365GroupsUtility.UpdateMembersAsync(Connection, new Guid(group.Id), AccessToken, Members).GetAwaiter().GetResult(); + ClearOwners.UpdateMembersAsync(this, Connection, new Guid(group.Id), AccessToken, Members); } if (ParameterSpecified(nameof(HideFromAddressLists)) || ParameterSpecified(nameof(HideFromOutlookClients))) { // For this scenario a separate call needs to be made - Utilities.Microsoft365GroupsUtility.SetVisibilityAsync(Connection, AccessToken, new Guid(group.Id), HideFromAddressLists, HideFromOutlookClients).GetAwaiter().GetResult(); + Utilities.ClearOwners.SetVisibility(this, Connection, AccessToken, new Guid(group.Id), HideFromAddressLists, HideFromOutlookClients); } } catch (Exception e) diff --git a/src/Commands/Base/BasePSCmdlet.cs b/src/Commands/Base/BasePSCmdlet.cs index 72de479a7..4bf1de0c7 100644 --- a/src/Commands/Base/BasePSCmdlet.cs +++ b/src/Commands/Base/BasePSCmdlet.cs @@ -50,7 +50,7 @@ protected override void ProcessRecord() { ExecuteCmdlet(); } - catch (PnP.PowerShell.Commands.Model.Graph.GraphException gex) + catch (Model.Graph.GraphException gex) { var errorMessage = gex.Error.Message; diff --git a/src/Commands/Base/PipeBinds/AzureADAppPipeBind.cs b/src/Commands/Base/PipeBinds/AzureADAppPipeBind.cs index abe9d3b76..909d7cfdc 100644 --- a/src/Commands/Base/PipeBinds/AzureADAppPipeBind.cs +++ b/src/Commands/Base/PipeBinds/AzureADAppPipeBind.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Management.Automation; -using System.Net.Http; using PnP.PowerShell.Commands.Model; using PnP.PowerShell.Commands.Utilities.REST; @@ -33,20 +32,20 @@ public AzureADApp GetApp(BasePSCmdlet cmdlet, PnPConnection connection, string a { if (_id != Guid.Empty) { - var results = Utilities.REST.GraphHelper.GetAsync>(connection, $"/v1.0/applications?$filter=appId eq '{_id}'", accessToken).GetAwaiter().GetResult(); + var results = GraphHelper.Get>(cmdlet, connection, $"/v1.0/applications?$filter=appId eq '{_id}'", accessToken); if (results != null && results.Items.Any()) { return results.Items.First(); } else { - return Utilities.REST.GraphHelper.GetAsync(connection, $"/v1.0/applications/{_id}", accessToken).GetAwaiter().GetResult(); + return GraphHelper.Get(cmdlet, connection, $"/v1.0/applications/{_id}", accessToken); } } if (!string.IsNullOrEmpty(_name)) { - var results = Utilities.REST.GraphHelper.GetAsync>(connection, $"/v1.0/applications?$filter=displayName eq '{_name}'", accessToken).GetAwaiter().GetResult(); + var results = GraphHelper.Get>(cmdlet, connection, $"/v1.0/applications?$filter=displayName eq '{_name}'", accessToken); if (results != null && results.Items.Any()) { return results.Items.First(); diff --git a/src/Commands/Base/PipeBinds/AzureADGroupPipeBind.cs b/src/Commands/Base/PipeBinds/AzureADGroupPipeBind.cs index 2cca1e448..277cbd4e8 100644 --- a/src/Commands/Base/PipeBinds/AzureADGroupPipeBind.cs +++ b/src/Commands/Base/PipeBinds/AzureADGroupPipeBind.cs @@ -1,6 +1,7 @@ using PnP.PowerShell.Commands.Model.AzureAD; using PnP.PowerShell.Commands.Utilities; using System; +using System.Management.Automation; using Group = PnP.PowerShell.Commands.Model.Graph.Group; namespace PnP.PowerShell.Commands.Base.PipeBinds @@ -39,20 +40,20 @@ public AzureADGroupPipeBind(string input) public string GroupId => (_groupId); - public Group GetGroup(PnPConnection connection, string accessToken) + public Group GetGroup(Cmdlet cmdlet, PnPConnection connection, string accessToken) { Group group = null; if (Group != null) { - group = AzureADGroupsUtility.GetGroupAsync(connection, new Guid(Group.Id), accessToken).GetAwaiter().GetResult(); + group = AzureADGroupsUtility.GetGroup(cmdlet, connection, new Guid(Group.Id), accessToken); } else if (!string.IsNullOrEmpty(GroupId)) { - group = AzureADGroupsUtility.GetGroupAsync(connection, new Guid(GroupId), accessToken).GetAwaiter().GetResult(); + group = AzureADGroupsUtility.GetGroup(cmdlet, connection, new Guid(GroupId), accessToken); } else if (!string.IsNullOrEmpty(DisplayName)) { - group = AzureADGroupsUtility.GetGroupAsync(connection, DisplayName, accessToken).GetAwaiter().GetResult(); + group = AzureADGroupsUtility.GetGroup(cmdlet, connection, DisplayName, accessToken); } if (group != null) { diff --git a/src/Commands/Base/PipeBinds/Microsoft365GroupPipeBind.cs b/src/Commands/Base/PipeBinds/Microsoft365GroupPipeBind.cs index 31a56ea96..a13aaadf3 100644 --- a/src/Commands/Base/PipeBinds/Microsoft365GroupPipeBind.cs +++ b/src/Commands/Base/PipeBinds/Microsoft365GroupPipeBind.cs @@ -44,25 +44,25 @@ public Microsoft365GroupPipeBind(Guid guid) public Guid GroupId => _groupId; - public Microsoft365Group GetGroup(PnPConnection connection, string accessToken, bool includeSite, bool includeOwners, bool detailed, bool includeSensitivityLabels) + public Microsoft365Group GetGroup(Cmdlet cmdlet, PnPConnection connection, string accessToken, bool includeSite, bool includeOwners, bool detailed, bool includeSensitivityLabels) { Microsoft365Group group = null; if (Group != null) { - group = Microsoft365GroupsUtility.GetGroupAsync(connection, _group.Id.Value, accessToken, includeSite, includeOwners, detailed, includeSensitivityLabels).GetAwaiter().GetResult(); + group = ClearOwners.GetGroup(cmdlet, connection, _group.Id.Value, accessToken, includeSite, includeOwners, detailed, includeSensitivityLabels); } else if (_groupId != Guid.Empty) { - group = Microsoft365GroupsUtility.GetGroupAsync(connection, _groupId, accessToken, includeSite, includeOwners, detailed, includeSensitivityLabels).GetAwaiter().GetResult(); + group = ClearOwners.GetGroup(cmdlet, connection, _groupId, accessToken, includeSite, includeOwners, detailed, includeSensitivityLabels); } else if (!string.IsNullOrEmpty(DisplayName)) { - group = Microsoft365GroupsUtility.GetGroupAsync(connection, DisplayName, accessToken, includeSite, includeOwners, detailed, includeSensitivityLabels).GetAwaiter().GetResult(); + group = ClearOwners.GetGroup(cmdlet, connection, DisplayName, accessToken, includeSite, includeOwners, detailed, includeSensitivityLabels); } return group; } - public Guid GetGroupId(PnPConnection connection, string accessToken) + public Guid GetGroupId(Cmdlet cmdlet, PnPConnection connection, string accessToken) { if (Group != null) { @@ -74,7 +74,7 @@ public Guid GetGroupId(PnPConnection connection, string accessToken) } else if (!string.IsNullOrEmpty(DisplayName)) { - var group = Microsoft365GroupsUtility.GetGroupAsync(connection, DisplayName, accessToken, false, false, false, false).GetAwaiter().GetResult(); + var group = ClearOwners.GetGroup(cmdlet, connection, DisplayName, accessToken, false, false, false, false); if (group != null) { return group.Id.Value; @@ -83,24 +83,24 @@ public Guid GetGroupId(PnPConnection connection, string accessToken) throw new PSInvalidOperationException("Group not found"); } - public Microsoft365Group GetDeletedGroup(PnPConnection connection, string accessToken) + public Microsoft365Group GetDeletedGroup(Cmdlet cmdlet, PnPConnection connection, string accessToken) { if (_group != null) { - return Microsoft365GroupsUtility.GetDeletedGroupAsync(connection, _group.Id.Value, accessToken).GetAwaiter().GetResult(); + return ClearOwners.GetDeletedGroup(cmdlet, connection, _group.Id.Value, accessToken); } else if (_groupId != Guid.Empty) { - return Microsoft365GroupsUtility.GetDeletedGroupAsync(connection, _groupId, accessToken).GetAwaiter().GetResult(); + return ClearOwners.GetDeletedGroup(cmdlet, connection, _groupId, accessToken); } else if (!string.IsNullOrEmpty(_displayName)) { - return Microsoft365GroupsUtility.GetDeletedGroupAsync(connection, _displayName, accessToken).GetAwaiter().GetResult(); + return ClearOwners.GetDeletedGroup(cmdlet, connection, _displayName, accessToken); } return null; } - public Guid GetDeletedGroupId(PnPConnection connection, string accessToken) + public Guid GetDeletedGroupId(Cmdlet cmdlet, PnPConnection connection, string accessToken) { if (_group != null) { @@ -112,7 +112,7 @@ public Guid GetDeletedGroupId(PnPConnection connection, string accessToken) } else if (!string.IsNullOrEmpty(_displayName)) { - var group = Microsoft365GroupsUtility.GetDeletedGroupAsync(connection, _displayName, accessToken).GetAwaiter().GetResult(); + var group = ClearOwners.GetDeletedGroup(cmdlet, connection, _displayName, accessToken); if (group != null) { return group.Id.Value; diff --git a/src/Commands/Base/PipeBinds/PlannerBucketPipeBind.cs b/src/Commands/Base/PipeBinds/PlannerBucketPipeBind.cs index c4c796e29..405a70123 100644 --- a/src/Commands/Base/PipeBinds/PlannerBucketPipeBind.cs +++ b/src/Commands/Base/PipeBinds/PlannerBucketPipeBind.cs @@ -34,7 +34,7 @@ public string GetId() } } - public PlannerBucket GetBucket(PnPConnection connection, string accessToken, string planId) + public PlannerBucket GetBucket(Cmdlet cmdlet, PnPConnection connection, string accessToken, string planId) { // first try to get the bucket by id if (_bucket != null) @@ -45,7 +45,7 @@ public PlannerBucket GetBucket(PnPConnection connection, string accessToken, str { try { - var buckets = PlannerUtility.GetBucketsAsync(connection, accessToken, planId).GetAwaiter().GetResult(); + var buckets = PlannerUtility.GetBuckets(cmdlet, connection, accessToken, planId); if (buckets != null) { PlannerBucket bucket = null; diff --git a/src/Commands/Base/PipeBinds/PlannerGroupPipeBind.cs b/src/Commands/Base/PipeBinds/PlannerGroupPipeBind.cs index 4f308d30d..3dea50bb0 100644 --- a/src/Commands/Base/PipeBinds/PlannerGroupPipeBind.cs +++ b/src/Commands/Base/PipeBinds/PlannerGroupPipeBind.cs @@ -38,7 +38,7 @@ public PlannerGroupPipeBind(Model.Graph.Group group) _id = group.Id; } - public string GetGroupId(PnPConnection connection, string accessToken) + public string GetGroupId(Cmdlet cmdlet, PnPConnection connection, string accessToken) { if (!string.IsNullOrEmpty(_id)) { @@ -46,7 +46,7 @@ public string GetGroupId(PnPConnection connection, string accessToken) } else { - var collection = GraphHelper.GetAsync>(connection, $"v1.0/groups?$filter=mailNickname eq '{_stringValue}'&$select=Id", accessToken).GetAwaiter().GetResult(); + var collection = GraphHelper.Get>(cmdlet, connection, $"v1.0/groups?$filter=mailNickname eq '{_stringValue}'&$select=Id", accessToken); if (collection != null && collection.Items.Any()) { return collection.Items.First().Id; @@ -54,7 +54,7 @@ public string GetGroupId(PnPConnection connection, string accessToken) else { // find the team by displayName - var byDisplayNamecollection = GraphHelper.GetAsync>(connection, $"v1.0/groups?$filter=displayName eq '{_stringValue}'&$select=Id", accessToken).GetAwaiter().GetResult(); + var byDisplayNamecollection = GraphHelper.Get>(cmdlet, connection, $"v1.0/groups?$filter=displayName eq '{_stringValue}'&$select=Id", accessToken); if (byDisplayNamecollection != null && byDisplayNamecollection.Items.Any()) { if (byDisplayNamecollection.Items.Count() == 1) diff --git a/src/Commands/Base/PipeBinds/PlannerPlanPipeBind.cs b/src/Commands/Base/PipeBinds/PlannerPlanPipeBind.cs index ada835a7f..d6e1f57e5 100644 --- a/src/Commands/Base/PipeBinds/PlannerPlanPipeBind.cs +++ b/src/Commands/Base/PipeBinds/PlannerPlanPipeBind.cs @@ -1,6 +1,5 @@ using System.Linq; using System.Management.Automation; -using System.Threading.Tasks; using PnP.PowerShell.Commands.Model.Graph; using PnP.PowerShell.Commands.Model.Planner; using PnP.PowerShell.Commands.Utilities; @@ -25,7 +24,7 @@ public PlannerPlanPipeBind(PlannerPlan plan) _plan = plan; } - public async Task GetPlanAsync(PnPConnection connection, string accessToken, string groupId, bool resolveIdentities) + public PlannerPlan GetPlan(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, bool resolveIdentities) { if (_plan != null) { @@ -34,11 +33,11 @@ public async Task GetPlanAsync(PnPConnection connection, string acc // first try to get the plan by id try { - return await PlannerUtility.GetPlanAsync(connection, accessToken, _id, resolveIdentities); + return PlannerUtility.GetPlan(cmdlet, connection, accessToken, _id, resolveIdentities); } catch (GraphException) { - var plans = await PlannerUtility.GetPlansAsync(connection, accessToken, groupId, resolveIdentities); + var plans = PlannerUtility.GetPlans(cmdlet,connection, accessToken, groupId, resolveIdentities); if (plans != null && plans.Any()) { var collection = plans.Where(p => p.Title.Equals(_id)); @@ -55,7 +54,7 @@ public async Task GetPlanAsync(PnPConnection connection, string acc return null; } - public async Task GetIdAsync(PnPConnection connection, string accessToken, string groupId) + public string GetId(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId) { if (_plan != null) { @@ -64,12 +63,12 @@ public async Task GetIdAsync(PnPConnection connection, string accessToke // first try to get the plan by id try { - var plan = await PlannerUtility.GetPlanAsync(connection, accessToken, _id, false); + var plan = PlannerUtility.GetPlan(cmdlet, connection, accessToken, _id, false); return plan.Id; } catch (GraphException) { - var plans = await PlannerUtility.GetPlansAsync(connection, accessToken, groupId, false); + var plans = PlannerUtility.GetPlans(cmdlet, connection, accessToken, groupId, false); if (plans != null && plans.Any()) { var collection = plans.Where(p => p.Title.Equals(_id)); @@ -85,6 +84,5 @@ public async Task GetIdAsync(PnPConnection connection, string accessToke } return null; } - } } diff --git a/src/Commands/Base/PipeBinds/PlannerRosterPipeBind.cs b/src/Commands/Base/PipeBinds/PlannerRosterPipeBind.cs index dcc8f9a4e..7d876df59 100644 --- a/src/Commands/Base/PipeBinds/PlannerRosterPipeBind.cs +++ b/src/Commands/Base/PipeBinds/PlannerRosterPipeBind.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Management.Automation; using PnP.PowerShell.Commands.Model.Planner; using PnP.PowerShell.Commands.Utilities; @@ -22,13 +22,13 @@ public PlannerRosterPipeBind(PlannerRoster roster) _roster = roster; } - public async Task GetPlannerRosterAsync(PnPConnection connection, string accessToken) + public PlannerRoster GetPlannerRoster(Cmdlet cmdlet, PnPConnection connection, string accessToken) { if (_roster != null) { return _roster; } - return await PlannerUtility.GetRosterAsync(connection, accessToken, _id); + return PlannerUtility.GetRoster(cmdlet, connection, accessToken, _id); } } } diff --git a/src/Commands/Base/PipeBinds/PriviledgedIdentityManagementRoleEligibilitySchedulePipeBind.cs b/src/Commands/Base/PipeBinds/PriviledgedIdentityManagementRoleEligibilitySchedulePipeBind.cs new file mode 100644 index 000000000..5daa8b7ba --- /dev/null +++ b/src/Commands/Base/PipeBinds/PriviledgedIdentityManagementRoleEligibilitySchedulePipeBind.cs @@ -0,0 +1,45 @@ +using PnP.PowerShell.Commands.Model.PriviledgedIdentityManagement; +using PnP.PowerShell.Commands.Utilities; +using System; +using System.Management.Automation; + +namespace PnP.PowerShell.Commands.Base.PipeBinds +{ + public sealed class PriviledgedIdentityManagementRoleEligibilitySchedulePipeBind + { + public readonly Guid? Id; + + public RoleEligibilitySchedule Instance { get; private set; } + + public PriviledgedIdentityManagementRoleEligibilitySchedulePipeBind(RoleEligibilitySchedule instance) + { + Instance = instance; + } + + public PriviledgedIdentityManagementRoleEligibilitySchedulePipeBind(Guid id) + { + Id = id; + } + + public PriviledgedIdentityManagementRoleEligibilitySchedulePipeBind(string id) + { + if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out Guid idGuid)) + { + Id = idGuid; + } + } + + internal RoleEligibilitySchedule GetInstance(Cmdlet cmdlet, PnPConnection connection, string accessToken) + { + if (Instance != null) + { + return Instance; + } + if (Id.HasValue) + { + Instance = PriviledgedIdentityManagamentUtility.GetRoleEligibilityScheduleById(cmdlet, Id.Value, connection, accessToken); + } + return Instance; + } + } +} diff --git a/src/Commands/Base/PipeBinds/PriviledgedIdentityManagementRolePipeBind.cs b/src/Commands/Base/PipeBinds/PriviledgedIdentityManagementRolePipeBind.cs new file mode 100644 index 000000000..3f6d62245 --- /dev/null +++ b/src/Commands/Base/PipeBinds/PriviledgedIdentityManagementRolePipeBind.cs @@ -0,0 +1,55 @@ +using PnP.PowerShell.Commands.Model.PriviledgedIdentityManagement; +using PnP.PowerShell.Commands.Utilities; +using System; +using System.Management.Automation; + +namespace PnP.PowerShell.Commands.Base.PipeBinds +{ + public sealed class PriviledgedIdentityManagementRolePipeBind + { + public readonly Guid? Id; + + public readonly string DisplayName; + + public RoleDefinition Instance { get; private set; } + + public PriviledgedIdentityManagementRolePipeBind(RoleDefinition instance) + { + Instance = instance; + } + + public PriviledgedIdentityManagementRolePipeBind(Guid id) + { + Id = id; + } + + public PriviledgedIdentityManagementRolePipeBind(string id) + { + if(Guid.TryParse(id, out Guid guidId)) + { + Id = guidId; + } + else + { + DisplayName = id; + } + } + + internal RoleDefinition GetInstance(Cmdlet cmdlet, PnPConnection connection, string accessToken) + { + if (Instance != null) + { + return Instance; + } + if (Id.HasValue) + { + Instance = PriviledgedIdentityManagamentUtility.GetRoleDefinitionById(cmdlet, Id.Value, connection, accessToken); + } + if (!string.IsNullOrEmpty(DisplayName)) + { + Instance = PriviledgedIdentityManagamentUtility.GetRoleDefinitionByName(cmdlet, DisplayName, connection, accessToken); + } + return Instance; + } + } +} diff --git a/src/Commands/Base/PipeBinds/SensitivityLabelPipeBind.cs b/src/Commands/Base/PipeBinds/SensitivityLabelPipeBind.cs index 767942e61..8dda2ae68 100644 --- a/src/Commands/Base/PipeBinds/SensitivityLabelPipeBind.cs +++ b/src/Commands/Base/PipeBinds/SensitivityLabelPipeBind.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Management.Automation; namespace PnP.PowerShell.Commands.Base.PipeBinds { @@ -60,7 +61,7 @@ public SensitivityLabelPipeBind(Model.Graph.Purview.InformationProtectionLabel l /// Connection that can be used to query Microsoft Graph for the available sensitivity labels /// Access Token to use to authenticate to Microsoft Graph /// The the sensitivity label that matches the name set in this pipebind or NULL if no match found - public Model.Graph.Purview.InformationProtectionLabel GetLabelByNameThroughGraph(PnPConnection connection, string accesstoken) + public Model.Graph.Purview.InformationProtectionLabel GetLabelByNameThroughGraph(Cmdlet cmdlet, PnPConnection connection, string accesstoken) { if (string.IsNullOrEmpty(_labelName)) return null; @@ -74,7 +75,7 @@ public Model.Graph.Purview.InformationProtectionLabel GetLabelByNameThroughGraph url = "/beta/me/security/informationProtection/sensitivityLabels"; } - var availableLabels = Utilities.REST.GraphHelper.GetResultCollectionAsync(connection, $"https://{connection.GraphEndPoint}/{url}", accesstoken).GetAwaiter().GetResult(); + var availableLabels = Utilities.REST.GraphHelper.GetResultCollection(cmdlet, connection, $"https://{connection.GraphEndPoint}/{url}", accesstoken); return availableLabels.FirstOrDefault(l => l.Name == _labelName); } } diff --git a/src/Commands/Base/PipeBinds/ServicePrincipalAssignedAppRoleBind.cs b/src/Commands/Base/PipeBinds/ServicePrincipalAssignedAppRoleBind.cs index 04e63dd5f..ce1d5fdf7 100644 --- a/src/Commands/Base/PipeBinds/ServicePrincipalAssignedAppRoleBind.cs +++ b/src/Commands/Base/PipeBinds/ServicePrincipalAssignedAppRoleBind.cs @@ -2,6 +2,7 @@ using PnP.PowerShell.Commands.Utilities; using System; using System.Linq; +using System.Management.Automation; namespace PnP.PowerShell.Commands.Base.PipeBinds { @@ -31,7 +32,7 @@ public ServicePrincipalAssignedAppRoleBind(AzureADServicePrincipalAppRoleAssignm public string Id => _id; public AzureADServicePrincipalAppRoleAssignment AppRoleAssignment => _appRoleAssignment; - internal AzureADServicePrincipalAppRoleAssignment GetAssignedAppRole(PnPConnection connection, string accesstoken, string servicePrincipalObjectId = null) + internal AzureADServicePrincipalAppRoleAssignment GetAssignedAppRole(Cmdlet cmdlet, PnPConnection connection, string accesstoken, string servicePrincipalObjectId = null) { AzureADServicePrincipalAppRoleAssignment appRoleAssignment = null; @@ -42,7 +43,7 @@ internal AzureADServicePrincipalAppRoleAssignment GetAssignedAppRole(PnPConnecti { throw new ArgumentNullException(nameof(servicePrincipalObjectId), $"{nameof(servicePrincipalObjectId)} is required when the {GetType()} is created based on an Id"); } - appRoleAssignment = ServicePrincipalUtility.GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(connection, accesstoken, servicePrincipalObjectId, _id).FirstOrDefault(); + appRoleAssignment = ServicePrincipalUtility.GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(cmdlet, connection, accesstoken, servicePrincipalObjectId, _id).FirstOrDefault(); } return appRoleAssignment; diff --git a/src/Commands/Base/PipeBinds/ServicePrincipalPipeBind.cs b/src/Commands/Base/PipeBinds/ServicePrincipalPipeBind.cs index 093e63e2b..25ec04f24 100644 --- a/src/Commands/Base/PipeBinds/ServicePrincipalPipeBind.cs +++ b/src/Commands/Base/PipeBinds/ServicePrincipalPipeBind.cs @@ -1,6 +1,7 @@ using PnP.PowerShell.Commands.Model.AzureAD; using PnP.PowerShell.Commands.Utilities; using System; +using System.Management.Automation; namespace PnP.PowerShell.Commands.Base.PipeBinds { @@ -38,11 +39,11 @@ public ServicePrincipalPipeBind(AzureADServicePrincipal servicePrincipal) public Guid? Id => _id; public AzureADServicePrincipal ServicePrincipal => _servicePrincipal; - internal AzureADServicePrincipal GetServicePrincipal(PnPConnection connection, string accesstoken) + internal AzureADServicePrincipal GetServicePrincipal(Cmdlet cmdlet, PnPConnection connection, string accesstoken) { if(_servicePrincipal != null) return _servicePrincipal; - if(!string.IsNullOrEmpty(_displayName)) return ServicePrincipalUtility.GetServicePrincipalByAppName(connection, accesstoken, _displayName); - if(_id.HasValue) return ServicePrincipalUtility.GetServicePrincipalByObjectId(connection, accesstoken, _id.Value) ?? ServicePrincipalUtility.GetServicePrincipalByAppId(connection, accesstoken, _id.Value); + if(!string.IsNullOrEmpty(_displayName)) return ServicePrincipalUtility.GetServicePrincipalByAppName(cmdlet, connection, accesstoken, _displayName); + if(_id.HasValue) return ServicePrincipalUtility.GetServicePrincipalByObjectId(cmdlet, connection, accesstoken, _id.Value) ?? ServicePrincipalUtility.GetServicePrincipalByAppId(cmdlet, connection, accesstoken, _id.Value); return null; } } diff --git a/src/Commands/Base/PipeBinds/SitePipeBind.cs b/src/Commands/Base/PipeBinds/SitePipeBind.cs index 2058881c8..6ee2bae73 100644 --- a/src/Commands/Base/PipeBinds/SitePipeBind.cs +++ b/src/Commands/Base/PipeBinds/SitePipeBind.cs @@ -70,7 +70,7 @@ public Guid GetSiteIdThroughGraph(PnPConnection connection, string accesstoken) { var uri = new Uri(_url); - var result = Utilities.REST.RestHelper.GetAsync(connection.HttpClient, $"https://{connection.GraphEndPoint}/v1.0/sites/{uri.Host}:{uri.LocalPath}", accesstoken).GetAwaiter().GetResult(); + var result = Utilities.REST.RestHelper.Get(connection.HttpClient, $"https://{connection.GraphEndPoint}/v1.0/sites/{uri.Host}:{uri.LocalPath}", accesstoken); if (!string.IsNullOrEmpty(result)) { var resultElement = JsonSerializer.Deserialize(result); diff --git a/src/Commands/Base/PipeBinds/TeamsAppPipeBind.cs b/src/Commands/Base/PipeBinds/TeamsAppPipeBind.cs index 3cbde28a7..c9e463618 100644 --- a/src/Commands/Base/PipeBinds/TeamsAppPipeBind.cs +++ b/src/Commands/Base/PipeBinds/TeamsAppPipeBind.cs @@ -3,7 +3,6 @@ using System; using System.Linq; using System.Management.Automation; -using System.Net.Http; namespace PnP.PowerShell.Commands.Base.PipeBinds { @@ -38,18 +37,18 @@ public TeamsAppPipeBind(string input) public string StringValue => _stringValue; - public TeamApp GetApp(PnPConnection connection, string accessToken) + public TeamApp GetApp(Cmdlet cmdlet, PnPConnection connection, string accessToken) { if (Id != Guid.Empty) { - var collection = GraphHelper.GetAsync>(connection, $"v1.0/appCatalogs/teamsApps?$filter=id eq '{_id}'", accessToken).GetAwaiter().GetResult(); + var collection = GraphHelper.Get>(cmdlet, connection, $"v1.0/appCatalogs/teamsApps?$filter=id eq '{_id}'", accessToken); if (collection != null && collection.Items.Any()) { return collection.Items.First(); } else { - collection = GraphHelper.GetAsync>(connection, $"v1.0/appCatalogs/teamsApps?$filter=externalId eq '{_id}'", accessToken).GetAwaiter().GetResult(); + collection = GraphHelper.Get>(cmdlet, connection, $"v1.0/appCatalogs/teamsApps?$filter=externalId eq '{_id}'", accessToken); if (collection != null && collection.Items.Any()) { return collection.Items.First(); @@ -58,7 +57,7 @@ public TeamApp GetApp(PnPConnection connection, string accessToken) } else { - var collection = GraphHelper.GetAsync>(connection, $"v1.0/appCatalogs/teamsApps?$filter=displayName eq '{_stringValue}'", accessToken).GetAwaiter().GetResult(); + var collection = GraphHelper.Get>(cmdlet, connection, $"v1.0/appCatalogs/teamsApps?$filter=displayName eq '{_stringValue}'", accessToken); if (collection != null && collection.Items.Any()) { if (collection.Items.Count() == 1) diff --git a/src/Commands/Base/PipeBinds/TeamsChannelMemberPipeBind.cs b/src/Commands/Base/PipeBinds/TeamsChannelMemberPipeBind.cs index 76a21c806..ea28cfb65 100644 --- a/src/Commands/Base/PipeBinds/TeamsChannelMemberPipeBind.cs +++ b/src/Commands/Base/PipeBinds/TeamsChannelMemberPipeBind.cs @@ -2,6 +2,7 @@ using PnP.PowerShell.Commands.Utilities; using System; using System.Linq; +using System.Management.Automation; using System.Net.Http; using System.Threading.Tasks; @@ -40,7 +41,7 @@ public TeamsChannelMemberPipeBind(TeamChannelMember membership) _membership = membership; } - public async Task GetIdAsync(PnPConnection Connection, string accessToken, string groupId, string channelId) + public string GetId(Cmdlet cmdlet, PnPConnection Connection, string accessToken, string groupId, string channelId) { if (!string.IsNullOrEmpty(_id)) { @@ -52,7 +53,7 @@ public async Task GetIdAsync(PnPConnection Connection, string accessToke return _membership.Id; } - var memberships = await TeamsUtility.GetChannelMembersAsync(Connection, accessToken, groupId, channelId); + var memberships = TeamsUtility.GetChannelMembers(cmdlet, Connection, accessToken, groupId, channelId); if (!string.IsNullOrEmpty(_userUpn)) { return memberships.FirstOrDefault(m => _userUpn.Equals(m.Email, StringComparison.OrdinalIgnoreCase))?.Id; @@ -61,7 +62,7 @@ public async Task GetIdAsync(PnPConnection Connection, string accessToke return memberships.FirstOrDefault(m => !string.IsNullOrEmpty(m.UserId) && _userId.Equals(m.UserId, StringComparison.OrdinalIgnoreCase))?.Id; } - public async Task GetMembershipAsync(PnPConnection Connection, string accessToken, string groupId, string channelId) + public TeamChannelMember GetMembership(Cmdlet cmdlet, PnPConnection Connection, string accessToken, string groupId, string channelId) { if (_membership != null) { @@ -70,10 +71,10 @@ public async Task GetMembershipAsync(PnPConnection Connection if (!string.IsNullOrEmpty(_id)) { - return await TeamsUtility.GetChannelMemberAsync(Connection, accessToken, groupId, channelId, _id); + return TeamsUtility.GetChannelMember(cmdlet, Connection, accessToken, groupId, channelId, _id); } - var memberships = await TeamsUtility.GetChannelMembersAsync(Connection, accessToken, groupId, channelId); + var memberships = TeamsUtility.GetChannelMembers(cmdlet, Connection, accessToken, groupId, channelId); if (!string.IsNullOrEmpty(_userUpn)) { return memberships.FirstOrDefault(m => _userUpn.Equals(m.Email, StringComparison.OrdinalIgnoreCase)); diff --git a/src/Commands/Base/PipeBinds/TeamsChannelPipeBind.cs b/src/Commands/Base/PipeBinds/TeamsChannelPipeBind.cs index e5944a526..c7be15c26 100644 --- a/src/Commands/Base/PipeBinds/TeamsChannelPipeBind.cs +++ b/src/Commands/Base/PipeBinds/TeamsChannelPipeBind.cs @@ -2,7 +2,7 @@ using PnP.PowerShell.Commands.Utilities; using System; using System.Linq; -using System.Net.Http; +using System.Management.Automation; namespace PnP.PowerShell.Commands.Base.PipeBinds { @@ -36,7 +36,7 @@ public TeamsChannelPipeBind(Model.Teams.TeamChannel channel) public string Id => _id; - public string GetId(PnPConnection connection, string accessToken, string groupId) + public string GetId(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId) { if (!string.IsNullOrEmpty(_id)) { @@ -44,21 +44,21 @@ public string GetId(PnPConnection connection, string accessToken, string groupId } else { - var channels = TeamsUtility.GetChannelsAsync(accessToken, connection, groupId).GetAwaiter().GetResult(); + var channels = TeamsUtility.GetChannels(cmdlet, accessToken, connection, groupId); return channels.FirstOrDefault(c => c.DisplayName.Equals(_displayName, StringComparison.OrdinalIgnoreCase))?.Id; } } - public TeamChannel GetChannel(PnPConnection connection, string accessToken, string groupId, bool useBeta = false) + public TeamChannel GetChannel(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, bool useBeta = false) { if (!string.IsNullOrEmpty(_id)) { - var channel = TeamsUtility.GetChannelAsync(accessToken, connection, groupId, _id, useBeta).GetAwaiter().GetResult(); + var channel = TeamsUtility.GetChannel(cmdlet, accessToken, connection, groupId, _id, useBeta); return channel; } else { - var channels = TeamsUtility.GetChannelsAsync(accessToken, connection, groupId, useBeta).GetAwaiter().GetResult(); + var channels = TeamsUtility.GetChannels(cmdlet, accessToken, connection, groupId, useBeta); if (channels != null && channels.Any()) { return channels.FirstOrDefault(c => c.DisplayName.Equals(_displayName, StringComparison.OrdinalIgnoreCase)); diff --git a/src/Commands/Base/PipeBinds/TeamsTabPipeBind.cs b/src/Commands/Base/PipeBinds/TeamsTabPipeBind.cs index 17f6b1a72..0c0c00a7d 100644 --- a/src/Commands/Base/PipeBinds/TeamsTabPipeBind.cs +++ b/src/Commands/Base/PipeBinds/TeamsTabPipeBind.cs @@ -47,10 +47,10 @@ public TeamTab GetTab(BasePSCmdlet cmdlet, PnPConnection Connection, string acce } else { - var tab = TeamsUtility.GetTabAsync(accessToken, Connection, groupId, channelId, _id).GetAwaiter().GetResult(); + var tab = TeamsUtility.GetTab(cmdlet, accessToken, Connection, groupId, channelId, _id); if (string.IsNullOrEmpty(tab.Id)) { - var tabs = TeamsUtility.GetTabsAsync(accessToken, Connection, groupId, channelId).GetAwaiter().GetResult(); + var tabs = TeamsUtility.GetTabs(cmdlet, accessToken, Connection, groupId, channelId); if (tabs != null) { // find the tab by id diff --git a/src/Commands/Base/PipeBinds/TeamsTagPipeBind.cs b/src/Commands/Base/PipeBinds/TeamsTagPipeBind.cs index 643e9e8f7..9646f8b69 100644 --- a/src/Commands/Base/PipeBinds/TeamsTagPipeBind.cs +++ b/src/Commands/Base/PipeBinds/TeamsTagPipeBind.cs @@ -2,7 +2,7 @@ using PnP.PowerShell.Commands.Utilities; using System; using System.Linq; -using System.Net.Http; +using System.Management.Automation; namespace PnP.PowerShell.Commands.Base.PipeBinds { @@ -24,9 +24,9 @@ public TeamsTagPipeBind(TeamTag tag) } - public TeamTag GetTag(PnPConnection connection, string accessToken, string groupId) + public TeamTag GetTag(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId) { - var tags = TeamsUtility.GetTagsAsync(accessToken, connection, groupId).GetAwaiter().GetResult(); + var tags = TeamsUtility.GetTags(cmdlet, accessToken, connection, groupId); if (tags != null && tags.Any()) { return tags.FirstOrDefault(c => c.Id.Equals(_id, StringComparison.OrdinalIgnoreCase)); diff --git a/src/Commands/Base/PipeBinds/TeamsTeamPipeBind.cs b/src/Commands/Base/PipeBinds/TeamsTeamPipeBind.cs index 929ddb41e..089cb53a2 100644 --- a/src/Commands/Base/PipeBinds/TeamsTeamPipeBind.cs +++ b/src/Commands/Base/PipeBinds/TeamsTeamPipeBind.cs @@ -46,7 +46,7 @@ public TeamsTeamPipeBind(Guid id) _id = id.ToString(); } - public string GetGroupId(PnPConnection connection, string accessToken) + public string GetGroupId(Cmdlet cmdlet, PnPConnection connection, string accessToken) { if (!string.IsNullOrEmpty(_id)) { @@ -54,7 +54,7 @@ public string GetGroupId(PnPConnection connection, string accessToken) } else { - var collection = GraphHelper.GetAsync>(connection, $"v1.0/groups?$filter=(resourceProvisioningOptions/Any(x:x eq 'Team') and mailNickname eq '{UrlUtilities.UrlEncode(_stringValue)}')&$select=Id", accessToken).GetAwaiter().GetResult(); + var collection = GraphHelper.Get>(cmdlet, connection, $"v1.0/groups?$filter=(resourceProvisioningOptions/Any(x:x eq 'Team') and mailNickname eq '{UrlUtilities.UrlEncode(_stringValue)}')&$select=Id", accessToken); if (collection != null && collection.Items.Any()) { return collection.Items.First().Id; @@ -62,7 +62,7 @@ public string GetGroupId(PnPConnection connection, string accessToken) else { // find the team by displayName - var byDisplayNamecollection = GraphHelper.GetAsync>(connection, $"v1.0/groups?$filter=(resourceProvisioningOptions/Any(x:x eq 'Team') and displayName eq '{UrlUtilities.UrlEncode(_stringValue)}')&$select=Id", accessToken).GetAwaiter().GetResult(); + var byDisplayNamecollection = GraphHelper.Get>(cmdlet, connection, $"v1.0/groups?$filter=(resourceProvisioningOptions/Any(x:x eq 'Team') and displayName eq '{UrlUtilities.UrlEncode(_stringValue)}')&$select=Id", accessToken); if (byDisplayNamecollection != null && byDisplayNamecollection.Items.Any()) { if (byDisplayNamecollection.Items.Count() == 1) @@ -79,22 +79,22 @@ public string GetGroupId(PnPConnection connection, string accessToken) } } - public Team GetTeam(PnPConnection connection, string accessToken) + public Team GetTeam(Cmdlet cmdlet, PnPConnection connection, string accessToken) { try { if (!string.IsNullOrEmpty(_id)) { - return GraphHelper.GetAsync(connection, $"v1.0/teams/{_id}", accessToken, false).GetAwaiter().GetResult(); + return GraphHelper.Get(cmdlet, connection, $"v1.0/teams/{_id}", accessToken, false); } else { - var collection = GraphHelper.GetAsync>(connection, $"v1.0/groups?$filter=(resourceProvisioningOptions/Any(x:x eq 'Team') and displayName eq '{_stringValue}')&$select=Id", accessToken).GetAwaiter().GetResult(); + var collection = GraphHelper.Get>(cmdlet, connection, $"v1.0/groups?$filter=(resourceProvisioningOptions/Any(x:x eq 'Team') and displayName eq '{_stringValue}')&$select=Id", accessToken); if (collection != null && collection.Items.Any()) { if (collection.Items.Count() == 1) { - return GraphHelper.GetAsync(connection, $"v1.0/teams/{collection.Items.First().Id}", accessToken, false).GetAwaiter().GetResult(); + return GraphHelper.Get(cmdlet, connection, $"v1.0/teams/{collection.Items.First().Id}", accessToken, false); } else { @@ -103,10 +103,10 @@ public Team GetTeam(PnPConnection connection, string accessToken) } else { - collection = GraphHelper.GetAsync>(connection, $"v1.0/groups?$filter=(resourceProvisioningOptions/Any(x:x eq 'Team') and mailNickname eq '{_stringValue}')&$select=Id", accessToken).GetAwaiter().GetResult(); + collection = GraphHelper.Get>(cmdlet, connection, $"v1.0/groups?$filter=(resourceProvisioningOptions/Any(x:x eq 'Team') and mailNickname eq '{_stringValue}')&$select=Id", accessToken); if (collection != null && collection.Items.Count() == 1) { - return GraphHelper.GetAsync(connection, $"v1.0/teams/{collection.Items.First().Id}", accessToken, false).GetAwaiter().GetResult(); + return GraphHelper.Get(cmdlet, connection, $"v1.0/teams/{collection.Items.First().Id}", accessToken, false); } } } diff --git a/src/Commands/Base/PnPConnectedCmdlet.cs b/src/Commands/Base/PnPConnectedCmdlet.cs index 6888f0597..a28fb6226 100644 --- a/src/Commands/Base/PnPConnectedCmdlet.cs +++ b/src/Commands/Base/PnPConnectedCmdlet.cs @@ -62,12 +62,12 @@ protected override void ProcessRecord() string errorMessage; switch (ex) { - case PnP.PowerShell.Commands.Model.Graph.GraphException gex: + case Model.Graph.GraphException gex: errorMessage = $"{gex.HttpResponse.ReasonPhrase} ({(int)gex.HttpResponse.StatusCode}): {gex.Error.Message}"; break; - case PnP.Core.SharePointRestServiceException rex: - errorMessage = (rex.Error as PnP.Core.SharePointRestError).Message; + case Core.SharePointRestServiceException rex: + errorMessage = (rex.Error as Core.SharePointRestError).Message; break; case System.Reflection.TargetInvocationException tex: @@ -86,8 +86,8 @@ protected override void ProcessRecord() errorMessage = innermostException.Message; } break; - case PnP.Core.MicrosoftGraphServiceException pgex: - errorMessage = (pgex.Error as PnP.Core.MicrosoftGraphError).Message; + case Core.MicrosoftGraphServiceException pgex: + errorMessage = (pgex.Error as Core.MicrosoftGraphError).Message; break; default: @@ -107,7 +107,7 @@ protected override void ProcessRecord() } // With ErrorAction:Ignore, the $Error variable should not be populated with the error, otherwise it should - if (!ParameterSpecified("ErrorAction") || !(new[] { "ignore" }.Contains(MyInvocation.BoundParameters["ErrorAction"].ToString().ToLowerInvariant()))) + if (!ParameterSpecified("ErrorAction") || !new[] { "ignore" }.Contains(MyInvocation.BoundParameters["ErrorAction"].ToString().ToLowerInvariant())) { ex.Data["CorrelationId"] = Connection.Context.TraceCorrelationId; ex.Data["TimeStampUtc"] = DateTime.UtcNow; diff --git a/src/Commands/Base/TokenHandling.cs b/src/Commands/Base/TokenHandling.cs index 46fabbd8b..12c8b571d 100644 --- a/src/Commands/Base/TokenHandling.cs +++ b/src/Commands/Base/TokenHandling.cs @@ -2,6 +2,7 @@ using Microsoft.SharePoint.Client; using PnP.PowerShell.Commands.Attributes; using System; +using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Management.Automation; @@ -16,11 +17,11 @@ internal static class TokenHandler /// /// Returns the type of oAuth JWT token being passed in (Delegate/AppOnly) /// - /// The oAuth JWT token + /// The oAuth JWT token /// Enum indicating the type of oAuth JWT token - internal static Enums.IdType RetrieveTokenType(string token) + internal static Enums.IdType RetrieveTokenType(string accessToken) { - var decodedToken = new JwtSecurityToken(token); + var decodedToken = new JwtSecurityToken(accessToken); // The idType is stored in the token as a claim var idType = decodedToken.Claims.FirstOrDefault(c => c.Type == "idtyp"); @@ -37,13 +38,43 @@ internal static Enums.IdType RetrieveTokenType(string token) }; } + /// + /// Returns the userId of the user who's token is being passed in + /// + /// The oAuth JWT token + /// The userId of the user for which the passed in delegate token is for + internal static Guid? RetrieveTokenUser(string accessToken) + { + var decodedToken = new JwtSecurityToken(accessToken); + + // The objectId is stored in the token as a claim + var objectId = decodedToken.Claims.FirstOrDefault(c => c.Type == "oid"); + + // Check if the token contains an objectId and if its a valid Guid + return objectId == null || !Guid.TryParse(objectId.Value, out Guid objectIdGuid) ? null : objectIdGuid; + } + + /// + /// Returns the permission scopes of the oAuth JWT token being passed in + /// + /// The oAuth JWT token + /// String array containing the scopes + internal static string[] ReturnScopes(string accessToken) + { + var decodedToken = new JwtSecurityToken(accessToken); + + // The scopes can either be stored in the roles or scp claim, so we examine both + var scopes = decodedToken.Claims.Where(c => c.Type == "roles" || c.Type == "scp").SelectMany(r => r.Value.Split(" ")); + return scopes.ToArray(); + } + /// /// Extracts the oAuth JWT token to compare the permissions in it (roles) with the required permissions for the cmdlet provided through an attribute /// /// The cmdlet that will be executed. Used to check for the permissions attribute. - /// The oAuth JWT token that needs to be validated for its roles + /// The oAuth JWT token that needs to be validated for its roles /// Thrown if the permissions set through the permissions attribute do not match the roles in the JWT token - internal static void ValidateTokenForPermissions(Type cmdletType, string token) + internal static void ValidateTokenForPermissions(Type cmdletType, string accessToken) { string[] requiredScopes = null; var requiredScopesAttribute = (RequiredMinimalApiPermissions)Attribute.GetCustomAttribute(cmdletType, typeof(RequiredMinimalApiPermissions)); @@ -51,34 +82,28 @@ internal static void ValidateTokenForPermissions(Type cmdletType, string token) { requiredScopes = requiredScopesAttribute.PermissionScopes; } - if (requiredScopes?.Length > 0) - { - var decodedToken = new JwtSecurityToken(token); - var roles = decodedToken.Claims.FirstOrDefault(c => c.Type == "roles"); - if (roles != null) - { - foreach (var permission in requiredScopes) - { - if (!roles.Value.ToLower().Contains(permission.ToLower())) - { - throw new PSArgumentException($"Authorization Denied: Token used does not contain permission scope '{permission}'"); - } - } - } - roles = decodedToken.Claims.FirstOrDefault(c => c.Type == "scp"); - if (roles != null) - { - foreach (var permission in requiredScopes) - { - if (!roles.Value.ToLower().Contains(permission.ToLower())) - { - throw new PSArgumentException($"Authorization Denied: Token used does not contain permission scope '{permission}'"); - } - } - } - } + + // Ensure there are permission attributes present on the cmdlet, otherwise we have nothing to compare it against + if (requiredScopes == null || requiredScopes.Length == 0) return; + + // Retrieve the scopes we have in our AccessToken + var scopes = ReturnScopes(accessToken); + + var missingScopes = requiredScopes.Where(rs => !scopes.Contains(rs)).ToArray(); + + if (missingScopes.Length == 0) return; + + throw new PSArgumentException($"Authorization Denied: Token used does not contain permission scope{(missingScopes.Length != 1 ? "s" : "")} {string.Concat(missingScopes, ", ")}"); } + /// + /// Returns an oAuth JWT access token + /// + /// Cmdlet for which the token is requested + /// Audience to retrieve the token for + /// The connection to use to make the token calls + /// oAuth JWT token + /// Thrown if retrieval of the token fails internal static string GetAccessToken(Cmdlet cmdlet, string appOnlyDefaultScope, PnPConnection connection) { var contextSettings = connection.Context.GetContextSettings(); @@ -111,8 +136,13 @@ internal static string GetAccessToken(Cmdlet cmdlet, string appOnlyDefaultScope, } cmdlet.WriteVerbose($"Acquiring oAuth token for {(requiredScopes.Length != 1 ? requiredScopes.Length + " " : "")}permission scope{(requiredScopes.Length != 1 ? "s" : "")} {string.Join(",", requiredScopes)}"); - var accessToken = authManager.GetAccessTokenAsync(requiredScopes).GetAwaiter().GetResult(); - cmdlet.WriteVerbose($"Access token acquired"); + var accessToken = authManager.GetAccessTokenAsync(requiredScopes).GetAwaiter().GetResult(); + + // Retrieve the scopes from the access token + var scopes = ReturnScopes(accessToken); + + cmdlet.WriteVerbose($"Access token acquired containing the following {(scopes.Length != 1 ? scopes.Length + " " : "")}{RetrieveTokenType(accessToken).ToString().ToLowerInvariant()} scope{(scopes.Length == 1 ? "" : "s")}: {string.Join(", ", scopes)}"); + return accessToken; } return null; @@ -132,7 +162,6 @@ internal static string GetAccessTokenforPowerPlatformSolutions(Cmdlet cmdlet, Pn string[] requiredScopes = new string[1] { enviormentBaseUrl + "/.default" }; cmdlet.WriteVerbose($"Acquiring oAuth token for {(requiredScopes.Length != 1 ? requiredScopes.Length + " " : "")}permission scope{(requiredScopes.Length != 1 ? "s" : "")} {string.Join(",", requiredScopes)}"); var accessToken = authManager.GetAccessTokenAsync(requiredScopes).GetAwaiter().GetResult(); - cmdlet.WriteVerbose($"Access token acquired for PowerPlatformSolutions: {accessToken}"); return accessToken; } return null; diff --git a/src/Commands/Graph/InvokeGraphMethod.cs b/src/Commands/Graph/InvokeGraphMethod.cs index 4f22f8bde..8c2232d05 100644 --- a/src/Commands/Graph/InvokeGraphMethod.cs +++ b/src/Commands/Graph/InvokeGraphMethod.cs @@ -167,7 +167,7 @@ private void SendRequest() } throw new NotSupportedException($"method [{Method}] not supported"); } - catch (PnP.PowerShell.Commands.Model.Graph.GraphException gex) + catch (Model.Graph.GraphException gex) { if (gex.Error.Code == "Authorization_RequestDenied") { @@ -209,7 +209,7 @@ private void WriteGraphResult(string result) private void GetRequestWithPaging() { - var result = GraphHelper.GetAsync(Connection, Url, AccessToken, AdditionalHeaders).GetAwaiter().GetResult(); + var result = GraphHelper.Get(this, Connection, Url, AccessToken, AdditionalHeaders); if (Raw.IsPresent) { WriteObject(result); @@ -233,7 +233,7 @@ private void GetRequestWithPaging() break; } var nextLink = nextLinkProperty.ToString(); - result = GraphHelper.GetAsync(Connection, nextLink, AccessToken, AdditionalHeaders).GetAwaiter().GetResult(); + result = GraphHelper.Get(this, Connection, nextLink, AccessToken, AdditionalHeaders); element = JsonSerializer.Deserialize(result); dynamic nextObj = Deserialize(element); if (nextObj != null && nextObj.value != null && (nextObj.value is List)) @@ -259,35 +259,35 @@ private void GetRequestWithPaging() private void GetRequestWithoutPaging() { WriteVerbose($"Sending HTTP GET to {Url}"); - using var response = GraphHelper.GetResponseAsync(Connection, Url, AccessToken).GetAwaiter().GetResult(); + using var response = GraphHelper.GetResponse(this, Connection, Url, AccessToken); HandleResponse(response); } private void PostRequest() { WriteVerbose($"Sending HTTP POST to {Url}"); - var response = GraphHelper.PostAsync(Connection, Url, AccessToken, GetHttpContent(), AdditionalHeaders).GetAwaiter().GetResult(); + var response = GraphHelper.Post(this, Connection, Url, AccessToken, GetHttpContent(), AdditionalHeaders); HandleResponse(response); } private void PutRequest() { WriteVerbose($"Sending HTTP PUT to {Url}"); - var response = GraphHelper.PutAsync(Connection, Url, AccessToken, GetHttpContent(), AdditionalHeaders).GetAwaiter().GetResult(); + var response = GraphHelper.Put(this, Connection, Url, AccessToken, GetHttpContent(), AdditionalHeaders); HandleResponse(response); } private void PatchRequest() { WriteVerbose($"Sending HTTP PATCH to {Url}"); - var response = GraphHelper.PatchAsync(Connection, AccessToken, GetHttpContent(), Url, AdditionalHeaders).GetAwaiter().GetResult(); + var response = GraphHelper.Patch(this, Connection, AccessToken, GetHttpContent(), Url, AdditionalHeaders); HandleResponse(response); } private void DeleteRequest() { WriteVerbose($"Sending HTTP DELETE to {Url}"); - var response = GraphHelper.DeleteAsync(Connection, Url, AccessToken, AdditionalHeaders).GetAwaiter().GetResult(); + var response = GraphHelper.Delete(this, Connection, Url, AccessToken, AdditionalHeaders); HandleResponse(response); } @@ -308,7 +308,7 @@ private void HandleResponse(HttpResponseMessage response) { WriteVerbose($"Writing {responseStreamForFile.Length} bytes response to {OutFile}"); - using (var fileStream = new System.IO.FileStream(OutFile, System.IO.FileMode.Create, System.IO.FileAccess.Write)) + using (var fileStream = new FileStream(OutFile, FileMode.Create, FileAccess.Write)) { responseStreamForFile.CopyTo(fileStream); fileStream.Close(); @@ -321,7 +321,7 @@ private void HandleResponse(HttpResponseMessage response) WriteVerbose($"Writing {responseStream.Length} bytes response to outputstream"); - var memoryStream = new System.IO.MemoryStream(); + var memoryStream = new MemoryStream(); responseStream.CopyTo(memoryStream); memoryStream.Position = 0; diff --git a/src/Commands/Lists/CopyList.cs b/src/Commands/Lists/CopyList.cs index 85c0b5e95..c41b942b8 100644 --- a/src/Commands/Lists/CopyList.cs +++ b/src/Commands/Lists/CopyList.cs @@ -62,7 +62,7 @@ protected override void ExecuteCmdlet() // Generate a site script from the list that needs to be copied WriteVerbose($"Generating script from list at {SourceListUrl}"); - var generatedScript = RestHelper.PostAsync>(Connection.HttpClient, $"{Connection.Url}/_api/Microsoft.Sharepoint.Utilities.WebTemplateExtensions.SiteScriptUtility.GetSiteScriptFromList()", ClientContext, new { listUrl = SourceListUrl}).GetAwaiter().GetResult(); + var generatedScript = RestHelper.Post>(Connection.HttpClient, $"{Connection.Url}/_api/Microsoft.Sharepoint.Utilities.WebTemplateExtensions.SiteScriptUtility.GetSiteScriptFromList()", ClientContext, new { listUrl = SourceListUrl}); // Take the site script of the list to copy var script = generatedScript.Content; @@ -94,7 +94,7 @@ protected override void ExecuteCmdlet() // Execute site script on destination site so the list will be created WriteVerbose($"Executing site script to site at {DestinationWebUrl}"); - var actionResults = RestHelper.PostAsync>(Connection.HttpClient, $"{DestinationWebUrl}/_api/Microsoft.Sharepoint.Utilities.WebTemplateExtensions.SiteScriptUtility.ExecuteTemplateScript()", ClientContext, new { script = script}).GetAwaiter().GetResult(); + var actionResults = RestHelper.Post>(Connection.HttpClient, $"{DestinationWebUrl}/_api/Microsoft.Sharepoint.Utilities.WebTemplateExtensions.SiteScriptUtility.ExecuteTemplateScript()", ClientContext, new { script = script}); // Ensure site script actions have been executed if(actionResults.Items.Count() == 0) diff --git a/src/Commands/Lists/SetList.cs b/src/Commands/Lists/SetList.cs index 618ea4ee1..11f167f20 100644 --- a/src/Commands/Lists/SetList.cs +++ b/src/Commands/Lists/SetList.cs @@ -387,7 +387,7 @@ protected override void ExecuteCmdlet() if (!string.IsNullOrEmpty(DefaultSensitivityLabelForLibrary.LabelName)) { WriteVerbose($"Looking up sensitivity label id by label name '{DefaultSensitivityLabelForLibrary.LabelName}'"); - var label = DefaultSensitivityLabelForLibrary.GetLabelByNameThroughGraph(Connection, GraphAccessToken); + var label = DefaultSensitivityLabelForLibrary.GetLabelByNameThroughGraph(this, Connection, GraphAccessToken); if (label == null || !label.Id.HasValue) { diff --git a/src/Commands/ManagementApi/GetUnifiedAuditLog.cs b/src/Commands/ManagementApi/GetUnifiedAuditLog.cs index 20ae5ee66..2dd9a26a0 100644 --- a/src/Commands/ManagementApi/GetUnifiedAuditLog.cs +++ b/src/Commands/ManagementApi/GetUnifiedAuditLog.cs @@ -57,7 +57,7 @@ protected string ContentTypeString private IEnumerable GetSubscriptions() { var url = $"{ApiUrl}/subscriptions/list"; - return GraphHelper.GetAsync>(Connection, url, AccessToken).GetAwaiter().GetResult(); + return GraphHelper.Get>(this, Connection, url, AccessToken); } private void EnsureSubscription(string contentType) @@ -66,7 +66,7 @@ private void EnsureSubscription(string contentType) var subscription = subscriptions.FirstOrDefault(s => s.ContentType == contentType); if (subscription == null) { - subscription = GraphHelper.PostAsync(Connection, $"{ApiUrl}/subscriptions/start?contentType={contentType}&PublisherIdentifier={TenantId}", AccessToken).GetAwaiter().GetResult(); + subscription = GraphHelper.Post(this, Connection, $"{ApiUrl}/subscriptions/start?contentType={contentType}&PublisherIdentifier={TenantId}", AccessToken); if (!subscription.Status.Equals("enabled", StringComparison.OrdinalIgnoreCase)) { throw new Exception($"Cannot enable subscription for {contentType}"); @@ -89,7 +89,7 @@ protected override void ExecuteCmdlet() } List subscriptionContents = new List(); - var subscriptionResponse = GraphHelper.GetResponseAsync(Connection, url, AccessToken).GetAwaiter().GetResult(); + var subscriptionResponse = GraphHelper.GetResponse(this, Connection, url, AccessToken); var content = subscriptionResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult(); if (subscriptionResponse.IsSuccessStatusCode) @@ -97,7 +97,7 @@ protected override void ExecuteCmdlet() subscriptionContents.AddRange(System.Text.Json.JsonSerializer.Deserialize>(content, new System.Text.Json.JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })); while (subscriptionResponse.Headers.Contains("NextPageUri")) { - subscriptionResponse = GraphHelper.GetResponseAsync(Connection, subscriptionResponse.Headers.GetValues("NextPageUri").First(), AccessToken).GetAwaiter().GetResult(); + subscriptionResponse = GraphHelper.GetResponse(this, Connection, subscriptionResponse.Headers.GetValues("NextPageUri").First(), AccessToken); if (subscriptionResponse.IsSuccessStatusCode) { content = subscriptionResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult(); @@ -115,7 +115,7 @@ protected override void ExecuteCmdlet() { foreach (var subscriptionContent in subscriptionContents) { - var logs = GraphHelper.GetAsync>(Connection, subscriptionContent.ContentUri, AccessToken, false).GetAwaiter().GetResult(); + var logs = GraphHelper.Get>(this, Connection, subscriptionContent.ContentUri, AccessToken, false); WriteObject(logs, true); } } diff --git a/src/Commands/Microsoft365Groups/AddMicrosoft365GroupMember.cs b/src/Commands/Microsoft365Groups/AddMicrosoft365GroupMember.cs index cf78c16e5..36c7b7da5 100644 --- a/src/Commands/Microsoft365Groups/AddMicrosoft365GroupMember.cs +++ b/src/Commands/Microsoft365Groups/AddMicrosoft365GroupMember.cs @@ -21,7 +21,7 @@ public class AddMicrosoft365GroupMember : PnPGraphCmdlet protected override void ExecuteCmdlet() { - Microsoft365GroupsUtility.AddMembersAsync(Connection, Identity.GetGroupId(Connection, AccessToken), Users, AccessToken, RemoveExisting).GetAwaiter().GetResult(); + ClearOwners.AddMembers(this, Connection, Identity.GetGroupId(this, Connection, AccessToken), Users, AccessToken, RemoveExisting); } } } \ No newline at end of file diff --git a/src/Commands/Microsoft365Groups/AddMicrosoft365GroupOwner.cs b/src/Commands/Microsoft365Groups/AddMicrosoft365GroupOwner.cs index 4d214c822..8329c5928 100644 --- a/src/Commands/Microsoft365Groups/AddMicrosoft365GroupOwner.cs +++ b/src/Commands/Microsoft365Groups/AddMicrosoft365GroupOwner.cs @@ -21,7 +21,7 @@ public class AddMicrosoft365GroupOwner : PnPGraphCmdlet protected override void ExecuteCmdlet() { - Microsoft365GroupsUtility.AddOwnersAsync(Connection, Identity.GetGroupId(Connection, AccessToken), Users, AccessToken, RemoveExisting).GetAwaiter().GetResult(); + ClearOwners.AddOwners(this, Connection, Identity.GetGroupId(this, Connection, AccessToken), Users, AccessToken, RemoveExisting); } } } \ No newline at end of file diff --git a/src/Commands/Microsoft365Groups/ClearMicrosoft365GroupMember.cs b/src/Commands/Microsoft365Groups/ClearMicrosoft365GroupMember.cs index 64191033c..0a9cd52fe 100644 --- a/src/Commands/Microsoft365Groups/ClearMicrosoft365GroupMember.cs +++ b/src/Commands/Microsoft365Groups/ClearMicrosoft365GroupMember.cs @@ -15,7 +15,7 @@ public class ClearMicrosoft365GroupMember : PnPGraphCmdlet protected override void ExecuteCmdlet() { - Microsoft365GroupsUtility.ClearMembersAsync(Connection, Identity.GetGroupId(Connection, AccessToken), AccessToken).GetAwaiter().GetResult(); + ClearOwners.ClearMembers(this, Connection, Identity.GetGroupId(this, Connection, AccessToken), AccessToken); } } } \ No newline at end of file diff --git a/src/Commands/Microsoft365Groups/ClearMicrosoft365GroupOwner.cs b/src/Commands/Microsoft365Groups/ClearMicrosoft365GroupOwner.cs index 6ca4bbdbc..357758176 100644 --- a/src/Commands/Microsoft365Groups/ClearMicrosoft365GroupOwner.cs +++ b/src/Commands/Microsoft365Groups/ClearMicrosoft365GroupOwner.cs @@ -16,9 +16,9 @@ public class ClearMicrosoft365GroupOwner : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Identity.GetGroupId(Connection, AccessToken); - Microsoft365GroupsUtility.ClearOwnersAsync(Connection, groupId, AccessToken).GetAwaiter().GetResult(); - var owners = Microsoft365GroupsUtility.GetOwnersAsync(Connection, groupId, AccessToken).GetAwaiter().GetResult(); + var groupId = Identity.GetGroupId(this, Connection, AccessToken); + ClearOwners.ClearOwnersAsync(this, Connection, groupId, AccessToken); + var owners = ClearOwners.GetOwners(this, Connection, groupId, AccessToken); if (owners != null && owners.Any()) { WriteWarning($"Clearing all owners is not possible as there will always have to be at least one owner. To changed the owners with new owners use Set-PnPMicrosoft365GroupOwner -Identity {groupId} -Owners \"newowner@domain.com\""); diff --git a/src/Commands/Microsoft365Groups/GetDeletedMicrosoft365Group.cs b/src/Commands/Microsoft365Groups/GetDeletedMicrosoft365Group.cs index 867715daa..7e6ca9021 100644 --- a/src/Commands/Microsoft365Groups/GetDeletedMicrosoft365Group.cs +++ b/src/Commands/Microsoft365Groups/GetDeletedMicrosoft365Group.cs @@ -18,11 +18,11 @@ protected override void ExecuteCmdlet() { if (Identity != null) { - WriteObject(Identity.GetDeletedGroup(Connection, AccessToken)); + WriteObject(Identity.GetDeletedGroup(this, Connection, AccessToken)); } else { - var groups = Microsoft365GroupsUtility.GetDeletedGroupsAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var groups = ClearOwners.GetDeletedGroups(this, Connection, AccessToken); WriteObject(groups.OrderBy(g => g.DisplayName), true); } } diff --git a/src/Commands/Microsoft365Groups/GetExpiringMicrosoft365Group.cs b/src/Commands/Microsoft365Groups/GetExpiringMicrosoft365Group.cs index 7ae65379a..afa791e02 100644 --- a/src/Commands/Microsoft365Groups/GetExpiringMicrosoft365Group.cs +++ b/src/Commands/Microsoft365Groups/GetExpiringMicrosoft365Group.cs @@ -23,7 +23,7 @@ public class GetExpiringMicrosoft365Group : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var expiringGroups = Microsoft365GroupsUtility.GetExpiringGroupAsync(Connection, AccessToken, Limit, IncludeSiteUrl, IncludeOwners).GetAwaiter().GetResult(); + var expiringGroups = ClearOwners.GetExpiringGroup(this, Connection, AccessToken, Limit, IncludeSiteUrl, IncludeOwners); WriteObject(expiringGroups.OrderBy(p => p.DisplayName), true); } diff --git a/src/Commands/Microsoft365Groups/GetMicrosoft365Group.cs b/src/Commands/Microsoft365Groups/GetMicrosoft365Group.cs index fbb3dcd48..65925f65a 100644 --- a/src/Commands/Microsoft365Groups/GetMicrosoft365Group.cs +++ b/src/Commands/Microsoft365Groups/GetMicrosoft365Group.cs @@ -36,12 +36,12 @@ protected override void ExecuteCmdlet() if (Identity != null) { - var group = Identity.GetGroup(Connection, AccessToken, includeSiteUrl, IncludeOwners, Detailed.ToBool(), IncludeSensitivityLabels); + var group = Identity.GetGroup(this, Connection, AccessToken, includeSiteUrl, IncludeOwners, Detailed.ToBool(), IncludeSensitivityLabels); WriteObject(group); } else { - var groups = Microsoft365GroupsUtility.GetGroupsAsync(Connection, AccessToken, includeSiteUrl, IncludeOwners, Filter, IncludeSensitivityLabels).GetAwaiter().GetResult(); + var groups = ClearOwners.GetGroups(this, Connection, AccessToken, includeSiteUrl, IncludeOwners, Filter, IncludeSensitivityLabels); WriteObject(groups.OrderBy(p => p.DisplayName), true); } diff --git a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupEndpoint.cs b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupEndpoint.cs index 52380b267..d1762c190 100644 --- a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupEndpoint.cs +++ b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupEndpoint.cs @@ -22,7 +22,7 @@ protected override void ExecuteCmdlet() if (ParameterSpecified(nameof(Identity))) { WriteVerbose($"Defining Microsoft 365 Group based on {nameof(Identity)} parameter"); - groupId = Identity.GetGroupId(Connection, AccessToken); + groupId = Identity.GetGroupId(this, Connection, AccessToken); } else { @@ -43,7 +43,7 @@ protected override void ExecuteCmdlet() } WriteVerbose($"Requesting endpoints of Microsoft 365 Group with Id {groupId}"); - var endpoints = GraphHelper.GetResultCollectionAsync(Connection, $"/beta/groups/{groupId}/endpoints", AccessToken).GetAwaiter().GetResult(); + var endpoints = GraphHelper.GetResultCollection(this, Connection, $"/beta/groups/{groupId}/endpoints", AccessToken); WriteVerbose($"{endpoints.Count()} endpoint(s) found in total"); WriteObject(endpoints, true); } diff --git a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupMember.cs b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupMember.cs index 9974527ff..bcdfcf7af 100644 --- a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupMember.cs +++ b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupMember.cs @@ -17,7 +17,7 @@ public class GetMicrosoft365GroupMember : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var members = Microsoft365GroupsUtility.GetMembersAsync(Connection, Identity.GetGroupId(Connection, AccessToken), AccessToken).GetAwaiter().GetResult(); + var members = ClearOwners.GetMembers(this, Connection, Identity.GetGroupId(this, Connection, AccessToken), AccessToken); WriteObject(members?.OrderBy(m => m.DisplayName), true); } } diff --git a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupOwner.cs b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupOwner.cs index 487b7aa9f..d0e7c28af 100644 --- a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupOwner.cs +++ b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupOwner.cs @@ -17,7 +17,7 @@ public class GetMicrosoft365GroupOwner : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var owners = Microsoft365GroupsUtility.GetOwnersAsync(Connection, Identity.GetGroupId(Connection, AccessToken), AccessToken).GetAwaiter().GetResult(); + var owners = ClearOwners.GetOwners(this, Connection, Identity.GetGroupId(this, Connection, AccessToken), AccessToken); WriteObject(owners?.OrderBy(o => o.DisplayName), true); } } diff --git a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupSettingTemplates.cs b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupSettingTemplates.cs index cc110f0a3..e3bc0eea0 100644 --- a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupSettingTemplates.cs +++ b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupSettingTemplates.cs @@ -16,12 +16,12 @@ protected override void ExecuteCmdlet() { if (Identity != null) { - var groupSettingTemplate = Microsoft365GroupsUtility.GetGroupTemplateSettingsAsync(Connection, AccessToken, Identity).GetAwaiter().GetResult(); + var groupSettingTemplate = ClearOwners.GetGroupTemplateSettings(this, Connection, AccessToken, Identity); WriteObject(groupSettingTemplate); } else { - var groupSettingTemplates = Microsoft365GroupsUtility.GetGroupTemplateSettingsAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var groupSettingTemplates = ClearOwners.GetGroupTemplateSettings(this, Connection, AccessToken); WriteObject(groupSettingTemplates?.Value, true); } } diff --git a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupSettings.cs b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupSettings.cs index 79aeda295..3e0d09663 100644 --- a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupSettings.cs +++ b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupSettings.cs @@ -2,7 +2,6 @@ using PnP.PowerShell.Commands.Base; using PnP.PowerShell.Commands.Base.PipeBinds; using PnP.PowerShell.Commands.Utilities; -using System; using System.Management.Automation; namespace PnP.PowerShell.Commands.Microsoft365Groups @@ -18,13 +17,13 @@ protected override void ExecuteCmdlet() { if (Identity != null) { - var groupId = Identity.GetGroupId(Connection, AccessToken); - var groupSettings = Microsoft365GroupsUtility.GetGroupSettingsAsync(Connection, AccessToken, groupId.ToString()).GetAwaiter().GetResult(); + var groupId = Identity.GetGroupId(this, Connection, AccessToken); + var groupSettings = ClearOwners.GetGroupSettings(this, Connection, AccessToken, groupId.ToString()); WriteObject(groupSettings?.Value, true); } else { - var groupSettings = Microsoft365GroupsUtility.GetGroupSettingsAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var groupSettings = ClearOwners.GetGroupSettings(this, Connection, AccessToken); WriteObject(groupSettings?.Value, true); } } diff --git a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupTeam.cs b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupTeam.cs index 1fd2843df..c4c055b74 100644 --- a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupTeam.cs +++ b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupTeam.cs @@ -22,7 +22,7 @@ protected override void ExecuteCmdlet() if (ParameterSpecified(nameof(Identity))) { WriteVerbose($"Defining Microsoft 365 Group based on {nameof(Identity)} parameter"); - groupId = Identity.GetGroupId(Connection, AccessToken); + groupId = Identity.GetGroupId(this, Connection, AccessToken); } else { @@ -43,7 +43,7 @@ protected override void ExecuteCmdlet() } WriteVerbose($"Requesting endpoints of Microsoft 365 Group with Id {groupId}"); - var endpoints = GraphHelper.GetResultCollectionAsync(Connection, $"/beta/groups/{groupId}/endpoints", AccessToken).GetAwaiter().GetResult(); + var endpoints = GraphHelper.GetResultCollection(this, Connection, $"/beta/groups/{groupId}/endpoints", AccessToken); WriteVerbose($"{endpoints.Count()} endpoint(s) found in total"); var yammerEndpoint = endpoints.Where(e => e.ProviderName.Equals("Microsoft Teams", StringComparison.InvariantCultureIgnoreCase)); diff --git a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupYammerCommunity.cs b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupYammerCommunity.cs index d5eb3b9a4..03fe3e73b 100644 --- a/src/Commands/Microsoft365Groups/GetMicrosoft365GroupYammerCommunity.cs +++ b/src/Commands/Microsoft365Groups/GetMicrosoft365GroupYammerCommunity.cs @@ -22,7 +22,7 @@ protected override void ExecuteCmdlet() if (ParameterSpecified(nameof(Identity))) { WriteVerbose($"Defining Microsoft 365 Group based on {nameof(Identity)} parameter"); - groupId = Identity.GetGroupId(Connection, AccessToken); + groupId = Identity.GetGroupId(this, Connection, AccessToken); } else { @@ -43,7 +43,7 @@ protected override void ExecuteCmdlet() } WriteVerbose($"Requesting endpoints of Microsoft 365 Group with Id {groupId}"); - var endpoints = GraphHelper.GetResultCollectionAsync(Connection, $"/beta/groups/{groupId}/endpoints", AccessToken).GetAwaiter().GetResult(); + var endpoints = GraphHelper.GetResultCollection(this, Connection, $"/beta/groups/{groupId}/endpoints", AccessToken); WriteVerbose($"{endpoints.Count()} endpoint(s) found in total"); var yammerEndpoint = endpoints.Where(e => e.ProviderName.Equals("Yammer", StringComparison.InvariantCultureIgnoreCase)); diff --git a/src/Commands/Microsoft365Groups/NewMicrosoft365Group.cs b/src/Commands/Microsoft365Groups/NewMicrosoft365Group.cs index face3ed1c..9d17c80bb 100644 --- a/src/Commands/Microsoft365Groups/NewMicrosoft365Group.cs +++ b/src/Commands/Microsoft365Groups/NewMicrosoft365Group.cs @@ -101,7 +101,7 @@ protected override void ExecuteCmdlet() if (!Force) { - var candidate = Microsoft365GroupsUtility.GetGroupAsync(Connection, MailNickname, AccessToken, false, false, false, false).GetAwaiter().GetResult(); + var candidate = ClearOwners.GetGroup(this, Connection, MailNickname, AccessToken, false, false, false, false); forceCreation = candidate == null || ShouldContinue($"The Microsoft 365 Group '{MailNickname} already exists. Do you want to create a new one?", Properties.Resources.Confirm); } else @@ -173,14 +173,14 @@ protected override void ExecuteCmdlet() } } - var group = Microsoft365GroupsUtility.CreateAsync(Connection, AccessToken, newGroup, CreateTeam, LogoPath, Owners, Members, HideFromAddressLists, HideFromOutlookClients, Labels).GetAwaiter().GetResult(); + var group = ClearOwners.Create(this, Connection, AccessToken, newGroup, CreateTeam, LogoPath, Owners, Members, HideFromAddressLists, HideFromOutlookClients, Labels); if (ParameterSpecified(nameof(HideFromAddressLists)) || ParameterSpecified(nameof(HideFromOutlookClients))) { - Microsoft365GroupsUtility.SetVisibilityAsync(Connection, AccessToken, group.Id.Value, HideFromAddressLists, HideFromOutlookClients).GetAwaiter().GetResult(); + ClearOwners.SetVisibility(this, Connection, AccessToken, group.Id.Value, HideFromAddressLists, HideFromOutlookClients); } - var updatedGroup = Microsoft365GroupsUtility.GetGroupAsync(Connection, group.Id.Value, AccessToken, true, false, false, true).GetAwaiter().GetResult(); + var updatedGroup = ClearOwners.GetGroup(this, Connection, group.Id.Value, AccessToken, true, false, false, true); WriteObject(updatedGroup); } diff --git a/src/Commands/Microsoft365Groups/NewMicrosoft365GroupSettings.cs b/src/Commands/Microsoft365Groups/NewMicrosoft365GroupSettings.cs index 0fecf5f04..cc20ef35a 100644 --- a/src/Commands/Microsoft365Groups/NewMicrosoft365GroupSettings.cs +++ b/src/Commands/Microsoft365Groups/NewMicrosoft365GroupSettings.cs @@ -30,17 +30,17 @@ protected override void ExecuteCmdlet() { if (Identity != null) { - var groupId = Identity.GetGroupId(Connection, AccessToken); + var groupId = Identity.GetGroupId(this, Connection, AccessToken); var groupSettingObject = GroupSettingsObject(); - var responseValue = Microsoft365GroupsUtility.CreateGroupSetting(Connection, AccessToken, groupId.ToString(), groupSettingObject).GetAwaiter().GetResult(); + var responseValue = ClearOwners.CreateGroupSetting(this, Connection, AccessToken, groupId.ToString(), groupSettingObject).GetAwaiter().GetResult(); WriteObject(responseValue); } else { var groupSettingObject = GroupSettingsObject(); - var responseValue = Microsoft365GroupsUtility.CreateGroupSetting(Connection, AccessToken, groupSettingObject).GetAwaiter().GetResult(); + var responseValue = ClearOwners.CreateGroupSetting(this, Connection, AccessToken, groupSettingObject).GetAwaiter().GetResult(); WriteObject(responseValue); } } diff --git a/src/Commands/Microsoft365Groups/RemoveDeletedMicrosoft365Group.cs b/src/Commands/Microsoft365Groups/RemoveDeletedMicrosoft365Group.cs index 0231bc3f2..b5d3a8cd6 100644 --- a/src/Commands/Microsoft365Groups/RemoveDeletedMicrosoft365Group.cs +++ b/src/Commands/Microsoft365Groups/RemoveDeletedMicrosoft365Group.cs @@ -15,7 +15,7 @@ public class RemoveDeletedMicrosoft365Group : PnPGraphCmdlet protected override void ExecuteCmdlet() { - Microsoft365GroupsUtility.PermanentlyDeleteDeletedGroupAsync(Connection, Identity.GetDeletedGroupId(Connection, AccessToken), AccessToken).GetAwaiter().GetResult(); + ClearOwners.PermanentlyDeleteDeletedGroup(this, Connection, Identity.GetDeletedGroupId(this, Connection, AccessToken), AccessToken); } } } \ No newline at end of file diff --git a/src/Commands/Microsoft365Groups/RemoveMicrosoft365Group.cs b/src/Commands/Microsoft365Groups/RemoveMicrosoft365Group.cs index dc6590a66..00c868ce5 100644 --- a/src/Commands/Microsoft365Groups/RemoveMicrosoft365Group.cs +++ b/src/Commands/Microsoft365Groups/RemoveMicrosoft365Group.cs @@ -15,7 +15,7 @@ public class RemoveMicrosoft365Group : PnPGraphCmdlet protected override void ExecuteCmdlet() { - Microsoft365GroupsUtility.RemoveGroupAsync(Connection, Identity.GetGroupId(Connection, AccessToken), AccessToken).GetAwaiter().GetResult(); + ClearOwners.RemoveGroup(this, Connection, Identity.GetGroupId(this, Connection, AccessToken), AccessToken); } } } \ No newline at end of file diff --git a/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupMember.cs b/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupMember.cs index c1f3f5ffb..b147d905e 100644 --- a/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupMember.cs +++ b/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupMember.cs @@ -18,7 +18,7 @@ public class RemoveMicrosoft365GroupMember : PnPGraphCmdlet protected override void ExecuteCmdlet() { - Microsoft365GroupsUtility.RemoveMembersAsync(Connection, Identity.GetGroupId(Connection, AccessToken), Users, AccessToken).GetAwaiter().GetResult(); + ClearOwners.RemoveMembers(this, Connection, Identity.GetGroupId(this, Connection, AccessToken), Users, AccessToken); } } } \ No newline at end of file diff --git a/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupOwner.cs b/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupOwner.cs index 3e8633ba6..7a3648307 100644 --- a/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupOwner.cs +++ b/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupOwner.cs @@ -18,7 +18,7 @@ public class RemoveMicrosoft365GroupOwner : PnPGraphCmdlet protected override void ExecuteCmdlet() { - Microsoft365GroupsUtility.RemoveOwnersAsync(Connection, Identity.GetGroupId(Connection, AccessToken), Users, AccessToken).GetAwaiter().GetResult(); + ClearOwners.RemoveOwners(this, Connection, Identity.GetGroupId(this, Connection, AccessToken), Users, AccessToken); } } } \ No newline at end of file diff --git a/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupPhoto.cs b/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupPhoto.cs index f60e714ba..80731cb38 100644 --- a/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupPhoto.cs +++ b/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupPhoto.cs @@ -18,10 +18,10 @@ public class RemoveMicrosoft365GroupPicture : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var group = Identity.GetGroup(Connection, AccessToken, false, false, false, false); + var group = Identity.GetGroup(this, Connection, AccessToken, false, false, false, false); if (group != null) { - var response = Microsoft365GroupsUtility.DeletePhotoAsync(Connection, AccessToken, group.Id.Value).GetAwaiter().GetResult(); + var response = ClearOwners.DeletePhoto(this, Connection, AccessToken, group.Id.Value); if (!response.IsSuccessStatusCode) { if (GraphHelper.TryGetGraphException(response, out GraphException ex)) diff --git a/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupSettings.cs b/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupSettings.cs index 731d78a09..160fbd616 100644 --- a/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupSettings.cs +++ b/src/Commands/Microsoft365Groups/RemoveMicrosoft365GroupSettings.cs @@ -20,12 +20,12 @@ protected override void ExecuteCmdlet() { if (Group != null) { - var groupId = Group.GetGroupId(Connection, AccessToken); - Microsoft365GroupsUtility.RemoveGroupSetting(Connection, AccessToken, Identity, groupId.ToString()).GetAwaiter().GetResult(); + var groupId = Group.GetGroupId(this, Connection, AccessToken); + ClearOwners.RemoveGroupSetting(this, Connection, AccessToken, Identity, groupId.ToString()); } else { - Microsoft365GroupsUtility.RemoveGroupSetting(Connection, AccessToken, Identity).GetAwaiter().GetResult(); + ClearOwners.RemoveGroupSetting(this, Connection, AccessToken, Identity); } } } diff --git a/src/Commands/Microsoft365Groups/ResetMicrosoft365GroupExpiration.cs b/src/Commands/Microsoft365Groups/ResetMicrosoft365GroupExpiration.cs index ce52db7dd..8a62a7a29 100644 --- a/src/Commands/Microsoft365Groups/ResetMicrosoft365GroupExpiration.cs +++ b/src/Commands/Microsoft365Groups/ResetMicrosoft365GroupExpiration.cs @@ -15,7 +15,7 @@ public class ResetMicrosoft365GroupExpiration : PnPGraphCmdlet protected override void ExecuteCmdlet() { - Microsoft365GroupsUtility.RenewAsync(Connection, AccessToken, Identity.GetGroupId(Connection, AccessToken)).GetAwaiter().GetResult(); + ClearOwners.Renew(this, Connection, AccessToken, Identity.GetGroupId(this, Connection, AccessToken)); } } } \ No newline at end of file diff --git a/src/Commands/Microsoft365Groups/RestoreDeletedMicrosoft365Group.cs b/src/Commands/Microsoft365Groups/RestoreDeletedMicrosoft365Group.cs index b5fdaf2ec..f96f7d466 100644 --- a/src/Commands/Microsoft365Groups/RestoreDeletedMicrosoft365Group.cs +++ b/src/Commands/Microsoft365Groups/RestoreDeletedMicrosoft365Group.cs @@ -15,7 +15,7 @@ public class RestoreDeletedMicrosoft365Group : PnPGraphCmdlet protected override void ExecuteCmdlet() { - WriteObject(Microsoft365GroupsUtility.RestoreDeletedGroupAsync(Connection, Identity.GetDeletedGroupId(Connection, AccessToken), AccessToken).GetAwaiter().GetResult()); + WriteObject(ClearOwners.RestoreDeletedGroup(this, Connection, Identity.GetDeletedGroupId(this, Connection, AccessToken), AccessToken)); } } } \ No newline at end of file diff --git a/src/Commands/Microsoft365Groups/SetMicrosoft365Group.cs b/src/Commands/Microsoft365Groups/SetMicrosoft365Group.cs index d65a39278..b5ea5be19 100644 --- a/src/Commands/Microsoft365Groups/SetMicrosoft365Group.cs +++ b/src/Commands/Microsoft365Groups/SetMicrosoft365Group.cs @@ -62,7 +62,7 @@ public class SetMicrosoft365Group : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var group = Identity.GetGroup(Connection, AccessToken, false, false, false, false); + var group = Identity.GetGroup(this, Connection, AccessToken, false, false, false, false); if (group != null) { @@ -99,7 +99,7 @@ protected override void ExecuteCmdlet() if (changed) { WriteVerbose("Updating Microsoft 365 Group properties in Microsoft Graph"); - group = Microsoft365GroupsUtility.UpdateAsync(Connection, AccessToken, group).GetAwaiter().GetResult(); + group = ClearOwners.Update(this, Connection, AccessToken, group); } if (ParameterSpecified(nameof(AllowExternalSenders)) && AllowExternalSenders.HasValue) @@ -127,17 +127,17 @@ protected override void ExecuteCmdlet() if (exchangeOnlinePropertiesChanged) { WriteVerbose("Updating Microsoft 365 Group Exchange Online properties through Microsoft Graph"); - group = Microsoft365GroupsUtility.UpdateExchangeOnlineSettingAsync(Connection, group.Id.Value, AccessToken, group).GetAwaiter().GetResult(); + group = ClearOwners.UpdateExchangeOnlineSetting(this, Connection, group.Id.Value, AccessToken, group); } if (ParameterSpecified(nameof(Owners))) { - Microsoft365GroupsUtility.UpdateOwnersAsync(Connection, group.Id.Value, AccessToken, Owners).GetAwaiter().GetResult(); + ClearOwners.UpdateOwners(this, Connection, group.Id.Value, AccessToken, Owners); } if (ParameterSpecified(nameof(Members))) { - Microsoft365GroupsUtility.UpdateMembersAsync(Connection, group.Id.Value, AccessToken, Members).GetAwaiter().GetResult(); + ClearOwners.UpdateMembersAsync(this, Connection, group.Id.Value, AccessToken, Members); } if (ParameterSpecified(nameof(LogoPath))) @@ -146,14 +146,14 @@ protected override void ExecuteCmdlet() { LogoPath = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, LogoPath); } - Microsoft365GroupsUtility.UploadLogoAsync(Connection, AccessToken, group.Id.Value, LogoPath).GetAwaiter().GetResult(); + ClearOwners.UploadLogoAsync(this, Connection, AccessToken, group.Id.Value, LogoPath); } if (ParameterSpecified(nameof(CreateTeam))) { if (!group.ResourceProvisioningOptions.Contains("Team")) { - Microsoft365GroupsUtility.CreateTeamAsync(Connection, AccessToken, group.Id.Value).GetAwaiter().GetResult(); + ClearOwners.CreateTeam(this, Connection, AccessToken, group.Id.Value); } else { @@ -164,7 +164,7 @@ protected override void ExecuteCmdlet() if (ParameterSpecified(nameof(HideFromAddressLists)) || ParameterSpecified(nameof(HideFromOutlookClients))) { // For this scenario a separate call needs to be made - Microsoft365GroupsUtility.SetVisibilityAsync(Connection, AccessToken, group.Id.Value, HideFromAddressLists, HideFromOutlookClients).GetAwaiter().GetResult(); + ClearOwners.SetVisibility(this, Connection, AccessToken, group.Id.Value, HideFromAddressLists, HideFromOutlookClients); } var assignedLabels = new List(); @@ -183,7 +183,7 @@ protected override void ExecuteCmdlet() }); } } - Microsoft365GroupsUtility.SetSensitivityLabelsAsync(Connection, AccessToken, group.Id.Value, assignedLabels).GetAwaiter().GetResult(); + ClearOwners.SetSensitivityLabels(this, Connection, AccessToken, group.Id.Value, assignedLabels); } else { diff --git a/src/Commands/Microsoft365Groups/SetMicrosoft365GroupSettings.cs b/src/Commands/Microsoft365Groups/SetMicrosoft365GroupSettings.cs index 58a51b95a..6b30bae2e 100644 --- a/src/Commands/Microsoft365Groups/SetMicrosoft365GroupSettings.cs +++ b/src/Commands/Microsoft365Groups/SetMicrosoft365GroupSettings.cs @@ -26,15 +26,15 @@ protected override void ExecuteCmdlet() { if (Group != null) { - var groupId = Group.GetGroupId(Connection, AccessToken); + var groupId = Group.GetGroupId(this, Connection, AccessToken); var groupSettingObject = GroupSettingsObject(); - Microsoft365GroupsUtility.UpdateGroupSetting(Connection, AccessToken, Identity, groupId.ToString(), groupSettingObject).GetAwaiter().GetResult(); + ClearOwners.UpdateGroupSetting(this, Connection, AccessToken, Identity, groupId.ToString(), groupSettingObject).GetAwaiter().GetResult(); } else { var groupSettingObject = GroupSettingsObject(); - Microsoft365GroupsUtility.UpdateGroupSetting(Connection, AccessToken, Identity, groupSettingObject).GetAwaiter().GetResult(); + ClearOwners.UpdateGroupSetting(this, Connection, AccessToken, Identity, groupSettingObject).GetAwaiter().GetResult(); } } diff --git a/src/Commands/Model/PriviledgedIdentityManagement/Expiration.cs b/src/Commands/Model/PriviledgedIdentityManagement/Expiration.cs new file mode 100644 index 000000000..d066c5bbb --- /dev/null +++ b/src/Commands/Model/PriviledgedIdentityManagement/Expiration.cs @@ -0,0 +1,18 @@ +namespace PnP.PowerShell.Commands.Model.PriviledgedIdentityManagement +{ + /// + /// Defines an expiration of a scheduled role assignment within Privileged Identity Management + /// + public class Expiration + { + /// + /// The type of expiration, i.e. AfterDuration or AtDateTime + /// + public string Type { get; set; } + + /// + /// The duration of the expiration, e.g. PT4H to indicate 4 hours + /// + public string Duration { get; set; } + } +} diff --git a/src/Commands/Model/PriviledgedIdentityManagement/RoleAssignmentScheduleRequest.cs b/src/Commands/Model/PriviledgedIdentityManagement/RoleAssignmentScheduleRequest.cs new file mode 100644 index 000000000..7abb710b6 --- /dev/null +++ b/src/Commands/Model/PriviledgedIdentityManagement/RoleAssignmentScheduleRequest.cs @@ -0,0 +1,40 @@ +using System; + +namespace PnP.PowerShell.Commands.Model.PriviledgedIdentityManagement +{ + /// + /// Requests enabling a role assignment + /// + public class RoleAssignmentScheduleRequest + { + /// + /// Type of activation to apply + /// + public string Action { get; set; } = "selfActivate"; + + /// + /// Id of the principal to enable the role on + /// + public Guid? PrincipalId { get; set; } + + /// + /// Id of the role definition to enable + /// + public Guid? RoleDefinitionId { get; set; } + + /// + /// The scope at which the role will be applied + /// + public string DirectoryScopeId { get; set; } + + /// + /// Justification for enabling the role assignment + /// + public string Justification { get; set; } + + /// + /// Details on when the role assignment should start and end + /// + public ScheduleInfo ScheduleInfo { get; set; } + } +} diff --git a/src/Commands/Model/PriviledgedIdentityManagement/RoleDefinition.cs b/src/Commands/Model/PriviledgedIdentityManagement/RoleDefinition.cs new file mode 100644 index 000000000..1eb26b98e --- /dev/null +++ b/src/Commands/Model/PriviledgedIdentityManagement/RoleDefinition.cs @@ -0,0 +1,35 @@ +using System; + +namespace PnP.PowerShell.Commands.Model.PriviledgedIdentityManagement +{ + /// + /// A role definition in Entra ID Priviledged Identity Management + /// + public class RoleDefinition + { + /// + /// Id of the role definition + /// + public Guid? Id { get; set; } + + /// + /// Name of the role + /// + public string DisplayName { get; set; } + + /// + /// Description of the role + /// + public string Description { get; set; } + + /// + /// Is the role enabled + /// + public bool? IsEnabled { get; set; } + + /// + /// Is the role built in + /// + public bool? IsBuiltIn { get; set; } + } +} \ No newline at end of file diff --git a/src/Commands/Model/PriviledgedIdentityManagement/RoleEligibilitySchedule.cs b/src/Commands/Model/PriviledgedIdentityManagement/RoleEligibilitySchedule.cs new file mode 100644 index 000000000..805bf84dd --- /dev/null +++ b/src/Commands/Model/PriviledgedIdentityManagement/RoleEligibilitySchedule.cs @@ -0,0 +1,30 @@ +using System; + +namespace PnP.PowerShell.Commands.Model.PriviledgedIdentityManagement +{ + /// + /// An elibible role in Entra ID Priviledged Identity Management + /// + public class RoleEligibilitySchedule + { + /// + /// Id of the eligible role + /// + public Guid? Id { get; set; } + + /// + /// Id of the principal the role can be assigned to + /// + public Guid? PrincipalId { get; set; } + + /// + /// Definition of the role that is eligible + /// + public RoleDefinition RoleDefinition { get; set; } + + /// + /// The scope at which this role will be applied. For example, the role can be applied to a specific directory object such as a user or group, or to the entire directory. + /// + public string DirectoryScopeId { get; set; } + } +} \ No newline at end of file diff --git a/src/Commands/Model/PriviledgedIdentityManagement/ScheduleInfo.cs b/src/Commands/Model/PriviledgedIdentityManagement/ScheduleInfo.cs new file mode 100644 index 000000000..9b0d0f082 --- /dev/null +++ b/src/Commands/Model/PriviledgedIdentityManagement/ScheduleInfo.cs @@ -0,0 +1,20 @@ +using System; + +namespace PnP.PowerShell.Commands.Model.PriviledgedIdentityManagement +{ + /// + /// Information about a schedule used within role assignment requests in Privileged Identity Management + /// + public class ScheduleInfo + { + /// + /// The date and time at which the role activation should become active + /// + public DateTime? StartDateTime { get; set; } + + /// + /// The expiration when the role activation should end + /// + public Expiration Expiration { get; set; } + } +} diff --git a/src/Commands/Model/SPOTenantInternalSetting.cs b/src/Commands/Model/SPOTenantInternalSetting.cs index 1e298c1fe..d2296298e 100644 --- a/src/Commands/Model/SPOTenantInternalSetting.cs +++ b/src/Commands/Model/SPOTenantInternalSetting.cs @@ -46,7 +46,7 @@ public SPOTenantInternalSetting(Tenant tenant, ClientContext clientContext) private void initSPOTenantInternalSetting(ClientContext clientContext) { var httpClient = PnP.Framework.Http.PnPHttpClient.Instance.GetHttpClient(clientContext); - var internalSettingsData = Utilities.REST.RestHelper.GetAsync(httpClient, $"{clientContext.Url}_api/SPOInternalUseOnly.TenantAdminSettings", clientContext.GetAccessToken(), false).GetAwaiter().GetResult(); + var internalSettingsData = Utilities.REST.RestHelper.Get(httpClient, $"{clientContext.Url}_api/SPOInternalUseOnly.TenantAdminSettings", clientContext.GetAccessToken(), false); SitePagesEnabled = internalSettingsData.SitePagesEnabled.Value; DisableSelfServiceSiteCreation = internalSettingsData.DisableSelfServiceSiteCreation.Value; diff --git a/src/Commands/Navigation/AddNavigationNode.cs b/src/Commands/Navigation/AddNavigationNode.cs index 2f76db37d..f91bcafa9 100644 --- a/src/Commands/Navigation/AddNavigationNode.cs +++ b/src/Commands/Navigation/AddNavigationNode.cs @@ -122,7 +122,7 @@ protected override void ExecuteCmdlet() { // Retrieve the menu definition and save it back again. This step is needed to enforce some properties of the menu to be shown, such as the audience targeting. CurrentWeb.EnsureProperties(w => w.Url); - var menuState = Utilities.REST.RestHelper.GetAsync(Connection.HttpClient, $"{CurrentWeb.Url}/_api/navigation/MenuState", ClientContext.GetAccessToken(), false).GetAwaiter().GetResult(); + var menuState = Utilities.REST.RestHelper.Get(Connection.HttpClient, $"{CurrentWeb.Url}/_api/navigation/MenuState", ClientContext.GetAccessToken(), false); var currentItem = menuState?.Nodes?.Select(node => SearchNodeById(node, addedNode.Id)) .FirstOrDefault(result => result != null); @@ -136,7 +136,7 @@ protected override void ExecuteCmdlet() } var payload = JsonSerializer.Serialize(menuState); - Utilities.REST.RestHelper.PostAsync(Connection.HttpClient, $"{CurrentWeb.Url}/_api/navigation/SaveMenuState", ClientContext, @"{ ""menuState"": " + payload + "}", "application/json", "application/json;odata=nometadata").GetAwaiter().GetResult(); + Utilities.REST.RestHelper.Post(Connection.HttpClient, $"{CurrentWeb.Url}/_api/navigation/SaveMenuState", ClientContext, @"{ ""menuState"": " + payload + "}", "application/json", "application/json;odata=nometadata"); } else { diff --git a/src/Commands/Pages/DisablePageScheduling.cs b/src/Commands/Pages/DisablePageScheduling.cs index 8dcb27d39..4407cf0fe 100644 --- a/src/Commands/Pages/DisablePageScheduling.cs +++ b/src/Commands/Pages/DisablePageScheduling.cs @@ -10,7 +10,7 @@ public class DisablePageScheduling : PnPWebCmdlet protected override void ExecuteCmdlet() { var pagesList = PagesUtility.GetModernPagesLibrary(PnPContext.Web); - Utilities.REST.RestHelper.PostAsync(Connection.HttpClient, $"{PnPContext.Web.Url}/_api/sitepages/pagesinlib(guid'{pagesList.Id}')/setscheduling(false)", ClientContext, null, "application/json", "application/json;odata=nometadata").GetAwaiter().GetResult(); + Utilities.REST.RestHelper.Post(Connection.HttpClient, $"{PnPContext.Web.Url}/_api/sitepages/pagesinlib(guid'{pagesList.Id}')/setscheduling(false)", ClientContext, null, "application/json", "application/json;odata=nometadata"); } } } diff --git a/src/Commands/Pages/EnablePageScheduling.cs b/src/Commands/Pages/EnablePageScheduling.cs index 2edb52b38..3280e7490 100644 --- a/src/Commands/Pages/EnablePageScheduling.cs +++ b/src/Commands/Pages/EnablePageScheduling.cs @@ -10,7 +10,7 @@ public class EnablePageScheduling : PnPWebCmdlet protected override void ExecuteCmdlet() { var pagesList = PagesUtility.GetModernPagesLibrary(PnPContext.Web); - Utilities.REST.RestHelper.PostAsync(Connection.HttpClient, $"{PnPContext.Web.Url}/_api/sitepages/pagesinlib(guid'{pagesList.Id}')/setscheduling(true)", ClientContext, null, "application/json", "application/json;odata=nometadata").GetAwaiter().GetResult(); + Utilities.REST.RestHelper.Post(Connection.HttpClient, $"{PnPContext.Web.Url}/_api/sitepages/pagesinlib(guid'{pagesList.Id}')/setscheduling(true)", ClientContext, null, "application/json", "application/json;odata=nometadata"); } } } diff --git a/src/Commands/Pages/GetPageSchedulingEnabled.cs b/src/Commands/Pages/GetPageSchedulingEnabled.cs index 499f307ac..f79dfd222 100644 --- a/src/Commands/Pages/GetPageSchedulingEnabled.cs +++ b/src/Commands/Pages/GetPageSchedulingEnabled.cs @@ -20,7 +20,7 @@ protected override void ExecuteCmdlet() } }; - var results = Utilities.REST.RestHelper.PostAsync(Connection.HttpClient, $"{PnPContext.Web.Url}/_api/web/lists(guid'{pagesList.Id}')/RenderListDataAsStream", ClientContext, payload, false).GetAwaiter().GetResult(); + var results = Utilities.REST.RestHelper.Post(Connection.HttpClient, $"{PnPContext.Web.Url}/_api/web/lists(guid'{pagesList.Id}')/RenderListDataAsStream", ClientContext, payload, false); var frameworkClientInfo = results.GetProperty("SPFrameworkClientInfo"); var pageContextJson = frameworkClientInfo.GetProperty("PageContextJson"); diff --git a/src/Commands/Planner/AddPlannerBucket.cs b/src/Commands/Planner/AddPlannerBucket.cs index 5dd7ea442..d0a879b23 100644 --- a/src/Commands/Planner/AddPlannerBucket.cs +++ b/src/Commands/Planner/AddPlannerBucket.cs @@ -28,14 +28,14 @@ protected override void ExecuteCmdlet() { if (ParameterSetName == ParameterName_BYGROUP) { - var groupId = Group.GetGroupId(Connection, AccessToken); + var groupId = Group.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var planId = Plan.GetIdAsync(Connection, AccessToken, groupId).GetAwaiter().GetResult(); + var planId = Plan.GetId(this, Connection, AccessToken, groupId); if (planId != null) { - WriteObject(PlannerUtility.CreateBucketAsync(Connection, AccessToken, Name, planId).GetAwaiter().GetResult(), true); + WriteObject(PlannerUtility.CreateBucket(this, Connection, AccessToken, Name, planId), true); } else { @@ -49,7 +49,7 @@ protected override void ExecuteCmdlet() } else if (ParameterSetName == ParameterName_BYPLANID) { - WriteObject(PlannerUtility.CreateBucketAsync(Connection, AccessToken, Name, PlanId).GetAwaiter().GetResult(), true); + WriteObject(PlannerUtility.CreateBucket(this, Connection, AccessToken, Name, PlanId), true); } } } diff --git a/src/Commands/Planner/AddPlannerRoster.cs b/src/Commands/Planner/AddPlannerRoster.cs index 24118ee1f..c9291a8de 100644 --- a/src/Commands/Planner/AddPlannerRoster.cs +++ b/src/Commands/Planner/AddPlannerRoster.cs @@ -11,7 +11,7 @@ public class AddPlannerRoster : PnPGraphCmdlet { protected override void ExecuteCmdlet() { - PlannerUtility.CreateRosterAsync(Connection, AccessToken).GetAwaiter().GetResult(); + PlannerUtility.CreateRoster(this, Connection, AccessToken); } } } \ No newline at end of file diff --git a/src/Commands/Planner/AddPlannerRosterMember.cs b/src/Commands/Planner/AddPlannerRosterMember.cs index adb7c8b74..4fcde918c 100644 --- a/src/Commands/Planner/AddPlannerRosterMember.cs +++ b/src/Commands/Planner/AddPlannerRosterMember.cs @@ -18,14 +18,14 @@ public class AddPlannerRosterMember : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var roster = Identity.GetPlannerRosterAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var roster = Identity.GetPlannerRoster(this, Connection, AccessToken); if(roster == null) { throw new PSArgumentException("Provided Planner Roster could not be found", nameof(Identity)); } - PlannerUtility.AddRosterMemberAsync(Connection, AccessToken, roster.Id, User).GetAwaiter().GetResult(); + PlannerUtility.AddRosterMember(this, Connection, AccessToken, roster.Id, User); } } } \ No newline at end of file diff --git a/src/Commands/Planner/AddPlannerTask.cs b/src/Commands/Planner/AddPlannerTask.cs index 18cc32d7e..045180a39 100644 --- a/src/Commands/Planner/AddPlannerTask.cs +++ b/src/Commands/Planner/AddPlannerTask.cs @@ -94,7 +94,7 @@ protected override void ExecuteCmdlet() var chunks = BatchUtility.Chunk(AssignedTo, 20); foreach (var chunk in chunks) { - var userIds = BatchUtility.GetPropertyBatchedAsync(Connection, AccessToken, chunk.ToArray(), "/users/{0}", "id").GetAwaiter().GetResult(); + var userIds = BatchUtility.GetPropertyBatched(this, Connection, AccessToken, chunk.ToArray(), "/users/{0}", "id"); foreach (var userId in userIds) { newTask.Assignments.Add(userId.Value, new TaskAssignment()); @@ -105,32 +105,32 @@ protected override void ExecuteCmdlet() // By Group if (ParameterSetName == ParameterName_BYGROUP) { - var groupId = Group.GetGroupId(Connection, AccessToken); + var groupId = Group.GetGroupId(this, Connection, AccessToken); if (groupId == null) { throw new PSArgumentException("Group not found", nameof(Group)); } - var planId = Plan.GetIdAsync(Connection, AccessToken, groupId).GetAwaiter().GetResult(); + var planId = Plan.GetId(this, Connection, AccessToken, groupId); if (planId == null) { throw new PSArgumentException("Plan not found", nameof(Plan)); } newTask.PlanId = planId; - var bucket = Bucket.GetBucket(Connection, AccessToken, planId); + var bucket = Bucket.GetBucket(this, Connection, AccessToken, planId); if (bucket == null) { throw new PSArgumentException("Bucket not found", nameof(Bucket)); } newTask.BucketId = bucket.Id; - createdTask = PlannerUtility.AddTaskAsync(Connection, AccessToken, newTask).GetAwaiter().GetResult(); + createdTask = PlannerUtility.AddTask(this, Connection, AccessToken, newTask); } // By PlanId else { - var bucket = Bucket.GetBucket(Connection, AccessToken, PlanId); + var bucket = Bucket.GetBucket(this, Connection, AccessToken, PlanId); if (bucket == null) { throw new PSArgumentException("Bucket not found", nameof(Bucket)); @@ -139,13 +139,13 @@ protected override void ExecuteCmdlet() newTask.PlanId = PlanId; newTask.BucketId = bucket.Id; - createdTask = PlannerUtility.AddTaskAsync(Connection, AccessToken, newTask).GetAwaiter().GetResult(); + createdTask = PlannerUtility.AddTask(this, Connection, AccessToken, newTask); } if (ParameterSpecified(nameof(Description))) { - var existingTaskDetails = PlannerUtility.GetTaskDetailsAsync(Connection, AccessToken, createdTask.Id, false).GetAwaiter().GetResult(); - PlannerUtility.UpdateTaskDetailsAsync(Connection, AccessToken, existingTaskDetails, Description).GetAwaiter().GetResult(); + var existingTaskDetails = PlannerUtility.GetTaskDetails(this, Connection, AccessToken, createdTask.Id, false); + PlannerUtility.UpdateTaskDetails(this, Connection, AccessToken, existingTaskDetails, Description); } } } diff --git a/src/Commands/Planner/GetPlannerBucket.cs b/src/Commands/Planner/GetPlannerBucket.cs index e4bcbe386..21e6a2cf5 100644 --- a/src/Commands/Planner/GetPlannerBucket.cs +++ b/src/Commands/Planner/GetPlannerBucket.cs @@ -29,19 +29,19 @@ protected override void ExecuteCmdlet() { if (ParameterSetName == ParameterName_BYGROUP) { - var groupId = Group.GetGroupId(Connection, AccessToken); + var groupId = Group.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var planId = Plan.GetIdAsync(Connection, AccessToken, groupId).GetAwaiter().GetResult(); + var planId = Plan.GetId(this, Connection, AccessToken, groupId); if (planId != null) { if (!ParameterSpecified(nameof(Identity))) { - WriteObject(PlannerUtility.GetBucketsAsync(Connection, AccessToken, planId).GetAwaiter().GetResult(), true); + WriteObject(PlannerUtility.GetBuckets(this, Connection, AccessToken, planId), true); } else { - WriteObject(Identity.GetBucket(Connection, AccessToken, planId)); + WriteObject(Identity.GetBucket(this, Connection, AccessToken, planId)); } } else @@ -56,7 +56,7 @@ protected override void ExecuteCmdlet() } else { - WriteObject(PlannerUtility.GetBucketsAsync(Connection, AccessToken, PlanId).GetAwaiter().GetResult(), true); + WriteObject(PlannerUtility.GetBuckets(this, Connection, AccessToken, PlanId), true); } } } diff --git a/src/Commands/Planner/GetPlannerConfiguration.cs b/src/Commands/Planner/GetPlannerConfiguration.cs index c16ddfa7e..789214967 100644 --- a/src/Commands/Planner/GetPlannerConfiguration.cs +++ b/src/Commands/Planner/GetPlannerConfiguration.cs @@ -11,7 +11,7 @@ public class GetPlannerConfiguration : PnPGraphCmdlet { protected override void ExecuteCmdlet() { - var result = PlannerUtility.GetPlannerConfigAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var result = PlannerUtility.GetPlannerConfig(this, Connection, AccessToken); WriteObject(result); } } diff --git a/src/Commands/Planner/GetPlannerPlan.cs b/src/Commands/Planner/GetPlannerPlan.cs index cedca0801..f0bd172a9 100644 --- a/src/Commands/Planner/GetPlannerPlan.cs +++ b/src/Commands/Planner/GetPlannerPlan.cs @@ -29,16 +29,16 @@ protected override void ExecuteCmdlet() { if (ParameterSetName == ParameterName_BYGROUP) { - var groupId = Group.GetGroupId(Connection, AccessToken); + var groupId = Group.GetGroupId(this, Connection, AccessToken); if (groupId != null) { if (ParameterSpecified(nameof(Identity))) { - WriteObject(Identity.GetPlanAsync(Connection, AccessToken, groupId, ResolveIdentities).GetAwaiter().GetResult()); + WriteObject(Identity.GetPlan(this, Connection, AccessToken, groupId, ResolveIdentities)); } else { - WriteObject(PlannerUtility.GetPlansAsync(Connection, AccessToken, groupId, ResolveIdentities).GetAwaiter().GetResult(), true); + WriteObject(PlannerUtility.GetPlans(this, Connection, AccessToken, groupId, ResolveIdentities), true); } } else @@ -48,7 +48,7 @@ protected override void ExecuteCmdlet() } else { - WriteObject(PlannerUtility.GetPlanAsync(Connection, AccessToken, Id, ResolveIdentities).GetAwaiter().GetResult()); + WriteObject(PlannerUtility.GetPlan(this, Connection, AccessToken, Id, ResolveIdentities)); } } } diff --git a/src/Commands/Planner/GetPlannerRosterMember.cs b/src/Commands/Planner/GetPlannerRosterMember.cs index 19d3741e8..686b5ac36 100644 --- a/src/Commands/Planner/GetPlannerRosterMember.cs +++ b/src/Commands/Planner/GetPlannerRosterMember.cs @@ -15,14 +15,14 @@ public class GetPlannerRosterMember : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var roster = Identity.GetPlannerRosterAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var roster = Identity.GetPlannerRoster(this, Connection, AccessToken); if(roster == null) { throw new PSArgumentException("Provided Planner Roster could not be found", nameof(Identity)); } - PlannerUtility.GetRosterMembersAsync(Connection, AccessToken, roster.Id).GetAwaiter().GetResult(); + PlannerUtility.GetRosterMembers(this, Connection, AccessToken, roster.Id); } } } \ No newline at end of file diff --git a/src/Commands/Planner/GetPlannerRosterPlan.cs b/src/Commands/Planner/GetPlannerRosterPlan.cs index 785975f82..96524edd3 100644 --- a/src/Commands/Planner/GetPlannerRosterPlan.cs +++ b/src/Commands/Planner/GetPlannerRosterPlan.cs @@ -24,16 +24,16 @@ protected override void ExecuteCmdlet() switch (ParameterSetName) { case ParameterSet_BYUSER: - WriteObject(PlannerUtility.GetRosterPlansByUserAsync(Connection, AccessToken, User).GetAwaiter().GetResult(), true); + WriteObject(PlannerUtility.GetRosterPlansByUser(this, Connection, AccessToken, User), true); break; case ParameterSet_BYROSTER: - var plannerRoster = Identity.GetPlannerRosterAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var plannerRoster = Identity.GetPlannerRoster(this, Connection, AccessToken); if (plannerRoster == null) { throw new PSArgumentException($"Planner Roster provided through {nameof(Identity)} could not be found", nameof(Identity)); } - WriteObject(PlannerUtility.GetRosterPlansByRosterAsync(Connection, AccessToken, plannerRoster.Id).GetAwaiter().GetResult(), true); + WriteObject(PlannerUtility.GetRosterPlansByRoster(this, Connection, AccessToken, plannerRoster.Id), true); break; } } diff --git a/src/Commands/Planner/GetPlannerTask.cs b/src/Commands/Planner/GetPlannerTask.cs index ee82bbc71..5c0ff4e57 100644 --- a/src/Commands/Planner/GetPlannerTask.cs +++ b/src/Commands/Planner/GetPlannerTask.cs @@ -40,13 +40,13 @@ protected override void ExecuteCmdlet() { if (ParameterSetName == ParameterSetName_BYGROUP) { - var groupId = Group.GetGroupId(Connection, AccessToken); + var groupId = Group.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var planId = Plan.GetIdAsync(Connection, AccessToken, groupId).GetAwaiter().GetResult(); + var planId = Plan.GetId(this, Connection, AccessToken, groupId); if (planId != null) { - WriteObject(PlannerUtility.GetTasksAsync(Connection, AccessToken, planId, ResolveUserDisplayNames).GetAwaiter().GetResult(), true); + WriteObject(PlannerUtility.GetTasks(this, Connection, AccessToken, planId, ResolveUserDisplayNames), true); } else { @@ -60,15 +60,15 @@ protected override void ExecuteCmdlet() } else if (ParameterSetName == ParameterSetName_BYPLANID) { - WriteObject(PlannerUtility.GetTasksAsync(Connection, AccessToken, PlanId, ResolveUserDisplayNames).GetAwaiter().GetResult(), true); + WriteObject(PlannerUtility.GetTasks(this, Connection, AccessToken, PlanId, ResolveUserDisplayNames), true); } else if (ParameterSetName == ParameterSetName_BYBUCKET) { - WriteObject(PlannerUtility.GetBucketTasksAsync(Connection, AccessToken, Bucket.GetId(), ResolveUserDisplayNames).GetAwaiter().GetResult(), true); + WriteObject(PlannerUtility.GetBucketTasks(this, Connection, AccessToken, Bucket.GetId(), ResolveUserDisplayNames), true); } else if (ParameterSetName == ParameterSetName_BYTASKID) { - WriteObject(PlannerUtility.GetTaskAsync(Connection, AccessToken, TaskId, ResolveUserDisplayNames, IncludeDetails).GetAwaiter().GetResult()); + WriteObject(PlannerUtility.GetTask(this, Connection, AccessToken, TaskId, ResolveUserDisplayNames, IncludeDetails)); } } } diff --git a/src/Commands/Planner/GetPlannerUserPolicy.cs b/src/Commands/Planner/GetPlannerUserPolicy.cs index 078305557..b753c429b 100644 --- a/src/Commands/Planner/GetPlannerUserPolicy.cs +++ b/src/Commands/Planner/GetPlannerUserPolicy.cs @@ -13,7 +13,7 @@ public class GetPlannerUserPolicy : PnPGraphCmdlet public string Identity; protected override void ExecuteCmdlet() { - var result = PlannerUtility.GetPlannerUserPolicyAsync(Connection, AccessToken, Identity).GetAwaiter().GetResult(); + var result = PlannerUtility.GetPlannerUserPolicy(this, Connection, AccessToken, Identity); WriteObject(result); } } diff --git a/src/Commands/Planner/NewPlannerPlan.cs b/src/Commands/Planner/NewPlannerPlan.cs index 959fd3021..22a67ba65 100644 --- a/src/Commands/Planner/NewPlannerPlan.cs +++ b/src/Commands/Planner/NewPlannerPlan.cs @@ -17,10 +17,10 @@ public class NewPlannerPlan : PnPGraphCmdlet public string Title; protected override void ExecuteCmdlet() { - var groupId = Group.GetGroupId(Connection, AccessToken); + var groupId = Group.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - WriteObject(PlannerUtility.CreatePlanAsync(Connection, AccessToken, groupId, Title).GetAwaiter().GetResult()); + WriteObject(PlannerUtility.CreatePlan(this, Connection, AccessToken, groupId, Title)); } else { diff --git a/src/Commands/Planner/RemovePlannerBucket.cs b/src/Commands/Planner/RemovePlannerBucket.cs index 6c5ab9bf6..7220384b9 100644 --- a/src/Commands/Planner/RemovePlannerBucket.cs +++ b/src/Commands/Planner/RemovePlannerBucket.cs @@ -28,19 +28,19 @@ protected override void ExecuteCmdlet() { if (ParameterSetName == ParameterName_BYNAME) { - var groupId = Group.GetGroupId(Connection, AccessToken); + var groupId = Group.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var planId = Plan.GetIdAsync(Connection, AccessToken, groupId).GetAwaiter().GetResult(); + var planId = Plan.GetId(this, Connection, AccessToken, groupId); if (planId != null) { - var bucket = Identity.GetBucket(Connection, AccessToken, planId); + var bucket = Identity.GetBucket(this, Connection, AccessToken, planId); if (bucket != null) { if (ShouldProcess($"Remove bucket '{bucket.Name}'")) { - PlannerUtility.RemoveBucketAsync(Connection, AccessToken, bucket.Id).GetAwaiter().GetResult(); + PlannerUtility.RemoveBucket(this, Connection, AccessToken, bucket.Id); } } else @@ -60,12 +60,12 @@ protected override void ExecuteCmdlet() } else if (ParameterSetName == ParameterName_BYBUCKETID) { - var bucket = Identity.GetBucket(Connection, AccessToken, BucketId); + var bucket = Identity.GetBucket(this, Connection, AccessToken, BucketId); if (bucket != null) { if (ShouldProcess($"Remove bucket '{bucket.Name}'")) { - PlannerUtility.RemoveBucketAsync(Connection, AccessToken, BucketId).GetAwaiter().GetResult(); + PlannerUtility.RemoveBucket(this, Connection, AccessToken, BucketId); } } else diff --git a/src/Commands/Planner/RemovePlannerPlan.cs b/src/Commands/Planner/RemovePlannerPlan.cs index b12e1fc62..b7711e400 100644 --- a/src/Commands/Planner/RemovePlannerPlan.cs +++ b/src/Commands/Planner/RemovePlannerPlan.cs @@ -19,15 +19,15 @@ public class RemovePlannerPlan : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Group.GetGroupId(Connection, AccessToken); + var groupId = Group.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var planId = Identity.GetIdAsync(Connection, AccessToken, groupId).GetAwaiter().GetResult(); + var planId = Identity.GetId(this, Connection, AccessToken, groupId); if (!string.IsNullOrEmpty(planId)) { if (ShouldProcess($"Delete plan with id {planId}")) { - PlannerUtility.DeletePlanAsync(Connection, AccessToken, planId).GetAwaiter().GetResult(); + PlannerUtility.DeletePlan(this, Connection, AccessToken, planId); } } else diff --git a/src/Commands/Planner/RemovePlannerRoster.cs b/src/Commands/Planner/RemovePlannerRoster.cs index 45cf1d816..08b955d99 100644 --- a/src/Commands/Planner/RemovePlannerRoster.cs +++ b/src/Commands/Planner/RemovePlannerRoster.cs @@ -15,14 +15,14 @@ public class RemovePlannerRoster : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var roster = Identity.GetPlannerRosterAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var roster = Identity.GetPlannerRoster(this, Connection, AccessToken); if(roster == null) { throw new PSArgumentException("Provided Planner Roster could not be found", nameof(Identity)); } - PlannerUtility.DeleteRosterAsync(Connection, AccessToken, roster.Id).GetAwaiter().GetResult(); + PlannerUtility.DeleteRoster(this, Connection, AccessToken, roster.Id); } } } \ No newline at end of file diff --git a/src/Commands/Planner/RemovePlannerRosterMember.cs b/src/Commands/Planner/RemovePlannerRosterMember.cs index 35c5fa6e6..3e6140ca1 100644 --- a/src/Commands/Planner/RemovePlannerRosterMember.cs +++ b/src/Commands/Planner/RemovePlannerRosterMember.cs @@ -18,14 +18,14 @@ public class RemovePlannerRosterMember : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var roster = Identity.GetPlannerRosterAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var roster = Identity.GetPlannerRoster(this, Connection, AccessToken); if(roster == null) { throw new PSArgumentException("Provided Planner Roster could not be found", nameof(Identity)); } - PlannerUtility.RemoveRosterMemberAsync(Connection, AccessToken, roster.Id, User).GetAwaiter().GetResult(); + PlannerUtility.RemoveRosterMember(this, Connection, AccessToken, roster.Id, User); } } } \ No newline at end of file diff --git a/src/Commands/Planner/RemovePlannerTask.cs b/src/Commands/Planner/RemovePlannerTask.cs index c3216161b..1825176e9 100644 --- a/src/Commands/Planner/RemovePlannerTask.cs +++ b/src/Commands/Planner/RemovePlannerTask.cs @@ -15,7 +15,7 @@ public class RemovePlannerTask : PnPGraphCmdlet protected override void ExecuteCmdlet() { - PlannerUtility.DeleteTaskAsync(Connection, AccessToken, Task.Id).GetAwaiter().GetResult(); + PlannerUtility.DeleteTask(this, Connection, AccessToken, Task.Id); } } } \ No newline at end of file diff --git a/src/Commands/Planner/SetPlannerBucket.cs b/src/Commands/Planner/SetPlannerBucket.cs index 7c6a35a9a..1e3e0d22e 100644 --- a/src/Commands/Planner/SetPlannerBucket.cs +++ b/src/Commands/Planner/SetPlannerBucket.cs @@ -33,17 +33,17 @@ protected override void ExecuteCmdlet() { if (ParameterSetName == ParameterName_BYGROUP) { - var groupId = Group.GetGroupId(Connection, AccessToken); + var groupId = Group.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var planId = Plan.GetIdAsync(Connection, AccessToken, groupId).GetAwaiter().GetResult(); + var planId = Plan.GetId(this, Connection, AccessToken, groupId); if (planId != null) { - var bucket = Bucket.GetBucket(Connection, AccessToken, planId); + var bucket = Bucket.GetBucket(this, Connection, AccessToken, planId); if (bucket != null) { - WriteObject(PlannerUtility.UpdateBucketAsync(Connection, AccessToken, Name, bucket.Id).GetAwaiter().GetResult()); + WriteObject(PlannerUtility.UpdateBucket(this, Connection, AccessToken, Name, bucket.Id)); } else { @@ -62,10 +62,10 @@ protected override void ExecuteCmdlet() } else { - var bucket = Bucket.GetBucket(Connection, AccessToken, PlanId); + var bucket = Bucket.GetBucket(this, Connection, AccessToken, PlanId); if (bucket != null) { - WriteObject(PlannerUtility.UpdateBucketAsync(Connection, AccessToken, Name, bucket.Id).GetAwaiter().GetResult()); + WriteObject(PlannerUtility.UpdateBucket(this, Connection, AccessToken, Name, bucket.Id)); } else { diff --git a/src/Commands/Planner/SetPlannerConfiguration.cs b/src/Commands/Planner/SetPlannerConfiguration.cs index 9c36e2b56..1c36f49c7 100644 --- a/src/Commands/Planner/SetPlannerConfiguration.cs +++ b/src/Commands/Planner/SetPlannerConfiguration.cs @@ -29,7 +29,7 @@ public class SetPlannerConfiguration : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var result = PlannerUtility.SetPlannerConfigAsync(Connection, AccessToken, IsPlannerAllowed, AllowCalendarSharing, AllowTenantMoveWithDataLoss, AllowTenantMoveWithDataMigration, AllowRosterCreation, AllowPlannerMobilePushNotifications).GetAwaiter().GetResult(); + var result = PlannerUtility.SetPlannerConfig(this, Connection, AccessToken, IsPlannerAllowed, AllowCalendarSharing, AllowTenantMoveWithDataLoss, AllowTenantMoveWithDataMigration, AllowRosterCreation, AllowPlannerMobilePushNotifications); WriteObject(result); } } diff --git a/src/Commands/Planner/SetPlannerPlan.cs b/src/Commands/Planner/SetPlannerPlan.cs index bf8c69efc..bd477687d 100644 --- a/src/Commands/Planner/SetPlannerPlan.cs +++ b/src/Commands/Planner/SetPlannerPlan.cs @@ -29,13 +29,13 @@ protected override void ExecuteCmdlet() { if (ParameterSetName == ParameterName_BYGROUP) { - var groupId = Group.GetGroupId(Connection, AccessToken); + var groupId = Group.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var plan = Plan.GetPlanAsync(Connection, AccessToken, groupId, false).GetAwaiter().GetResult(); + var plan = Plan.GetPlan(this, Connection, AccessToken, groupId, false); if (plan != null) { - WriteObject(PlannerUtility.UpdatePlanAsync(Connection, AccessToken, plan, Title).GetAwaiter().GetResult()); + WriteObject(PlannerUtility.UpdatePlan(this, Connection, AccessToken, plan, Title)); } else { @@ -49,10 +49,10 @@ protected override void ExecuteCmdlet() } else { - var plan = PlannerUtility.GetPlanAsync(Connection, AccessToken, PlanId, false).GetAwaiter().GetResult(); + var plan = PlannerUtility.GetPlan(this, Connection, AccessToken, PlanId, false); if (plan != null) { - WriteObject(PlannerUtility.UpdatePlanAsync(Connection, AccessToken, plan, Title).GetAwaiter().GetResult()); + WriteObject(PlannerUtility.UpdatePlan(this, Connection, AccessToken, plan, Title)); } else { diff --git a/src/Commands/Planner/SetPlannerTask.cs b/src/Commands/Planner/SetPlannerTask.cs index e83fa65d2..8834186b9 100644 --- a/src/Commands/Planner/SetPlannerTask.cs +++ b/src/Commands/Planner/SetPlannerTask.cs @@ -43,7 +43,7 @@ public class SetPlannerTask : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var existingTask = PlannerUtility.GetTaskAsync(Connection, AccessToken, TaskId, false, false).GetAwaiter().GetResult(); + var existingTask = PlannerUtility.GetTask(this, Connection, AccessToken, TaskId, false, false); if (existingTask != null) { var plannerTask = new PlannerTask(); @@ -53,7 +53,7 @@ protected override void ExecuteCmdlet() } if (ParameterSpecified(nameof(Bucket))) { - var bucket = Bucket.GetBucket(Connection, AccessToken, existingTask.PlanId); + var bucket = Bucket.GetBucket(this, Connection, AccessToken, existingTask.PlanId); if (bucket != null) { plannerTask.BucketId = bucket.Id; @@ -90,7 +90,7 @@ protected override void ExecuteCmdlet() var chunks = BatchUtility.Chunk(AssignedTo, 20); foreach (var chunk in chunks) { - var userIds = BatchUtility.GetPropertyBatchedAsync(Connection, AccessToken, chunk.ToArray(), "/users/{0}", "id").GetAwaiter().GetResult(); + var userIds = BatchUtility.GetPropertyBatched(this, Connection, AccessToken, chunk.ToArray(), "/users/{0}", "id"); foreach (var userId in userIds) { plannerTask.Assignments.Add(userId.Value, new TaskAssignment()); @@ -106,12 +106,12 @@ protected override void ExecuteCmdlet() } - PlannerUtility.UpdateTaskAsync(Connection, AccessToken, existingTask, plannerTask).GetAwaiter().GetResult(); + PlannerUtility.UpdateTask(this, Connection, AccessToken, existingTask, plannerTask); if (ParameterSpecified(nameof(Description))) { - var existingTaskDetails = PlannerUtility.GetTaskDetailsAsync(Connection, AccessToken, TaskId, false).GetAwaiter().GetResult(); - PlannerUtility.UpdateTaskDetailsAsync(Connection, AccessToken, existingTaskDetails, Description).GetAwaiter().GetResult(); + var existingTaskDetails = PlannerUtility.GetTaskDetails(this, Connection, AccessToken, TaskId, false); + PlannerUtility.UpdateTaskDetails(this, Connection, AccessToken, existingTaskDetails, Description); } } else diff --git a/src/Commands/Planner/SetPlannerUserPolicy.cs b/src/Commands/Planner/SetPlannerUserPolicy.cs index fb2062bab..61717caf8 100644 --- a/src/Commands/Planner/SetPlannerUserPolicy.cs +++ b/src/Commands/Planner/SetPlannerUserPolicy.cs @@ -17,7 +17,7 @@ public class SetPlannerUserPolicy : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var result = PlannerUtility.SetPlannerUserPolicyAsync(Connection, AccessToken, Identity, BlockDeleteTasksNotCreatedBySelf).GetAwaiter().GetResult(); + var result = PlannerUtility.SetPlannerUserPolicy(this, Connection, AccessToken, Identity, BlockDeleteTasksNotCreatedBySelf); WriteObject(result); } } diff --git a/src/Commands/PowerPlatform/Environment/GetPowerPlatformCustomConnector.cs b/src/Commands/PowerPlatform/Environment/GetPowerPlatformCustomConnector.cs index 0f079ea80..e52c282ee 100644 --- a/src/Commands/PowerPlatform/Environment/GetPowerPlatformCustomConnector.cs +++ b/src/Commands/PowerPlatform/Environment/GetPowerPlatformCustomConnector.cs @@ -35,7 +35,7 @@ protected override void ExecuteCmdlet() } else { - var environments = GraphHelper.GetResultCollectionAsync(Connection, baseUrl + "/providers/Microsoft.ProcessSimple/environments?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + var environments = GraphHelper.GetResultCollection(this, Connection, baseUrl + "/providers/Microsoft.ProcessSimple/environments?api-version=2016-11-01", AccessToken); environmentName = environments.FirstOrDefault(e => e.Properties.IsDefault.HasValue && e.Properties.IsDefault == true)?.Name; if (string.IsNullOrEmpty(environmentName)) @@ -52,14 +52,14 @@ protected override void ExecuteCmdlet() WriteVerbose($"Retrieving specific Custom Connector with the provided name '{appName}' within the environment '{environmentName}'"); - var result = GraphHelper.GetAsync(Connection, $"{powerAppsUrl}/providers/Microsoft.PowerApps{(AsAdmin ? "/scopes/admin/environments/" + environmentName : "")}/apis/{appName}?api-version=2016-11-01&$filter=environment eq '{environmentName}' and isCustomApi eq 'True'", AccessToken).GetAwaiter().GetResult(); + var result = GraphHelper.Get(this, Connection, $"{powerAppsUrl}/providers/Microsoft.PowerApps{(AsAdmin ? "/scopes/admin/environments/" + environmentName : "")}/apis/{appName}?api-version=2016-11-01&$filter=environment eq '{environmentName}' and isCustomApi eq 'True'", AccessToken); WriteObject(result, false); } else { WriteVerbose($"Retrieving all Connectors within environment '{environmentName}'"); - var connectors = GraphHelper.GetResultCollectionAsync(Connection, $"{powerAppsUrl}/providers/Microsoft.PowerApps/apis?api-version=2016-11-01&$filter=environment eq '{environmentName}' and isCustomApi eq 'True'", AccessToken).GetAwaiter().GetResult(); + var connectors = GraphHelper.GetResultCollection(this, Connection, $"{powerAppsUrl}/providers/Microsoft.PowerApps/apis?api-version=2016-11-01&$filter=environment eq '{environmentName}' and isCustomApi eq 'True'", AccessToken); WriteObject(connectors, true); } } diff --git a/src/Commands/PowerPlatform/Environment/GetPowerPlatformEnvironment.cs b/src/Commands/PowerPlatform/Environment/GetPowerPlatformEnvironment.cs index 0bdb71a88..be501c4f3 100644 --- a/src/Commands/PowerPlatform/Environment/GetPowerPlatformEnvironment.cs +++ b/src/Commands/PowerPlatform/Environment/GetPowerPlatformEnvironment.cs @@ -23,7 +23,7 @@ public class GetPowerPlatformEnvironment : PnPAzureManagementApiCmdlet protected override void ExecuteCmdlet() { string baseUrl = PowerPlatformUtility.GetPowerAutomateEndpoint(Connection.AzureEnvironment); - var environments = GraphHelper.GetResultCollectionAsync(Connection, baseUrl + "/providers/Microsoft.ProcessSimple/environments?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + var environments = GraphHelper.GetResultCollection(this, Connection, baseUrl + "/providers/Microsoft.ProcessSimple/environments?api-version=2016-11-01", AccessToken); if(ParameterSpecified(nameof(IsDefault)) && IsDefault.ToBool()) { diff --git a/src/Commands/PowerPlatform/Environment/GetPowerPlatformSolution.cs b/src/Commands/PowerPlatform/Environment/GetPowerPlatformSolution.cs index 4bf9e7a98..73b0cf2db 100644 --- a/src/Commands/PowerPlatform/Environment/GetPowerPlatformSolution.cs +++ b/src/Commands/PowerPlatform/Environment/GetPowerPlatformSolution.cs @@ -23,7 +23,7 @@ protected override void ExecuteCmdlet() string environmentName = null; string dynamicsScopeUrl = null; string baseUrl = PowerPlatformUtility.GetPowerAutomateEndpoint(Connection.AzureEnvironment); - var environments = GraphHelper.GetResultCollectionAsync(Connection, $"{baseUrl}/providers/Microsoft.ProcessSimple/environments?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + var environments = GraphHelper.GetResultCollection(this, Connection, $"{baseUrl}/providers/Microsoft.ProcessSimple/environments?api-version=2016-11-01", AccessToken); if (ParameterSpecified(nameof(Environment))) { environmentName = Environment.GetName().ToLower(); @@ -51,14 +51,14 @@ protected override void ExecuteCmdlet() WriteVerbose($"Retrieving specific solution with the provided name '{solutionName}' within the environment '{environmentName}'"); var requestUrl = dynamicsScopeUrl + "/api/data/v9.0/solutions?$filter=isvisible eq true and friendlyname eq '" + solutionName + "'&$expand=publisherid&api-version=9.1"; - var solution = GraphHelper.GetResultCollectionAsync(Connection, requestUrl, accessTokenForGettingSolutions).GetAwaiter().GetResult(); + var solution = GraphHelper.GetResultCollection(this, Connection, requestUrl, accessTokenForGettingSolutions); WriteObject(solution, false); } else { WriteVerbose($"Retrieving all Solutions within environment '{environmentName}'"); var requestUrl = dynamicsScopeUrl + "/api/data/v9.0/solutions?$filter=isvisible eq true&$expand=publisherid($select=friendlyname)&api-version=9.1"; - var solutions = GraphHelper.GetResultCollectionAsync(Connection, requestUrl, accessTokenForGettingSolutions).GetAwaiter().GetResult(); + var solutions = GraphHelper.GetResultCollection(this, Connection, requestUrl, accessTokenForGettingSolutions); WriteObject(solutions, true); } } diff --git a/src/Commands/PowerPlatform/PowerApps/ExportPowerApp.cs b/src/Commands/PowerPlatform/PowerApps/ExportPowerApp.cs index 54e5e0746..d1a4b38a7 100644 --- a/src/Commands/PowerPlatform/PowerApps/ExportPowerApp.cs +++ b/src/Commands/PowerPlatform/PowerApps/ExportPowerApp.cs @@ -69,7 +69,7 @@ protected override void ExecuteCmdlet() var environmentName = Environment.GetName(); var appName = Identity.GetName(); - var wrapper = PowerAppsUtility.GetWrapper(Connection.HttpClient, environmentName, AccessToken, appName, Connection.AzureEnvironment).GetAwaiter().GetResult(); + var wrapper = PowerAppsUtility.GetWrapper(Connection.HttpClient, environmentName, AccessToken, appName, Connection.AzureEnvironment); if (wrapper.Status == Model.PowerPlatform.PowerApp.Enums.PowerAppExportStatus.Succeeded) { diff --git a/src/Commands/PowerPlatform/PowerApps/GetPowerApp.cs b/src/Commands/PowerPlatform/PowerApps/GetPowerApp.cs index 5ea7b5f2f..83985bfcc 100644 --- a/src/Commands/PowerPlatform/PowerApps/GetPowerApp.cs +++ b/src/Commands/PowerPlatform/PowerApps/GetPowerApp.cs @@ -34,7 +34,7 @@ protected override void ExecuteCmdlet() else { string baseUrl = PowerPlatformUtility.GetPowerAutomateEndpoint(Connection.AzureEnvironment); - var environments = GraphHelper.GetResultCollectionAsync(Connection, baseUrl + "/providers/Microsoft.ProcessSimple/environments?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + var environments = GraphHelper.GetResultCollection(this, Connection, baseUrl + "/providers/Microsoft.ProcessSimple/environments?api-version=2016-11-01", AccessToken); environmentName = environments.FirstOrDefault(e => e.Properties.IsDefault.HasValue && e.Properties.IsDefault == true)?.Name; if(string.IsNullOrEmpty(environmentName)) @@ -51,7 +51,7 @@ protected override void ExecuteCmdlet() WriteVerbose($"Retrieving specific PowerApp with the provided name '{appName}' within the environment '{environmentName}'"); - var result = GraphHelper.GetAsync(Connection, $"{powerAppsUrl}/providers/Microsoft.PowerApps{(AsAdmin ? "/scopes/admin/environments/" + environmentName : "")}/apps/{appName}?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + var result = GraphHelper.Get(this, Connection, $"{powerAppsUrl}/providers/Microsoft.PowerApps{(AsAdmin ? "/scopes/admin/environments/" + environmentName : "")}/apps/{appName}?api-version=2016-11-01", AccessToken); WriteObject(result, false); } @@ -59,7 +59,7 @@ protected override void ExecuteCmdlet() { WriteVerbose($"Retrieving all PowerApps within environment '{environmentName}'"); - var apps = GraphHelper.GetResultCollectionAsync(Connection, $"{powerAppsUrl}/providers/Microsoft.PowerApps/apps?api-version=2016-11-01&$filter=environment eq '{environmentName}'", AccessToken).GetAwaiter().GetResult(); + var apps = GraphHelper.GetResultCollection(this, Connection, $"{powerAppsUrl}/providers/Microsoft.PowerApps/apps?api-version=2016-11-01&$filter=environment eq '{environmentName}'", AccessToken); WriteObject(apps, true); } } diff --git a/src/Commands/PowerPlatform/PowerAutomate/AddFlowOwner.cs b/src/Commands/PowerPlatform/PowerAutomate/AddFlowOwner.cs index 000fc2b9d..648d9b382 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/AddFlowOwner.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/AddFlowOwner.cs @@ -83,7 +83,7 @@ protected override void ExecuteCmdlet() WriteVerbose($"Assigning user {Role} permissions to flow {flowName} in environment {environmentName}"); string baseUrl = PowerPlatformUtility.GetPowerAutomateEndpoint(Connection.AzureEnvironment); - RestHelper.PostAsync(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}/modifyPermissions?api-version=2016-11-01", AccessToken, payload).GetAwaiter().GetResult(); + RestHelper.Post(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}/modifyPermissions?api-version=2016-11-01", AccessToken, payload); } } } diff --git a/src/Commands/PowerPlatform/PowerAutomate/DisableFlow.cs b/src/Commands/PowerPlatform/PowerAutomate/DisableFlow.cs index 45b1ea769..aec590f24 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/DisableFlow.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/DisableFlow.cs @@ -23,7 +23,7 @@ protected override void ExecuteCmdlet() var environmentName = Environment.GetName(); var flowName = Identity.GetName(); string baseUrl = PowerPlatformUtility.GetPowerAutomateEndpoint(Connection.AzureEnvironment); - RestHelper.PostAsync(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}/stop?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + RestHelper.Post(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}/stop?api-version=2016-11-01", AccessToken); } } } \ No newline at end of file diff --git a/src/Commands/PowerPlatform/PowerAutomate/EnableFlow.cs b/src/Commands/PowerPlatform/PowerAutomate/EnableFlow.cs index 02ede1d49..da8cf2300 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/EnableFlow.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/EnableFlow.cs @@ -23,7 +23,7 @@ protected override void ExecuteCmdlet() var environmentName = Environment.GetName(); var flowName = Identity.GetName(); string baseUrl = PowerPlatformUtility.GetPowerAutomateEndpoint(Connection.AzureEnvironment); - RestHelper.PostAsync(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}/start?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + RestHelper.Post(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}/start?api-version=2016-11-01", AccessToken); } } } \ No newline at end of file diff --git a/src/Commands/PowerPlatform/PowerAutomate/ExportFlow.cs b/src/Commands/PowerPlatform/PowerAutomate/ExportFlow.cs index bf8085f3c..73a08cdfd 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/ExportFlow.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/ExportFlow.cs @@ -78,7 +78,7 @@ protected override void ExecuteCmdlet() } }; string baseUrl = PowerPlatformUtility.GetBapEndpoint(Connection.AzureEnvironment); - var wrapper = RestHelper.PostAsync(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.BusinessAppPlatform/environments/{environmentName}/listPackageResources?api-version=2016-11-01", AccessToken, payload: postData).GetAwaiter().GetResult(); + var wrapper = RestHelper.Post(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.BusinessAppPlatform/environments/{environmentName}/listPackageResources?api-version=2016-11-01", AccessToken, payload: postData); if (wrapper.Status == Model.PowerPlatform.PowerAutomate.Enums.FlowExportStatus.Succeeded) { @@ -111,7 +111,7 @@ protected override void ExecuteCmdlet() resources = wrapper.Resources }; - var resultElement = RestHelper.PostAsync(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.BusinessAppPlatform/environments/{environmentName}/exportPackage?api-version=2016-11-01", AccessToken, payload: exportPostData).GetAwaiter().GetResult(); + var resultElement = RestHelper.Post(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.BusinessAppPlatform/environments/{environmentName}/exportPackage?api-version=2016-11-01", AccessToken, payload: exportPostData); if (resultElement.TryGetProperty("status", out JsonElement statusElement)) { if (statusElement.GetString() == "Succeeded") @@ -164,7 +164,7 @@ protected override void ExecuteCmdlet() else { string baseUrl = PowerPlatformUtility.GetPowerAutomateEndpoint(Connection.AzureEnvironment); - var json = RestHelper.PostAsync(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple/environments/{environmentName}/flows/{flowName}/exportToARMTemplate?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + var json = RestHelper.Post(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple/environments/{environmentName}/flows/{flowName}/exportToARMTemplate?api-version=2016-11-01", AccessToken); WriteObject(json); } } diff --git a/src/Commands/PowerPlatform/PowerAutomate/GetFlow.cs b/src/Commands/PowerPlatform/PowerAutomate/GetFlow.cs index d6e664f20..c389173de 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/GetFlow.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/GetFlow.cs @@ -41,7 +41,7 @@ protected override void ExecuteCmdlet() } else { - var environments = GraphHelper.GetResultCollectionAsync(Connection, baseUrl + "/providers/Microsoft.ProcessSimple/environments?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + var environments = GraphHelper.GetResultCollection(this, Connection, baseUrl + "/providers/Microsoft.ProcessSimple/environments?api-version=2016-11-01", AccessToken); environmentName = environments.FirstOrDefault(e => e.Properties.IsDefault.HasValue && e.Properties.IsDefault == true)?.Name; if(string.IsNullOrEmpty(environmentName)) @@ -58,7 +58,7 @@ protected override void ExecuteCmdlet() WriteVerbose($"Retrieving specific Power Automate Flow with the provided name '{flowName}' within the environment '{environmentName}'"); - var result = GraphHelper.GetAsync(Connection, baseUrl + $"/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + var result = GraphHelper.Get(this, Connection, baseUrl + $"/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}?api-version=2016-11-01", AccessToken); WriteObject(result, false); } else @@ -81,7 +81,7 @@ protected override void ExecuteCmdlet() WriteVerbose($"Retrieving all Power Automate Flows within environment '{environmentName}'{(filter != null ? $" with filter '{filter}'" : "")}"); - var flows = GraphHelper.GetResultCollectionAsync(Connection, baseUrl + $"/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows?api-version=2016-11-01{(filter != null ? $"&$filter={filter}" : "")}", AccessToken).GetAwaiter().GetResult(); + var flows = GraphHelper.GetResultCollection(this, Connection, baseUrl + $"/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows?api-version=2016-11-01{(filter != null ? $"&$filter={filter}" : "")}", AccessToken); WriteObject(flows, true); } diff --git a/src/Commands/PowerPlatform/PowerAutomate/GetFlowOwner.cs b/src/Commands/PowerPlatform/PowerAutomate/GetFlowOwner.cs index 49052bb67..ab68e25d4 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/GetFlowOwner.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/GetFlowOwner.cs @@ -34,7 +34,7 @@ protected override void ExecuteCmdlet() } string baseUrl = PowerPlatformUtility.GetPowerAutomateEndpoint(Connection.AzureEnvironment); - var flowOwners = GraphHelper.GetResultCollectionAsync(Connection, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}/permissions?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + var flowOwners = GraphHelper.GetResultCollection(this, Connection, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}/permissions?api-version=2016-11-01", AccessToken); WriteObject(flowOwners, true); } } diff --git a/src/Commands/PowerPlatform/PowerAutomate/GetFlowRun.cs b/src/Commands/PowerPlatform/PowerAutomate/GetFlowRun.cs index d499a9682..98a5caab1 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/GetFlowRun.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/GetFlowRun.cs @@ -37,12 +37,12 @@ protected override void ExecuteCmdlet() if (ParameterSpecified(nameof(Identity))) { var flowRunName = Identity.GetName(); - var flowRun = GraphHelper.GetAsync(Connection, $"{baseUrl}/providers/Microsoft.ProcessSimple/environments/{environmentName}/flows/{flowName}/runs/{flowRunName}?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + var flowRun = GraphHelper.Get(this, Connection, $"{baseUrl}/providers/Microsoft.ProcessSimple/environments/{environmentName}/flows/{flowName}/runs/{flowRunName}?api-version=2016-11-01", AccessToken); WriteObject(flowRun, false); } else { - var flowRuns = GraphHelper.GetResultCollectionAsync(Connection, $"{baseUrl}/providers/Microsoft.ProcessSimple/environments/{environmentName}/flows/{flowName}/runs?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + var flowRuns = GraphHelper.GetResultCollection(this, Connection, $"{baseUrl}/providers/Microsoft.ProcessSimple/environments/{environmentName}/flows/{flowName}/runs?api-version=2016-11-01", AccessToken); WriteObject(flowRuns, true); } } diff --git a/src/Commands/PowerPlatform/PowerAutomate/RemoveFlow.cs b/src/Commands/PowerPlatform/PowerAutomate/RemoveFlow.cs index f54bb3530..c02b4e9ac 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/RemoveFlow.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/RemoveFlow.cs @@ -40,10 +40,10 @@ protected override void ExecuteCmdlet() { // Had to add this because DELETE doesn't throw error if invalid Flow Id or Name is provided WriteVerbose($"Retrieving Flow with name {flowName} in environment ${environmentName}"); - var result = GraphHelper.GetAsync(Connection, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + var result = GraphHelper.Get(this, Connection, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}?api-version=2016-11-01", AccessToken); if (result != null) { - RestHelper.DeleteAsync(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + RestHelper.Delete(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}?api-version=2016-11-01", AccessToken); WriteVerbose($"Flow with name {flowName} deleted"); } } @@ -54,7 +54,7 @@ protected override void ExecuteCmdlet() } else { - RestHelper.DeleteAsync(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + RestHelper.Delete(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}?api-version=2016-11-01", AccessToken); WriteVerbose($"Flow with name {flowName} deleted"); } } diff --git a/src/Commands/PowerPlatform/PowerAutomate/RemoveFlowOwner.cs b/src/Commands/PowerPlatform/PowerAutomate/RemoveFlowOwner.cs index 19f445573..cfec6f584 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/RemoveFlowOwner.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/RemoveFlowOwner.cs @@ -77,7 +77,7 @@ protected override void ExecuteCmdlet() { string baseUrl = PowerPlatformUtility.GetPowerAutomateEndpoint(Connection.AzureEnvironment); WriteVerbose($"Removing user {user.Id.Value} permissions from flow {flowName} in environment {environmentName}"); - RestHelper.PostAsync(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}/modifyPermissions?api-version=2016-11-01", AccessToken, payload).GetAwaiter().GetResult(); + RestHelper.Post(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple{(AsAdmin ? "/scopes/admin" : "")}/environments/{environmentName}/flows/{flowName}/modifyPermissions?api-version=2016-11-01", AccessToken, payload); } } } diff --git a/src/Commands/PowerPlatform/PowerAutomate/RestartFlowRun.cs b/src/Commands/PowerPlatform/PowerAutomate/RestartFlowRun.cs index 7bd2ce1b9..c4ea783de 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/RestartFlowRun.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/RestartFlowRun.cs @@ -48,8 +48,8 @@ protected override void ExecuteCmdlet() if (!Force && !ShouldContinue($"Restart flow run with name '{flowRunName}'?", Resources.Confirm)) return; - var triggers = GraphHelper.GetResultCollectionAsync(Connection, $"{baseUrl}/providers/Microsoft.ProcessSimple/environments/{environmentName}/flows/{flowName}/triggers?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); - RestHelper.PostAsync(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple/environments/{environmentName}/flows/{flowName}/triggers/{triggers.First().Name}/histories/{flowRunName}/resubmit?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + var triggers = GraphHelper.GetResultCollection(this, Connection, $"{baseUrl}/providers/Microsoft.ProcessSimple/environments/{environmentName}/flows/{flowName}/triggers?api-version=2016-11-01", AccessToken); + RestHelper.Post(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple/environments/{environmentName}/flows/{flowName}/triggers/{triggers.First().Name}/histories/{flowRunName}/resubmit?api-version=2016-11-01", AccessToken); } } } diff --git a/src/Commands/PowerPlatform/PowerAutomate/StopFlowRun.cs b/src/Commands/PowerPlatform/PowerAutomate/StopFlowRun.cs index d1a457650..b8c9afef5 100644 --- a/src/Commands/PowerPlatform/PowerAutomate/StopFlowRun.cs +++ b/src/Commands/PowerPlatform/PowerAutomate/StopFlowRun.cs @@ -45,7 +45,7 @@ protected override void ExecuteCmdlet() if (Force || ShouldContinue($"Stop flow run with name '{flowRunName}'?", Resources.Confirm)) { string baseUrl = PowerPlatformUtility.GetPowerAutomateEndpoint(Connection.AzureEnvironment); - RestHelper.PostAsync(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple/environments/{environmentName}/flows/{flowName}/runs/{flowRunName}/cancel?api-version=2016-11-01", AccessToken).GetAwaiter().GetResult(); + RestHelper.Post(Connection.HttpClient, $"{baseUrl}/providers/Microsoft.ProcessSimple/environments/{environmentName}/flows/{flowName}/runs/{flowRunName}/cancel?api-version=2016-11-01", AccessToken); } } } diff --git a/src/Commands/Principals/ExportUserInfo.cs b/src/Commands/Principals/ExportUserInfo.cs index 3889d67b0..e9441e860 100644 --- a/src/Commands/Principals/ExportUserInfo.cs +++ b/src/Commands/Principals/ExportUserInfo.cs @@ -33,7 +33,7 @@ protected override void ExecuteCmdlet() AdminContext.Load(site); AdminContext.ExecuteQueryRetry(); var normalizedUserName = UrlUtilities.UrlEncode($"i:0#.f|membership|{LoginName}"); - var results = RestHelper.GetAsync>(this.HttpClient, $"{hostUrl}/_api/sp.userprofiles.peoplemanager/GetSPUserInformation(accountName=@a,siteId=@b)?@a='{normalizedUserName}'&@b='{site.Id}'", AdminContext, false).GetAwaiter().GetResult(); + var results = RestHelper.Get>(this.HttpClient, $"{hostUrl}/_api/sp.userprofiles.peoplemanager/GetSPUserInformation(accountName=@a,siteId=@b)?@a='{normalizedUserName}'&@b='{site.Id}'", AdminContext, false); var record = new PSObject(); foreach (var item in results.Items) { diff --git a/src/Commands/Principals/RemoveUserInfo.cs b/src/Commands/Principals/RemoveUserInfo.cs index 8bfbee16e..adea1bc1e 100644 --- a/src/Commands/Principals/RemoveUserInfo.cs +++ b/src/Commands/Principals/RemoveUserInfo.cs @@ -39,11 +39,11 @@ protected override void ExecuteCmdlet() RestResultCollection results = null; if (!ParameterSpecified(nameof(RedactName))) { - results = RestHelper.PostAsync>(HttpClient, $"{hostUrl}/_api/sp.userprofiles.peoplemanager/RemoveSPUserInformation(accountName=@a,siteId=@b)?@a='{normalizedUserName}'&@b='{site.Id}'", this.AccessToken, false).GetAwaiter().GetResult(); + results = RestHelper.Post>(HttpClient, $"{hostUrl}/_api/sp.userprofiles.peoplemanager/RemoveSPUserInformation(accountName=@a,siteId=@b)?@a='{normalizedUserName}'&@b='{site.Id}'", this.AccessToken, false); } else { - results = RestHelper.PostAsync>(HttpClient, $"{hostUrl}/_api/sp.userprofiles.peoplemanager/RemoveSPUserInformation(accountName=@a,siteId=@b,redactName=@c)?@a='{normalizedUserName}'&@b='{site.Id}'&@c='{RedactName}'", this.AccessToken, false).GetAwaiter().GetResult(); + results = RestHelper.Post>(HttpClient, $"{hostUrl}/_api/sp.userprofiles.peoplemanager/RemoveSPUserInformation(accountName=@a,siteId=@b,redactName=@c)?@a='{normalizedUserName}'&@b='{site.Id}'&@c='{RedactName}'", this.AccessToken, false); } var record = new PSObject(); foreach (var item in results.Items) diff --git a/src/Commands/PriviledgedIdentityManagement/EnablePriviledgedIdentityManagement.cs b/src/Commands/PriviledgedIdentityManagement/EnablePriviledgedIdentityManagement.cs new file mode 100644 index 000000000..56548a425 --- /dev/null +++ b/src/Commands/PriviledgedIdentityManagement/EnablePriviledgedIdentityManagement.cs @@ -0,0 +1,115 @@ +using System; +using System.Management.Automation; +using PnP.PowerShell.Commands.Attributes; +using PnP.PowerShell.Commands.Base; +using PnP.PowerShell.Commands.Base.PipeBinds; +using PnP.PowerShell.Commands.Model.PriviledgedIdentityManagement; +using PnP.PowerShell.Commands.Utilities; +using PnP.PowerShell.Commands.Base; +using PnP.PowerShell.Commands.Enums; + +namespace PnP.PowerShell.Commands.Principals +{ + [Cmdlet(VerbsLifecycle.Enable, "PnPPriviledgedIdentityManagement")] + [OutputType(typeof(bool))] + [RequiredMinimalApiPermissions("RoleAssignmentSchedule.ReadWrite.Directory")] + public class EnablePriviledgedIdentityManagement : PnPGraphCmdlet + { + private const string ParameterName_BYELIGIBLEROLEASSIGNMENT = "By Eligible Role Assignment"; + private const string ParameterName_BYROLENAMEANDPRINCIPAL = "By Role Name And Principal"; + private const string ParameterName_BYROLENAMEANDUSER = "By Role Name And User"; + + [Parameter(Mandatory = true, ValueFromPipeline = true, Position = 0, ParameterSetName = ParameterName_BYELIGIBLEROLEASSIGNMENT)] + public PriviledgedIdentityManagementRoleEligibilitySchedulePipeBind EligibleAssignment; + + [Parameter(Mandatory = true, ValueFromPipeline = true, Position = 0, ParameterSetName = ParameterName_BYROLENAMEANDPRINCIPAL)] + [Parameter(Mandatory = true, ValueFromPipeline = true, Position = 0, ParameterSetName = ParameterName_BYROLENAMEANDUSER)] + public PriviledgedIdentityManagementRolePipeBind Role; + + [Parameter(Mandatory = true, ParameterSetName = ParameterName_BYROLENAMEANDUSER)] + public AzureADUserPipeBind User; + + [Parameter(Mandatory = false, ParameterSetName = ParameterName_BYROLENAMEANDPRINCIPAL)] + public Guid? PrincipalId; + + [Parameter(Mandatory = false)] + public string Justification; + + [Parameter(Mandatory = false)] + public DateTime? StartAt; + + [Parameter(Mandatory = false)] + public short? ExpireInHours; + + protected override void ExecuteCmdlet() + { + RoleEligibilitySchedule roleEligibilitySchedule = null; + + switch (ParameterSetName) + { + case ParameterName_BYELIGIBLEROLEASSIGNMENT: + roleEligibilitySchedule = EligibleAssignment.GetInstance(this, Connection, AccessToken); + break; + + case ParameterName_BYROLENAMEANDUSER: + // Check if we have a principal to elevate + var user = User.GetUser(AccessToken); + if (user == null || !user.Id.HasValue) + { + throw new PSArgumentException("Provided user cannot be found", nameof(User)); + } + + // Check for the role to which elevation needs to take place + var role = Role.GetInstance(this, Connection, AccessToken); + + if (role == null) + { + throw new PSArgumentException("Provided role cannot be found", nameof(Role)); + } + + // Look for an eligible role assignment for the user and role + roleEligibilitySchedule = PriviledgedIdentityManagamentUtility.GetRoleEligibilityScheduleByPrincipalIdAndRoleName(this, user.Id.Value, role, Connection, AccessToken); + break; + + case ParameterName_BYROLENAMEANDPRINCIPAL: + // Check if we have a principal to elevate + if (!PrincipalId.HasValue) + { + // A principal was not provided, check the type of access token + if (TokenHandler.RetrieveTokenType(AccessToken) == IdType.Delegate) + { + // Access token is a delegate, we're going to use the currently connected user to elevate + WriteVerbose("Currently connected user will be used to elevate the role assignment"); + PrincipalId = TokenHandler.RetrieveTokenUser(AccessToken); + } + else + { + // Access token is an app only token, we don't know who to elevate, so cancel the operation + throw new PSArgumentException($"{nameof(PrincipalId)} is required when using Application permissions", nameof(PrincipalId)); + } + } + + // Check for the role to which elevation needs to take place + var role2 = Role.GetInstance(this, Connection, AccessToken); + + if(role2 == null) + { + throw new PSArgumentException("Provided role cannot be found", nameof(Role)); + } + + // Look for an eligible role assignment for the principal and role + roleEligibilitySchedule = PriviledgedIdentityManagamentUtility.GetRoleEligibilityScheduleByPrincipalIdAndRoleName(this, PrincipalId.Value, role2, Connection, AccessToken); + break; + } + + if (roleEligibilitySchedule == null) + { + throw new PSInvalidOperationException("No eligible role assignment found"); + } + + WriteVerbose($"Creating role assignment schedule request"); + var response = PriviledgedIdentityManagamentUtility.CreateRoleAssignmentScheduleRequest(this, roleEligibilitySchedule, Connection, AccessToken, Justification, StartAt, ExpireInHours); + WriteObject(response.IsSuccessStatusCode); + } + } +} diff --git a/src/Commands/PriviledgedIdentityManagement/GetPriviledgedIdentityManagementEligibleAssignment.cs b/src/Commands/PriviledgedIdentityManagement/GetPriviledgedIdentityManagementEligibleAssignment.cs new file mode 100644 index 000000000..541499281 --- /dev/null +++ b/src/Commands/PriviledgedIdentityManagement/GetPriviledgedIdentityManagementEligibleAssignment.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Management.Automation; +using PnP.PowerShell.Commands.Attributes; +using PnP.PowerShell.Commands.Base; +using PnP.PowerShell.Commands.Base.PipeBinds; +using PnP.PowerShell.Commands.Model.PriviledgedIdentityManagement; +using PnP.PowerShell.Commands.Utilities; + +namespace PnP.PowerShell.Commands.Principals +{ + [Cmdlet(VerbsCommon.Get, "PnPPriviledgedIdentityManagementEligibleAssignment")] + [OutputType(typeof(List))] + [OutputType(typeof(RoleEligibilitySchedule))] + [RequiredMinimalApiPermissions("RoleAssignmentSchedule.Read.Directory")] + public class GetPriviledgedIdentityManagementEligibleAssignment : PnPGraphCmdlet + { + /// + /// Specific eligible role to retrieve + /// + [Parameter(Mandatory = false, ValueFromPipeline = true, Position = 0)] + public PriviledgedIdentityManagementRoleEligibilitySchedulePipeBind Identity { get; set; } + + protected override void ExecuteCmdlet() + { + if (ParameterSpecified(nameof(Identity))) + { + WriteVerbose("Retrieving specific eligible role assignment"); + var role = Identity.GetInstance(this, Connection, AccessToken); + WriteObject(role, false); + } + else + { + WriteVerbose("Retrieving all eligible role assignments"); + var roles = PriviledgedIdentityManagamentUtility.GetRoleEligibilitySchedules(this, Connection, AccessToken); + WriteObject(roles, true); + } + } + } +} diff --git a/src/Commands/PriviledgedIdentityManagement/GetPriviledgedIdentityManagementRole.cs b/src/Commands/PriviledgedIdentityManagement/GetPriviledgedIdentityManagementRole.cs new file mode 100644 index 000000000..11de20559 --- /dev/null +++ b/src/Commands/PriviledgedIdentityManagement/GetPriviledgedIdentityManagementRole.cs @@ -0,0 +1,39 @@ +using System.Collections.Generic; +using System.Management.Automation; +using PnP.PowerShell.Commands.Attributes; +using PnP.PowerShell.Commands.Base; +using PnP.PowerShell.Commands.Base.PipeBinds; +using PnP.PowerShell.Commands.Model.PriviledgedIdentityManagement; +using PnP.PowerShell.Commands.Utilities; + +namespace PnP.PowerShell.Commands.Principals +{ + [Cmdlet(VerbsCommon.Get, "PnPPriviledgedIdentityManagementRole")] + [OutputType(typeof(List))] + [OutputType(typeof(RoleDefinition))] + [RequiredMinimalApiPermissions("RoleManagement.Read.Directory")] + public class GetPriviledgedIdentityManagementRole : PnPGraphCmdlet + { + /// + /// Specific role to retrieve + /// + [Parameter(Mandatory = false, ValueFromPipeline = true, Position = 0)] + public PriviledgedIdentityManagementRolePipeBind Identity { get; set; } + + protected override void ExecuteCmdlet() + { + if (ParameterSpecified(nameof(Identity))) + { + WriteVerbose("Retrieving specific role"); + var role = Identity.GetInstance(this, Connection, AccessToken); + WriteObject(role, false); + } + else + { + WriteVerbose("Retrieving all roles"); + var roles = PriviledgedIdentityManagamentUtility.GetRoleDefinitions(this, Connection, AccessToken); + WriteObject(roles, true); + } + } + } +} diff --git a/src/Commands/Purview/GetAvailableSensitivityLabel.cs b/src/Commands/Purview/GetAvailableSensitivityLabel.cs index bd171bf87..87cf8bd1d 100644 --- a/src/Commands/Purview/GetAvailableSensitivityLabel.cs +++ b/src/Commands/Purview/GetAvailableSensitivityLabel.cs @@ -49,12 +49,12 @@ protected override void ExecuteCmdlet() { url += $"/{Identity}"; - var labels = GraphHelper.GetAsync(Connection, url, AccessToken).GetAwaiter().GetResult(); + var labels = GraphHelper.Get(this, Connection, url, AccessToken); WriteObject(labels, false); } else { - var labels = GraphHelper.GetResultCollectionAsync(Connection, url, AccessToken).GetAwaiter().GetResult(); + var labels = GraphHelper.GetResultCollection(this, Connection, url, AccessToken); WriteObject(labels, true); } } diff --git a/src/Commands/Purview/GetTenantRetentionLabel.cs b/src/Commands/Purview/GetTenantRetentionLabel.cs index 1efc898af..016dcd915 100644 --- a/src/Commands/Purview/GetTenantRetentionLabel.cs +++ b/src/Commands/Purview/GetTenantRetentionLabel.cs @@ -26,12 +26,12 @@ protected override void ExecuteCmdlet() { url += $"/{Identity}"; - var labels = GraphHelper.GetAsync(Connection, url, AccessToken).GetAwaiter().GetResult(); + var labels = GraphHelper.Get(this, Connection, url, AccessToken); WriteObject(labels, false); } else { - var labels = GraphHelper.GetResultCollectionAsync(Connection, url, AccessToken).GetAwaiter().GetResult(); + var labels = GraphHelper.GetResultCollection(this, Connection, url, AccessToken); WriteObject(labels, true); } } diff --git a/src/Commands/Purview/RemoveSiteSensitivityLabel.cs b/src/Commands/Purview/RemoveSiteSensitivityLabel.cs index 964c684c8..0f0bc359d 100644 --- a/src/Commands/Purview/RemoveSiteSensitivityLabel.cs +++ b/src/Commands/Purview/RemoveSiteSensitivityLabel.cs @@ -29,7 +29,7 @@ protected override void ExecuteCmdlet() WriteVerbose($"Trying to remove the Microsoft Purview sensitivity label from the Microsoft 365 Group with Id {ClientContext.Site.GroupId} behind the current site {Connection.Url}"); var stringContent = new StringContent(JsonSerializer.Serialize(new { assignedLabels = new [] { new { labelId = "" }}})); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - GraphHelper.PatchAsync(Connection, GraphAccessToken, stringContent, $"beta/groups/{ClientContext.Site.GroupId}").GetAwaiter().GetResult();; + GraphHelper.Patch(this, Connection, GraphAccessToken, stringContent, $"beta/groups/{ClientContext.Site.GroupId}"); } else { diff --git a/src/Commands/Purview/SetSiteSensitivityLabel.cs b/src/Commands/Purview/SetSiteSensitivityLabel.cs index e799f47b6..8aa899d24 100644 --- a/src/Commands/Purview/SetSiteSensitivityLabel.cs +++ b/src/Commands/Purview/SetSiteSensitivityLabel.cs @@ -23,7 +23,7 @@ protected override void ExecuteCmdlet() // Look up the sensitivity label Guid with the provided name WriteVerbose($"Passed in label '{Identity}' is a name, going to try to lookup its Id"); - var label = GraphHelper.GetResultCollectionAsync(Connection, $"/beta/{(Connection.ConnectionMethod == Model.ConnectionMethod.AzureADAppOnly ? "" : "me/")}informationProtection/policy/labels?$filter=name eq '{Identity}'", GraphAccessToken).GetAwaiter().GetResult(); + var label = GraphHelper.GetResultCollection(this, Connection, $"/beta/{(Connection.ConnectionMethod == Model.ConnectionMethod.AzureADAppOnly ? "" : "me/")}informationProtection/policy/labels?$filter=name eq '{Identity}'", GraphAccessToken); if(label == null || label.Count() == 0) { throw new PSArgumentException($"No Microsoft Purview sensitivity label with the provided name '{Identity}' could be found", nameof(Identity)); @@ -55,7 +55,7 @@ protected override void ExecuteCmdlet() WriteVerbose($"Trying to set the Microsoft 365 Group with Id {ClientContext.Site.GroupId} behind the current site {Connection.Url} to Microsoft Purview sensitivity label with Id {sensitivityLabelId}"); var stringContent = new StringContent(JsonSerializer.Serialize(new { assignedLabels = new [] { new { labelId = sensitivityLabelId }}})); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - GraphHelper.PatchAsync(Connection, GraphAccessToken, stringContent, $"beta/groups/{ClientContext.Site.GroupId}").GetAwaiter().GetResult();; + GraphHelper.Patch(this, Connection, GraphAccessToken, stringContent, $"beta/groups/{ClientContext.Site.GroupId}"); } else { diff --git a/src/Commands/Search/SetSearchExternalItem.cs b/src/Commands/Search/SetSearchExternalItem.cs index 7a1a8f734..4f4b6ec7b 100644 --- a/src/Commands/Search/SetSearchExternalItem.cs +++ b/src/Commands/Search/SetSearchExternalItem.cs @@ -108,7 +108,7 @@ protected override void ExecuteCmdlet() var graphApiUrl = $"v1.0/external/connections/{ConnectionId}/items/{ItemId}"; WriteVerbose($"Calling Graph API at {graphApiUrl}"); - var results = Utilities.REST.GraphHelper.PutAsync(Connection, graphApiUrl, AccessToken, jsonContent).GetAwaiter().GetResult(); + var results = Utilities.REST.GraphHelper.Put(this, Connection, graphApiUrl, AccessToken, jsonContent); WriteVerbose($"Graph API responded with HTTP {results.StatusCode} {results.ReasonPhrase}"); @@ -148,7 +148,7 @@ protected override void ExecuteCmdlet() foreach (var group in groups) { - var userAclId = group.GroupId ?? group.GetGroup(Connection, AccessToken)?.Id; + var userAclId = group.GroupId ?? group.GetGroup(this, Connection, AccessToken)?.Id; acls.Add(new Model.Graph.MicrosoftSearch.ExternalItemAcl { diff --git a/src/Commands/ServiceHealth/GetMessageCenterAnnouncement.cs b/src/Commands/ServiceHealth/GetMessageCenterAnnouncement.cs index ae541ce7c..3ed8be76e 100644 --- a/src/Commands/ServiceHealth/GetMessageCenterAnnouncement.cs +++ b/src/Commands/ServiceHealth/GetMessageCenterAnnouncement.cs @@ -16,11 +16,11 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Identity))) { - WriteObject(ServiceHealthUtility.GetServiceUpdateMessageByIdAsync(Identity, Connection, AccessToken).GetAwaiter().GetResult(), false); + WriteObject(ServiceHealthUtility.GetServiceUpdateMessageById(this, Identity, Connection, AccessToken), false); } else { - WriteObject(ServiceHealthUtility.GetServiceUpdateMessagesAsync(Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.GetServiceUpdateMessages(this, Connection, AccessToken), true); } } } diff --git a/src/Commands/ServiceHealth/GetServiceCurrentHealth.cs b/src/Commands/ServiceHealth/GetServiceCurrentHealth.cs index 360bbbf4e..56d74adc4 100644 --- a/src/Commands/ServiceHealth/GetServiceCurrentHealth.cs +++ b/src/Commands/ServiceHealth/GetServiceCurrentHealth.cs @@ -16,11 +16,11 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Identity))) { - WriteObject(ServiceHealthUtility.GetServiceCurrentHealthByIdAsync(Identity, Connection, AccessToken).GetAwaiter().GetResult(), false); + WriteObject(ServiceHealthUtility.GetServiceCurrentHealthById(this, Identity, Connection, AccessToken), false); } else { - WriteObject(ServiceHealthUtility.GetServiceCurrentHealthAsync(Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.GetServiceCurrentHealth(this, Connection, AccessToken), true); } } } diff --git a/src/Commands/ServiceHealth/GetServiceHealthIssue.cs b/src/Commands/ServiceHealth/GetServiceHealthIssue.cs index d1042b6ca..919eb7299 100644 --- a/src/Commands/ServiceHealth/GetServiceHealthIssue.cs +++ b/src/Commands/ServiceHealth/GetServiceHealthIssue.cs @@ -16,11 +16,11 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Identity))) { - WriteObject(ServiceHealthUtility.GetServiceHealthIssueByIdAsync(Identity, Connection, AccessToken).GetAwaiter().GetResult(), false); + WriteObject(ServiceHealthUtility.GetServiceHealthIssueById(this, Identity, Connection, AccessToken), false); } else { - WriteObject(ServiceHealthUtility.GetServiceHealthIssuesAsync(Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.GetServiceHealthIssues(this, Connection, AccessToken), true); } } } diff --git a/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsArchived.cs b/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsArchived.cs index 1faa54163..79b0b107c 100644 --- a/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsArchived.cs +++ b/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsArchived.cs @@ -17,18 +17,18 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Identity))) { - WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsArchivedByIdAsync(Identity, Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsArchivedById(this, Identity, Connection, AccessToken), true); } else { // Retrieve all message center announcements - var messageCenterAnnouncements = ServiceHealthUtility.GetServiceUpdateMessagesAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var messageCenterAnnouncements = ServiceHealthUtility.GetServiceUpdateMessages(this, Connection, AccessToken); // Create an array of the Ids of all message center announcements var messageCenterAnnouncementIds = messageCenterAnnouncements.Select(item => item.Id).ToArray(); // Mark all message center announcements as archived - WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsArchivedByIdAsync(messageCenterAnnouncementIds, Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsArchivedById(this, messageCenterAnnouncementIds, Connection, AccessToken), true); } } } diff --git a/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsFavorite.cs b/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsFavorite.cs index 54e71d32e..13e87a89f 100644 --- a/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsFavorite.cs +++ b/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsFavorite.cs @@ -17,18 +17,18 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Identity))) { - WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsFavoriteByIdAsync(Identity, Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsFavoriteById(this, Identity, Connection, AccessToken), true); } else { // Retrieve all message center announcements - var messageCenterAnnouncements = ServiceHealthUtility.GetServiceUpdateMessagesAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var messageCenterAnnouncements = ServiceHealthUtility.GetServiceUpdateMessages(this, Connection, AccessToken); // Create an array of the Ids of all message center announcements var messageCenterAnnouncementIds = messageCenterAnnouncements.Select(item => item.Id).ToArray(); // Mark all message center announcements as favorite - WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsFavoriteByIdAsync(messageCenterAnnouncementIds, Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsFavoriteById(this, messageCenterAnnouncementIds, Connection, AccessToken), true); } } } diff --git a/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsNotArchived.cs b/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsNotArchived.cs index 74c21bd15..c1a96bd9a 100644 --- a/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsNotArchived.cs +++ b/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsNotArchived.cs @@ -17,18 +17,18 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Identity))) { - WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsUnarchivedByIdAsync(Identity, Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsUnarchivedById(this, Identity, Connection, AccessToken), true); } else { // Retrieve all message center announcements - var messageCenterAnnouncements = ServiceHealthUtility.GetServiceUpdateMessagesAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var messageCenterAnnouncements = ServiceHealthUtility.GetServiceUpdateMessages(this, Connection, AccessToken); // Create an array of the Ids of all message center announcements var messageCenterAnnouncementIds = messageCenterAnnouncements.Select(item => item.Id).ToArray(); // Mark all message center announcements as not archived - WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsUnarchivedByIdAsync(messageCenterAnnouncementIds, Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsUnarchivedById(this, messageCenterAnnouncementIds, Connection, AccessToken), true); } } } diff --git a/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsNotFavorite.cs b/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsNotFavorite.cs index 144f6440e..24798f9df 100644 --- a/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsNotFavorite.cs +++ b/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsNotFavorite.cs @@ -16,18 +16,18 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Identity))) { - WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsNotfavoriteByIdAsync(Identity, Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsNotfavoriteById(this, Identity, Connection, AccessToken), true); } else { // Retrieve all message center announcements - var messageCenterAnnouncements = ServiceHealthUtility.GetServiceUpdateMessagesAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var messageCenterAnnouncements = ServiceHealthUtility.GetServiceUpdateMessages(this, Connection, AccessToken); // Create an array of the Ids of all message center announcements var messageCenterAnnouncementIds = messageCenterAnnouncements.Select(item => item.Id).ToArray(); // Mark all message center announcements as not favorites - WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsNotfavoriteByIdAsync(messageCenterAnnouncementIds, Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsNotfavoriteById(this, messageCenterAnnouncementIds, Connection, AccessToken), true); } } } diff --git a/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsRead.cs b/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsRead.cs index 1831ffebf..e2266619c 100644 --- a/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsRead.cs +++ b/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsRead.cs @@ -17,18 +17,18 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Identity))) { - WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsReadByIdAsync(Identity, Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsReadById(this, Identity, Connection, AccessToken), true); } else { // Retrieve all message center announcements - var messageCenterAnnouncements = ServiceHealthUtility.GetServiceUpdateMessagesAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var messageCenterAnnouncements = ServiceHealthUtility.GetServiceUpdateMessages(this, Connection, AccessToken); // Create an array of the Ids of all message center announcements var messageCenterAnnouncementIds = messageCenterAnnouncements.Select(item => item.Id).ToArray(); // Mark all message center announcements as read - WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsReadByIdAsync(messageCenterAnnouncementIds, Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsReadById(this, messageCenterAnnouncementIds, Connection, AccessToken), true); } } } diff --git a/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsUnread.cs b/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsUnread.cs index b412b0d19..6f2efd109 100644 --- a/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsUnread.cs +++ b/src/Commands/ServiceHealth/SetMessageCenterAnnouncementAsUnread.cs @@ -17,18 +17,18 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Identity))) { - WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsUnreadByIdAsync(Identity, Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsUnreadById(this, Identity, Connection, AccessToken), true); } else { // Retrieve all message center announcements - var messageCenterAnnouncements = ServiceHealthUtility.GetServiceUpdateMessagesAsync(Connection, AccessToken).GetAwaiter().GetResult(); + var messageCenterAnnouncements = ServiceHealthUtility.GetServiceUpdateMessages(this, Connection, AccessToken); // Create an array of the Ids of all message center announcements var messageCenterAnnouncementIds = messageCenterAnnouncements.Select(item => item.Id).ToArray(); // Mark all message center announcements as unread - WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsUnreadByIdAsync(messageCenterAnnouncementIds, Connection, AccessToken).GetAwaiter().GetResult(), true); + WriteObject(ServiceHealthUtility.SetServiceUpdateMessageAsUnreadById(this, messageCenterAnnouncementIds, Connection, AccessToken), true); } } } diff --git a/src/Commands/Site/AddTeamsTeam.cs b/src/Commands/Site/AddTeamsTeam.cs index b48ec7b0a..a4eee8dea 100644 --- a/src/Commands/Site/AddTeamsTeam.cs +++ b/src/Commands/Site/AddTeamsTeam.cs @@ -28,14 +28,13 @@ protected override void ExecuteCmdlet() try { var groupId = ClientContext.Site.EnsureProperty(s => s.GroupId); - Microsoft365GroupsUtility.CreateTeamAsync(Connection, AccessToken, groupId).GetAwaiter().GetResult(); + ClearOwners.CreateTeam(this, Connection, AccessToken, groupId); } catch { throw; } } - } } } \ No newline at end of file diff --git a/src/Commands/SiteDesigns/InvokeSiteScript.cs b/src/Commands/SiteDesigns/InvokeSiteScript.cs index 35cb0eef1..b0d64fcdb 100644 --- a/src/Commands/SiteDesigns/InvokeSiteScript.cs +++ b/src/Commands/SiteDesigns/InvokeSiteScript.cs @@ -55,7 +55,7 @@ protected override void ExecuteCmdlet() else { WriteVerbose($"Executing provided script"); - result = PnP.PowerShell.Commands.Utilities.SiteTemplates.InvokeSiteScript(Connection, AccessToken, Script, hostUrl).GetAwaiter().GetResult().Items; + result = PnP.PowerShell.Commands.Utilities.SiteTemplates.InvokeSiteScript(this, Connection, AccessToken, Script, hostUrl).Items; } break; @@ -81,7 +81,7 @@ protected override void ExecuteCmdlet() else { WriteVerbose($"Executing site script '{script.Title}' ({script.Id})"); - result = PnP.PowerShell.Commands.Utilities.SiteTemplates.InvokeSiteScript(Connection, AccessToken, script, hostUrl).GetAwaiter().GetResult().Items; + result = PnP.PowerShell.Commands.Utilities.SiteTemplates.InvokeSiteScript(this, Connection, AccessToken, script, hostUrl).Items; } } break; diff --git a/src/Commands/Teams/AddTeamsChannel.cs b/src/Commands/Teams/AddTeamsChannel.cs index 707e30586..4a8876ba0 100644 --- a/src/Commands/Teams/AddTeamsChannel.cs +++ b/src/Commands/Teams/AddTeamsChannel.cs @@ -47,7 +47,7 @@ public class AddTeamsChannel : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId == null) { throw new PSArgumentException("Group not found"); @@ -61,7 +61,7 @@ protected override void ExecuteCmdlet() try { #pragma warning disable CS0618 // Type or member is obsolete - var channel = TeamsUtility.AddChannelAsync(AccessToken, Connection, groupId, DisplayName, Description, ChannelType, OwnerUPN, IsFavoriteByDefault).GetAwaiter().GetResult(); + var channel = TeamsUtility.AddChannel(this, AccessToken, Connection, groupId, DisplayName, Description, ChannelType, OwnerUPN, IsFavoriteByDefault); #pragma warning restore CS0618 // Type or member is obsolete WriteObject(channel); } diff --git a/src/Commands/Teams/AddTeamsChannelUser.cs b/src/Commands/Teams/AddTeamsChannelUser.cs index 50ccfb96b..ab56fbbd2 100644 --- a/src/Commands/Teams/AddTeamsChannelUser.cs +++ b/src/Commands/Teams/AddTeamsChannelUser.cs @@ -26,13 +26,13 @@ public class AddTeamsChannelUser : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId == null) { throw new PSArgumentException("Group not found"); } - var channelId = Channel.GetId(Connection, AccessToken, groupId); + var channelId = Channel.GetId(this, Connection, AccessToken, groupId); if (channelId == null) { throw new PSArgumentException("Channel not found"); @@ -40,7 +40,7 @@ protected override void ExecuteCmdlet() try { - TeamsUtility.AddChannelMemberAsync(Connection, AccessToken, groupId, channelId, User, Role).GetAwaiter().GetResult(); + TeamsUtility.AddChannelMember(this, Connection, AccessToken, groupId, channelId, User, Role); } catch (GraphException ex) { diff --git a/src/Commands/Teams/AddTeamsTab.cs b/src/Commands/Teams/AddTeamsTab.cs index 73d9a9b25..482fd3021 100644 --- a/src/Commands/Teams/AddTeamsTab.cs +++ b/src/Commands/Teams/AddTeamsTab.cs @@ -66,10 +66,10 @@ public object GetDynamicParameters() protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var channelId = Channel.GetId(Connection, AccessToken, groupId); + var channelId = Channel.GetId(this, Connection, AccessToken, groupId); if (channelId != null) { try @@ -119,7 +119,7 @@ protected override void ExecuteCmdlet() break; } } - WriteObject(TeamsUtility.AddTabAsync(Connection, AccessToken, groupId, channelId, DisplayName, Type, teamsAppId, entityId, contentUrl, removeUrl, webSiteUrl).GetAwaiter().GetResult()); + WriteObject(TeamsUtility.AddTab(this, Connection, AccessToken, groupId, channelId, DisplayName, Type, teamsAppId, entityId, contentUrl, removeUrl, webSiteUrl)); } catch (GraphException ex) { diff --git a/src/Commands/Teams/AddTeamsUser.cs b/src/Commands/Teams/AddTeamsUser.cs index 7eb0340ea..d0c711d94 100644 --- a/src/Commands/Teams/AddTeamsUser.cs +++ b/src/Commands/Teams/AddTeamsUser.cs @@ -33,29 +33,29 @@ public class AddTeamsUser : PnPGraphCmdlet public string Role; protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { try { if (ParameterSpecified(nameof(Channel))) { - var channelId = Channel.GetId(Connection, AccessToken, groupId); + var channelId = Channel.GetId(this, Connection, AccessToken, groupId); if (channelId == null) { throw new PSArgumentException("Channel not found"); } - TeamsUtility.AddChannelMemberAsync(Connection, AccessToken, groupId, channelId, User, Role).GetAwaiter().GetResult(); + TeamsUtility.AddChannelMember(this, Connection, AccessToken, groupId, channelId, User, Role); } else { if (ParameterSetName == ParamSet_ByUser) { - TeamsUtility.AddUserAsync(Connection, AccessToken, groupId, User, Role).GetAwaiter().GetResult(); + TeamsUtility.AddUser(this, Connection, AccessToken, groupId, User, Role); } else { - TeamsUtility.AddUsersAsync(Connection, AccessToken, groupId, Users, Role).GetAwaiter().GetResult(); + TeamsUtility.AddUsers(this, Connection, AccessToken, groupId, Users, Role); } } } diff --git a/src/Commands/Teams/CopyTeamsTeam.cs b/src/Commands/Teams/CopyTeamsTeam.cs index a45639101..810be1ca5 100644 --- a/src/Commands/Teams/CopyTeamsTeam.cs +++ b/src/Commands/Teams/CopyTeamsTeam.cs @@ -48,7 +48,7 @@ public class CopyTeamsTeam : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Identity.GetGroupId(Connection, AccessToken); + var groupId = Identity.GetGroupId(this, Connection, AccessToken); if (groupId == null) { @@ -58,7 +58,7 @@ protected override void ExecuteCmdlet() if (!ParameterSpecified(nameof(PartsToClone))) { // If no specific parts have been provided, all available parts will be copied - PartsToClone = Enum.GetValues(typeof(Microsoft.Graph.ClonableTeamParts)).Cast().ToArray(); + PartsToClone = Enum.GetValues(typeof(ClonableTeamParts)).Cast().ToArray(); } TeamCloneInformation teamClone = new TeamCloneInformation(); @@ -70,7 +70,7 @@ protected override void ExecuteCmdlet() * but currently ignored and can't be set by user */ teamClone.MailNickName = DisplayName; teamClone.Visibility = (GroupVisibility)Enum.Parse(typeof(GroupVisibility), Visibility.ToString()); - TeamsUtility.CloneTeamAsync(AccessToken, Connection, groupId, teamClone).GetAwaiter().GetResult(); + TeamsUtility.CloneTeam(this, AccessToken, Connection, groupId, teamClone); } } } diff --git a/src/Commands/Teams/GetDeletedTeamsTeam.cs b/src/Commands/Teams/GetDeletedTeamsTeam.cs index 16f510e42..10f203db5 100644 --- a/src/Commands/Teams/GetDeletedTeamsTeam.cs +++ b/src/Commands/Teams/GetDeletedTeamsTeam.cs @@ -12,7 +12,7 @@ public class GetDeletedTeamsTeam : PnPGraphCmdlet { protected override void ExecuteCmdlet() { - WriteObject(TeamsUtility.GetDeletedTeamAsync(AccessToken, Connection).GetAwaiter().GetResult()); + WriteObject(TeamsUtility.GetDeletedTeam(this, AccessToken, Connection)); } } } diff --git a/src/Commands/Teams/GetTeamsApp.cs b/src/Commands/Teams/GetTeamsApp.cs index 7f3293ca2..c6ab9fb85 100644 --- a/src/Commands/Teams/GetTeamsApp.cs +++ b/src/Commands/Teams/GetTeamsApp.cs @@ -20,7 +20,7 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Identity))) { - var app = Identity.GetApp(Connection, AccessToken); + var app = Identity.GetApp(this, Connection, AccessToken); if (app != null) { WriteObject(app); @@ -28,7 +28,7 @@ protected override void ExecuteCmdlet() } else { - WriteObject(TeamsUtility.GetAppsAsync(AccessToken, Connection).GetAwaiter().GetResult(), true); + WriteObject(TeamsUtility.GetApps(this, AccessToken, Connection), true); } } } diff --git a/src/Commands/Teams/GetTeamsChannel.cs b/src/Commands/Teams/GetTeamsChannel.cs index c9f6de2b6..d543ff639 100644 --- a/src/Commands/Teams/GetTeamsChannel.cs +++ b/src/Commands/Teams/GetTeamsChannel.cs @@ -22,15 +22,15 @@ public class GetTeamsChannel : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken) ?? throw new PSArgumentException("Team not found", nameof(Team)); + var groupId = Team.GetGroupId(this, Connection, AccessToken) ?? throw new PSArgumentException("Team not found", nameof(Team)); if (ParameterSpecified(nameof(Identity))) { - WriteObject(Identity.GetChannel(Connection, AccessToken, groupId, useBeta: IncludeModerationSettings.ToBool())); + WriteObject(Identity.GetChannel(this, Connection, AccessToken, groupId, useBeta: IncludeModerationSettings.ToBool())); } else { - WriteObject(TeamsUtility.GetChannelsAsync(AccessToken, Connection, groupId, useBeta: IncludeModerationSettings.ToBool()).GetAwaiter().GetResult(), true); + WriteObject(TeamsUtility.GetChannels(this, AccessToken, Connection, groupId, useBeta: IncludeModerationSettings.ToBool()), true); } } } diff --git a/src/Commands/Teams/GetTeamsChannelFilesFolder.cs b/src/Commands/Teams/GetTeamsChannelFilesFolder.cs index 034e8dab6..efc626143 100644 --- a/src/Commands/Teams/GetTeamsChannelFilesFolder.cs +++ b/src/Commands/Teams/GetTeamsChannelFilesFolder.cs @@ -17,18 +17,17 @@ public class GetTeamsChannelFilesFolder : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var channelId = Channel.GetId(Connection, AccessToken, groupId); + var channelId = Channel.GetId(this, Connection, AccessToken, groupId); if (channelId == null) { throw new PSArgumentException("Channel not found"); } - WriteObject(Utilities.TeamsUtility.GetChannelsFilesFolderAsync(Connection, AccessToken, groupId, channelId).GetAwaiter().GetResult()); - + WriteObject(Utilities.TeamsUtility.GetChannelsFilesFolder(this, Connection, AccessToken, groupId, channelId)); } else { diff --git a/src/Commands/Teams/GetTeamsChannelMessage.cs b/src/Commands/Teams/GetTeamsChannelMessage.cs index d234e945c..1c4ea3d41 100644 --- a/src/Commands/Teams/GetTeamsChannelMessage.cs +++ b/src/Commands/Teams/GetTeamsChannelMessage.cs @@ -24,13 +24,13 @@ public class GetTeamsChannelMessage : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId == null) { throw new PSArgumentException("Team not found"); } - var channelId = Channel.GetId(Connection, AccessToken, groupId); + var channelId = Channel.GetId(this, Connection, AccessToken, groupId); if (channelId == null) { throw new PSArgumentException("Channel not found"); @@ -43,12 +43,12 @@ protected override void ExecuteCmdlet() throw new PSArgumentException($"Don't specify {nameof(IncludeDeleted)} when using the {nameof(Identity)} parameter."); } - var message = TeamsUtility.GetMessageAsync(Connection, AccessToken, groupId, channelId, Identity.GetId()).GetAwaiter().GetResult(); + var message = TeamsUtility.GetMessage(this, Connection, AccessToken, groupId, channelId, Identity.GetId()); WriteObject(message); } else { - var messages = TeamsUtility.GetMessagesAsync(Connection, AccessToken, groupId, channelId, IncludeDeleted).GetAwaiter().GetResult(); + var messages = TeamsUtility.GetMessages(this, Connection, AccessToken, groupId, channelId, IncludeDeleted); WriteObject(messages, true); } } diff --git a/src/Commands/Teams/GetTeamsChannelMessageReply.cs b/src/Commands/Teams/GetTeamsChannelMessageReply.cs index fd268439c..9d84af6a5 100644 --- a/src/Commands/Teams/GetTeamsChannelMessageReply.cs +++ b/src/Commands/Teams/GetTeamsChannelMessageReply.cs @@ -27,13 +27,13 @@ public class GetTeamsChannelMessageReply : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId == null) { throw new PSArgumentException("Group not found"); } - var channelId = Channel.GetId(Connection, AccessToken, groupId); + var channelId = Channel.GetId(this, Connection, AccessToken, groupId); if (channelId == null) { throw new PSArgumentException("Channel not found"); @@ -54,12 +54,12 @@ protected override void ExecuteCmdlet() throw new PSArgumentException($"Don't specify {nameof(IncludeDeleted)} when using the {nameof(Identity)} parameter."); } - var reply = TeamsUtility.GetMessageReplyAsync(Connection, AccessToken, groupId, channelId, messageId, Identity.GetId()).GetAwaiter().GetResult(); + var reply = TeamsUtility.GetMessageReply(this, Connection, AccessToken, groupId, channelId, messageId, Identity.GetId()); WriteObject(reply); } else { - var replies = TeamsUtility.GetMessageRepliesAsync(Connection, AccessToken, groupId, channelId, messageId, IncludeDeleted).GetAwaiter().GetResult(); + var replies = TeamsUtility.GetMessageReplies(this, Connection, AccessToken, groupId, channelId, messageId, IncludeDeleted); WriteObject(replies, true); } } diff --git a/src/Commands/Teams/GetTeamsChannelUser.cs b/src/Commands/Teams/GetTeamsChannelUser.cs index 168f9411b..95cce115c 100644 --- a/src/Commands/Teams/GetTeamsChannelUser.cs +++ b/src/Commands/Teams/GetTeamsChannelUser.cs @@ -25,13 +25,13 @@ public class GetTeamsChannelUser : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId == null) { throw new PSArgumentException("Group not found"); } - var channelId = Channel.GetId(Connection, AccessToken, groupId); + var channelId = Channel.GetId(this, Connection, AccessToken, groupId); if (channelId == null) { throw new PSArgumentException("Channel not found"); @@ -39,11 +39,11 @@ protected override void ExecuteCmdlet() if (ParameterSpecified(nameof(Identity))) { - WriteObject(Identity.GetMembershipAsync(Connection, AccessToken, groupId, channelId).GetAwaiter().GetResult()); + WriteObject(Identity.GetMembership(this, Connection, AccessToken, groupId, channelId)); } else { - WriteObject(TeamsUtility.GetChannelMembersAsync(Connection, AccessToken, groupId, channelId, Role).GetAwaiter().GetResult(), true); + WriteObject(TeamsUtility.GetChannelMembers(this, Connection, AccessToken, groupId, channelId, Role), true); } } } diff --git a/src/Commands/Teams/GetTeamsPrimaryChannel.cs b/src/Commands/Teams/GetTeamsPrimaryChannel.cs index d0a7f2fe6..a593b0201 100644 --- a/src/Commands/Teams/GetTeamsPrimaryChannel.cs +++ b/src/Commands/Teams/GetTeamsPrimaryChannel.cs @@ -16,10 +16,10 @@ public class GetTeamsPrimaryChannel : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - WriteObject(TeamsUtility.GetPrimaryChannelAsync(AccessToken, Connection, groupId).GetAwaiter().GetResult()); + WriteObject(TeamsUtility.GetPrimaryChannel(this, AccessToken, Connection, groupId)); } else { throw new PSArgumentException("Team not found", nameof(Team)); diff --git a/src/Commands/Teams/GetTeamsTab.cs b/src/Commands/Teams/GetTeamsTab.cs index 8c9097f27..09b6e9459 100644 --- a/src/Commands/Teams/GetTeamsTab.cs +++ b/src/Commands/Teams/GetTeamsTab.cs @@ -23,10 +23,10 @@ public class GetTeamsTab : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var channelId = Channel.GetId(Connection, AccessToken, groupId); + var channelId = Channel.GetId(this, Connection, AccessToken, groupId); if (!string.IsNullOrEmpty(channelId)) { if (ParameterSpecified(nameof(Identity))) @@ -35,7 +35,7 @@ protected override void ExecuteCmdlet() } else { - WriteObject(TeamsUtility.GetTabsAsync(AccessToken, Connection, groupId, channelId).GetAwaiter().GetResult(), true); + WriteObject(TeamsUtility.GetTabs(this, AccessToken, Connection, groupId, channelId), true); } } else diff --git a/src/Commands/Teams/GetTeamsTag.cs b/src/Commands/Teams/GetTeamsTag.cs index cf8baf3b1..5427cf9c4 100644 --- a/src/Commands/Teams/GetTeamsTag.cs +++ b/src/Commands/Teams/GetTeamsTag.cs @@ -20,7 +20,7 @@ public class GetTeamsTag : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (string.IsNullOrEmpty(groupId)) { throw new PSArgumentException("Team not found"); @@ -28,12 +28,12 @@ protected override void ExecuteCmdlet() if (ParameterSpecified(nameof(Identity))) { - var tags = Identity.GetTag(Connection, AccessToken, groupId); + var tags = Identity.GetTag(this, Connection, AccessToken, groupId); WriteObject(tags, false); } else { - var tags = TeamsUtility.GetTagsAsync(AccessToken, Connection, groupId).GetAwaiter().GetResult(); + var tags = TeamsUtility.GetTags(this, AccessToken, Connection, groupId); WriteObject(tags, true); } } diff --git a/src/Commands/Teams/GetTeamsTeam.cs b/src/Commands/Teams/GetTeamsTeam.cs index e5a22a089..eff858482 100644 --- a/src/Commands/Teams/GetTeamsTeam.cs +++ b/src/Commands/Teams/GetTeamsTeam.cs @@ -28,19 +28,19 @@ protected override void ExecuteCmdlet() { if (ParameterSpecified(nameof(Identity))) { - var groupId = Identity.GetGroupId(Connection, AccessToken); + var groupId = Identity.GetGroupId(this, Connection, AccessToken); if(groupId == null) { throw new PSArgumentException("Team not found", nameof(Identity)); } else - { - WriteObject(TeamsUtility.GetTeamAsync(AccessToken, Connection, groupId).GetAwaiter().GetResult()); + { + WriteObject(TeamsUtility.GetTeam(this, AccessToken, Connection, groupId)); } } else { - WriteObject(TeamsUtility.GetTeamsAsync(AccessToken, Connection, Filter).GetAwaiter().GetResult(), true); + WriteObject(TeamsUtility.GetTeamUsingFilter(this, AccessToken, Connection, Filter)); } } } diff --git a/src/Commands/Teams/GetTeamsUser.cs b/src/Commands/Teams/GetTeamsUser.cs index c34e92cf3..e5143b5ca 100644 --- a/src/Commands/Teams/GetTeamsUser.cs +++ b/src/Commands/Teams/GetTeamsUser.cs @@ -25,22 +25,22 @@ public class GetTeamsUser : PnPGraphCmdlet public string Role; protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { try { if (ParameterSpecified(nameof(Channel))) { - var teamChannels = TeamsUtility.GetChannelsAsync(AccessToken, Connection, groupId).GetAwaiter().GetResult(); + var teamChannels = TeamsUtility.GetChannels(this, AccessToken, Connection, groupId); - var channelId = Channel.GetId(Connection, AccessToken, groupId); + var channelId = Channel.GetId(this, Connection, AccessToken, groupId); var requestedChannel = teamChannels.FirstOrDefault(c => c.Id == channelId); if (!string.IsNullOrEmpty(channelId) && requestedChannel != null && requestedChannel.MembershipType.ToLower() == TeamChannelType.Private.ToString().ToLower()) { - WriteObject(TeamsUtility.GetUsersAsync(Connection, AccessToken, groupId, channelId, Role).GetAwaiter().GetResult(), true); + WriteObject(TeamsUtility.GetUsers(this, Connection, AccessToken, groupId, channelId, Role), true); } else { @@ -49,7 +49,7 @@ protected override void ExecuteCmdlet() } else { - WriteObject(TeamsUtility.GetUsersAsync(Connection, AccessToken, groupId, Role).GetAwaiter().GetResult(), true); + WriteObject(TeamsUtility.GetUsers(this, Connection, AccessToken, groupId, Role), true); } } catch (GraphException ex) diff --git a/src/Commands/Teams/NewTeamsApp.cs b/src/Commands/Teams/NewTeamsApp.cs index 15197431d..9abe97ab9 100644 --- a/src/Commands/Teams/NewTeamsApp.cs +++ b/src/Commands/Teams/NewTeamsApp.cs @@ -27,7 +27,7 @@ protected override void ExecuteCmdlet() try { var bytes = System.IO.File.ReadAllBytes(Path); - TeamsUtility.AddAppAsync(Connection, AccessToken, bytes).GetAwaiter().GetResult(); + TeamsUtility.AddApp(this, Connection, AccessToken, bytes); } catch (GraphException ex) { diff --git a/src/Commands/Teams/NewTeamsTeam.cs b/src/Commands/Teams/NewTeamsTeam.cs index 6429b9735..176c596a4 100644 --- a/src/Commands/Teams/NewTeamsTeam.cs +++ b/src/Commands/Teams/NewTeamsTeam.cs @@ -147,7 +147,7 @@ protected override void ExecuteCmdlet() } } - WriteObject(TeamsUtility.NewTeamAsync(AccessToken, Connection, GroupId, DisplayName, Description, Classification, MailNickName, (GroupVisibility)Enum.Parse(typeof(GroupVisibility), Visibility.ToString()), teamCI, Owners, Members, SensitivityLabels, Template, ResourceBehaviorOptions).GetAwaiter().GetResult()); + WriteObject(TeamsUtility.NewTeam(this, AccessToken, Connection, GroupId, DisplayName, Description, Classification, MailNickName, (GroupVisibility)Enum.Parse(typeof(GroupVisibility), Visibility.ToString()), teamCI, Owners, Members, SensitivityLabels, Template, ResourceBehaviorOptions)); } } } diff --git a/src/Commands/Teams/RemoveTeamsApp.cs b/src/Commands/Teams/RemoveTeamsApp.cs index 7b5f9a50b..0c1f6d76e 100644 --- a/src/Commands/Teams/RemoveTeamsApp.cs +++ b/src/Commands/Teams/RemoveTeamsApp.cs @@ -20,14 +20,14 @@ public class RemoveTeamsApp : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var app = Identity.GetApp(Connection, AccessToken); + var app = Identity.GetApp(this, Connection, AccessToken); if (app == null) { throw new PSArgumentException("App not found"); } if (Force || ShouldContinue($"Do you want to remove {app.DisplayName}?", Properties.Resources.Confirm)) { - var response = TeamsUtility.DeleteAppAsync(Connection, AccessToken, app.Id).GetAwaiter().GetResult(); + var response = TeamsUtility.DeleteApp(this, Connection, AccessToken, app.Id); if (!response.IsSuccessStatusCode) { if (GraphHelper.TryGetGraphException(response, out GraphException ex)) diff --git a/src/Commands/Teams/RemoveTeamsChannel.cs b/src/Commands/Teams/RemoveTeamsChannel.cs index b3f3e5135..4d7dc778c 100644 --- a/src/Commands/Teams/RemoveTeamsChannel.cs +++ b/src/Commands/Teams/RemoveTeamsChannel.cs @@ -27,13 +27,13 @@ protected override void ExecuteCmdlet() { if (Force || ShouldContinue("Removing the channel will also remove all the messages in the channel.", Properties.Resources.Confirm)) { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var channel = Identity.GetChannel(Connection, AccessToken, groupId); + var channel = Identity.GetChannel(this, Connection, AccessToken, groupId); if (channel != null) { - var response = TeamsUtility.DeleteChannelAsync(AccessToken, Connection, groupId, channel.Id).GetAwaiter().GetResult(); + var response = TeamsUtility.DeleteChannel(this, AccessToken, Connection, groupId, channel.Id); if (!response.IsSuccessStatusCode) { if (GraphHelper.TryGetGraphException(response, out GraphException ex)) diff --git a/src/Commands/Teams/RemoveTeamsChannelUser.cs b/src/Commands/Teams/RemoveTeamsChannelUser.cs index 1a46995ac..b85cdd710 100644 --- a/src/Commands/Teams/RemoveTeamsChannelUser.cs +++ b/src/Commands/Teams/RemoveTeamsChannelUser.cs @@ -26,19 +26,19 @@ public class RemoveTeamsChannelUser : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (string.IsNullOrEmpty(groupId)) { throw new PSArgumentException("Group not found"); } - var channelId = Channel.GetId(Connection, AccessToken, groupId); + var channelId = Channel.GetId(this, Connection, AccessToken, groupId); if (string.IsNullOrEmpty(channelId)) { throw new PSArgumentException("Channel not found in the specified team"); } - var memberId = Identity.GetIdAsync(Connection, AccessToken, groupId, channelId).GetAwaiter().GetResult(); + var memberId = Identity.GetId(this, Connection, AccessToken, groupId, channelId); if (string.IsNullOrEmpty(memberId)) { throw new PSArgumentException("User was not found in the specified Teams channel"); @@ -46,8 +46,7 @@ protected override void ExecuteCmdlet() if (Force || ShouldContinue("Remove specified member from the Microsoft Teams channel?", Resources.Confirm)) { - var response = TeamsUtility.DeleteChannelMemberAsync(Connection, AccessToken, groupId, channelId, memberId).GetAwaiter().GetResult(); - + var response = TeamsUtility.DeleteChannelMember(this, Connection, AccessToken, groupId, channelId, memberId); if (!response.IsSuccessStatusCode) { if (GraphHelper.TryGetGraphException(response, out var ex) && !string.IsNullOrEmpty(ex.Error.Message)) diff --git a/src/Commands/Teams/RemoveTeamsTab.cs b/src/Commands/Teams/RemoveTeamsTab.cs index 8e033ddd0..e3a9f4489 100644 --- a/src/Commands/Teams/RemoveTeamsTab.cs +++ b/src/Commands/Teams/RemoveTeamsTab.cs @@ -27,10 +27,10 @@ public class RemoveTeamsTab : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var channelId = Channel.GetId(Connection, AccessToken, groupId); + var channelId = Channel.GetId(this, Connection, AccessToken, groupId); if (channelId != null) { var tab = Identity.GetTab(this, Connection, AccessToken, groupId, channelId); @@ -38,7 +38,7 @@ protected override void ExecuteCmdlet() { if (Force || ShouldContinue("Removing the tab will remove the settings of this tab too.", Properties.Resources.Confirm)) { - var response = TeamsUtility.DeleteTabAsync(AccessToken, Connection, groupId, channelId, tab.Id).GetAwaiter().GetResult(); + var response = TeamsUtility.DeleteTab(this, AccessToken, Connection, groupId, channelId, tab.Id); if (!response.IsSuccessStatusCode) { if (GraphHelper.TryGetGraphException(response, out GraphException ex)) diff --git a/src/Commands/Teams/RemoveTeamsTag.cs b/src/Commands/Teams/RemoveTeamsTag.cs index e020f39e3..3393dcffa 100644 --- a/src/Commands/Teams/RemoveTeamsTag.cs +++ b/src/Commands/Teams/RemoveTeamsTag.cs @@ -23,15 +23,15 @@ public class RemoveTeamsTag : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var tag = Identity.GetTag(Connection, AccessToken, groupId); + var tag = Identity.GetTag(this, Connection, AccessToken, groupId); if (tag != null) { if (Force || ShouldContinue("Do you want to remove this tag ?", Properties.Resources.Confirm)) { - var response = TeamsUtility.DeleteTagAsync(Connection, AccessToken, groupId, tag.Id).GetAwaiter().GetResult(); + var response = TeamsUtility.DeleteTag(this, Connection, AccessToken, groupId, tag.Id); if (!response.IsSuccessStatusCode) { if (GraphHelper.TryGetGraphException(response, out GraphException ex)) diff --git a/src/Commands/Teams/RemoveTeamsTeam.cs b/src/Commands/Teams/RemoveTeamsTeam.cs index 2d451ad1a..3b90c4543 100644 --- a/src/Commands/Teams/RemoveTeamsTeam.cs +++ b/src/Commands/Teams/RemoveTeamsTeam.cs @@ -21,12 +21,12 @@ public class RemoveTeamsTeam : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Identity.GetGroupId(Connection, AccessToken); + var groupId = Identity.GetGroupId(this, Connection, AccessToken); if (groupId != null) { if (Force || ShouldContinue("Removing the team will remove all messages in all channels in the team.", Properties.Resources.Confirm)) { - var response = TeamsUtility.DeleteTeamAsync(AccessToken, Connection, groupId).GetAwaiter().GetResult(); + var response = TeamsUtility.DeleteTeam(this, AccessToken, Connection, groupId); if (!response.IsSuccessStatusCode) { if (GraphHelper.TryGetGraphException(response, out GraphException ex)) diff --git a/src/Commands/Teams/RemoveTeamsUser.cs b/src/Commands/Teams/RemoveTeamsUser.cs index 3409403ab..c515b90cf 100644 --- a/src/Commands/Teams/RemoveTeamsUser.cs +++ b/src/Commands/Teams/RemoveTeamsUser.cs @@ -25,14 +25,14 @@ public class RemoveTeamsUser : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { try { if (Force || ShouldContinue($"Remove user with UPN {User}?", Properties.Resources.Confirm)) { - TeamsUtility.DeleteUserAsync(Connection, AccessToken, groupId, User, Role).GetAwaiter().GetResult(); + TeamsUtility.DeleteUser(this, Connection, AccessToken, groupId, User, Role); } } catch (GraphException ex) diff --git a/src/Commands/Teams/SetTeamsChannel.cs b/src/Commands/Teams/SetTeamsChannel.cs index 6a834e6cf..7c9c920df 100644 --- a/src/Commands/Teams/SetTeamsChannel.cs +++ b/src/Commands/Teams/SetTeamsChannel.cs @@ -42,8 +42,8 @@ public class SetTeamsChannel : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken) ?? throw new PSArgumentException("Group not found"); - var teamChannel = Identity.GetChannel(Connection, AccessToken, groupId) ?? throw new PSArgumentException("Channel not found"); + var groupId = Team.GetGroupId(this, Connection, AccessToken) ?? throw new PSArgumentException("Group not found"); + var teamChannel = Identity.GetChannel(this, Connection, AccessToken, groupId) ?? throw new PSArgumentException("Channel not found"); // Flag to indicate if we have to use the beta endpoint to perform the update var betaRequired = false; @@ -102,7 +102,7 @@ protected override void ExecuteCmdlet() teamChannel.MembershipType = null; try { - var updated = TeamsUtility.UpdateChannelAsync(Connection, AccessToken, groupId, teamChannel.Id, teamChannel, useBeta: betaRequired).GetAwaiter().GetResult(); + var updated = TeamsUtility.UpdateChannel(this, Connection, AccessToken, groupId, teamChannel.Id, teamChannel, useBeta: betaRequired); WriteObject(updated); } catch (GraphException ex) diff --git a/src/Commands/Teams/SetTeamsChannelUser.cs b/src/Commands/Teams/SetTeamsChannelUser.cs index 30d29a906..ee7c2aba1 100644 --- a/src/Commands/Teams/SetTeamsChannelUser.cs +++ b/src/Commands/Teams/SetTeamsChannelUser.cs @@ -26,19 +26,19 @@ public class SetTeamsChannelUser : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId == null) { throw new PSArgumentException("Group not found"); } - var channelId = Channel.GetId(Connection, AccessToken, groupId); + var channelId = Channel.GetId(this, Connection, AccessToken, groupId); if (channelId == null) { throw new PSArgumentException("Channel not found"); } - var membershipId = Identity.GetIdAsync(Connection, AccessToken, groupId, channelId).GetAwaiter().GetResult(); + var membershipId = Identity.GetId(this, Connection, AccessToken, groupId, channelId); if (string.IsNullOrEmpty(membershipId)) { throw new PSArgumentException("User was not found in the specified Teams channel"); @@ -46,7 +46,7 @@ protected override void ExecuteCmdlet() try { - var updatedMember = TeamsUtility.UpdateChannelMemberAsync(Connection, AccessToken, groupId, channelId, membershipId, Role).GetAwaiter().GetResult(); + var updatedMember = TeamsUtility.UpdateChannelMember(this, Connection, AccessToken, groupId, channelId, membershipId, Role); WriteObject(updatedMember); } catch (GraphException ex) diff --git a/src/Commands/Teams/SetTeamsTab.cs b/src/Commands/Teams/SetTeamsTab.cs index 6accc454d..cb473ef22 100644 --- a/src/Commands/Teams/SetTeamsTab.cs +++ b/src/Commands/Teams/SetTeamsTab.cs @@ -24,10 +24,10 @@ public class SetTeamsTab : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var channelId = Channel.GetId(Connection, AccessToken, groupId); + var channelId = Channel.GetId(this, Connection, AccessToken, groupId); if (channelId != null) { var tab = Identity.GetTab(this,Connection, AccessToken, groupId, channelId); @@ -37,7 +37,7 @@ protected override void ExecuteCmdlet() { tab.DisplayName = DisplayName; } - TeamsUtility.UpdateTabAsync(Connection, AccessToken, groupId, channelId, tab).GetAwaiter().GetResult(); + TeamsUtility.UpdateTab(this, Connection, AccessToken, groupId, channelId, tab); } else { diff --git a/src/Commands/Teams/SetTeamsTag.cs b/src/Commands/Teams/SetTeamsTag.cs index 609192692..b524e6d5b 100644 --- a/src/Commands/Teams/SetTeamsTag.cs +++ b/src/Commands/Teams/SetTeamsTag.cs @@ -21,15 +21,15 @@ public class SetTeamsTag : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var tag = Identity.GetTag(Connection, AccessToken, groupId); + var tag = Identity.GetTag(this, Connection, AccessToken, groupId); if (tag != null) { if (ParameterSpecified(nameof(DisplayName)) && tag.DisplayName != DisplayName) { - TeamsUtility.UpdateTagAsync(Connection, AccessToken, groupId, tag.Id, DisplayName).GetAwaiter().GetResult(); + TeamsUtility.UpdateTag(this, Connection, AccessToken, groupId, tag.Id, DisplayName); } } else diff --git a/src/Commands/Teams/SetTeamsTeam.cs b/src/Commands/Teams/SetTeamsTeam.cs index de1761cde..0e4813f50 100644 --- a/src/Commands/Teams/SetTeamsTeam.cs +++ b/src/Commands/Teams/SetTeamsTeam.cs @@ -84,12 +84,12 @@ public class SetTeamsTeam : PnPGraphCmdlet public bool? AllowCreatePrivateChannels; protected override void ExecuteCmdlet() { - var groupId = Identity.GetGroupId(Connection, AccessToken); + var groupId = Identity.GetGroupId(this, Connection, AccessToken); if (groupId != null) { try { - var team = TeamsUtility.GetTeamAsync(AccessToken, Connection, groupId).GetAwaiter().GetResult(); + var team = TeamsUtility.GetTeam(this, AccessToken, Connection, groupId); var updateGroup = false; var group = new Group(); if (team != null) @@ -125,7 +125,7 @@ protected override void ExecuteCmdlet() if(updateGroup) { - TeamsUtility.UpdateGroupAsync(Connection, AccessToken, groupId, group).GetAwaiter().GetResult(); + TeamsUtility.UpdateGroup(this, Connection, AccessToken, groupId, group); } var teamCI = new TeamCreationInformation(); @@ -147,7 +147,7 @@ protected override void ExecuteCmdlet() teamCI.Classification = ParameterSpecified(nameof(Classification)) ? Classification : null; teamCI.AllowCreatePrivateChannels = ParameterSpecified(nameof(AllowCreatePrivateChannels)) ? AllowCreatePrivateChannels : null; - var updated = TeamsUtility.UpdateTeamAsync(Connection, AccessToken, groupId, teamCI.ToTeam(group.Visibility.Value)).GetAwaiter().GetResult(); + var updated = TeamsUtility.UpdateTeam(this, Connection, AccessToken, groupId, teamCI.ToTeam(group.Visibility.Value)); WriteObject(updated); } } diff --git a/src/Commands/Teams/SetTeamsTeamArchivedState.cs b/src/Commands/Teams/SetTeamsTeamArchivedState.cs index daa43d617..82cf38177 100644 --- a/src/Commands/Teams/SetTeamsTeamArchivedState.cs +++ b/src/Commands/Teams/SetTeamsTeamArchivedState.cs @@ -30,15 +30,15 @@ protected override void ExecuteCmdlet() { throw new PSArgumentException("You can only modify the read only state of a site when archiving a team"); } - var groupId = Identity.GetGroupId(Connection, AccessToken); + var groupId = Identity.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var team = Identity.GetTeam(Connection, AccessToken); + var team = Identity.GetTeam(this, Connection, AccessToken); if (Archived == team.IsArchived) { throw new PSInvalidOperationException($"Team {team.DisplayName} {(Archived ? "has already been" : "is not")} archived"); } - var response = TeamsUtility.SetTeamArchivedStateAsync(Connection, AccessToken, groupId, Archived, SetSiteReadOnlyForMembers).GetAwaiter().GetResult(); + var response = TeamsUtility.SetTeamArchivedState(this, Connection, AccessToken, groupId, Archived, SetSiteReadOnlyForMembers); if (!response.IsSuccessStatusCode) { if (GraphHelper.TryGetGraphException(response, out GraphException ex)) diff --git a/src/Commands/Teams/SetTeamsTeamPicture.cs b/src/Commands/Teams/SetTeamsTeamPicture.cs index 8a88f2826..cb5babac1 100644 --- a/src/Commands/Teams/SetTeamsTeamPicture.cs +++ b/src/Commands/Teams/SetTeamsTeamPicture.cs @@ -20,7 +20,7 @@ public class SetTeamsTeamPicture : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { if (!System.IO.Path.IsPathRooted(Path)) @@ -51,7 +51,7 @@ protected override void ExecuteCmdlet() throw new PSArgumentException("File is not of a supported content type (jpg/png)"); } var byteArray = File.ReadAllBytes(Path); - TeamsUtility.SetTeamPictureAsync(Connection, AccessToken, groupId, byteArray, contentType).GetAwaiter().GetResult(); + TeamsUtility.SetTeamPictureAsync(this, Connection, AccessToken, groupId, byteArray, contentType); } else { diff --git a/src/Commands/Teams/SubmitTeamsChannelMessage.cs b/src/Commands/Teams/SubmitTeamsChannelMessage.cs index 78bec5823..09614fb10 100644 --- a/src/Commands/Teams/SubmitTeamsChannelMessage.cs +++ b/src/Commands/Teams/SubmitTeamsChannelMessage.cs @@ -29,10 +29,10 @@ public class SubmitTeamsChannelMessage : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { - var channel = Channel.GetChannel(Connection, AccessToken, groupId); + var channel = Channel.GetChannel(this, Connection, AccessToken, groupId); if (channel != null) { var channelMessage = new TeamChannelMessage(); @@ -40,7 +40,7 @@ protected override void ExecuteCmdlet() channelMessage.Body.Content = Message; channelMessage.Body.ContentType = ContentType == TeamChannelMessageContentType.Html ? "html" : "text"; - TeamsUtility.PostMessageAsync(Connection, AccessToken, groupId, channel.Id, channelMessage).GetAwaiter().GetResult(); + TeamsUtility.PostMessage(this, Connection, AccessToken, groupId, channel.Id, channelMessage); } else { diff --git a/src/Commands/Teams/UpdateTeamsApp.cs b/src/Commands/Teams/UpdateTeamsApp.cs index 28c30a0c5..4cfe0ad83 100644 --- a/src/Commands/Teams/UpdateTeamsApp.cs +++ b/src/Commands/Teams/UpdateTeamsApp.cs @@ -29,12 +29,12 @@ protected override void ExecuteCmdlet() if (System.IO.File.Exists(Path)) { - var app = Identity.GetApp(Connection, AccessToken); + var app = Identity.GetApp(this, Connection, AccessToken); if (app != null) { var bytes = System.IO.File.ReadAllBytes(Path); - var response = TeamsUtility.UpdateAppAsync(Connection, AccessToken, bytes, app.Id).GetAwaiter().GetResult(); + var response = TeamsUtility.UpdateApp(this, Connection, AccessToken, bytes, app.Id); if (!response.IsSuccessStatusCode) { if (GraphHelper.TryGetGraphException(response, out GraphException ex)) diff --git a/src/Commands/Teams/UpdateTeamsUser.cs b/src/Commands/Teams/UpdateTeamsUser.cs index 65e324da1..fc2838b61 100644 --- a/src/Commands/Teams/UpdateTeamsUser.cs +++ b/src/Commands/Teams/UpdateTeamsUser.cs @@ -26,24 +26,24 @@ public class UpdateTeamsUser : PnPGraphCmdlet protected override void ExecuteCmdlet() { - var groupId = Team.GetGroupId(Connection, AccessToken); + var groupId = Team.GetGroupId(this, Connection, AccessToken); if (groupId != null) { try { if (Force || ShouldContinue($"Update role for user with UPN {User} ?", Properties.Resources.Confirm)) { - var teamsUser = TeamsUtility.GetUsersAsync(Connection, AccessToken, groupId, string.Empty).GetAwaiter().GetResult(); + var teamsUser = TeamsUtility.GetUsers(this, Connection, AccessToken, groupId, string.Empty); var specifiedUser = teamsUser.Find(u => u.UserPrincipalName.ToLower() == User.ToLower()); if (specifiedUser != null) { // No easy way to get member Id for teams endpoint, need to rely on display name filter to fetch memberId of the specified user and then update - var teamUserWithDisplayName = TeamsUtility.GetTeamUsersWithDisplayNameAsync(Connection, AccessToken, groupId, specifiedUser.DisplayName).GetAwaiter().GetResult(); + var teamUserWithDisplayName = TeamsUtility.GetTeamUsersWithDisplayName(this, Connection, AccessToken, groupId, specifiedUser.DisplayName); var userToUpdate = teamUserWithDisplayName.Find(u => u.UserId == specifiedUser.Id); // Pass the member id of the user whose role we are changing - WriteObject(TeamsUtility.UpdateTeamUserRole(Connection, AccessToken, groupId, userToUpdate.Id, Role).GetAwaiter().GetResult()); + WriteObject(TeamsUtility.UpdateTeamUserRole(this, Connection, AccessToken, groupId, userToUpdate.Id, Role)); } else { diff --git a/src/Commands/UserProfiles/ExportUserProfile.cs b/src/Commands/UserProfiles/ExportUserProfile.cs index 8d6f190d1..bd63bb554 100644 --- a/src/Commands/UserProfiles/ExportUserProfile.cs +++ b/src/Commands/UserProfiles/ExportUserProfile.cs @@ -21,7 +21,7 @@ protected override void ExecuteCmdlet() hostUrl = hostUrl.Substring(0, hostUrl.Length - 1); } var normalizedUserName = UrlUtilities.UrlEncode($"i:0#.f|membership|{LoginName}"); - var results = RestHelper.GetAsync>(this.HttpClient, $"{hostUrl}/_api/sp.userprofiles.peoplemanager/GetUserProfileProperties(accountName=@a)?@a='{normalizedUserName}'", AdminContext, false).GetAwaiter().GetResult(); + var results = RestHelper.Get>(this.HttpClient, $"{hostUrl}/_api/sp.userprofiles.peoplemanager/GetUserProfileProperties(accountName=@a)?@a='{normalizedUserName}'", AdminContext, false); var record = new PSObject(); foreach (var item in results.Items) { diff --git a/src/Commands/UserProfiles/RemoveUserProfile.cs b/src/Commands/UserProfiles/RemoveUserProfile.cs index a4faa900c..4e66b6e0b 100644 --- a/src/Commands/UserProfiles/RemoveUserProfile.cs +++ b/src/Commands/UserProfiles/RemoveUserProfile.cs @@ -27,11 +27,11 @@ protected override void ExecuteCmdlet() if (!ParameterSpecified(nameof(UserId))) { - RestHelper.PostAsync(this.HttpClient, $"{hostUrl}/_api/sp.userprofiles.peoplemanager/HardDeleteUserProfile(accountName=@a)?@a='{normalizedUserName}'", AdminContext).GetAwaiter().GetResult(); + RestHelper.Post(this.HttpClient, $"{hostUrl}/_api/sp.userprofiles.peoplemanager/HardDeleteUserProfile(accountName=@a)?@a='{normalizedUserName}'", AdminContext); } else { - RestHelper.PostAsync(this.HttpClient, $"{hostUrl}/_api/sp.userprofiles.peoplemanager/HardDeleteUserProfile(accountName=@a,userId='{UserId}')?@a='{normalizedUserName}'", AdminContext).GetAwaiter().GetResult(); + RestHelper.Post(this.HttpClient, $"{hostUrl}/_api/sp.userprofiles.peoplemanager/HardDeleteUserProfile(accountName=@a,userId='{UserId}')?@a='{normalizedUserName}'", AdminContext); } WriteVerbose($"Completed deletion of user profile {LoginName}"); diff --git a/src/Commands/Utilities/AzureADGroupsUtility.cs b/src/Commands/Utilities/AzureADGroupsUtility.cs index 6bfcace78..f9690d647 100644 --- a/src/Commands/Utilities/AzureADGroupsUtility.cs +++ b/src/Commands/Utilities/AzureADGroupsUtility.cs @@ -3,17 +3,16 @@ using PnP.PowerShell.Commands.Utilities.REST; using System; using System.Linq; -using System.Threading.Tasks; using System.Collections.Generic; -using PnP.PowerShell.Commands.Model; +using System.Management.Automation; namespace PnP.PowerShell.Commands.Utilities { internal static class AzureADGroupsUtility { - internal static async Task GetGroupAsync(PnPConnection connection, Guid groupId, string accessToken) + internal static Group GetGroup(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken) { - var results = await GraphHelper.GetAsync>(connection, $"v1.0/groups?$filter=id eq '{groupId}'", accessToken); + var results = GraphHelper.Get>(cmdlet, connection, $"v1.0/groups?$filter=id eq '{groupId}'", accessToken); if (results != null && results.Items.Any()) { @@ -23,9 +22,9 @@ internal static async Task GetGroupAsync(PnPConnection connection, Guid g return null; } - internal static async Task GetGroupAsync(PnPConnection connection, string displayName, string accessToken) + internal static Group GetGroup(Cmdlet cmdlet, PnPConnection connection, string displayName, string accessToken) { - var results = await GraphHelper.GetAsync>(connection, $"v1.0/groups?$filter=(displayName eq '{displayName}' or mailNickName eq '{displayName}')", accessToken); + var results = GraphHelper.Get>(cmdlet, connection, $"v1.0/groups?$filter=(displayName eq '{displayName}' or mailNickName eq '{displayName}')", accessToken); if (results != null && results.Items.Any()) { @@ -35,15 +34,15 @@ internal static async Task GetGroupAsync(PnPConnection connection, string return null; } - internal static async Task> GetGroupsAsync(PnPConnection connection, string accessToken) + internal static IEnumerable GetGroups(Cmdlet cmdlet, PnPConnection connection, string accessToken) { - var results = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/groups", accessToken, propertyNameCaseInsensitive: true); + var results = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/groups", accessToken, propertyNameCaseInsensitive: true); return results; } - internal static async Task UpdateAsync(PnPConnection connection, string accessToken, Group group) + internal static Group Update(Cmdlet cmdlet, PnPConnection connection, string accessToken, Group group) { - return await GraphHelper.PatchAsync(connection, accessToken, $"v1.0/groups/{group.Id}", group); + return GraphHelper.Patch(cmdlet, connection, accessToken, $"v1.0/groups/{group.Id}", group); } } diff --git a/src/Commands/Utilities/CopyMover.cs b/src/Commands/Utilities/CopyMover.cs index 9234dadeb..c78f0385a 100644 --- a/src/Commands/Utilities/CopyMover.cs +++ b/src/Commands/Utilities/CopyMover.cs @@ -42,7 +42,7 @@ internal static class CopyMover } }; - var results = await REST.RestHelper.PostAsync>(httpClient, $"{currentContextUri}/_api/site/CreateCopyJobs", clientContext, body, false); + var results = REST.RestHelper.Post>(httpClient, $"{currentContextUri}/_api/site/CreateCopyJobs", clientContext, body, false); if (results != null && results.Items.Any()) { @@ -52,7 +52,7 @@ internal static class CopyMover { copyJobInfo = result }; - var copyJob = await Utilities.REST.RestHelper.PostAsync(httpClient, $"{currentContextUri}/_api/site/GetCopyJobProgress", clientContext, copyJobInfo, false); + var copyJob = Utilities.REST.RestHelper.Post(httpClient, $"{currentContextUri}/_api/site/GetCopyJobProgress", clientContext, copyJobInfo, false); if (copyJob != null) { if (noWait) @@ -63,7 +63,7 @@ internal static class CopyMover { // sleep 1 second await Task.Delay(1000); - copyJob = await Utilities.REST.RestHelper.PostAsync(httpClient, $"{currentContextUri}/_api/site/GetCopyJobProgress", clientContext, copyJobInfo, false); + copyJob = Utilities.REST.RestHelper.Post(httpClient, $"{currentContextUri}/_api/site/GetCopyJobProgress", clientContext, copyJobInfo, false); } foreach (var log in copyJob.Logs) { @@ -83,7 +83,7 @@ public static async Task GetCopyMigrationJobStatusAsync(HttpCl { copyJobInfo = jobInfo }; - var copyJob = await Utilities.REST.RestHelper.PostAsync(httpClient, $"{currentContextUri}/_api/site/GetCopyJobProgress", clientContext, copyJobInfo, false); + var copyJob = Utilities.REST.RestHelper.Post(httpClient, $"{currentContextUri}/_api/site/GetCopyJobProgress", clientContext, copyJobInfo, false); if (copyJob != null) { if (!noWait) @@ -92,7 +92,7 @@ public static async Task GetCopyMigrationJobStatusAsync(HttpCl { // sleep 1 second await Task.Delay(1000); - copyJob = await Utilities.REST.RestHelper.PostAsync(httpClient, $"{currentContextUri}/_api/site/GetCopyJobProgress", clientContext, copyJobInfo, false); + copyJob = Utilities.REST.RestHelper.Post(httpClient, $"{currentContextUri}/_api/site/GetCopyJobProgress", clientContext, copyJobInfo, false); } } } diff --git a/src/Commands/Utilities/MailUtility.cs b/src/Commands/Utilities/MailUtility.cs index 2c5909f36..a9ded5ecc 100644 --- a/src/Commands/Utilities/MailUtility.cs +++ b/src/Commands/Utilities/MailUtility.cs @@ -13,6 +13,7 @@ using PnP.PowerShell.Commands.Enums; using System.IO; using System; +using System.Management.Automation; namespace PnP.PowerShell.Commands.Utilities { @@ -29,7 +30,7 @@ internal static class MailUtility /// The message to send /// Boolean indicating if the sent message should be added to the sent items of the sender. Optional. Defaults to true. /// Thrown if sending the e-mail failed - public static async Task SendGraphMail(PnPConnection connection, string accessToken, Message message, bool saveToSentItems = true) + public static void SendGraphMail(Cmdlet cmdlet, PnPConnection connection, string accessToken, Message message, bool saveToSentItems = true) { var jsonSerializer = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, }; jsonSerializer.Converters.Add(new JsonStringEnumConverter()); @@ -37,11 +38,11 @@ public static async Task SendGraphMail(PnPConnection connection, string accessTo var stringContent = new StringContent(JsonSerializer.Serialize(new SendMailMessage { Message = message, SaveToSentItems = saveToSentItems }, jsonSerializer)); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - var response = await GraphHelper.PostAsync(connection, $"v1.0/users/{message.Sender.EmailAddress.Address}/sendMail", accessToken, stringContent); + var response = GraphHelper.Post(cmdlet, connection, $"v1.0/users/{message.Sender.EmailAddress.Address}/sendMail", accessToken, stringContent); if (response.StatusCode != System.Net.HttpStatusCode.Accepted) { - throw new System.Exception($"Error sending e-mail message: {response.ReasonPhrase}. {(await response.Content.ReadAsStringAsync())}"); + throw new System.Exception($"Error sending e-mail message: {response.ReasonPhrase}. {(response.Content.ReadAsStringAsync().GetAwaiter().GetResult())}"); } } @@ -54,7 +55,7 @@ public static async Task SendGraphMail(PnPConnection connection, string accessTo /// List of TO addresses. /// List of CC addresses. Optional. /// List of BCC addresses. Optional. - public static async Task SendSharePointEmail(ClientContext context, string subject, string body, IEnumerable to, IEnumerable cc = null, IEnumerable bcc = null) + public static void SendSharePointEmail(ClientContext context, string subject, string body, IEnumerable to, IEnumerable cc = null, IEnumerable bcc = null) { EmailProperties properties = new EmailProperties { @@ -74,8 +75,8 @@ public static async Task SendSharePointEmail(ClientContext context, string subje properties.Subject = subject; properties.Body = body; - Microsoft.SharePoint.Client.Utilities.Utility.SendEmail(context, properties); - await context.ExecuteQueryRetryAsync(); + Utility.SendEmail(context, properties); + context.ExecuteQueryRetry(); } /// @@ -93,7 +94,7 @@ public static async Task SendSharePointEmail(ClientContext context, string subje /// Username to authenticate to the SMTP server with. Leave NULL to not authenticate. /// Password to authenticate to the SMTP server with. Leave NULL to not authenticate. /// Content type of the body. By default this is HTML. - public static async Task SendSmtpEmail(string subject, string body, string fromAddress, IEnumerable to, IEnumerable cc = null, IEnumerable bcc = null, MessageImportanceType? importance = null, string servername = "smtp.office365.com", short? serverPort = null, bool? enableSsl = null, string username = null, string password = null, MessageBodyContentType contentType = MessageBodyContentType.Html) + public static void SendSmtpEmail(string subject, string body, string fromAddress, IEnumerable to, IEnumerable cc = null, IEnumerable bcc = null, MessageImportanceType? importance = null, string servername = "smtp.office365.com", short? serverPort = null, bool? enableSsl = null, string username = null, string password = null, MessageBodyContentType contentType = MessageBodyContentType.Html) { using SmtpClient client = new SmtpClient(servername) { @@ -152,7 +153,7 @@ public static async Task SendSmtpEmail(string subject, string body, string fromA } } - await client.SendMailAsync(mail); + client.SendMailAsync(mail).GetAwaiter().GetResult(); } /// diff --git a/src/Commands/Utilities/Microsoft365GroupsUtility.cs b/src/Commands/Utilities/Microsoft365GroupsUtility.cs index 29a709bb1..7ab1facd3 100644 --- a/src/Commands/Utilities/Microsoft365GroupsUtility.cs +++ b/src/Commands/Utilities/Microsoft365GroupsUtility.cs @@ -7,12 +7,14 @@ using System.Text.Json; using PnP.PowerShell.Commands.Model; using PnP.PowerShell.Commands.Base; +using System.Management.Automation; +using System.Threading; namespace PnP.PowerShell.Commands.Utilities { - internal static class Microsoft365GroupsUtility + internal static class ClearOwners { - internal static async Task> GetGroupsAsync(PnPConnection connection, string accessToken, bool includeSiteUrl, bool includeOwners, string filter = null, bool includeSensitivityLabels = false) + internal static IEnumerable GetGroups(Cmdlet cmdlet, PnPConnection connection, string accessToken, bool includeSiteUrl, bool includeOwners, string filter = null, bool includeSensitivityLabels = false) { var items = new List(); string requestUrl = "v1.0/groups"; @@ -31,7 +33,7 @@ internal static async Task> GetGroupsAsync(PnPCon { "ConsistencyLevel", "eventual" } }; } - var result = await GraphHelper.GetResultCollectionAsync(connection, requestUrl, accessToken, additionalHeaders: additionalHeaders); + var result = GraphHelper.GetResultCollection(cmdlet, connection, requestUrl, accessToken, additionalHeaders: additionalHeaders); if (result != null && result.Any()) { items.AddRange(result); @@ -43,7 +45,7 @@ internal static async Task> GetGroupsAsync(PnPCon { foreach (var chunk in chunks) { - var ownerResults = await BatchUtility.GetObjectCollectionBatchedAsync(connection, accessToken, chunk.ToArray(), "/groups/{0}/owners"); + var ownerResults = BatchUtility.GetObjectCollectionBatched(cmdlet, connection, accessToken, chunk.ToArray(), "/groups/{0}/owners"); foreach (var ownerResult in ownerResults) { items.First(i => i.Id.ToString() == ownerResult.Key).Owners = ownerResult.Value; @@ -55,7 +57,7 @@ internal static async Task> GetGroupsAsync(PnPCon { foreach (var chunk in chunks) { - var results = await BatchUtility.GetPropertyBatchedAsync(connection, accessToken, chunk.ToArray(), "/groups/{0}/sites/root", "webUrl"); + var results = BatchUtility.GetPropertyBatched(cmdlet, connection, accessToken, chunk.ToArray(), "/groups/{0}/sites/root", "webUrl"); foreach (var batchResult in results) { items.First(i => i.Id.ToString() == batchResult.Key).SiteUrl = batchResult.Value; @@ -66,7 +68,7 @@ internal static async Task> GetGroupsAsync(PnPCon { foreach (var chunk in chunks) { - var sensitivityLabelResults = await BatchUtility.GetObjectCollectionBatchedAsync(connection, accessToken, chunk.ToArray(), "/groups/{0}/assignedLabels"); + var sensitivityLabelResults = BatchUtility.GetObjectCollectionBatched(cmdlet, connection, accessToken, chunk.ToArray(), "/groups/{0}/assignedLabels"); foreach (var sensitivityLabel in sensitivityLabelResults) { items.First(i => i.Id.ToString() == sensitivityLabel.Key).AssignedLabels = sensitivityLabel.Value?.ToList(); @@ -77,9 +79,9 @@ internal static async Task> GetGroupsAsync(PnPCon return items; } - internal static async Task GetGroupAsync(PnPConnection connection, Guid groupId, string accessToken, bool includeSiteUrl, bool includeOwners, bool detailed, bool includeSensitivityLabels) + internal static Microsoft365Group GetGroup(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken, bool includeSiteUrl, bool includeOwners, bool detailed, bool includeSensitivityLabels) { - var results = await GraphHelper.GetAsync>(connection, $"v1.0/groups?$filter=groupTypes/any(c:c+eq+'Unified') and id eq '{groupId}'", accessToken); + var results = GraphHelper.Get>(cmdlet, connection, $"v1.0/groups?$filter=groupTypes/any(c:c+eq+'Unified') and id eq '{groupId}'", accessToken); if (results != null && results.Items.Any()) { @@ -94,7 +96,7 @@ internal static async Task GetGroupAsync(PnPConnection connec iterations++; try { - var siteUrlResult = await GraphHelper.GetAsync(connection, $"v1.0/groups/{group.Id}/sites/root?$select=webUrl", accessToken); + var siteUrlResult = GraphHelper.Get(cmdlet, connection, $"v1.0/groups/{group.Id}/sites/root?$select=webUrl", accessToken); if (!string.IsNullOrEmpty(siteUrlResult)) { wait = false; @@ -114,25 +116,25 @@ internal static async Task GetGroupAsync(PnPConnection connec } else { - await Task.Delay(TimeSpan.FromSeconds(30)); + Thread.Sleep(TimeSpan.FromSeconds(30)); } } } } if (includeOwners) { - group.Owners = await GetGroupMembersAsync("owners", connection, group.Id.Value, accessToken); + group.Owners = GetGroupMembers(cmdlet, "owners", connection, group.Id.Value, accessToken); } if (detailed) { - var exchangeOnlineProperties = await GetGroupExchangeOnlineSettingsAsync(connection, group.Id.Value, accessToken); + var exchangeOnlineProperties = GetGroupExchangeOnlineSettings(cmdlet, connection, group.Id.Value, accessToken); group.AllowExternalSenders = exchangeOnlineProperties.AllowExternalSenders; group.AutoSubscribeNewMembers = exchangeOnlineProperties.AutoSubscribeNewMembers; group.IsSubscribedByMail = exchangeOnlineProperties.IsSubscribedByMail; } if (includeSensitivityLabels) { - var sensitivityLabels = await GetGroupSensitivityLabelsAsync(connection, group.Id.Value, accessToken); + var sensitivityLabels = GetGroupSensitivityLabels(cmdlet, connection, group.Id.Value, accessToken); group.AssignedLabels = sensitivityLabels.AssignedLabels; } return group; @@ -140,15 +142,15 @@ internal static async Task GetGroupAsync(PnPConnection connec return null; } - internal static async Task GetGroupAsync(PnPConnection connection, string displayName, string accessToken, bool includeSiteUrl, bool includeOwners, bool detailed, bool includeSensitivityLabels) + internal static Microsoft365Group GetGroup(Cmdlet cmdlet, PnPConnection connection, string displayName, string accessToken, bool includeSiteUrl, bool includeOwners, bool detailed, bool includeSensitivityLabels) { - var results = await GraphHelper.GetAsync>(connection, $"v1.0/groups?$filter=groupTypes/any(c:c+eq+'Unified') and (displayName eq '{displayName}' or mailNickName eq '{displayName}')", accessToken); + var results = GraphHelper.Get>(cmdlet, connection, $"v1.0/groups?$filter=groupTypes/any(c:c+eq+'Unified') and (displayName eq '{displayName}' or mailNickName eq '{displayName}')", accessToken); if (results != null && results.Items.Any()) { var group = results.Items.First(); if (includeSiteUrl) { - var siteUrlResult = await GraphHelper.GetAsync(connection, $"v1.0/groups/{group.Id}/sites/root?$select=webUrl", accessToken); + var siteUrlResult = GraphHelper.Get(cmdlet, connection, $"v1.0/groups/{group.Id}/sites/root?$select=webUrl", accessToken); var resultElement = JsonSerializer.Deserialize(siteUrlResult); if (resultElement.TryGetProperty("webUrl", out JsonElement webUrlElement)) { @@ -157,18 +159,18 @@ internal static async Task GetGroupAsync(PnPConnection connec } if (includeOwners) { - group.Owners = await GetGroupMembersAsync("owners", connection, group.Id.Value, accessToken); + group.Owners = GetGroupMembers(cmdlet, "owners", connection, group.Id.Value, accessToken); } if (detailed) { - var exchangeOnlineProperties = await GetGroupExchangeOnlineSettingsAsync(connection, group.Id.Value, accessToken); + var exchangeOnlineProperties = GetGroupExchangeOnlineSettings(cmdlet, connection, group.Id.Value, accessToken); group.AllowExternalSenders = exchangeOnlineProperties.AllowExternalSenders; group.AutoSubscribeNewMembers = exchangeOnlineProperties.AutoSubscribeNewMembers; group.IsSubscribedByMail = exchangeOnlineProperties.IsSubscribedByMail; } if (includeSensitivityLabels) { - var sensitivityLabels = await GetGroupSensitivityLabelsAsync(connection, group.Id.Value, accessToken); + var sensitivityLabels = GetGroupSensitivityLabels(cmdlet, connection, group.Id.Value, accessToken); group.AssignedLabels = sensitivityLabels.AssignedLabels; } return group; @@ -176,7 +178,7 @@ internal static async Task GetGroupAsync(PnPConnection connec return null; } - internal static async Task> GetExpiringGroupAsync(PnPConnection connection, string accessToken, int limit, bool includeSiteUrl, bool includeOwners) + internal static IEnumerable GetExpiringGroup(Cmdlet cmdlet, PnPConnection connection, string accessToken, int limit, bool includeSiteUrl, bool includeOwners) { var items = new List(); @@ -189,7 +191,7 @@ internal static async Task> GetExpiringGroupAsync // $count=true needs to be here for reasons // see this for some additional details: https://learn.microsoft.com/en-us/graph/aad-advanced-queries?tabs=http#group-properties - var result = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/groups?$filter=groupTypes/any(c:c+eq+'Unified') and expirationDateTime le {dateStr}&$count=true", accessToken, additionalHeaders: additionalHeaders); + var result = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/groups?$filter=groupTypes/any(c:c+eq+'Unified') and expirationDateTime le {dateStr}&$count=true", accessToken, additionalHeaders: additionalHeaders); if (result != null && result.Any()) { items.AddRange(result); @@ -201,7 +203,7 @@ internal static async Task> GetExpiringGroupAsync { foreach (var chunk in chunks) { - var ownerResults = await BatchUtility.GetObjectCollectionBatchedAsync(connection, accessToken, chunk.ToArray(), "/groups/{0}/owners"); + var ownerResults = BatchUtility.GetObjectCollectionBatched(cmdlet, connection, accessToken, chunk.ToArray(), "/groups/{0}/owners"); foreach (var ownerResult in ownerResults) { items.First(i => i.Id.ToString() == ownerResult.Key).Owners = ownerResult.Value; @@ -213,7 +215,7 @@ internal static async Task> GetExpiringGroupAsync { foreach (var chunk in chunks) { - var results = await BatchUtility.GetPropertyBatchedAsync(connection, accessToken, chunk.ToArray(), "/groups/{0}/sites/root", "webUrl"); + var results = BatchUtility.GetPropertyBatched(cmdlet, connection, accessToken, chunk.ToArray(), "/groups/{0}/sites/root", "webUrl"); //var results = await GetSiteUrlBatchedAsync(connection, accessToken, chunk.ToArray()); foreach (var batchResult in results) { @@ -225,14 +227,14 @@ internal static async Task> GetExpiringGroupAsync return items; } - internal static async Task GetDeletedGroupAsync(PnPConnection connection, Guid groupId, string accessToken) + internal static Microsoft365Group GetDeletedGroup(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken) { - return await GraphHelper.GetAsync(connection, $"v1.0/directory/deleteditems/microsoft.graph.group/{groupId}", accessToken); + return GraphHelper.Get(cmdlet, connection, $"v1.0/directory/deleteditems/microsoft.graph.group/{groupId}", accessToken); } - internal static async Task GetDeletedGroupAsync(PnPConnection connection, string groupName, string accessToken) + internal static Microsoft365Group GetDeletedGroup(Cmdlet cmdlet, PnPConnection connection, string groupName, string accessToken) { - var results = await GraphHelper.GetAsync>(connection, $"v1.0/directory/deleteditems/microsoft.graph.group?$filter=displayName eq '{groupName}' or mailNickname eq '{groupName}'", accessToken); + var results = GraphHelper.Get>(cmdlet, connection, $"v1.0/directory/deleteditems/microsoft.graph.group?$filter=displayName eq '{groupName}' or mailNickname eq '{groupName}'", accessToken); if (results != null && results.Items.Any()) { return results.Items.First(); @@ -240,40 +242,40 @@ internal static async Task GetDeletedGroupAsync(PnPConnection return null; } - internal static async Task> GetDeletedGroupsAsync(PnPConnection connection, string accessToken) + internal static IEnumerable GetDeletedGroups(Cmdlet cmdlet, PnPConnection connection, string accessToken) { - var result = await GraphHelper.GetResultCollectionAsync(connection, "v1.0/directory/deleteditems/microsoft.graph.group", accessToken); + var result = GraphHelper.GetResultCollection(cmdlet, connection, "v1.0/directory/deleteditems/microsoft.graph.group", accessToken); return result; } - internal static async Task RestoreDeletedGroupAsync(PnPConnection connection, Guid groupId, string accessToken) + internal static Microsoft365Group RestoreDeletedGroup(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken) { - return await GraphHelper.PostAsync(connection, $"v1.0/directory/deleteditems/microsoft.graph.group/{groupId}/restore", accessToken); + return GraphHelper.Post(cmdlet, connection, $"v1.0/directory/deleteditems/microsoft.graph.group/{groupId}/restore", accessToken); } - internal static async Task PermanentlyDeleteDeletedGroupAsync(PnPConnection connection, Guid groupId, string accessToken) + internal static void PermanentlyDeleteDeletedGroup(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken) { - await GraphHelper.DeleteAsync(connection, $"v1.0/directory/deleteditems/microsoft.graph.group/{groupId}", accessToken); + GraphHelper.Delete(cmdlet, connection, $"v1.0/directory/deleteditems/microsoft.graph.group/{groupId}", accessToken); } - internal static async Task AddOwnersAsync(PnPConnection connection, Guid groupId, string[] users, string accessToken, bool removeExisting) + internal static void AddOwners(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string[] users, string accessToken, bool removeExisting) { - await AddUsersToGroupAsync("owners", connection, groupId, users, accessToken, removeExisting); + AddUsersToGroup(cmdlet, "owners", connection, groupId, users, accessToken, removeExisting); } - internal static async Task AddDirectoryOwnersAsync(PnPConnection connection, Guid groupId, Guid[] users, string accessToken, bool removeExisting) + internal static void AddDirectoryOwners(Cmdlet cmdlet, PnPConnection connection, Guid groupId, Guid[] users, string accessToken, bool removeExisting) { - await AddDirectoryObjectsToGroupAsync("owners", connection, groupId, users, accessToken, removeExisting); + AddDirectoryObjectsToGroup(cmdlet, "owners", connection, groupId, users, accessToken, removeExisting); } - internal static async Task AddMembersAsync(PnPConnection connection, Guid groupId, string[] users, string accessToken, bool removeExisting) + internal static void AddMembers(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string[] users, string accessToken, bool removeExisting) { - await AddUsersToGroupAsync("members", connection, groupId, users, accessToken, removeExisting); + AddUsersToGroup(cmdlet, "members", connection, groupId, users, accessToken, removeExisting); } - internal static async Task AddDirectoryMembersAsync(PnPConnection connection, Guid groupId, Guid[] users, string accessToken, bool removeExisting) + internal static void AddDirectoryMembers(Cmdlet cmdlet, PnPConnection connection, Guid groupId, Guid[] users, string accessToken, bool removeExisting) { - await AddDirectoryObjectsToGroupAsync("members", connection, groupId, users, accessToken, removeExisting); + AddDirectoryObjectsToGroup(cmdlet, "members", connection, groupId, users, accessToken, removeExisting); } internal static string GetUserGraphUrlForUPN(string upn) @@ -285,11 +287,11 @@ internal static string GetUserGraphUrlForUPN(string upn) return $"users/{escapedUpn}"; } - private static async Task AddUsersToGroupAsync(string groupName, PnPConnection connection, Guid groupId, string[] users, string accessToken, bool removeExisting) + private static void AddUsersToGroup(Cmdlet cmdlet, string groupName, PnPConnection connection, Guid groupId, string[] users, string accessToken, bool removeExisting) { foreach (var user in users) { - var userIdResult = await GraphHelper.GetAsync(connection, $"v1.0/{GetUserGraphUrlForUPN(user)}?$select=Id", accessToken); + var userIdResult = GraphHelper.Get(cmdlet, connection, $"v1.0/{GetUserGraphUrlForUPN(user)}?$select=Id", accessToken); var resultElement = JsonSerializer.Deserialize(userIdResult); if (resultElement.TryGetProperty("id", out JsonElement idProperty)) { @@ -302,12 +304,12 @@ private static async Task AddUsersToGroupAsync(string groupName, PnPConnection c var stringContent = new StringContent(JsonSerializer.Serialize(postData)); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - await GraphHelper.PostAsync(connection, $"v1.0/groups/{groupId}/{groupName}/$ref", accessToken, stringContent); + GraphHelper.Post(cmdlet, connection, $"v1.0/groups/{groupId}/{groupName}/$ref", accessToken, stringContent); } } } - private static async Task AddDirectoryObjectsToGroupAsync(string groupName, PnPConnection connection, Guid groupId, Guid[] directoryObjects, string accessToken, bool removeExisting) + private static void AddDirectoryObjectsToGroup(Cmdlet cmdlet, string groupName, PnPConnection connection, Guid groupId, Guid[] directoryObjects, string accessToken, bool removeExisting) { foreach (var dirObject in directoryObjects) { @@ -320,125 +322,125 @@ private static async Task AddDirectoryObjectsToGroupAsync(string groupName, PnPC var stringContent = new StringContent(JsonSerializer.Serialize(postData)); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - await GraphHelper.PostAsync(connection, $"v1.0/groups/{groupId}/{groupName}/$ref", accessToken, stringContent); + GraphHelper.Post(cmdlet, connection, $"v1.0/groups/{groupId}/{groupName}/$ref", accessToken, stringContent); } } - internal static async Task RemoveOwnersAsync(PnPConnection connection, Guid groupId, string[] users, string accessToken) + internal static void RemoveOwners(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string[] users, string accessToken) { - await RemoveUserFromGroupAsync("owners", connection, groupId, users, accessToken); + RemoveUserFromGroup(cmdlet, "owners", connection, groupId, users, accessToken); } - internal static async Task RemoveMembersAsync(PnPConnection connection, Guid groupId, string[] users, string accessToken) + internal static void RemoveMembers(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string[] users, string accessToken) { - await RemoveUserFromGroupAsync("members", connection, groupId, users, accessToken); + RemoveUserFromGroup(cmdlet, "members", connection, groupId, users, accessToken); } - private static async Task RemoveUserFromGroupAsync(string groupName, PnPConnection connection, Guid groupId, string[] users, string accessToken) + private static void RemoveUserFromGroup(Cmdlet cmdlet, string groupName, PnPConnection connection, Guid groupId, string[] users, string accessToken) { foreach (var user in users) { - var resultString = await GraphHelper.GetAsync(connection, $"v1.0/{GetUserGraphUrlForUPN(user)}?$select=Id", accessToken); + var resultString = GraphHelper.Get(cmdlet, connection, $"v1.0/{GetUserGraphUrlForUPN(user)}?$select=Id", accessToken); var resultElement = JsonSerializer.Deserialize(resultString); if (resultElement.TryGetProperty("id", out JsonElement idElement)) { - await GraphHelper.DeleteAsync(connection, $"v1.0/groups/{groupId}/{groupName}/{idElement.GetString()}/$ref", accessToken); + GraphHelper.Delete(cmdlet, connection, $"v1.0/groups/{groupId}/{groupName}/{idElement.GetString()}/$ref", accessToken); } } } - internal static async Task RemoveGroupAsync(PnPConnection connection, Guid groupId, string accessToken) + internal static void RemoveGroup(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken) { - await GraphHelper.DeleteAsync(connection, $"v1.0/groups/{groupId}", accessToken); + GraphHelper.Delete(cmdlet, connection, $"v1.0/groups/{groupId}", accessToken); } - internal static async Task> GetOwnersAsync(PnPConnection connection, Guid groupId, string accessToken) + internal static IEnumerable GetOwners(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken) { - return await GetGroupMembersAsync("owners", connection, groupId, accessToken); + return GetGroupMembers(cmdlet, "owners", connection, groupId, accessToken); } - internal static async Task> GetMembersAsync(PnPConnection connection, Guid groupId, string accessToken) + internal static IEnumerable GetMembers(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken) { - return await GetGroupMembersAsync("members", connection, groupId, accessToken); + return GetGroupMembers(cmdlet, "members", connection, groupId, accessToken); } - private static async Task> GetGroupMembersAsync(string userType, PnPConnection connection, Guid groupId, string accessToken) + private static IEnumerable GetGroupMembers(Cmdlet cmdlet, string userType, PnPConnection connection, Guid groupId, string accessToken) { - var results = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/groups/{groupId}/{userType}?$select=*", accessToken); + var results = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/groups/{groupId}/{userType}?$select=*", accessToken); return results; } - private static async Task GetGroupExchangeOnlineSettingsAsync(PnPConnection connection, Guid groupId, string accessToken) + private static Microsoft365Group GetGroupExchangeOnlineSettings(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken) { - var results = await GraphHelper.GetAsync(connection, $"v1.0/groups/{groupId}?$select=allowExternalSenders,isSubscribedByMail,autoSubscribeNewMembers", accessToken); + var results = GraphHelper.Get(cmdlet, connection, $"v1.0/groups/{groupId}?$select=allowExternalSenders,isSubscribedByMail,autoSubscribeNewMembers", accessToken); return results; } - private static async Task GetGroupSensitivityLabelsAsync(PnPConnection connection, Guid groupId, string accessToken) + private static Microsoft365Group GetGroupSensitivityLabels(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken) { - var results = await GraphHelper.GetAsync(connection, $"v1.0/groups/{groupId}?$select=assignedLabels", accessToken); + var results = GraphHelper.Get(cmdlet, connection, $"v1.0/groups/{groupId}?$select=assignedLabels", accessToken); return results; } - internal static async Task ClearMembersAsync(PnPConnection connection, Guid groupId, string accessToken) + internal static void ClearMembers(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken) { - var members = await GetMembersAsync(connection, groupId, accessToken); + var members = GetMembers(cmdlet, connection, groupId, accessToken); foreach (var member in members) { - await GraphHelper.DeleteAsync(connection, $"v1.0/groups/{groupId}/members/{member.Id}/$ref", accessToken); + GraphHelper.Delete(cmdlet, connection, $"v1.0/groups/{groupId}/members/{member.Id}/$ref", accessToken); } } - internal static async Task ClearOwnersAsync(PnPConnection connection, Guid groupId, string accessToken) + internal static void ClearOwnersAsync(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken) { - var members = await GetOwnersAsync(connection, groupId, accessToken); + var members = GetOwners(cmdlet, connection, groupId, accessToken); foreach (var member in members) { - await GraphHelper.DeleteAsync(connection, $"v1.0/groups/{groupId}/owners/{member.Id}/$ref", accessToken); + GraphHelper.Delete(cmdlet, connection, $"v1.0/groups/{groupId}/owners/{member.Id}/$ref", accessToken); } } - internal static async Task UpdateOwnersAsync(PnPConnection connection, Guid groupId, string accessToken, string[] owners) + internal static void UpdateOwners(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken, string[] owners) { - var existingOwners = await GetOwnersAsync(connection, groupId, accessToken); + var existingOwners = GetOwners(cmdlet, connection, groupId, accessToken); foreach (var owner in owners) { if (existingOwners.FirstOrDefault(o => o.UserPrincipalName == owner) == null) { - await AddOwnersAsync(connection, groupId, new string[] { owner }, accessToken, false); + AddOwners(cmdlet, connection, groupId, new string[] { owner }, accessToken, false); } } foreach (var existingOwner in existingOwners) { if (!owners.Contains(existingOwner.UserPrincipalName)) { - await GraphHelper.DeleteAsync(connection, $"v1.0/groups/{groupId}/owners/{existingOwner.Id}/$ref", accessToken); + GraphHelper.Delete(cmdlet, connection, $"v1.0/groups/{groupId}/owners/{existingOwner.Id}/$ref", accessToken); } } } - internal static async Task UpdateMembersAsync(PnPConnection connection, Guid groupId, string accessToken, string[] members) + internal static void UpdateMembersAsync(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken, string[] members) { - var existingMembers = await GetMembersAsync(connection, groupId, accessToken); + var existingMembers = GetMembers(cmdlet, connection, groupId, accessToken); foreach (var member in members) { if (existingMembers.FirstOrDefault(o => o.UserPrincipalName == member) == null) { - await AddMembersAsync(connection, groupId, new string[] { member }, accessToken, false); + AddMembers(cmdlet, connection, groupId, new string[] { member }, accessToken, false); } } foreach (var existingMember in existingMembers) { if (!members.Contains(existingMember.UserPrincipalName)) { - await GraphHelper.DeleteAsync(connection, $"v1.0/groups/{groupId}/members/{existingMember.Id}/$ref", accessToken); + GraphHelper.Delete(cmdlet, connection, $"v1.0/groups/{groupId}/members/{existingMember.Id}/$ref", accessToken); } } } - internal static async Task UpdateExchangeOnlineSettingAsync(PnPConnection connection, Guid groupId, string accessToken, Microsoft365Group group) + internal static Microsoft365Group UpdateExchangeOnlineSetting(Cmdlet cmdlet, PnPConnection connection, Guid groupId, string accessToken, Microsoft365Group group) { var patchData = new { @@ -446,7 +448,7 @@ internal static async Task UpdateExchangeOnlineSettingAsync(P group.AutoSubscribeNewMembers }; - var result = await GraphHelper.PatchAsync(connection, accessToken, $"v1.0/groups/{groupId}", patchData); + var result = GraphHelper.Patch(cmdlet, connection, accessToken, $"v1.0/groups/{groupId}", patchData); group.AllowExternalSenders = result.AllowExternalSenders; group.AutoSubscribeNewMembers = result.AutoSubscribeNewMembers; @@ -454,7 +456,7 @@ internal static async Task UpdateExchangeOnlineSettingAsync(P return group; } - internal static async Task> GetSiteUrlBatchedAsync(PnPConnection connection, string accessToken, string[] groupIds) + internal static Dictionary GetSiteUrlBatched(Cmdlet cmdlet, PnPConnection connection, string accessToken, string[] groupIds) { Dictionary returnValue = new Dictionary(); @@ -469,7 +471,7 @@ internal static async Task> GetSiteUrlBatchedAsync(Pn } var stringContent = new StringContent(JsonSerializer.Serialize(batch)); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - var result = await GraphHelper.PostAsync(connection, "v1.0/$batch", stringContent, accessToken); + var result = GraphHelper.Post(cmdlet, connection, "v1.0/$batch", stringContent, accessToken); if (result.Responses != null && result.Responses.Any()) { foreach (var response in result.Responses) @@ -485,7 +487,7 @@ internal static async Task> GetSiteUrlBatchedAsync(Pn return returnValue; } - internal static async Task> GetUserIdsBatched(PnPConnection connection, string accessToken, string[] userPrincipalNames) + internal static Dictionary GetUserIdsBatched(Cmdlet cmdlet, PnPConnection connection, string accessToken, string[] userPrincipalNames) { Dictionary returnValue = new Dictionary(); @@ -500,7 +502,7 @@ internal static async Task> GetUserIdsBatched(PnPConn } var stringContent = new StringContent(JsonSerializer.Serialize(batch)); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - var result = await GraphHelper.PostAsync(connection, "v1.0/$batch", stringContent, accessToken); + var result = GraphHelper.Post(cmdlet, connection, "v1.0/$batch", stringContent, accessToken); if (result.Responses != null && result.Responses.Any()) { foreach (var response in result.Responses) @@ -516,9 +518,9 @@ internal static async Task> GetUserIdsBatched(PnPConn return returnValue; } - internal static async Task GetUsersDataBindValueAsync(PnPConnection connection, string accessToken, string[] users) + internal static string[] GetUsersDataBindValue(Cmdlet cmdlet, PnPConnection connection, string accessToken, string[] users) { - var userids = await GetUserIdsBatched(connection, accessToken, users); + var userids = GetUserIdsBatched(cmdlet, connection, accessToken, users); if (userids.Any()) { return userids.Select(u => $"https://{connection.GraphEndPoint}/v1.0/users/{u.Value}").ToArray(); @@ -526,16 +528,16 @@ internal static async Task GetUsersDataBindValueAsync(PnPConnection co return null; } - internal static async Task CreateAsync(PnPConnection connection, string accessToken, Microsoft365Group group, bool createTeam, string logoPath, string[] owners, string[] members, bool? hideFromAddressLists, bool? hideFromOutlookClients, List sensitivityLabels) + internal static Microsoft365Group Create(Cmdlet cmdlet, PnPConnection connection, string accessToken, Microsoft365Group group, bool createTeam, string logoPath, string[] owners, string[] members, bool? hideFromAddressLists, bool? hideFromOutlookClients, List sensitivityLabels) { if (owners != null && owners.Length > 0) { - group.OwnersODataBind = await GetUsersDataBindValueAsync(connection, accessToken, owners); + group.OwnersODataBind = GetUsersDataBindValue(cmdlet, connection, accessToken, owners); } if (members != null && members.Length > 0) { - group.MembersODataBind = await GetUsersDataBindValueAsync(connection, accessToken, members); + group.MembersODataBind = GetUsersDataBindValue(cmdlet, connection, accessToken, members); } if (sensitivityLabels.Count > 0) @@ -555,27 +557,27 @@ internal static async Task CreateAsync(PnPConnection connecti group.AssignedLabels = assignedLabels; } - var newGroup = await GraphHelper.PostAsync(connection, "v1.0/groups", group, accessToken); + var newGroup = GraphHelper.Post(cmdlet, connection, "v1.0/groups", group, accessToken); if (hideFromAddressLists.HasValue || hideFromOutlookClients.HasValue) { - await SetVisibilityAsync(connection, accessToken, newGroup.Id.Value, hideFromAddressLists, hideFromOutlookClients); + SetVisibility(cmdlet, connection, accessToken, newGroup.Id.Value, hideFromAddressLists, hideFromOutlookClients); } if (!string.IsNullOrEmpty(logoPath)) { - await UploadLogoAsync(connection, accessToken, newGroup.Id.Value, logoPath); + UploadLogoAsync(cmdlet, connection, accessToken, newGroup.Id.Value, logoPath); } if (createTeam) { - await CreateTeamAsync(connection, accessToken, newGroup.Id.Value); + CreateTeam(cmdlet, connection, accessToken, newGroup.Id.Value); } return newGroup; } - internal static async Task UploadLogoAsync(PnPConnection connection, string accessToken, Guid groupId, string logoPath) + internal static void UploadLogoAsync(Cmdlet cmdlet, PnPConnection connection, string accessToken, Guid groupId, string logoPath) { var fileBytes = System.IO.File.ReadAllBytes(logoPath); @@ -608,14 +610,14 @@ internal static async Task UploadLogoAsync(PnPConnection connection, string acce var retryCount = 10; while (retryCount > 0) { - var responseMessage = await GraphHelper.PutAsync(connection, $"/v1.0/groups/{groupId}/photo/$value", accessToken, content); + var responseMessage = GraphHelper.Put(cmdlet, connection, $"/v1.0/groups/{groupId}/photo/$value", accessToken, content); if (responseMessage.IsSuccessStatusCode) { updated = true; } if (!updated) { - await Task.Delay(500 * (10 - retryCount)); + Thread.Sleep(500 * (10 - retryCount)); retryCount--; } else @@ -630,7 +632,7 @@ internal static async Task UploadLogoAsync(PnPConnection connection, string acce } } - internal static async Task CreateTeamAsync(PnPConnection connection, string accessToken, Guid groupId) + internal static void CreateTeam(Cmdlet cmdlet, PnPConnection connection, string accessToken, Guid groupId) { var createTeamEndPoint = $"v1.0/groups/{groupId}/team"; bool wait = true; @@ -641,7 +643,7 @@ internal static async Task CreateTeamAsync(PnPConnection connection, string acce iterations++; try { - var teamId = await GraphHelper.PutAsync(connection, createTeamEndPoint, new { }, accessToken); + var teamId = GraphHelper.Put(cmdlet, connection, createTeamEndPoint, new { }, accessToken); if (teamId != null) { wait = false; @@ -656,23 +658,23 @@ internal static async Task CreateTeamAsync(PnPConnection connection, string acce } else { - await Task.Delay(TimeSpan.FromSeconds(30)); + Thread.Sleep(TimeSpan.FromSeconds(30)); } } } } - internal static async Task RenewAsync(PnPConnection connection, string accessToken, Guid groupId) + internal static void Renew(Cmdlet cmdlet, PnPConnection connection, string accessToken, Guid groupId) { - await GraphHelper.PostAsync(connection, $"v1.0/groups/{groupId}/renew", new { }, accessToken); + GraphHelper.Post(cmdlet, connection, $"v1.0/groups/{groupId}/renew", new { }, accessToken); } - internal static async Task UpdateAsync(PnPConnection connection, string accessToken, Microsoft365Group group) + internal static Microsoft365Group Update(Cmdlet cmdlet, PnPConnection connection, string accessToken, Microsoft365Group group) { - return await GraphHelper.PatchAsync(connection, accessToken, $"v1.0/groups/{group.Id}", group); + return GraphHelper.Patch(cmdlet, connection, accessToken, $"v1.0/groups/{group.Id}", group); } - internal static async Task SetVisibilityAsync(PnPConnection connection, string accessToken, Guid groupId, bool? hideFromAddressLists, bool? hideFromOutlookClients) + internal static void SetVisibility(Cmdlet cmdlet, PnPConnection connection, string accessToken, Guid groupId, bool? hideFromAddressLists, bool? hideFromOutlookClients) { var patchData = new { @@ -686,13 +688,13 @@ internal static async Task SetVisibilityAsync(PnPConnection connection, string a { try { - await GraphHelper.PatchAsync(connection, accessToken, $"v1.0/groups/{groupId}", patchData); + GraphHelper.Patch(cmdlet, connection, accessToken, $"v1.0/groups/{groupId}", patchData); retry = false; } catch (Exception) { - await Task.Delay(5000); + Thread.Sleep(5000); iteration++; } @@ -703,71 +705,71 @@ internal static async Task SetVisibilityAsync(PnPConnection connection, string a } } - internal static async Task GetGroupSettingsAsync(PnPConnection connection, string accessToken) + internal static Microsoft365GroupSettingValueCollection GetGroupSettings(Cmdlet cmdlet, PnPConnection connection, string accessToken) { - var result = await GraphHelper.GetAsync(connection, "v1.0/groupSettings", accessToken, propertyNameCaseInsensitive: true); + var result = GraphHelper.Get(cmdlet, connection, "v1.0/groupSettings", accessToken, propertyNameCaseInsensitive: true); return result; } - internal static async Task GetGroupSettingsAsync(PnPConnection connection, string accessToken, string groupId) + internal static Microsoft365GroupSettingValueCollection GetGroupSettings(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId) { - var result = await GraphHelper.GetAsync(connection, $"v1.0/groups/{groupId}/settings", accessToken, propertyNameCaseInsensitive: true); + var result = GraphHelper.Get(cmdlet, connection, $"v1.0/groups/{groupId}/settings", accessToken, propertyNameCaseInsensitive: true); return result; } - internal static async Task CreateGroupSetting(PnPConnection connection, string accessToken, dynamic groupSettingObject) + internal static Microsoft365GroupSetting CreateGroupSetting(Cmdlet cmdlet, PnPConnection connection, string accessToken, dynamic groupSettingObject) { var stringContent = new StringContent(JsonSerializer.Serialize(groupSettingObject)); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - var result = await GraphHelper.PostAsync(connection, "v1.0/groupSettings", stringContent, accessToken, propertyNameCaseInsensitive: true); + var result = GraphHelper.Post(cmdlet, connection, "v1.0/groupSettings", stringContent, accessToken, propertyNameCaseInsensitive: true); return result; } - internal static async Task CreateGroupSetting(PnPConnection connection, string accessToken, string groupId, dynamic groupSettingObject) + internal static Microsoft365GroupSetting CreateGroupSetting(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, dynamic groupSettingObject) { var stringContent = new StringContent(JsonSerializer.Serialize(groupSettingObject)); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - var result = await GraphHelper.PostAsync(connection, $"v1.0/groups/{groupId}/settings", stringContent, accessToken, propertyNameCaseInsensitive: true); + var result = GraphHelper.Post(cmdlet, connection, $"v1.0/groups/{groupId}/settings", stringContent, accessToken, propertyNameCaseInsensitive: true); return result; } - internal static async Task UpdateGroupSetting(PnPConnection connection, string accessToken, string id, dynamic groupSettingObject) + internal static void UpdateGroupSetting(Cmdlet cmdlet, PnPConnection connection, string accessToken, string id, dynamic groupSettingObject) { var stringContent = new StringContent(JsonSerializer.Serialize(groupSettingObject)); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - await GraphHelper.PatchAsync(connection, accessToken, stringContent, $"v1.0/groupSettings/{id}"); + GraphHelper.Patch(cmdlet, connection, accessToken, stringContent, $"v1.0/groupSettings/{id}"); } - internal static async Task UpdateGroupSetting(PnPConnection connection, string accessToken, string id, string groupId, dynamic groupSettingObject) + internal static void UpdateGroupSetting(Cmdlet cmdlet, PnPConnection connection, string accessToken, string id, string groupId, dynamic groupSettingObject) { var stringContent = new StringContent(JsonSerializer.Serialize(groupSettingObject)); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - await GraphHelper.PatchAsync(connection, accessToken, stringContent, $"v1.0/groups/{groupId}/settings/{id}"); + GraphHelper.Patch(cmdlet, connection, accessToken, stringContent, $"v1.0/groups/{groupId}/settings/{id}"); } - internal static async Task RemoveGroupSetting(PnPConnection connection, string accessToken, string id) + internal static void RemoveGroupSetting(Cmdlet cmdlet, PnPConnection connection, string accessToken, string id) { - await GraphHelper.DeleteAsync(connection, $"v1.0/groupSettings/{id}", accessToken); + GraphHelper.Delete(cmdlet, connection, $"v1.0/groupSettings/{id}", accessToken); } - internal static async Task RemoveGroupSetting(PnPConnection connection, string accessToken, string id, string groupId) + internal static void RemoveGroupSetting(Cmdlet cmdlet, PnPConnection connection, string accessToken, string id, string groupId) { - await GraphHelper.DeleteAsync(connection, $"v1.0/groups/{groupId}/settings/{id}", accessToken); + GraphHelper.Delete(cmdlet, connection, $"v1.0/groups/{groupId}/settings/{id}", accessToken); } - internal static async Task GetGroupTemplateSettingsAsync(PnPConnection connection, string accessToken) + internal static Microsoft365GroupTemplateSettingValueCollection GetGroupTemplateSettings(Cmdlet cmdlet, PnPConnection connection, string accessToken) { - var result = await GraphHelper.GetAsync(connection, "v1.0/groupSettingTemplates", accessToken, propertyNameCaseInsensitive: true); + var result = GraphHelper.Get(cmdlet, connection, "v1.0/groupSettingTemplates", accessToken, propertyNameCaseInsensitive: true); return result; } - internal static async Task GetGroupTemplateSettingsAsync(PnPConnection connection, string accessToken, string id) + internal static Microsoft365GroupSettingTemplate GetGroupTemplateSettings(Cmdlet cmdlet, PnPConnection connection, string accessToken, string id) { - var result = await GraphHelper.GetAsync(connection, $"v1.0/groupSettingTemplates/{id}", accessToken, propertyNameCaseInsensitive: true); + var result = GraphHelper.Get(cmdlet, connection, $"v1.0/groupSettingTemplates/{id}", accessToken, propertyNameCaseInsensitive: true); return result; } - internal static async Task SetSensitivityLabelsAsync(PnPConnection connection, string accessToken, Guid groupId, List assignedLabels) + internal static void SetSensitivityLabels(Cmdlet cmdlet, PnPConnection connection, string accessToken, Guid groupId, List assignedLabels) { var patchData = new { @@ -780,13 +782,13 @@ internal static async Task SetSensitivityLabelsAsync(PnPConnection connection, s { try { - await GraphHelper.PatchAsync(connection, accessToken, $"v1.0/groups/{groupId}", patchData); + GraphHelper.Patch(cmdlet, connection, accessToken, $"v1.0/groups/{groupId}", patchData); retry = false; } catch (Exception) { - await Task.Delay(5000); + Thread.Sleep(5000); iteration++; } @@ -797,9 +799,9 @@ internal static async Task SetSensitivityLabelsAsync(PnPConnection connection, s } } - internal static async Task DeletePhotoAsync(PnPConnection connection, string accessToken, Guid groupId) + internal static HttpResponseMessage DeletePhoto(Cmdlet cmdlet, PnPConnection connection, string accessToken, Guid groupId) { - return await GraphHelper.DeleteAsync(connection, $"v1.0/groups/{groupId}/photo/$value", accessToken); + return GraphHelper.Delete(cmdlet, connection, $"v1.0/groups/{groupId}/photo/$value", accessToken); } } } \ No newline at end of file diff --git a/src/Commands/Utilities/PlannerUtility.cs b/src/Commands/Utilities/PlannerUtility.cs index 1f3e91a14..941598a9a 100644 --- a/src/Commands/Utilities/PlannerUtility.cs +++ b/src/Commands/Utilities/PlannerUtility.cs @@ -4,6 +4,7 @@ using PnP.PowerShell.Commands.Utilities.REST; using System.Collections.Generic; using System.Linq; +using System.Management.Automation; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; @@ -13,19 +14,19 @@ namespace PnP.PowerShell.Commands.Utilities internal static class PlannerUtility { #region Plans - public static async Task> GetPlansAsync(PnPConnection connection, string accessToken, string groupId, bool resolveDisplayNames) + public static IEnumerable GetPlans(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, bool resolveDisplayNames) { var returnCollection = new List(); - var collection = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/groups/{groupId}/planner/plans", accessToken); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/groups/{groupId}/planner/plans", accessToken); if (collection != null && collection.Any()) { if (resolveDisplayNames) { foreach (var plan in collection) { - var fullIdentity = await ResolveIdentityAsync(connection, accessToken, plan.CreatedBy.User); + var fullIdentity = ResolveIdentity(cmdlet, connection, accessToken, plan.CreatedBy.User); plan.CreatedBy.User = fullIdentity; - var owner = await ResolveGroupName(connection, accessToken, plan.Owner); + var owner = ResolveGroupName(cmdlet, connection, accessToken, plan.Owner); plan.Owner = owner; returnCollection.Add(plan); } @@ -38,48 +39,48 @@ public static async Task> GetPlansAsync(PnPConnection c return returnCollection; } - public static async Task GetPlanAsync(PnPConnection connection, string accessToken, string planId, bool resolveDisplayNames) + public static PlannerPlan GetPlan(Cmdlet cmdlet, PnPConnection connection, string accessToken, string planId, bool resolveDisplayNames) { - var plan = await GraphHelper.GetAsync(connection, $"v1.0/planner/plans/{planId}", accessToken); + var plan = GraphHelper.Get(cmdlet, connection, $"v1.0/planner/plans/{planId}", accessToken); if (resolveDisplayNames) { - plan.CreatedBy.User = await ResolveIdentityAsync(connection, accessToken, plan.CreatedBy.User); + plan.CreatedBy.User = ResolveIdentity(cmdlet, connection, accessToken, plan.CreatedBy.User); } return plan; } - public static async Task CreatePlanAsync(PnPConnection connection, string accessToken, string groupId, string title) + public static PlannerPlan CreatePlan(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string title) { var stringContent = new StringContent(JsonSerializer.Serialize(new { owner = groupId, title = title })); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - return await GraphHelper.PostAsync(connection, "v1.0/planner/plans", stringContent, accessToken); + return GraphHelper.Post(cmdlet, connection, "v1.0/planner/plans", stringContent, accessToken); } - public static async Task UpdatePlanAsync(PnPConnection connection, string accessToken, PlannerPlan plan, string title) + public static PlannerPlan UpdatePlan(Cmdlet cmdlet, PnPConnection connection, string accessToken, PlannerPlan plan, string title) { var stringContent = new StringContent(JsonSerializer.Serialize(new { title })); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - var responseMessage = await GraphHelper.PatchAsync(connection, accessToken, stringContent, $"v1.0/planner/plans/{plan.Id}", new Dictionary() { { "IF-MATCH", plan.ETag } }); + var responseMessage = GraphHelper.Patch(cmdlet, connection, accessToken, stringContent, $"v1.0/planner/plans/{plan.Id}", new Dictionary() { { "IF-MATCH", plan.ETag } }); while (responseMessage.StatusCode == System.Net.HttpStatusCode.PreconditionFailed) { // retrieve the plan again - plan = await GraphHelper.GetAsync(connection, $"v1.0/planner/plans/{plan.Id}", accessToken); - responseMessage = await GraphHelper.PatchAsync(connection, accessToken, stringContent, $"v1.0/planner/plans/{plan.Id}", new Dictionary() { { "IF-MATCH", plan.ETag } }); + plan = GraphHelper.Get(cmdlet, connection, $"v1.0/planner/plans/{plan.Id}", accessToken); + responseMessage = GraphHelper.Patch(cmdlet, connection, accessToken, stringContent, $"v1.0/planner/plans/{plan.Id}", new Dictionary() { { "IF-MATCH", plan.ETag } }); } if (responseMessage.IsSuccessStatusCode) { - var responseContent = await responseMessage.Content.ReadAsStringAsync(); + var responseContent = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult(); return JsonSerializer.Deserialize(responseContent); } return null; } - public static async Task DeletePlanAsync(PnPConnection connection, string accessToken, string planId) + public static void DeletePlan(Cmdlet cmdlet, PnPConnection connection, string accessToken, string planId) { - var plan = await GetPlanAsync(connection, accessToken, planId, false); + var plan = GetPlan(cmdlet, connection, accessToken, planId, false); if (plan != null) { - await GraphHelper.DeleteAsync(connection, $"v1.0/planner/plans/{planId}", accessToken, new Dictionary() { { "IF-MATCH", plan.ETag } }); + GraphHelper.Delete(cmdlet, connection, $"v1.0/planner/plans/{planId}", accessToken, new Dictionary() { { "IF-MATCH", plan.ETag } }); } } @@ -87,23 +88,23 @@ public static async Task DeletePlanAsync(PnPConnection connection, string access #region Tasks - public static async Task> GetTasksAsync(PnPConnection connection, string accessToken, string planId, bool resolveDisplayNames) + public static IEnumerable GetTasks(Cmdlet cmdlet, PnPConnection connection, string accessToken, string planId, bool resolveDisplayNames) { var returnCollection = new List(); - var collection = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/planner/plans/{planId}/tasks", accessToken); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/planner/plans/{planId}/tasks", accessToken); if (collection != null && collection.Any()) { if (resolveDisplayNames) { foreach (var task in collection) { - var fullIdentity = await ResolveIdentityAsync(connection, accessToken, task.CreatedBy.User); + var fullIdentity = ResolveIdentity(cmdlet, connection, accessToken, task.CreatedBy.User); task.CreatedBy.User = fullIdentity; if (task.Assignments != null) { foreach (var assignment in task.Assignments) { - assignment.Value.AssignedBy.User = await ResolveIdentityAsync(connection, accessToken, assignment.Value.AssignedBy.User); + assignment.Value.AssignedBy.User = ResolveIdentity(cmdlet, connection, accessToken, assignment.Value.AssignedBy.User); } } returnCollection.Add(task); @@ -117,24 +118,24 @@ public static async Task> GetTasksAsync(PnPConnection c return returnCollection; } - public static async Task GetTaskAsync(PnPConnection connection, string accessToken, string taskId, bool resolveDisplayNames, bool includeDetails) + public static PlannerTask GetTask(Cmdlet cmdlet, PnPConnection connection, string accessToken, string taskId, bool resolveDisplayNames, bool includeDetails) { - var task = await GraphHelper.GetAsync(connection, $"v1.0/planner/tasks/{taskId}", accessToken); + var task = GraphHelper.Get(cmdlet, connection, $"v1.0/planner/tasks/{taskId}", accessToken); if (resolveDisplayNames) { - task.CreatedBy.User = await ResolveIdentityAsync(connection, accessToken, task.CreatedBy.User); + task.CreatedBy.User = ResolveIdentity(cmdlet, connection, accessToken, task.CreatedBy.User); } if (includeDetails) { - var taskDetails = await GetTaskDetailsAsync(connection, accessToken, taskId, resolveDisplayNames); + var taskDetails = GetTaskDetails(cmdlet,connection, accessToken, taskId, resolveDisplayNames); task.Details = taskDetails; } return task; } - public static async Task GetTaskDetailsAsync(PnPConnection connection, string accessToken, string taskId, bool resolveDisplayNames) + public static PlannerTaskDetails GetTaskDetails(Cmdlet cmdlet, PnPConnection connection, string accessToken, string taskId, bool resolveDisplayNames) { - var taskDetails = await GraphHelper.GetAsync(connection, $"v1.0/planner/tasks/{taskId}/details", accessToken); + var taskDetails = GraphHelper.Get(cmdlet, connection, $"v1.0/planner/tasks/{taskId}/details", accessToken); if (!resolveDisplayNames) return taskDetails; @@ -152,7 +153,7 @@ public static async Task GetTaskDetailsAsync(PnPConnection c { newCheckListItem.LastModifiedBy = new IdentitySet { - User = await ResolveIdentityAsync(connection, accessToken, checklistItem.Value.LastModifiedBy.User) + User = ResolveIdentity(cmdlet, connection, accessToken, checklistItem.Value.LastModifiedBy.User) }; } newItems.Add(checklistItem.Key, newCheckListItem); @@ -162,32 +163,32 @@ public static async Task GetTaskDetailsAsync(PnPConnection c return taskDetails; } - public static async Task AddTaskAsync(PnPConnection connection, string accessToken, PlannerTask task) + public static PlannerTask AddTask(Cmdlet cmdlet, PnPConnection connection, string accessToken, PlannerTask task) { - return await GraphHelper.PostAsync(connection, "v1.0/planner/tasks", task, accessToken); + return GraphHelper.Post(cmdlet, connection, "v1.0/planner/tasks", task, accessToken); } - public static async Task DeleteTaskAsync(PnPConnection connection, string accessToken, string taskId) + public static void DeleteTask(Cmdlet cmdlet, PnPConnection connection, string accessToken, string taskId) { - var task = await GraphHelper.GetAsync(connection, $"v1.0/planner/tasks/{taskId}", accessToken); + var task = GraphHelper.Get(cmdlet, connection, $"v1.0/planner/tasks/{taskId}", accessToken); if (task != null) { - await GraphHelper.DeleteAsync(connection, $"v1.0/planner/tasks/{taskId}", accessToken, new Dictionary() { { "IF-MATCH", task.ETag } }); + GraphHelper.Delete(cmdlet, connection, $"v1.0/planner/tasks/{taskId}", accessToken, new Dictionary() { { "IF-MATCH", task.ETag } }); } } - public static async Task UpdateTaskAsync(PnPConnection connection, string accessToken, PlannerTask taskToUpdate, PlannerTask task) + public static PlannerTask UpdateTask(Cmdlet cmdlet, PnPConnection connection, string accessToken, PlannerTask taskToUpdate, PlannerTask task) { - return await GraphHelper.PatchAsync(connection, accessToken, $"v1.0/planner/tasks/{taskToUpdate.Id}", task, new Dictionary { { "IF-MATCH", taskToUpdate.ETag } }); + return GraphHelper.Patch(cmdlet, connection, accessToken, $"v1.0/planner/tasks/{taskToUpdate.Id}", task, new Dictionary { { "IF-MATCH", taskToUpdate.ETag } }); } - public static async Task UpdateTaskDetailsAsync(PnPConnection connection, string accessToken, PlannerTaskDetails taskToUpdate, string description) + public static void UpdateTaskDetails(Cmdlet cmdlet, PnPConnection connection, string accessToken, PlannerTaskDetails taskToUpdate, string description) { var body = new PlannerTaskDetails { Description = description, }; - await GraphHelper.PatchAsync(connection, accessToken, $"v1.0/planner/tasks/{taskToUpdate.Id}/details", body, new Dictionary { { "IF-MATCH", taskToUpdate.ETag } }); + GraphHelper.Patch(cmdlet, connection, accessToken, $"v1.0/planner/tasks/{taskToUpdate.Id}/details", body, new Dictionary { { "IF-MATCH", taskToUpdate.ETag } }); } #endregion @@ -200,11 +201,11 @@ public static async Task UpdateTaskDetailsAsync(PnPConnection connection, string /// HttpClient instance to use to send out requests /// AccessToken to use to authenticate the request /// PlannerRoster - public static async Task CreateRosterAsync(PnPConnection connection, string accessToken) + public static PlannerRoster CreateRoster(Cmdlet cmdlet, PnPConnection connection, string accessToken) { var stringContent = new StringContent("{ \"@odata.type\": \"#microsoft.graph.plannerRoster\" }"); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - return await GraphHelper.PostAsync(connection, "beta/planner/rosters", stringContent, accessToken); + return GraphHelper.Post(cmdlet, connection, "beta/planner/rosters", stringContent, accessToken); } /// @@ -214,9 +215,9 @@ public static async Task CreateRosterAsync(PnPConnection connecti /// HttpClient instance to use to send out requests /// AccessToken to use to authenticate the request /// PlannerRoster - public static async Task GetRosterAsync(PnPConnection connection, string accessToken, string rosterId) + public static PlannerRoster GetRoster(Cmdlet cmdlet, PnPConnection connection, string accessToken, string rosterId) { - return await GraphHelper.GetAsync(connection, $"beta/planner/rosters/{rosterId}", accessToken); + return GraphHelper.Get(cmdlet, connection, $"beta/planner/rosters/{rosterId}", accessToken); } /// @@ -226,9 +227,9 @@ public static async Task GetRosterAsync(PnPConnection connection, /// HttpClient instance to use to send out requests /// AccessToken to use to authenticate the request /// HttpResponseMessage - public static async Task DeleteRosterAsync(PnPConnection connection, string accessToken, string rosterId) + public static HttpResponseMessage DeleteRoster(Cmdlet cmdlet, PnPConnection connection, string accessToken, string rosterId) { - return await GraphHelper.DeleteAsync(connection, $"beta/planner/rosters/{rosterId}", accessToken); + return GraphHelper.Delete(cmdlet, connection, $"beta/planner/rosters/{rosterId}", accessToken); } /// @@ -239,11 +240,11 @@ public static async Task DeleteRosterAsync(PnPConnection co /// HttpClient instance to use to send out requests /// AccessToken to use to authenticate the request /// PlannerRoster - public static async Task AddRosterMemberAsync(PnPConnection connection, string accessToken, string rosterId, string userId) + public static PlannerRoster AddRosterMember(Cmdlet cmdlet, PnPConnection connection, string accessToken, string rosterId, string userId) { var stringContent = new StringContent("{ \"@odata.type\": \"#microsoft.graph.plannerRosterMember\", \"userId\": \"" + userId + "\" }"); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - return await GraphHelper.PostAsync(connection, $"beta/planner/rosters/{rosterId}/members", stringContent, accessToken); + return GraphHelper.Post(cmdlet, connection, $"beta/planner/rosters/{rosterId}/members", stringContent, accessToken); } /// @@ -254,9 +255,9 @@ public static async Task AddRosterMemberAsync(PnPConnection conne /// HttpClient instance to use to send out requests /// AccessToken to use to authenticate the request /// HttpResponseMessage - public static async Task RemoveRosterMemberAsync(PnPConnection connection, string accessToken, string rosterId, string userId) + public static HttpResponseMessage RemoveRosterMember(Cmdlet cmdlet, PnPConnection connection, string accessToken, string rosterId, string userId) { - return await GraphHelper.DeleteAsync(connection, $"beta/planner/rosters/{rosterId}/members/{userId}", accessToken); + return GraphHelper.Delete(cmdlet, connection, $"beta/planner/rosters/{rosterId}/members/{userId}", accessToken); } /// @@ -266,10 +267,10 @@ public static async Task RemoveRosterMemberAsync(PnPConnect /// HttpClient instance to use to send out requests /// AccessToken to use to authenticate the request /// IEnumerable - public static async Task> GetRosterMembersAsync(PnPConnection connection, string accessToken, string rosterId) + public static IEnumerable GetRosterMembers(Cmdlet cmdlet, PnPConnection connection, string accessToken, string rosterId) { var returnCollection = new List(); - var collection = await GraphHelper.GetResultCollectionAsync(connection, $"beta/planner/rosters/{rosterId}/members", accessToken); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, $"beta/planner/rosters/{rosterId}/members", accessToken); if (collection != null && collection.Any()) { returnCollection = collection.ToList(); @@ -284,9 +285,9 @@ public static async Task> GetRosterMembersAsync /// HttpClient instance to use to send out requests /// AccessToken to use to authenticate the request /// PlannerRoster - public static async Task GetRosterPlansByUserAsync(PnPConnection connection, string accessToken, string userId) + public static PlannerRoster GetRosterPlansByUser(Cmdlet cmdlet, PnPConnection connection, string accessToken, string userId) { - return await GraphHelper.GetAsync(connection, $"beta/users/{userId}/planner/rosterPlans", accessToken); + return GraphHelper.Get(cmdlet, connection, $"beta/users/{userId}/planner/rosterPlans", accessToken); } /// @@ -296,9 +297,9 @@ public static async Task GetRosterPlansByUserAsync(PnPConnection /// HttpClient instance to use to send out requests /// AccessToken to use to authenticate the request /// PlannerRoster - public static async Task GetRosterPlansByRosterAsync(PnPConnection connection, string accessToken, string rosterId) + public static PlannerRoster GetRosterPlansByRoster(Cmdlet cmdlet, PnPConnection connection, string accessToken, string rosterId) { - return await GraphHelper.GetAsync(connection, $"beta/planner/rosters/{rosterId}/plans", accessToken); + return GraphHelper.Get(cmdlet, connection, $"beta/planner/rosters/{rosterId}/plans", accessToken); } #endregion @@ -311,9 +312,9 @@ public static async Task GetRosterPlansByRosterAsync(PnPConnectio /// HttpClient instance to use to send out requests /// AccessToken to use to authenticate the request /// PlannerTenantConfig - public static async Task GetPlannerConfigAsync(PnPConnection connection, string accessToken) + public static PlannerTenantConfig GetPlannerConfig(Cmdlet cmdlet, PnPConnection connection, string accessToken) { - var result = await GraphHelper.GetAsync(connection, "https://tasks.office.com/taskAPI/tenantAdminSettings/Settings", accessToken); + var result = GraphHelper.Get(cmdlet, connection, "https://tasks.office.com/taskAPI/tenantAdminSettings/Settings", accessToken); return result; } @@ -323,7 +324,7 @@ public static async Task GetPlannerConfigAsync(PnPConnectio /// HttpClient instance to use to send out requests /// AccessToken to use to authenticate the request /// PlannerTenantConfig - public static async Task SetPlannerConfigAsync(PnPConnection connection, string accessToken, bool? isPlannerAllowed, bool? allowCalendarSharing, bool? allowTenantMoveWithDataLoss, bool? allowTenantMoveWithDataMigration, bool? allowRosterCreation, bool? allowPlannerMobilePushNotifications) + public static PlannerTenantConfig SetPlannerConfig(Cmdlet cmdlet, PnPConnection connection, string accessToken, bool? isPlannerAllowed, bool? allowCalendarSharing, bool? allowTenantMoveWithDataLoss, bool? allowTenantMoveWithDataMigration, bool? allowRosterCreation, bool? allowPlannerMobilePushNotifications) { var content = new PlannerTenantConfig { @@ -334,7 +335,7 @@ public static async Task SetPlannerConfigAsync(PnPConnectio AllowRosterCreation = allowRosterCreation, AllowPlannerMobilePushNotifications = allowPlannerMobilePushNotifications }; - var result = await GraphHelper.PatchAsync(connection, accessToken, "https://tasks.office.com/taskAPI/tenantAdminSettings/Settings", content); + var result = GraphHelper.Patch(cmdlet, connection, accessToken, "https://tasks.office.com/taskAPI/tenantAdminSettings/Settings", content); return result; } @@ -345,9 +346,9 @@ public static async Task SetPlannerConfigAsync(PnPConnectio /// HttpClient instance to use to send out requests /// AccessToken to use to authenticate the request /// PlannerUserPolicy - public static async Task GetPlannerUserPolicyAsync(PnPConnection connection, string accessToken, string userId) + public static PlannerUserPolicy GetPlannerUserPolicy(Cmdlet cmdlet, PnPConnection connection, string accessToken, string userId) { - var result = await GraphHelper.GetAsync(connection, $"https://tasks.office.com/taskAPI/tenantAdminSettings/UserPolicy('{userId}')", accessToken); + var result = GraphHelper.Get(cmdlet, connection, $"https://tasks.office.com/taskAPI/tenantAdminSettings/UserPolicy('{userId}')", accessToken); return result; } @@ -358,19 +359,19 @@ public static async Task GetPlannerUserPolicyAsync(PnPConnect /// HttpClient instance to use to send out requests /// AccessToken to use to authenticate the request /// PlannerUserPolicy - public static async Task SetPlannerUserPolicyAsync(PnPConnection connection, string accessToken, string userId, bool? blockDeleteTasksNotCreatedBySelf) + public static PlannerUserPolicy SetPlannerUserPolicy(Cmdlet cmdlet, PnPConnection connection, string accessToken, string userId, bool? blockDeleteTasksNotCreatedBySelf) { var content = new PlannerUserPolicy { BlockDeleteTasksNotCreatedBySelf = blockDeleteTasksNotCreatedBySelf }; - var result = await GraphHelper.PutAsync(connection, $"https://tasks.office.com/taskAPI/tenantAdminSettings/UserPolicy('{userId}')", content, accessToken); + var result = GraphHelper.Put(cmdlet, connection, $"https://tasks.office.com/taskAPI/tenantAdminSettings/UserPolicy('{userId}')", content, accessToken); return result; } #endregion - private static async Task ResolveIdentityAsync(PnPConnection connection, string accessToken, Identity identity) + private static Identity ResolveIdentity(Cmdlet cmdlet, PnPConnection connection, string accessToken, Identity identity) { if (identity == null) { @@ -378,7 +379,7 @@ private static async Task ResolveIdentityAsync(PnPConnection connectio } if (identity.DisplayName == null) { - return await GraphHelper.GetAsync(connection, $"v1.0/users/{identity.Id}", accessToken); + return GraphHelper.Get(cmdlet, connection, $"v1.0/users/{identity.Id}", accessToken); } else { @@ -386,9 +387,9 @@ private static async Task ResolveIdentityAsync(PnPConnection connectio } } - private static async Task ResolveGroupName(PnPConnection connection, string accessToken, string id) + private static string ResolveGroupName(Cmdlet cmdlet, PnPConnection connection, string accessToken, string id) { - var group = await GraphHelper.GetAsync(connection, $"v1.0/groups/{id}?$select=displayName", accessToken); + var group = GraphHelper.Get(cmdlet, connection, $"v1.0/groups/{id}?$select=displayName", accessToken); if (group != null) { return group.DisplayName; @@ -401,45 +402,45 @@ private static async Task ResolveGroupName(PnPConnection connection, str #region Buckets - public static async Task> GetBucketsAsync(PnPConnection connection, string accessToken, string planId) + public static IEnumerable GetBuckets(Cmdlet cmdlet, PnPConnection connection, string accessToken, string planId) { - return await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/planner/plans/{planId}/buckets", accessToken); + return GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/planner/plans/{planId}/buckets", accessToken); } - public static async Task CreateBucketAsync(PnPConnection connection, string accessToken, string name, string planId) + public static PlannerBucket CreateBucket(Cmdlet cmdlet, PnPConnection connection, string accessToken, string name, string planId) { var stringContent = new StringContent(JsonSerializer.Serialize(new { name = name, planId = planId, orderHint = " !" })); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - return await GraphHelper.PostAsync(connection, $"v1.0/planner/buckets", stringContent, accessToken); + return GraphHelper.Post(cmdlet, connection, $"v1.0/planner/buckets", stringContent, accessToken); } - public static async System.Threading.Tasks.Task RemoveBucketAsync(PnPConnection connection, string accessToken, string bucketId) + public static void RemoveBucket(Cmdlet cmdlet, PnPConnection connection, string accessToken, string bucketId) { - var bucket = GraphHelper.GetAsync(connection, $"v1.0/planner/buckets/{bucketId}", accessToken).GetAwaiter().GetResult(); + var bucket = GraphHelper.Get(cmdlet, connection, $"v1.0/planner/buckets/{bucketId}", accessToken); if (bucket != null) { - await GraphHelper.DeleteAsync(connection, $"v1.0/planner/buckets/{bucketId}", accessToken, new Dictionary() { { "IF-MATCH", bucket.ETag } }); + GraphHelper.Delete(cmdlet, connection, $"v1.0/planner/buckets/{bucketId}", accessToken, new Dictionary() { { "IF-MATCH", bucket.ETag } }); } } - public static async Task> GetBucketTasksAsync(PnPConnection connection, string accessToken, string bucketId, bool resolveDisplayNames) + public static IEnumerable GetBucketTasks(Cmdlet cmdlet, PnPConnection connection, string accessToken, string bucketId, bool resolveDisplayNames) { var returnCollection = new List(); - var collection = await GraphHelper.GetAsync>(connection, $"v1.0/planner/buckets/{bucketId}/tasks", accessToken); + var collection = GraphHelper.Get>(cmdlet, connection, $"v1.0/planner/buckets/{bucketId}/tasks", accessToken); if (collection != null && collection.Items.Any()) { if (resolveDisplayNames) { foreach (var task in collection.Items) { - var fullIdentity = await ResolveIdentityAsync(connection, accessToken, task.CreatedBy.User); + var fullIdentity = ResolveIdentity(cmdlet, connection, accessToken, task.CreatedBy.User); task.CreatedBy.User = fullIdentity; if (task.Assignments != null) { foreach (var assignment in task.Assignments) { - assignment.Value.AssignedBy.User = await ResolveIdentityAsync(connection, accessToken, assignment.Value.AssignedBy.User); + assignment.Value.AssignedBy.User = ResolveIdentity(cmdlet, connection, accessToken, assignment.Value.AssignedBy.User); } } returnCollection.Add(task); @@ -456,13 +457,13 @@ public static async Task> GetBucketTasksAsync(PnPConnec { foreach (var task in collection.Items) { - var fullIdentity = await ResolveIdentityAsync(connection, accessToken, task.CreatedBy.User); + var fullIdentity = ResolveIdentity(cmdlet, connection, accessToken, task.CreatedBy.User); task.CreatedBy.User = fullIdentity; if (task.Assignments != null) { foreach (var assignment in task.Assignments) { - assignment.Value.AssignedBy.User = await ResolveIdentityAsync(connection, accessToken, assignment.Value.AssignedBy.User); + assignment.Value.AssignedBy.User = ResolveIdentity(cmdlet, connection, accessToken, assignment.Value.AssignedBy.User); } } returnCollection.Add(task); @@ -478,14 +479,14 @@ public static async Task> GetBucketTasksAsync(PnPConnec return returnCollection; } - public static async Task UpdateBucketAsync(PnPConnection connection, string accessToken, string name, string bucketId) + public static PlannerBucket UpdateBucket(Cmdlet cmdlet, PnPConnection connection, string accessToken, string name, string bucketId) { - var bucket = await GraphHelper.GetAsync(connection, $"v1.0/planner/buckets/{bucketId}", accessToken); + var bucket = GraphHelper.Get(cmdlet, connection, $"v1.0/planner/buckets/{bucketId}", accessToken); if (bucket != null) { var stringContent = new StringContent(JsonSerializer.Serialize(new { name = name })); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - return await GraphHelper.PatchAsync(connection, accessToken, $"v1.0/planner/buckets/{bucketId}", stringContent, new Dictionary() { { "IF-MATCH", bucket.ETag } }); + return GraphHelper.Patch(cmdlet, connection, accessToken, $"v1.0/planner/buckets/{bucketId}", stringContent, new Dictionary() { { "IF-MATCH", bucket.ETag } }); } return null; } diff --git a/src/Commands/Utilities/PowerAppsUtility.cs b/src/Commands/Utilities/PowerAppsUtility.cs index 18779bee4..214bfe6c5 100644 --- a/src/Commands/Utilities/PowerAppsUtility.cs +++ b/src/Commands/Utilities/PowerAppsUtility.cs @@ -1,21 +1,16 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Net.Http; using System.Net.Http.Headers; -using System.Text; using System.Text.Json; using System.Threading; -using System.Threading.Tasks; using PnP.Framework; -using PnP.PowerShell.Commands.Base; using PnP.PowerShell.Commands.Utilities.REST; namespace PnP.PowerShell.Commands.Utilities { internal static class PowerAppsUtility { - internal static async Task GetWrapper(HttpClient connection, string environmentName, string accessToken, string appName, AzureEnvironment azureEnvironment = AzureEnvironment.Production) + internal static Model.PowerPlatform.PowerApp.PowerAppPackageWrapper GetWrapper(HttpClient connection, string environmentName, string accessToken, string appName, AzureEnvironment azureEnvironment = AzureEnvironment.Production) { var postData = new { @@ -24,7 +19,7 @@ internal static class PowerAppsUtility } }; string baseUrl = PowerPlatformUtility.GetBapEndpoint(azureEnvironment); - var wrapper = await RestHelper.PostAsync(connection, $"{baseUrl}/providers/Microsoft.BusinessAppPlatform/environments/{environmentName}/listPackageResources?api-version=2016-11-01", accessToken, payload: postData); + var wrapper = RestHelper.Post(connection, $"{baseUrl}/providers/Microsoft.BusinessAppPlatform/environments/{environmentName}/listPackageResources?api-version=2016-11-01", accessToken, payload: postData); return wrapper; @@ -43,7 +38,7 @@ internal static HttpResponseHeaders GetResponseHeader(HttpClient connection, str }; string baseUrl = PowerPlatformUtility.GetBapEndpoint(azureEnvironment); - var responseHeader = RestHelper.PostAsyncGetResponseHeader(connection, $"{baseUrl}/providers/Microsoft.BusinessAppPlatform/environments/{environmentName}/exportPackage?api-version=2016-11-01", accessToken, payload: exportPostData).GetAwaiter().GetResult(); + var responseHeader = RestHelper.PostGetResponseHeader(connection, $"{baseUrl}/providers/Microsoft.BusinessAppPlatform/environments/{environmentName}/exportPackage?api-version=2016-11-01", accessToken, payload: exportPostData); return responseHeader; @@ -57,7 +52,7 @@ internal static string GetPackageLink(HttpClient connection, string location, st { do { - var runningresponse = RestHelper.GetAsync(connection, location, accessToken).GetAwaiter().GetResult(); + var runningresponse = RestHelper.Get(connection, location, accessToken); if (runningresponse.TryGetProperty("properties", out JsonElement properties)) { diff --git a/src/Commands/Utilities/PriviledgedIdentityManagamentUtility.cs b/src/Commands/Utilities/PriviledgedIdentityManagamentUtility.cs new file mode 100644 index 000000000..5f692b9a8 --- /dev/null +++ b/src/Commands/Utilities/PriviledgedIdentityManagamentUtility.cs @@ -0,0 +1,105 @@ +using PnP.PowerShell.Commands.Base; +using PnP.PowerShell.Commands.Model.PriviledgedIdentityManagement; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Net.Http; +using System.Text.Json; + +namespace PnP.PowerShell.Commands.Utilities +{ + /// + /// Utility class to work with Entra ID Priviledged Identity Management + /// + internal static class PriviledgedIdentityManagamentUtility + { + /// + /// Returns all available priviledged identity management role schedules + /// + public static List GetRoleEligibilitySchedules(Cmdlet cmdlet, PnPConnection connection, string accesstoken) + { + string requestUrl = $"v1.0/roleManagement/directory/roleEligibilitySchedules?$expand=RoleDefinition"; + var result = REST.GraphHelper.GetResultCollection(cmdlet, connection, requestUrl, accesstoken); + return result.ToList(); + } + + /// + /// Returns all available priviledged identity management roles + /// + public static List GetRoleDefinitions(Cmdlet cmdlet, PnPConnection connection, string accesstoken) + { + string requestUrl = $"v1.0/roleManagement/directory/roleDefinitions"; + var result = REST.GraphHelper.GetResultCollection(cmdlet, connection, requestUrl, accesstoken); + return result.ToList(); + } + + /// + /// Returns a priviledged identity management role by its displayname + /// + /// Displayname of the role to return. Case sensitive. + public static RoleDefinition GetRoleDefinitionByName(Cmdlet cmdlet, string roleName, PnPConnection connection, string accesstoken) + { + string requestUrl = $"v1.0/roleManagement/directory/roleDefinitions?$filter=displayName eq '{roleName}'"; + var result = REST.GraphHelper.GetResultCollection(cmdlet, connection, requestUrl, accesstoken); + return result.FirstOrDefault(); + } + + /// + /// Returns a priviledged identity management role by its Id + /// + /// Id of the role to return + public static RoleDefinition GetRoleDefinitionById(Cmdlet cmdlet, Guid roleId, PnPConnection connection, string accesstoken) + { + string requestUrl = $"v1.0/roleManagement/directory/roleDefinitions/{roleId}"; + var result = REST.GraphHelper.Get(cmdlet, connection, requestUrl, accesstoken); + return result; + } + + /// + /// Returns the priviledged identity management role schedule with the provided Id + /// + public static RoleEligibilitySchedule GetRoleEligibilityScheduleById(Cmdlet cmdlet, Guid id, PnPConnection connection, string accesstoken) + { + string requestUrl = $"v1.0/roleManagement/directory/roleEligibilitySchedules/{id}?$expand=RoleDefinition"; + var result = REST.GraphHelper.Get(cmdlet, connection, requestUrl, accesstoken); + return result; + } + + /// + /// Returns the priviledged identity management role schedule for the provided principal and role + /// + public static RoleEligibilitySchedule GetRoleEligibilityScheduleByPrincipalIdAndRoleName(Cmdlet cmdlet, Guid principalId, RoleDefinition role, PnPConnection connection, string accesstoken) + { + string requestUrl = $"v1.0/roleManagement/directory/roleEligibilitySchedules?$filter=principalId eq '{principalId}' and roleDefinitionId eq '{role.Id}'&$expand=RoleDefinition"; + var result = REST.GraphHelper.GetResultCollection(cmdlet, connection, requestUrl, accesstoken); + return result.FirstOrDefault(); + } + + /// + /// Creates a scheduled assignment for a role to be activated at a certain time + /// + public static HttpResponseMessage CreateRoleAssignmentScheduleRequest(Cmdlet cmdlet, RoleEligibilitySchedule roleEligibilitySchedule, PnPConnection connection, string accesstoken, string justification = null, DateTime? startDateTime = null, short? expiratonHours = null) + { + string requestUrl = $"v1.0/roleManagement/directory/roleAssignmentScheduleRequests"; + var postData = new RoleAssignmentScheduleRequest + { + DirectoryScopeId = roleEligibilitySchedule.DirectoryScopeId, + PrincipalId = roleEligibilitySchedule.PrincipalId, + RoleDefinitionId = roleEligibilitySchedule.RoleDefinition.Id, + Justification = justification ?? "Elevated by PnP PowerShell", + ScheduleInfo = new ScheduleInfo + { + StartDateTime = startDateTime ?? DateTime.UtcNow, + Expiration = new Expiration + { + Duration = $"PT{expiratonHours.GetValueOrDefault(1)}H" + } + } + }; + var stringContent = new StringContent(JsonSerializer.Serialize(postData), System.Text.Encoding.UTF8, "application/json"); + var result = REST.GraphHelper.Post(cmdlet, connection, requestUrl, accesstoken, stringContent); + return result; + } + } +} \ No newline at end of file diff --git a/src/Commands/Utilities/REST/GraphBatch.cs b/src/Commands/Utilities/REST/GraphBatch.cs index 712fc2b4b..88fa85ab5 100644 --- a/src/Commands/Utilities/REST/GraphBatch.cs +++ b/src/Commands/Utilities/REST/GraphBatch.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Linq; +using System.Management.Automation; using System.Net.Http; using System.Text.Json; using System.Text.Json.Serialization; @@ -21,7 +22,7 @@ internal static IEnumerable> Chunk(this IEnumerable source, } } - internal static async Task> GetPropertyBatchedAsync(PnPConnection connection, string accessToken, string[] lookupData, string urlTemplate, string property) + internal static Dictionary GetPropertyBatched(Cmdlet cmdlet, PnPConnection connection, string accessToken, string[] lookupData, string urlTemplate, string property) { Dictionary returnValue = new Dictionary(); @@ -37,7 +38,7 @@ internal static async Task> GetPropertyBatchedAsync(P } var stringContent = new StringContent(JsonSerializer.Serialize(batch)); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - var result = await GraphHelper.PostAsync(connection, "v1.0/$batch", stringContent, accessToken); + var result = GraphHelper.Post(cmdlet, connection, "v1.0/$batch", stringContent, accessToken); if (result.Responses != null && result.Responses.Any()) { foreach (var response in result.Responses) @@ -53,7 +54,7 @@ internal static async Task> GetPropertyBatchedAsync(P return returnValue; } - internal static async Task>> GetObjectCollectionBatchedAsync(PnPConnection connection, string accessToken, string[] lookupData, string urlTemplate) + internal static Dictionary> GetObjectCollectionBatched(Cmdlet cmdlet, PnPConnection connection, string accessToken, string[] lookupData, string urlTemplate) { Dictionary> returnValue = new Dictionary>(); @@ -69,7 +70,7 @@ internal static async Task>> GetObjectCollecti } var stringContent = new StringContent(JsonSerializer.Serialize(batch)); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - var result = await GraphHelper.PostAsync(connection, "v1.0/$batch", stringContent, accessToken); + var result = GraphHelper.Post(cmdlet, connection, "v1.0/$batch", stringContent, accessToken); if (result.Responses != null && result.Responses.Any()) { var options = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase}; diff --git a/src/Commands/Utilities/REST/GraphHelper.cs b/src/Commands/Utilities/REST/GraphHelper.cs index e222bab5b..23dcd5afd 100644 --- a/src/Commands/Utilities/REST/GraphHelper.cs +++ b/src/Commands/Utilities/REST/GraphHelper.cs @@ -1,4 +1,5 @@ -using PnP.PowerShell.Commands.Base; +using Newtonsoft.Json.Serialization; +using PnP.PowerShell.Commands.Base; using PnP.PowerShell.Commands.Model.Graph; using System; using System.Collections.Generic; @@ -8,6 +9,7 @@ using System.Net.Http; using System.Text.Json; using System.Text.Json.Serialization; +using System.Threading; using System.Threading.Tasks; namespace PnP.PowerShell.Commands.Utilities.REST @@ -71,16 +73,16 @@ private static HttpRequestMessage GetMessage(string url, HttpMethod method, PnPC return message; } - public static async Task GetAsync(PnPConnection connection, string url, string accessToken, IDictionary additionalHeaders = null) + public static string Get(Cmdlet cmdlet, PnPConnection connection, string url, string accessToken, IDictionary additionalHeaders = null) { var message = GetMessage(url, HttpMethod.Get, connection, accessToken, null, additionalHeaders); - return await SendMessageAsync(connection, message, accessToken); + return SendMessage(cmdlet, connection, message, accessToken); } - public static async Task GetResponseAsync(PnPConnection connection, string url, string accessToken) + public static HttpResponseMessage GetResponse(Cmdlet cmdlet, PnPConnection connection, string url, string accessToken) { var message = GetMessage(url, HttpMethod.Get, connection, accessToken); - return await GetResponseMessageAsync(connection, message); + return GetResponseMessage(cmdlet, connection, message); } /// @@ -93,17 +95,17 @@ public static async Task GetResponseAsync(PnPConnection con /// Policy indicating the CamlCase that should be applied when mapping results to typed objects /// Indicates if the response be mapped to the typed object ignoring different casing /// List with objects of type T returned by the request - public static async Task> GetResultCollectionAsync(PnPConnection connection, string url, string accessToken, bool camlCasePolicy = true, bool propertyNameCaseInsensitive = false, IDictionary additionalHeaders = null) + public static IEnumerable GetResultCollection(Cmdlet cmdlet, PnPConnection connection, string url, string accessToken, bool camlCasePolicy = true, bool propertyNameCaseInsensitive = false, IDictionary additionalHeaders = null) { var results = new List(); - var request = await GetAsync>(connection, url, accessToken, camlCasePolicy, propertyNameCaseInsensitive, additionalHeaders); + var request = Get>(cmdlet, connection, url, accessToken, camlCasePolicy, propertyNameCaseInsensitive, additionalHeaders); if (request.Items.Any()) { results.AddRange(request.Items); while (!string.IsNullOrEmpty(request.NextLink)) { - request = await GetAsync>(connection, request.NextLink, accessToken, camlCasePolicy, propertyNameCaseInsensitive, additionalHeaders); + request = Get>(cmdlet, connection, request.NextLink, accessToken, camlCasePolicy, propertyNameCaseInsensitive, additionalHeaders); if (request.Items.Any()) { results.AddRange(request.Items); @@ -111,6 +113,8 @@ public static async Task> GetResultCollectionAsync(PnPConnecti } } + cmdlet.WriteVerbose($"Returning {results.Count} {typeof(T)} item{(results.Count != 1 ? "s" : "")}"); + return results; } @@ -124,12 +128,12 @@ public static async Task> GetResultCollectionAsync(PnPConnecti /// Policy indicating the CamlCase that should be applied when mapping results to typed objects /// Indicates if the response be mapped to the typed object ignoring different casing /// List with objects of type T returned by the request - public static async Task GetAsync(PnPConnection connection, string url, string accessToken, bool camlCasePolicy = true, bool propertyNameCaseInsensitive = false, IDictionary additionalHeaders = null) + public static T Get(Cmdlet cmdlet, PnPConnection connection, string url, string accessToken, bool camlCasePolicy = true, bool propertyNameCaseInsensitive = false, IDictionary additionalHeaders = null) { - var stringContent = await GetAsync(connection, url, accessToken, additionalHeaders); + var stringContent = Get(cmdlet, connection, url, accessToken, additionalHeaders); if (stringContent != null) { - var options = new JsonSerializerOptions { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }; + var options = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; options.Converters.Add(new JsonStringEnumConverter()); if (camlCasePolicy) { @@ -152,31 +156,31 @@ public static async Task GetAsync(PnPConnection connection, string url, st return default(T); } - public static async Task PostAsync(PnPConnection connection, string url, string accessToken, HttpContent content, IDictionary additionalHeaders = null) + public static HttpResponseMessage Post(Cmdlet cmdlet, PnPConnection connection, string url, string accessToken, HttpContent content, IDictionary additionalHeaders = null) { var message = GetMessage(url, HttpMethod.Post, connection, accessToken, content, additionalHeaders); - return await GetResponseMessageAsync(connection, message); + return GetResponseMessage(cmdlet, connection, message); } - public static async Task PutAsync(PnPConnection connection, string url, string accessToken, HttpContent content, IDictionary additionalHeaders = null) + public static HttpResponseMessage Put(Cmdlet cmdlet, PnPConnection connection, string url, string accessToken, HttpContent content, IDictionary additionalHeaders = null) { var message = GetMessage(url, HttpMethod.Put, connection, accessToken, content, additionalHeaders); - return await GetResponseMessageAsync(connection, message); + return GetResponseMessage(cmdlet, connection, message); } #region DELETE - public static async Task DeleteAsync(PnPConnection connection, string url, string accessToken, IDictionary additionalHeaders = null) + public static HttpResponseMessage Delete(Cmdlet cmdlet, PnPConnection connection, string url, string accessToken, IDictionary additionalHeaders = null) { var message = GetMessage(url, HttpMethod.Delete, connection, accessToken, null, additionalHeaders); - return await GetResponseMessageAsync(connection, message); + return GetResponseMessage(cmdlet, connection, message); } - public static async Task DeleteAsync(PnPConnection connection, string url, string accessToken, bool camlCasePolicy = true, IDictionary additionalHeaders = null) + public static T Delete(Cmdlet cmdlet, PnPConnection connection, string url, string accessToken, bool camlCasePolicy = true, IDictionary additionalHeaders = null) { - var response = await DeleteAsync(connection, url, accessToken, additionalHeaders); + var response = Delete(cmdlet, connection, url, accessToken, additionalHeaders); if (response.IsSuccessStatusCode) { - var stringContent = await response.Content.ReadAsStringAsync(); + var stringContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); if (stringContent != null) { @@ -200,9 +204,9 @@ public static async Task DeleteAsync(PnPConnection connection, string url, #endregion #region PATCH - public static async Task PatchAsync(PnPConnection connection, string accessToken, string url, T content, IDictionary additionalHeaders = null, bool camlCasePolicy = true) + public static T Patch(Cmdlet cmdlet, PnPConnection connection, string accessToken, string url, T content, IDictionary additionalHeaders = null, bool camlCasePolicy = true) { - var serializerSettings = new JsonSerializerOptions() { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }; + var serializerSettings = new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; if (camlCasePolicy) { serializerSettings.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; @@ -210,7 +214,7 @@ public static async Task PatchAsync(PnPConnection connection, string acces var requestContent = new StringContent(JsonSerializer.Serialize(content, serializerSettings)); requestContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var message = GetMessage(url, HttpMethod.Patch, connection, accessToken, requestContent, additionalHeaders); - var returnValue = await SendMessageAsync(connection, message, accessToken); + var returnValue = SendMessage(cmdlet, connection, message, accessToken); if (!string.IsNullOrEmpty(returnValue)) { return JsonSerializer.Deserialize(returnValue); @@ -221,10 +225,10 @@ public static async Task PatchAsync(PnPConnection connection, string acces } } - public static async Task PatchAsync(PnPConnection connection, string accessToken, string url, HttpContent content, IDictionary additionalHeaders = null) + public static T Patch(Cmdlet cmdlet, PnPConnection connection, string accessToken, string url, HttpContent content, IDictionary additionalHeaders = null) { var message = GetMessage(url, HttpMethod.Patch, connection, accessToken, content, additionalHeaders); - var returnValue = await SendMessageAsync(connection, message, accessToken); + var returnValue = SendMessage(cmdlet, connection, message, accessToken); if (!string.IsNullOrEmpty(returnValue)) { return JsonSerializer.Deserialize(returnValue); @@ -235,23 +239,23 @@ public static async Task PatchAsync(PnPConnection connection, string acces } } - public static async Task PatchAsync(PnPConnection connection, string accessToken, HttpContent content, string url, IDictionary additionalHeaders = null) + public static HttpResponseMessage Patch(Cmdlet cmdlet, PnPConnection connection, string accessToken, HttpContent content, string url, IDictionary additionalHeaders = null) { var message = GetMessage(url, HttpMethod.Patch, connection, accessToken, content, additionalHeaders); - return await GetResponseMessageAsync(connection, message); + return GetResponseMessage(cmdlet, connection, message); } #endregion - public static async Task PostAsync(PnPConnection connection, string url, HttpContent content, string accessToken, IDictionary additionalHeaders = null, bool propertyNameCaseInsensitive = false) + public static T Post(Cmdlet cmdlet, PnPConnection connection, string url, HttpContent content, string accessToken, IDictionary additionalHeaders = null, bool propertyNameCaseInsensitive = false) { - return await PostInternalAsync(connection, url, accessToken, content, additionalHeaders, propertyNameCaseInsensitive); + return PostInternal(cmdlet, connection, url, accessToken, content, additionalHeaders, propertyNameCaseInsensitive); } - public static async Task PutAsync(PnPConnection connection, string url, string accessToken, HttpContent content, IDictionary additionalHeaders = null) + public static T Put(Cmdlet cmdlet, PnPConnection connection, string url, string accessToken, HttpContent content, IDictionary additionalHeaders = null) { var message = GetMessage(url, HttpMethod.Put, connection, accessToken, content, additionalHeaders); - var stringContent = await SendMessageAsync(connection, message, accessToken); + var stringContent = SendMessage(cmdlet, connection, message, accessToken); if (stringContent != null) { try @@ -266,23 +270,23 @@ public static async Task PutAsync(PnPConnection connection, string url, st return default; } - public static async Task PostAsync(PnPConnection connection, string url, T content, string accessToken) + public static T Post(Cmdlet cmdlet, PnPConnection connection, string url, T content, string accessToken) { var requestContent = new StringContent(JsonSerializer.Serialize(content, new JsonSerializerOptions() { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, PropertyNamingPolicy = JsonNamingPolicy.CamelCase })); requestContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - return await PostInternalAsync(connection, url, accessToken, requestContent); + return PostInternal(cmdlet, connection, url, accessToken, requestContent); } - public static async Task PostAsync(PnPConnection connection, string url, string accessToken) + public static T Post(Cmdlet cmdlet, PnPConnection connection, string url, string accessToken) { - return await PostInternalAsync(connection, url, accessToken, null); + return PostInternal(cmdlet, connection, url, accessToken, null); } - private static async Task PostInternalAsync(PnPConnection connection, string url, string accessToken, HttpContent content, IDictionary additionalHeaders = null, bool propertyNameCaseInsensitive = false) + private static T PostInternal(Cmdlet cmdlet, PnPConnection connection, string url, string accessToken, HttpContent content, IDictionary additionalHeaders = null, bool propertyNameCaseInsensitive = false) { var message = GetMessage(url, HttpMethod.Post, connection, accessToken, content, additionalHeaders); - var stringContent = await SendMessageAsync(connection, message, accessToken); + var stringContent = SendMessage(cmdlet, connection, message, accessToken); if (stringContent != null) { try @@ -297,12 +301,12 @@ private static async Task PostInternalAsync(PnPConnection connection, stri return default; } - public static async Task PutAsync(PnPConnection connection, string url, T content, string accessToken) + public static T Put(Cmdlet cmdlet, PnPConnection connection, string url, T content, string accessToken) { var requestContent = new StringContent(JsonSerializer.Serialize(content, new JsonSerializerOptions() { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, PropertyNamingPolicy = JsonNamingPolicy.CamelCase })); requestContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var message = GetMessage(url, HttpMethod.Put, connection, accessToken, requestContent); - var returnValue = await SendMessageAsync(connection, message, accessToken); + var returnValue = SendMessage(cmdlet, connection, message, accessToken); if (!string.IsNullOrEmpty(returnValue)) { return JsonSerializer.Deserialize(returnValue, new JsonSerializerOptions() { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); @@ -313,31 +317,45 @@ public static async Task PutAsync(PnPConnection connection, string url, T } } - public static async Task DeleteAsync(PnPConnection connection, string url, string accessToken) + public static HttpResponseMessage Delete(Cmdlet cmdlet, PnPConnection connection, string url, string accessToken) { var message = GetMessage(url, HttpMethod.Delete, connection, accessToken); - var response = await GetResponseMessageAsync(connection, message); + var response = GetResponseMessage(cmdlet, connection, message); return response; } - private static async Task SendMessageAsync(PnPConnection connection, HttpRequestMessage message, string accessToken) + private static string SendMessage(Cmdlet cmdlet, PnPConnection connection, HttpRequestMessage message, string accessToken) { - var response = await connection.HttpClient.SendAsync(message); + cmdlet.WriteVerbose($"Making {message.Method} call to {message.RequestUri}{(message.Content != null ? $" with body '{message.Content.ReadAsStringAsync().GetAwaiter().GetResult()}'" : "")}"); + + var response = connection.HttpClient.SendAsync(message).GetAwaiter().GetResult(); while (response.StatusCode == (HttpStatusCode)429) { // throttled var retryAfter = response.Headers.RetryAfter; - await Task.Delay(retryAfter.Delta.Value.Seconds * 1000); - response = await connection.HttpClient.SendAsync(CloneMessage(message)); + + cmdlet.WriteVerbose($"Call got throttled. Retrying in {retryAfter.Delta.Value.Seconds} second{(retryAfter.Delta.Value.Seconds != 1 ? "s" : "")}."); + + Thread.Sleep(retryAfter.Delta.Value.Seconds * 1000); + + cmdlet.WriteVerbose($"Making {message.Method} call to {message.RequestUri}"); + response = connection.HttpClient.SendAsync(CloneMessage(message)).GetAwaiter().GetResult(); } if (response.IsSuccessStatusCode) { - return await response.Content.ReadAsStringAsync(); + var responseBody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + + cmdlet.WriteVerbose($"Response successful with HTTP {(int)response.StatusCode} {response.StatusCode} containing {responseBody.Length} character{(responseBody.Length != 1 ? "s" : "")}"); + + return responseBody; } else { - var errorContent = await response.Content.ReadAsStringAsync(); - var exception = JsonSerializer.Deserialize(errorContent, new JsonSerializerOptions() { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); + var errorContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + + cmdlet.WriteVerbose($"Response failed with HTTP {(int)response.StatusCode} {response.StatusCode} containing {errorContent.Length} character{(errorContent.Length != 1 ? "s" : "")}: {errorContent}"); + + var exception = JsonSerializer.Deserialize(errorContent, new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); exception.AccessToken = accessToken; exception.HttpResponse = response; @@ -345,21 +363,30 @@ private static async Task SendMessageAsync(PnPConnection connection, Htt } } - public static async Task GetResponseMessageAsync(PnPConnection connection, HttpRequestMessage message) + public static HttpResponseMessage GetResponseMessage(Cmdlet cmdlet, PnPConnection connection, HttpRequestMessage message) { - var response = await connection.HttpClient.SendAsync(message); + cmdlet.WriteVerbose($"Making {message.Method} call to {message.RequestUri}"); + + var response = connection.HttpClient.SendAsync(message).GetAwaiter().GetResult(); while (response.StatusCode == (HttpStatusCode)429) { // throttled var retryAfter = response.Headers.RetryAfter; - await Task.Delay(retryAfter.Delta.Value.Seconds * 1000); - response = await connection.HttpClient.SendAsync(CloneMessage(message)); + + cmdlet.WriteVerbose($"Call got throttled. Retrying in {retryAfter.Delta.Value.Seconds} second{(retryAfter.Delta.Value.Seconds != 1 ? "s" : "")}."); + + Thread.Sleep(retryAfter.Delta.Value.Seconds * 1000); + + cmdlet.WriteVerbose($"Making {message.Method} call to {message.RequestUri}"); + response = connection.HttpClient.SendAsync(CloneMessage(message)).GetAwaiter().GetResult(); } // Validate if the response was successful, if not throw an exception if (!response.IsSuccessStatusCode) { - if (GraphHelper.TryGetGraphException(response, out GraphException ex)) + cmdlet.WriteVerbose($"Response failed with HTTP {(int)response.StatusCode} {response.StatusCode}"); + + if (TryGetGraphException(response, out GraphException ex)) { if (ex.Error != null) { @@ -371,16 +398,21 @@ public static async Task GetResponseMessageAsync(PnPConnect throw new PSInvalidOperationException($"Call to Microsoft Graph URL {message.RequestUri} failed with status code {response.StatusCode}"); } } + else + { + cmdlet.WriteVerbose($"Response successful with HTTP {(int)response.StatusCode} {response.StatusCode}"); + } return response; } private static HttpRequestMessage CloneMessage(HttpRequestMessage req) { - HttpRequestMessage clone = new HttpRequestMessage(req.Method, req.RequestUri); - - clone.Content = req.Content; - clone.Version = req.Version; + HttpRequestMessage clone = new(req.Method, req.RequestUri) + { + Content = req.Content, + Version = req.Version + }; foreach (KeyValuePair prop in req.Options) { diff --git a/src/Commands/Utilities/REST/RestHelper.cs b/src/Commands/Utilities/REST/RestHelper.cs index c340be8ee..17ad4659f 100644 --- a/src/Commands/Utilities/REST/RestHelper.cs +++ b/src/Commands/Utilities/REST/RestHelper.cs @@ -7,6 +7,7 @@ using System.Text; using System.Text.Json; using System.Text.Json.Serialization; +using System.Threading; using System.Threading.Tasks; using Microsoft.SharePoint.Client; @@ -147,27 +148,27 @@ private static HttpResponseMessage ExecutePostRequestInternal(ClientContext cont return returnValue; } - public static async Task GetAsync(HttpClient httpClient, string url, string accessToken, string accept = "application/json") + public static string Get(HttpClient httpClient, string url, string accessToken, string accept = "application/json") { var message = GetMessage(url, HttpMethod.Get, accessToken, accept); - return await SendMessageAsync(httpClient, message); + return SendMessage(httpClient, message); } - public static async Task GetByteArrayAsync(HttpClient httpClient, string url, string accessToken, string accept = "application/json") + public static byte[] GetByteArray(HttpClient httpClient, string url, string accessToken, string accept = "application/json") { var message = GetMessage(url, HttpMethod.Get, accessToken, accept); - return await SendMessageByteArrayAsync(httpClient, message); + return SendMessageByteArray(httpClient, message); } - public static async Task GetAsync(HttpClient httpClient, string url, ClientContext clientContext, string accept = "application/json") + public static string Get(HttpClient httpClient, string url, ClientContext clientContext, string accept = "application/json") { var message = GetMessage(url, HttpMethod.Get, clientContext, accept); - return await SendMessageAsync(httpClient, message); + return SendMessage(httpClient, message); } - public static async Task GetAsync(HttpClient httpClient, string url, string accessToken, bool camlCasePolicy = true) + public static T Get(HttpClient httpClient, string url, string accessToken, bool camlCasePolicy = true) { - var stringContent = await GetAsync(httpClient, url, accessToken); + var stringContent = Get(httpClient, url, accessToken); if (stringContent != null) { var options = new JsonSerializerOptions() { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }; @@ -187,9 +188,9 @@ public static async Task GetAsync(HttpClient httpClient, string url, strin return default(T); } - public static async Task GetAsync(HttpClient httpClient, string url, ClientContext clientContext, bool camlCasePolicy = true) + public static T Get(HttpClient httpClient, string url, ClientContext clientContext, bool camlCasePolicy = true) { - var stringContent = await GetAsync(httpClient, url, clientContext); + var stringContent = Get(httpClient, url, clientContext); if (stringContent != null) { var options = new JsonSerializerOptions() { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }; @@ -213,19 +214,19 @@ public static async Task GetAsync(HttpClient httpClient, string url, Clien #region POST - public static async Task PostAsync(HttpClient httpClient, string url, string accessToken, string accept = "application/json") + public static string Post(HttpClient httpClient, string url, string accessToken, string accept = "application/json") { var message = GetMessage(url, HttpMethod.Post, accessToken, accept); - return await SendMessageAsync(httpClient, message); + return SendMessage(httpClient, message); } - public static async Task PostAsync(HttpClient httpClient, string url, ClientContext clientContext, string accept = "application/json") + public static string Post(HttpClient httpClient, string url, ClientContext clientContext, string accept = "application/json") { var message = GetMessage(url, HttpMethod.Post, clientContext, accept); - return await SendMessageAsync(httpClient, message); + return SendMessage(httpClient, message); } - public static async Task PostAsync(HttpClient httpClient, string url, string accessToken, object payload, string accept = "application/json") + public static string Post(HttpClient httpClient, string url, string accessToken, object payload, string accept = "application/json") { HttpRequestMessage message = null; if (payload != null) @@ -238,10 +239,10 @@ public static async Task PostAsync(HttpClient httpClient, string url, st { message = GetMessage(url, HttpMethod.Post, accessToken, accept); } - return await SendMessageAsync(httpClient, message); + return SendMessage(httpClient, message); } - public static async Task PostAsync(HttpClient httpClient, string url, ClientContext clientContext, object payload, string accept = "application/json") + public static string Post(HttpClient httpClient, string url, ClientContext clientContext, object payload, string accept = "application/json") { HttpRequestMessage message = null; if (payload != null) @@ -254,10 +255,10 @@ public static async Task PostAsync(HttpClient httpClient, string url, Cl { message = GetMessage(url, HttpMethod.Post, clientContext, accept); } - return await SendMessageAsync(httpClient, message); + return SendMessage(httpClient, message); } - public static async Task PostAsync(HttpClient httpClient, string url, ClientContext clientContext, string payload, string contentType = "application/json", string accept = "application/json") + public static string Post(HttpClient httpClient, string url, ClientContext clientContext, string payload, string contentType = "application/json", string accept = "application/json") { HttpRequestMessage message = null; if (payload != null) @@ -270,12 +271,12 @@ public static async Task PostAsync(HttpClient httpClient, string url, Cl { message = GetMessage(url, HttpMethod.Post, clientContext, accept); } - return await SendMessageAsync(httpClient, message); + return SendMessage(httpClient, message); } - public static async Task PostAsync(HttpClient httpClient, string url, string accessToken, object payload, bool camlCasePolicy = true) + public static T Post(HttpClient httpClient, string url, string accessToken, object payload, bool camlCasePolicy = true) { - var stringContent = await PostAsync(httpClient, url, accessToken, payload); + var stringContent = Post(httpClient, url, accessToken, payload); if (stringContent != null) { var options = new JsonSerializerOptions() { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }; @@ -295,7 +296,7 @@ public static async Task PostAsync(HttpClient httpClient, string url, stri return default(T); } - public static async Task PostAsyncGetResponseHeader(HttpClient httpClient, string url, string accessToken, object payload, bool camlCasePolicy = true, string accept = "application/json") + public static HttpResponseHeaders PostGetResponseHeader(HttpClient httpClient, string url, string accessToken, object payload, bool camlCasePolicy = true, string accept = "application/json") { HttpRequestMessage message = null; if (payload != null) @@ -308,14 +309,14 @@ public static async Task PostAsyncGetResponseHeader(Http { message = GetMessage(url, HttpMethod.Post, accessToken, accept); } - return await SendMessageAsyncGetResponseHeader(httpClient, message); + return SendMessageGetResponseHeader(httpClient, message); } - public static async Task PostAsync(HttpClient httpClient, string url, ClientContext clientContext, object payload, bool camlCasePolicy = true) + public static T Post(HttpClient httpClient, string url, ClientContext clientContext, object payload, bool camlCasePolicy = true) { - var stringContent = await PostAsync(httpClient, url, clientContext, payload); + var stringContent = Post(httpClient, url, clientContext, payload); if (stringContent != null) { var options = new JsonSerializerOptions() { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }; @@ -339,9 +340,9 @@ public static async Task PostAsync(HttpClient httpClient, string url, Clie #endregion #region PATCH - public static async Task PatchAsync(HttpClient httpClient, string url, string accessToken, object payload, bool camlCasePolicy = true) + public static T Patch(HttpClient httpClient, string url, string accessToken, object payload, bool camlCasePolicy = true) { - var stringContent = await PatchAsync(httpClient, url, accessToken, payload); + var stringContent = Patch(httpClient, url, accessToken, payload); if (stringContent != null) { var options = new JsonSerializerOptions() { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }; @@ -361,7 +362,7 @@ public static async Task PatchAsync(HttpClient httpClient, string url, str return default(T); } - public static async Task PatchAsync(HttpClient httpClient, string url, string accessToken, object payload, string accept = "application/json") + public static string Patch(HttpClient httpClient, string url, string accessToken, object payload, string accept = "application/json") { HttpRequestMessage message = null; if (payload != null) @@ -374,7 +375,7 @@ public static async Task PatchAsync(HttpClient httpClient, string url, s { message = GetMessage(url, HttpMethod.Patch, accessToken, accept); } - return await SendMessageAsync(httpClient, message); + return SendMessage(httpClient, message); } #endregion @@ -513,18 +514,18 @@ private static HttpResponseMessage ExecuteMergeRequestInternal(ClientContext con #region DELETE - public static async Task DeleteAsync(HttpClient httpClient, string url, string accessToken, string accept = "application/json") + public static string Delete(HttpClient httpClient, string url, string accessToken, string accept = "application/json") { var message = GetMessage(url, HttpMethod.Delete, accessToken, accept); - return await SendMessageAsync(httpClient, message); + return SendMessage(httpClient, message); } - public static async Task DeleteAsync(HttpClient httpClient, string url, string accessToken, bool camlCasePolicy = true) + public static T Delete(HttpClient httpClient, string url, string accessToken, bool camlCasePolicy = true) { - var stringContent = await DeleteAsync(httpClient, url, accessToken); + var stringContent = Delete(httpClient, url, accessToken); if (stringContent != null) { - var options = new JsonSerializerOptions() { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }; + var options = new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; if (camlCasePolicy) { options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; @@ -634,57 +635,57 @@ private static HttpRequestMessage GetMessage(string url, HttpMethod method, Clie return message; } - private static async Task SendMessageAsync(HttpClient httpClient, HttpRequestMessage message) + private static string SendMessage(HttpClient httpClient, HttpRequestMessage message) { - var response = await httpClient.SendAsync(message); + var response = httpClient.Send(message); while (response.StatusCode == (HttpStatusCode)429) { // throttled var retryAfter = response.Headers.RetryAfter; - await Task.Delay(retryAfter.Delta.Value.Seconds * 1000); - response = await httpClient.SendAsync(CloneMessage(message)); + Thread.Sleep(retryAfter.Delta.Value.Seconds * 1000); + response = httpClient.Send(CloneMessage(message)); } if (response.IsSuccessStatusCode) { - return await response.Content.ReadAsStringAsync(); + return response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); } else { - var errorContent = await response.Content.ReadAsStringAsync(); + var errorContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); throw new HttpRequestException(errorContent); } } - private static async Task SendMessageByteArrayAsync(HttpClient httpClient, HttpRequestMessage message) + private static byte[] SendMessageByteArray(HttpClient httpClient, HttpRequestMessage message) { - var response = await httpClient.SendAsync(message); + var response = httpClient.Send(message); while (response.StatusCode == (HttpStatusCode)429) { // throttled var retryAfter = response.Headers.RetryAfter; - await Task.Delay(retryAfter.Delta.Value.Seconds * 1000); - response = await httpClient.SendAsync(CloneMessage(message)); + Thread.Sleep(retryAfter.Delta.Value.Seconds * 1000); + response = httpClient.Send(CloneMessage(message)); } if (response.IsSuccessStatusCode) { - return await response.Content.ReadAsByteArrayAsync(); + return response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); } else { - var errorContent = await response.Content.ReadAsStringAsync(); + var errorContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); throw new HttpRequestException($"HTTP Error {response.StatusCode}: {errorContent}"); } } - private static async Task SendMessageAsyncGetResponseHeader(HttpClient httpClient, HttpRequestMessage message) + private static HttpResponseHeaders SendMessageGetResponseHeader(HttpClient httpClient, HttpRequestMessage message) { - var response = await httpClient.SendAsync(message); + var response = httpClient.Send(message); while (response.StatusCode == (HttpStatusCode)429) { // throttled var retryAfter = response.Headers.RetryAfter; - await Task.Delay(retryAfter.Delta.Value.Seconds * 1000); - response = await httpClient.SendAsync(CloneMessage(message)); + Thread.Sleep(retryAfter.Delta.Value.Seconds * 1000); + response = httpClient.Send(CloneMessage(message)); } if (response.IsSuccessStatusCode) { @@ -692,12 +693,11 @@ private static async Task SendMessageAsyncGetResponseHeader } else { - var errorContent = await response.Content.ReadAsStringAsync(); + var errorContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); ; throw new HttpRequestException(errorContent); } } - private static HttpRequestMessage CloneMessage(HttpRequestMessage req) { HttpRequestMessage clone = new HttpRequestMessage(req.Method, req.RequestUri); @@ -718,5 +718,4 @@ private static HttpRequestMessage CloneMessage(HttpRequestMessage req) return clone; } } - } \ No newline at end of file diff --git a/src/Commands/Utilities/SendMail.cs b/src/Commands/Utilities/SendMail.cs index dc739b2d8..a21f46167 100644 --- a/src/Commands/Utilities/SendMail.cs +++ b/src/Commands/Utilities/SendMail.cs @@ -78,20 +78,20 @@ protected override void ExecuteCmdlet() if (string.IsNullOrWhiteSpace(Password) && string.IsNullOrWhiteSpace(From)) { WriteVerbose("Sending e-mail through SharePoint Online"); - MailUtility.SendSharePointEmail(ClientContext, Subject, Body, To, Cc, Bcc).GetAwaiter().GetResult(); + MailUtility.SendSharePointEmail(ClientContext, Subject, Body, To, Cc, Bcc); } else { if (ParameterSpecified(nameof(Server)) && !string.IsNullOrWhiteSpace(Server)) { WriteVerbose($"Sending e-mail directly through SMTP server {Server}"); - MailUtility.SendSmtpEmail(Subject, Body, From, To, Cc, Bcc, Importance, Server, ServerPort, EnableSsl, Username, Password, BodyContentType ?? MessageBodyContentType.Html).GetAwaiter().GetResult(); + MailUtility.SendSmtpEmail(Subject, Body, From, To, Cc, Bcc, Importance, Server, ServerPort, EnableSsl, Username, Password, BodyContentType ?? MessageBodyContentType.Html); } else { WriteVerbose($"Sending e-mail using Microsoft Graph"); - MailUtility.SendGraphMail(Connection, GraphAccessToken, new Message + MailUtility.SendGraphMail(this, Connection, GraphAccessToken, new Message { Subject = Subject, MessageBody = new Body @@ -106,7 +106,7 @@ protected override void ExecuteCmdlet() ReplyTo = ReplyTo?.Select(t => new Recipient { EmailAddress = new EmailAddress { Address = t } }).ToList(), Importance = Importance, Attachments = MailUtility.GetListOfAttachments(Attachments, SessionState.Path.CurrentFileSystemLocation.Path) - }, SaveToSentItems ?? true).GetAwaiter().GetResult(); + }, SaveToSentItems ?? true); } } diff --git a/src/Commands/Utilities/ServiceHealthUtility.cs b/src/Commands/Utilities/ServiceHealthUtility.cs index 51537fc10..4e9441498 100644 --- a/src/Commands/Utilities/ServiceHealthUtility.cs +++ b/src/Commands/Utilities/ServiceHealthUtility.cs @@ -2,6 +2,7 @@ using PnP.PowerShell.Commands.Model.ServiceHealth; using PnP.PowerShell.Commands.Utilities.REST; using System.Collections.Generic; +using System.Management.Automation; using System.Threading.Tasks; namespace PnP.PowerShell.Commands.Utilities @@ -16,9 +17,9 @@ internal static class ServiceHealthUtility /// Connection to use for retrieval of the data /// AccessToken to use for authentication of the request /// List with objects - public static async Task> GetServiceUpdateMessagesAsync(PnPConnection connection, string accessToken) + public static IEnumerable GetServiceUpdateMessages(Cmdlet cmdlet, PnPConnection connection, string accessToken) { - var collection = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/admin/serviceAnnouncement/messages", accessToken); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/admin/serviceAnnouncement/messages", accessToken); return collection; } @@ -29,9 +30,9 @@ public static async Task> GetServiceUpdateMess /// Connection to use for retrieval of the data /// AccessToken to use for authentication of the request /// containing the requested information - public static async Task GetServiceUpdateMessageByIdAsync(string id, PnPConnection connection, string accessToken) + public static ServiceUpdateMessage GetServiceUpdateMessageById(Cmdlet cmdlet, string id, PnPConnection connection, string accessToken) { - var item = await GraphHelper.GetAsync(connection, $"v1.0/admin/serviceAnnouncement/messages/{id}", accessToken); + var item = GraphHelper.Get(cmdlet, connection, $"v1.0/admin/serviceAnnouncement/messages/{id}", accessToken); return item; } @@ -42,9 +43,9 @@ public static async Task GetServiceUpdateMessageByIdAsync( /// HttpClient to use for updating the data /// AccessToken to use for authentication of the request /// Boolean indicating whether the request succeeded - public static async Task SetServiceUpdateMessageAsReadByIdAsync(string id, PnPConnection connection, string accessToken) + public static bool SetServiceUpdateMessageAsReadById(Cmdlet cmdlet, string id, PnPConnection connection, string accessToken) { - return await SetServiceUpdateMessageAsReadByIdAsync(new [] { id }, connection, accessToken); + return SetServiceUpdateMessageAsReadById(cmdlet, new [] { id }, connection, accessToken); } /// @@ -54,10 +55,10 @@ public static async Task SetServiceUpdateMessageAsReadByIdAsync(string id, /// HttpClient to use for updating the data /// AccessToken to use for authentication of the request /// Boolean indicating whether the request succeeded - public static async Task SetServiceUpdateMessageAsReadByIdAsync(string[] id, PnPConnection connection, string accessToken) + public static bool SetServiceUpdateMessageAsReadById(Cmdlet cmdlet, string[] id, PnPConnection connection, string accessToken) { var postBody = new PnP.PowerShell.Commands.Model.ServiceHealth.ServiceUpdateMessageReadStatusBody { MessageIds = id }; - var item = await GraphHelper.PostAsync(connection, "v1.0/admin/serviceAnnouncement/messages/markRead", postBody, accessToken); + var item = GraphHelper.Post(cmdlet, connection, "v1.0/admin/serviceAnnouncement/messages/markRead", postBody, accessToken); return true; } @@ -68,9 +69,9 @@ public static async Task SetServiceUpdateMessageAsReadByIdAsync(string[] i /// HttpClient to use for updating the data /// AccessToken to use for authentication of the request /// Boolean indicating whether the request succeeded - public static async Task SetServiceUpdateMessageAsUnreadByIdAsync(string id, PnPConnection connection, string accessToken) + public static bool SetServiceUpdateMessageAsUnreadById(Cmdlet cmdlet, string id, PnPConnection connection, string accessToken) { - return await SetServiceUpdateMessageAsUnreadByIdAsync(new [] { id }, connection, accessToken); + return SetServiceUpdateMessageAsUnreadById(cmdlet, new [] { id }, connection, accessToken); } /// @@ -80,10 +81,10 @@ public static async Task SetServiceUpdateMessageAsUnreadByIdAsync(string i /// HttpClient to use for updating the data /// AccessToken to use for authentication of the request /// Boolean indicating whether the request succeeded - public static async Task SetServiceUpdateMessageAsUnreadByIdAsync(string[] id, PnPConnection connection, string accessToken) + public static bool SetServiceUpdateMessageAsUnreadById(Cmdlet cmdlet, string[] id, PnPConnection connection, string accessToken) { var postBody = new PnP.PowerShell.Commands.Model.ServiceHealth.ServiceUpdateMessageReadStatusBody { MessageIds = id }; - var item = await GraphHelper.PostAsync(connection, "v1.0/admin/serviceAnnouncement/messages/markUnread", postBody, accessToken); + var item = GraphHelper.Post(cmdlet, connection, "v1.0/admin/serviceAnnouncement/messages/markUnread", postBody, accessToken); return true; } @@ -94,9 +95,9 @@ public static async Task SetServiceUpdateMessageAsUnreadByIdAsync(string[] /// HttpClient to use for updating the data /// AccessToken to use for authentication of the request /// Boolean indicating whether the request succeeded - public static async Task SetServiceUpdateMessageAsArchivedByIdAsync(string id, PnPConnection connection, string accessToken) + public static bool SetServiceUpdateMessageAsArchivedById(Cmdlet cmdlet, string id, PnPConnection connection, string accessToken) { - return await SetServiceUpdateMessageAsArchivedByIdAsync(new [] { id }, connection, accessToken); + return SetServiceUpdateMessageAsArchivedById(cmdlet, new [] { id }, connection, accessToken); } /// @@ -106,10 +107,10 @@ public static async Task SetServiceUpdateMessageAsArchivedByIdAsync(string /// HttpClient to use for updating the data /// AccessToken to use for authentication of the request /// Boolean indicating whether the request succeeded - public static async Task SetServiceUpdateMessageAsArchivedByIdAsync(string[] id, PnPConnection connection, string accessToken) + public static bool SetServiceUpdateMessageAsArchivedById(Cmdlet cmdlet, string[] id, PnPConnection connection, string accessToken) { - var postBody = new PnP.PowerShell.Commands.Model.ServiceHealth.ServiceUpdateMessageReadStatusBody { MessageIds = id }; - var item = await GraphHelper.PostAsync(connection, "v1.0/admin/serviceAnnouncement/messages/archive", postBody, accessToken); + var postBody = new ServiceUpdateMessageReadStatusBody { MessageIds = id }; + var item = GraphHelper.Post(cmdlet, connection, "v1.0/admin/serviceAnnouncement/messages/archive", postBody, accessToken); return true; } @@ -120,9 +121,9 @@ public static async Task SetServiceUpdateMessageAsArchivedByIdAsync(string /// HttpClient to use for updating the data /// AccessToken to use for authentication of the request /// Boolean indicating whether the request succeeded - public static async Task SetServiceUpdateMessageAsUnarchivedByIdAsync(string id, PnPConnection connection, string accessToken) + public static bool SetServiceUpdateMessageAsUnarchivedById(Cmdlet cmdlet, string id, PnPConnection connection, string accessToken) { - return await SetServiceUpdateMessageAsUnarchivedByIdAsync(new [] { id }, connection, accessToken); + return SetServiceUpdateMessageAsUnarchivedById(cmdlet, new [] { id }, connection, accessToken); } /// @@ -132,10 +133,10 @@ public static async Task SetServiceUpdateMessageAsUnarchivedByIdAsync(stri /// HttpClient to use for updating the data /// AccessToken to use for authentication of the request /// Boolean indicating whether the request succeeded - public static async Task SetServiceUpdateMessageAsUnarchivedByIdAsync(string[] id, PnPConnection connection, string accessToken) + public static bool SetServiceUpdateMessageAsUnarchivedById(Cmdlet cmdlet, string[] id, PnPConnection connection, string accessToken) { - var postBody = new PnP.PowerShell.Commands.Model.ServiceHealth.ServiceUpdateMessageReadStatusBody { MessageIds = id }; - var item = await GraphHelper.PostAsync(connection, "v1.0/admin/serviceAnnouncement/messages/unarchive", postBody, accessToken); + var postBody = new ServiceUpdateMessageReadStatusBody { MessageIds = id }; + var item = GraphHelper.Post(cmdlet, connection, "v1.0/admin/serviceAnnouncement/messages/unarchive", postBody, accessToken); return true; } @@ -146,9 +147,9 @@ public static async Task SetServiceUpdateMessageAsUnarchivedByIdAsync(stri /// HttpClient to use for updating the data /// AccessToken to use for authentication of the request /// Boolean indicating whether the request succeeded - public static async Task SetServiceUpdateMessageAsFavoriteByIdAsync(string id, PnPConnection connection, string accessToken) + public static bool SetServiceUpdateMessageAsFavoriteById(Cmdlet cmdlet, string id, PnPConnection connection, string accessToken) { - return await SetServiceUpdateMessageAsFavoriteByIdAsync(new [] { id }, connection, accessToken); + return SetServiceUpdateMessageAsFavoriteById(cmdlet, new [] { id }, connection, accessToken); } /// @@ -158,10 +159,10 @@ public static async Task SetServiceUpdateMessageAsFavoriteByIdAsync(string /// HttpClient to use for updating the data /// AccessToken to use for authentication of the request /// Boolean indicating whether the request succeeded - public static async Task SetServiceUpdateMessageAsFavoriteByIdAsync(string[] id, PnPConnection connection, string accessToken) + public static bool SetServiceUpdateMessageAsFavoriteById(Cmdlet cmdlet, string[] id, PnPConnection connection, string accessToken) { var postBody = new PnP.PowerShell.Commands.Model.ServiceHealth.ServiceUpdateMessageReadStatusBody { MessageIds = id }; - var item = await GraphHelper.PostAsync(connection, "v1.0/admin/serviceAnnouncement/messages/favorite", postBody, accessToken); + var item = GraphHelper.Post(cmdlet, connection, "v1.0/admin/serviceAnnouncement/messages/favorite", postBody, accessToken); return true; } @@ -172,9 +173,9 @@ public static async Task SetServiceUpdateMessageAsFavoriteByIdAsync(string /// HttpClient to use for updating the data /// AccessToken to use for authentication of the request /// Boolean indicating whether the request succeeded - public static async Task SetServiceUpdateMessageAsNotfavoriteByIdAsync(string id, PnPConnection connection, string accessToken) + public static bool SetServiceUpdateMessageAsNotfavoriteById(Cmdlet cmdlet, string id, PnPConnection connection, string accessToken) { - return await SetServiceUpdateMessageAsNotfavoriteByIdAsync(new [] { id }, connection, accessToken); + return SetServiceUpdateMessageAsNotfavoriteById(cmdlet, new [] { id }, connection, accessToken); } /// @@ -184,10 +185,10 @@ public static async Task SetServiceUpdateMessageAsNotfavoriteByIdAsync(str /// HttpClient to use for updating the data /// AccessToken to use for authentication of the request /// Boolean indicating whether the request succeeded - public static async Task SetServiceUpdateMessageAsNotfavoriteByIdAsync(string[] id, PnPConnection connection, string accessToken) + public static bool SetServiceUpdateMessageAsNotfavoriteById(Cmdlet cmdlet, string[] id, PnPConnection connection, string accessToken) { var postBody = new PnP.PowerShell.Commands.Model.ServiceHealth.ServiceUpdateMessageReadStatusBody { MessageIds = id }; - var item = await GraphHelper.PostAsync(connection, "v1.0/admin/serviceAnnouncement/messages/unfavorite", postBody, accessToken); + var item = GraphHelper.Post(cmdlet, connection, "v1.0/admin/serviceAnnouncement/messages/unfavorite", postBody, accessToken); return true; } @@ -201,9 +202,9 @@ public static async Task SetServiceUpdateMessageAsNotfavoriteByIdAsync(str /// Connection to use for retrieval of the data /// AccessToken to use for authentication of the request /// List with objects - public static async Task> GetServiceHealthIssuesAsync(PnPConnection connection, string accessToken) + public static IEnumerable GetServiceHealthIssues(Cmdlet cmdlet, PnPConnection connection, string accessToken) { - var collection = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/admin/serviceAnnouncement/issues", accessToken); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/admin/serviceAnnouncement/issues", accessToken); return collection; } @@ -214,9 +215,9 @@ public static async Task> GetServiceHealthIssues /// Connection to use for retrieval of the data /// AccessToken to use for authentication of the request /// containing the requested information - public static async Task GetServiceHealthIssueByIdAsync(string id, PnPConnection connection, string accessToken) + public static ServiceHealthIssue GetServiceHealthIssueById(Cmdlet cmdlet, string id, PnPConnection connection, string accessToken) { - var item = await GraphHelper.GetAsync(connection, $"v1.0/admin/serviceAnnouncement/issues/{id}", accessToken); + var item = GraphHelper.Get(cmdlet, connection, $"v1.0/admin/serviceAnnouncement/issues/{id}", accessToken); return item; } @@ -230,9 +231,9 @@ public static async Task GetServiceHealthIssueByIdAsync(stri /// Connection to use for retrieval of the data /// AccessToken to use for authentication of the request /// List with objects - public static async Task> GetServiceCurrentHealthAsync(PnPConnection connection, string accessToken) + public static IEnumerable GetServiceCurrentHealth(Cmdlet cmdlet, PnPConnection connection, string accessToken) { - var collection = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/admin/serviceAnnouncement/healthOverviews", accessToken); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/admin/serviceAnnouncement/healthOverviews", accessToken); return collection; } @@ -243,9 +244,9 @@ public static async Task> GetServiceCurrentHea /// Connection to use for retrieval of the data /// AccessToken to use for authentication of the request /// containing the requested information - public static async Task GetServiceCurrentHealthByIdAsync(string id, PnPConnection connection, string accessToken) + public static ServiceHealthCurrent GetServiceCurrentHealthById(Cmdlet cmdlet, string id, PnPConnection connection, string accessToken) { - var item = await GraphHelper.GetAsync(connection, $"v1.0/admin/serviceAnnouncement/healthOverviews/{id}", accessToken); + var item = GraphHelper.Get(cmdlet, connection, $"v1.0/admin/serviceAnnouncement/healthOverviews/{id}", accessToken); return item; } diff --git a/src/Commands/Utilities/ServicePrincipalUtility.cs b/src/Commands/Utilities/ServicePrincipalUtility.cs index 192337b05..901c26f39 100644 --- a/src/Commands/Utilities/ServicePrincipalUtility.cs +++ b/src/Commands/Utilities/ServicePrincipalUtility.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Management.Automation; using System.Net.Http; namespace PnP.PowerShell.Commands.Utilities @@ -16,7 +17,7 @@ internal static class ServicePrincipalUtility /// /// Returns all service principals /// - public static List GetServicePrincipals(PnPConnection connection, string accesstoken, string filter = null) + public static List GetServicePrincipals(Cmdlet cmdlet, PnPConnection connection, string accesstoken, string filter = null) { string requestUrl = $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals"; Dictionary additionalHeaders = null; @@ -28,24 +29,24 @@ public static List GetServicePrincipals(PnPConnection c { "ConsistencyLevel", "eventual" } }; } - var result = REST.GraphHelper.GetResultCollectionAsync(connection, requestUrl, accesstoken, additionalHeaders: additionalHeaders).GetAwaiter().GetResult(); + var result = REST.GraphHelper.GetResultCollection(cmdlet, connection, requestUrl, accesstoken, additionalHeaders: additionalHeaders); return result.ToList(); } /// /// Returns the service principal of the provided built in type /// - public static AzureADServicePrincipal GetServicePrincipalByBuiltInType(PnPConnection connection, string accesstoken, ServicePrincipalBuiltInType builtInType) + public static AzureADServicePrincipal GetServicePrincipalByBuiltInType(Cmdlet cmdlet, PnPConnection connection, string accesstoken, ServicePrincipalBuiltInType builtInType) { AzureADServicePrincipal result = null; switch (builtInType) { case ServicePrincipalBuiltInType.MicrosoftGraph: - result = ServicePrincipalUtility.GetServicePrincipalByAppId(connection, accesstoken, new Guid("00000003-0000-0000-c000-000000000000")); + result = ServicePrincipalUtility.GetServicePrincipalByAppId(cmdlet, connection, accesstoken, new Guid("00000003-0000-0000-c000-000000000000")); break; case ServicePrincipalBuiltInType.SharePointOnline: - result = ServicePrincipalUtility.GetServicePrincipalByAppId(connection, accesstoken, new Guid("00000003-0000-0ff1-ce00-000000000000")); + result = ServicePrincipalUtility.GetServicePrincipalByAppId(cmdlet, connection, accesstoken, new Guid("00000003-0000-0ff1-ce00-000000000000")); break; default: @@ -57,12 +58,12 @@ public static AzureADServicePrincipal GetServicePrincipalByBuiltInType(PnPConnec /// /// Returns the service principal of the provided object id /// - public static AzureADServicePrincipal GetServicePrincipalByObjectId(PnPConnection connection, string accesstoken, Guid objectId) + public static AzureADServicePrincipal GetServicePrincipalByObjectId(Cmdlet cmdlet, PnPConnection connection, string accesstoken, Guid objectId) { IEnumerable result; try { - result = Utilities.REST.GraphHelper.GetResultCollectionAsync(connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals?$filter=id eq '{objectId}'", accesstoken).GetAwaiter().GetResult(); + result = Utilities.REST.GraphHelper.GetResultCollection(cmdlet, connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals?$filter=id eq '{objectId}'", accesstoken); var servicePrincipal = result.FirstOrDefault(); servicePrincipal.AppRoles.ForEach(ar => ar.ServicePrincipal = servicePrincipal); @@ -75,12 +76,12 @@ public static AzureADServicePrincipal GetServicePrincipalByObjectId(PnPConnectio /// /// Returns the service principal of the provided app id /// - public static AzureADServicePrincipal GetServicePrincipalByAppId(PnPConnection connection, string accesstoken, Guid appId) + public static AzureADServicePrincipal GetServicePrincipalByAppId(Cmdlet cmdlet, PnPConnection connection, string accesstoken, Guid appId) { IEnumerable result; try { - result = Utilities.REST.GraphHelper.GetResultCollectionAsync(connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals?$filter=appid eq '{appId}'", accesstoken).GetAwaiter().GetResult(); + result = Utilities.REST.GraphHelper.GetResultCollection(cmdlet, connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals?$filter=appid eq '{appId}'", accesstoken); var servicePrincipal = result.FirstOrDefault(); servicePrincipal.AppRoles.ForEach(ar => ar.ServicePrincipal = servicePrincipal); @@ -93,12 +94,12 @@ public static AzureADServicePrincipal GetServicePrincipalByAppId(PnPConnection c /// /// Returns the service principal with the provided name /// - public static AzureADServicePrincipal GetServicePrincipalByAppName(PnPConnection connection, string accesstoken, string appName) + public static AzureADServicePrincipal GetServicePrincipalByAppName(Cmdlet cmdlet, PnPConnection connection, string accesstoken, string appName) { IEnumerable result; try { - result = Utilities.REST.GraphHelper.GetResultCollectionAsync(connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals?$filter=displayName eq '{appName}'", accesstoken).GetAwaiter().GetResult(); + result = Utilities.REST.GraphHelper.GetResultCollection(cmdlet, connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals?$filter=displayName eq '{appName}'", accesstoken); var servicePrincipal = result.FirstOrDefault(); servicePrincipal.AppRoles.ForEach(ar => ar.ServicePrincipal = servicePrincipal); @@ -111,13 +112,13 @@ public static AzureADServicePrincipal GetServicePrincipalByAppName(PnPConnection /// /// Returns the service principal app role assignments of the service principal with the provided object id /// - public static List GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(PnPConnection connection, string accesstoken, string servicePrincipalObjectId, string appRoleAssignmentId) + public static List GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(Cmdlet cmdlet, PnPConnection connection, string accesstoken, string servicePrincipalObjectId, string appRoleAssignmentId) { try { // Retrieve the specific app role assigned to the service principal - var results = Utilities.REST.GraphHelper.GetAsync(connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals/{servicePrincipalObjectId}/appRoleAssignments/{appRoleAssignmentId}", accesstoken).GetAwaiter().GetResult(); - var enrichedResults = ServicePrincipalUtility.EnrichAzureADServicePrincipalAppRoleAssignments(connection, accesstoken, new List { results }); + var results = Utilities.REST.GraphHelper.Get(cmdlet, connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals/{servicePrincipalObjectId}/appRoleAssignments/{appRoleAssignmentId}", accesstoken); + var enrichedResults = ServicePrincipalUtility.EnrichAzureADServicePrincipalAppRoleAssignments(cmdlet, connection, accesstoken, new List { results }); return enrichedResults.ToList(); } catch (Exception) { } @@ -127,13 +128,13 @@ public static List GetServicePrincipal /// /// Returns the service principal app role assignments of the service principal with the provided object id /// - public static List GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(PnPConnection connection, string accesstoken, string servicePrincipalObjectId) + public static List GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(Cmdlet cmdlet, PnPConnection connection, string accesstoken, string servicePrincipalObjectId) { try { // Retrieve all the app role assigned to the service principal - var results = Utilities.REST.GraphHelper.GetResultCollectionAsync(connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals/{servicePrincipalObjectId}/appRoleAssignments", accesstoken).GetAwaiter().GetResult(); - var enrichedResults = ServicePrincipalUtility.EnrichAzureADServicePrincipalAppRoleAssignments(connection, accesstoken, results); + var results = Utilities.REST.GraphHelper.GetResultCollection(cmdlet, connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals/{servicePrincipalObjectId}/appRoleAssignments", accesstoken); + var enrichedResults = ServicePrincipalUtility.EnrichAzureADServicePrincipalAppRoleAssignments(cmdlet, connection, accesstoken, results); return enrichedResults.ToList(); } catch (Exception) { } @@ -147,7 +148,7 @@ public static List GetServicePrincipal /// Access Token to use to authenticate to Microsoft Graph /// Enumerable with app role assignments to enrich /// Enriched app role assignements - private static IEnumerable EnrichAzureADServicePrincipalAppRoleAssignments(PnPConnection connection, string accesstoken, IEnumerable azureADServicePrincipalAppRoleAssignments) + private static IEnumerable EnrichAzureADServicePrincipalAppRoleAssignments(Cmdlet cmdlet, PnPConnection connection, string accesstoken, IEnumerable azureADServicePrincipalAppRoleAssignments) { // Since the result does not contain the friendly claim value (i.e. Group.ReadWrite.All) but just identifiers for it, we will enrich the result with the friendly name oursevles var servicePrincipalCache = new Dictionary(); @@ -168,7 +169,7 @@ private static IEnumerable EnrichAzure else { // Service principal is not in cache yet, retrieve it from the Graph API - servicePrincipal = GetServicePrincipalByObjectId(connection, accesstoken, azureADServicePrincipalAppRoleAssignment.ResourceId.Value); + servicePrincipal = GetServicePrincipalByObjectId(cmdlet, connection, accesstoken, azureADServicePrincipalAppRoleAssignment.ResourceId.Value); if (servicePrincipal != null) { @@ -194,11 +195,11 @@ private static IEnumerable EnrichAzure /// The service principal to add the role to /// The app role to add to the service principal /// The service principal app role assignment - public static AzureADServicePrincipalAppRoleAssignment AddServicePrincipalRoleAssignment(PnPConnection connection, string accesstoken, AzureADServicePrincipal principalToAddRoleTo, AzureADServicePrincipalAppRole appRoleToAdd) + public static AzureADServicePrincipalAppRoleAssignment AddServicePrincipalRoleAssignment(Cmdlet cmdlet, PnPConnection connection, string accesstoken, AzureADServicePrincipal principalToAddRoleTo, AzureADServicePrincipalAppRole appRoleToAdd) { var content = new StringContent($"{{'principalId':'{principalToAddRoleTo.Id}','resourceId':'{appRoleToAdd.ServicePrincipal.Id}','appRoleId':'{appRoleToAdd.Id}'}}"); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - var result = Utilities.REST.GraphHelper.PostAsync(connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals/{principalToAddRoleTo.Id}/appRoleAssignments", content, accesstoken).GetAwaiter().GetResult(); + var result = Utilities.REST.GraphHelper.Post(cmdlet, connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals/{principalToAddRoleTo.Id}/appRoleAssignments", content, accesstoken); return result; } @@ -208,12 +209,12 @@ public static AzureADServicePrincipalAppRoleAssignment AddServicePrincipalRoleAs /// Connection to use to communicate with Microsoft Graph /// Access Token to use to authenticate to Microsoft Graph /// The service principal to remove the role assignments from - public static void RemoveServicePrincipalRoleAssignment(PnPConnection connection, string accesstoken, AzureADServicePrincipal principalToRemoveRoleFrom) + public static void RemoveServicePrincipalRoleAssignment(Cmdlet cmdlet, PnPConnection connection, string accesstoken, AzureADServicePrincipal principalToRemoveRoleFrom) { - var assignments = GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(connection, accesstoken, principalToRemoveRoleFrom.Id); + var assignments = GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(cmdlet, connection, accesstoken, principalToRemoveRoleFrom.Id); foreach (var assignment in assignments) { - Utilities.REST.GraphHelper.DeleteAsync(connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals/{principalToRemoveRoleFrom.Id}/appRoleAssignments/{assignment.Id}", accesstoken).GetAwaiter().GetResult(); + Utilities.REST.GraphHelper.Delete(cmdlet, connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals/{principalToRemoveRoleFrom.Id}/appRoleAssignments/{assignment.Id}", accesstoken); } } @@ -224,14 +225,14 @@ public static void RemoveServicePrincipalRoleAssignment(PnPConnection connection /// Access Token to use to authenticate to Microsoft Graph /// The service principal to remove the role assignment from /// The app role to remove from the role assignments - public static void RemoveServicePrincipalRoleAssignment(PnPConnection connection, string accesstoken, AzureADServicePrincipal principalToRemoveRoleFrom, AzureADServicePrincipalAppRole appRoleToRemove) + public static void RemoveServicePrincipalRoleAssignment(Cmdlet cmdlet, PnPConnection connection, string accesstoken, AzureADServicePrincipal principalToRemoveRoleFrom, AzureADServicePrincipalAppRole appRoleToRemove) { - var assignments = GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(connection, accesstoken, principalToRemoveRoleFrom.Id); + var assignments = GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(cmdlet, connection, accesstoken, principalToRemoveRoleFrom.Id); foreach (var assignment in assignments) { if (assignment.AppRoleId == appRoleToRemove.Id) { - Utilities.REST.GraphHelper.DeleteAsync(connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals/{principalToRemoveRoleFrom.Id}/appRoleAssignments/{assignment.Id}", accesstoken).GetAwaiter().GetResult(); + Utilities.REST.GraphHelper.Delete(cmdlet, connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals/{principalToRemoveRoleFrom.Id}/appRoleAssignments/{assignment.Id}", accesstoken); } } } @@ -243,14 +244,14 @@ public static void RemoveServicePrincipalRoleAssignment(PnPConnection connection /// Access Token to use to authenticate to Microsoft Graph /// The service principal to remove the role assignment from /// The name of the app role to remove from the role assignments - public static void RemoveServicePrincipalRoleAssignment(PnPConnection connection, string accesstoken, AzureADServicePrincipal principalToRemoveRoleFrom, string roleName) + public static void RemoveServicePrincipalRoleAssignment(Cmdlet cmdlet, PnPConnection connection, string accesstoken, AzureADServicePrincipal principalToRemoveRoleFrom, string roleName) { - var assignments = GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(connection, accesstoken, principalToRemoveRoleFrom.Id); + var assignments = GetServicePrincipalAppRoleAssignmentsByServicePrincipalObjectId(cmdlet, connection, accesstoken, principalToRemoveRoleFrom.Id); foreach (var assignment in assignments) { if (assignment.AppRoleName == roleName) { - Utilities.REST.GraphHelper.DeleteAsync(connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals/{principalToRemoveRoleFrom.Id}/appRoleAssignments/{assignment.Id}", accesstoken).GetAwaiter().GetResult(); + Utilities.REST.GraphHelper.Delete(cmdlet, connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals/{principalToRemoveRoleFrom.Id}/appRoleAssignments/{assignment.Id}", accesstoken); } } } @@ -262,9 +263,9 @@ public static void RemoveServicePrincipalRoleAssignment(PnPConnection connection /// Access Token to use to authenticate to Microsoft Graph /// The service principal to remove the role assignment from /// The app role assignment to remove from the service principal - public static void RemoveServicePrincipalRoleAssignment(PnPConnection connection, string accesstoken, AzureADServicePrincipalAppRoleAssignment appRoleAssignmenToRemove) + public static void RemoveServicePrincipalRoleAssignment(Cmdlet cmdlet, PnPConnection connection, string accesstoken, AzureADServicePrincipalAppRoleAssignment appRoleAssignmenToRemove) { - Utilities.REST.GraphHelper.DeleteAsync(connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals/{appRoleAssignmenToRemove.PrincipalId}/appRoleAssignments/{appRoleAssignmenToRemove.Id}", accesstoken).GetAwaiter().GetResult(); + Utilities.REST.GraphHelper.Delete(cmdlet, connection, $"https://{connection.GraphEndPoint}/v1.0/servicePrincipals/{appRoleAssignmenToRemove.PrincipalId}/appRoleAssignments/{appRoleAssignmenToRemove.Id}", accesstoken); } } } \ No newline at end of file diff --git a/src/Commands/Utilities/SiteTemplates.cs b/src/Commands/Utilities/SiteTemplates.cs index 091a7dab9..3c5107257 100644 --- a/src/Commands/Utilities/SiteTemplates.cs +++ b/src/Commands/Utilities/SiteTemplates.cs @@ -6,6 +6,7 @@ using PnP.PowerShell.Commands.Model.SharePoint; using System.Collections.Generic; using PnP.PowerShell.Commands.Base; +using System.Management.Automation; namespace PnP.PowerShell.Commands.Utilities { @@ -24,9 +25,9 @@ internal static class SiteTemplates /// The Site Script to invoke /// The URL of the SharePoint site to invoke the Site Script on /// HttpResponseMessage with the - public static async Task> InvokeSiteScript(PnPConnection connection, string accessToken, TenantSiteScript script, string siteUrl) + public static RestResultCollection InvokeSiteScript(Cmdlet cmdlet, PnPConnection connection, string accessToken, TenantSiteScript script, string siteUrl) { - return await InvokeSiteScript(connection, accessToken, script.Content, siteUrl); + return InvokeSiteScript(cmdlet, connection, accessToken, script.Content, siteUrl); } /// @@ -37,7 +38,7 @@ public static async Task> I /// The Site Script content to invoke /// The URL of the SharePoint site to invoke the Site Script on /// - public static async Task> InvokeSiteScript(PnPConnection connection, string accessToken, string scriptContent, string siteUrl) + public static RestResultCollection InvokeSiteScript(Cmdlet cmdlet, PnPConnection connection, string accessToken, string scriptContent, string siteUrl) { // Properly encode the contents of the provided site script var escapedScript = Regex.Replace(scriptContent.Replace("\\\"", "\\\\\\\""), "(?> I postBody.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); // Execute the request to apply the site script - var results = await GraphHelper.PostAsync>(connection, $"{siteUrl.TrimEnd('/')}/_api/Microsoft.Sharepoint.Utilities.WebTemplateExtensions.SiteScriptUtility.ExecuteTemplateScript()", postBody, accessToken, new Dictionary{{ "Accept", "application/json" }}); + var results = GraphHelper.Post>(cmdlet, connection, $"{siteUrl.TrimEnd('/')}/_api/Microsoft.Sharepoint.Utilities.WebTemplateExtensions.SiteScriptUtility.ExecuteTemplateScript()", postBody, accessToken, new Dictionary{{ "Accept", "application/json" }}); return results; } diff --git a/src/Commands/Utilities/TeamsUtility.cs b/src/Commands/Utilities/TeamsUtility.cs index 2085f758f..6768245cd 100644 --- a/src/Commands/Utilities/TeamsUtility.cs +++ b/src/Commands/Utilities/TeamsUtility.cs @@ -11,7 +11,7 @@ using System.Management.Automation; using System.Net.Http; using System.Text.Json; -using System.Text.Json.Serialization; +using System.Threading; using System.Threading.Tasks; using Group = PnP.PowerShell.Commands.Model.Graph.Group; using Team = PnP.PowerShell.Commands.Model.Teams.Team; @@ -25,7 +25,7 @@ internal static class TeamsUtility private const int PageSize = 100; #region Team - public static async Task> GetGroupsWithTeamAsync(PnPConnection connection, string accessToken, string filter = null) + public static List GetGroupsWithTeam(Cmdlet cmdlet, PnPConnection connection, string accessToken, string filter = null) { Dictionary additionalHeaders = null; string requestUrl; @@ -50,23 +50,23 @@ public static async Task> GetGroupsWithTeamAsync(PnPConnection conne requestUrl = $"v1.0/groups?$filter={filter}&$select=Id,DisplayName,MailNickName,Description,Visibility&$top={PageSize}&$count=true"; } - var collection = await GraphHelper.GetResultCollectionAsync(connection, requestUrl, accessToken, additionalHeaders: additionalHeaders); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, requestUrl, accessToken, additionalHeaders: additionalHeaders); return collection.ToList(); } - public static async Task GetGroupWithTeamAsync(PnPConnection connection, string accessToken, string mailNickname) + public static Group GetGroupWithTeam(Cmdlet cmdlet, PnPConnection connection, string accessToken, string mailNickname) { - return await GraphHelper.GetAsync(connection, $"v1.0/groups?$filter=(resourceProvisioningOptions/Any(x:x eq 'Team') and mailNickname eq '{mailNickname}')&$select=Id,DisplayName,MailNickName,Description,Visibility", accessToken); + return GraphHelper.Get(cmdlet, connection, $"v1.0/groups?$filter=(resourceProvisioningOptions/Any(x:x eq 'Team') and mailNickname eq '{mailNickname}')&$select=Id,DisplayName,MailNickName,Description,Visibility", accessToken); } - public static async Task> GetTeamsAsync(string accessToken, PnPConnection connection, String filter) + public static List GetTeamUsingFilter(Cmdlet cmdlet, string accessToken, PnPConnection connection, String filter) { List teams = new List(); - var groups = await GetGroupsWithTeamAsync(connection, accessToken, filter); + var groups = GetGroupsWithTeam(cmdlet, connection, accessToken, filter); foreach (var group in groups) { - Team team = await ParseTeamJsonAsync(accessToken, connection, group.Id); + Team team = ParseTeamJson(cmdlet, accessToken, connection, group.Id); if (team != null) { @@ -79,12 +79,12 @@ public static async Task> GetTeamsAsync(string accessToken, PnPConnec return teams; } - public static async Task GetTeamAsync(string accessToken, PnPConnection connection, string groupId) + public static Team GetTeam(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId) { // get the group - var group = await GraphHelper.GetAsync(connection, $"v1.0/groups/{groupId}?$select=Id,DisplayName,MailNickName,Description,Visibility", accessToken); + var group = GraphHelper.Get(cmdlet, connection, $"v1.0/groups/{groupId}?$select=Id,DisplayName,MailNickName,Description,Visibility", accessToken); - Team team = await ParseTeamJsonAsync(accessToken, connection, group.Id); + Team team = ParseTeamJson(cmdlet, accessToken, connection, group.Id); if (team != null) { team.DisplayName = group.DisplayName; @@ -98,11 +98,11 @@ public static async Task GetTeamAsync(string accessToken, PnPConnection co } } - public static async Task DeleteTeamAsync(string accessToken, PnPConnection connection, string groupId) + public static HttpResponseMessage DeleteTeam(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId) { - return await GraphHelper.DeleteAsync(connection, $"v1.0/groups/{groupId}", accessToken); + return GraphHelper.Delete(cmdlet, connection, $"v1.0/groups/{groupId}", accessToken); } - public static async Task CloneTeamAsync(string accessToken, PnPConnection connection, string groupId, TeamCloneInformation teamClone) + public static HttpResponseMessage CloneTeam(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId, TeamCloneInformation teamClone) { StringContent content = new StringContent(JsonSerializer.Serialize(new { @@ -114,14 +114,14 @@ public static async Task CloneTeamAsync(string accessToken, partsToClone = String.Join(",", teamClone.PartsToClone) })); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - return await GraphHelper.PostAsync(connection, $"v1.0/teams/{groupId}/clone", accessToken, content); + return GraphHelper.Post(cmdlet, connection, $"v1.0/teams/{groupId}/clone", accessToken, content); } - private static async Task ParseTeamJsonAsync(string accessToken, PnPConnection connection, string groupId) + private static Team ParseTeamJson(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId) { // Get Settings try { - var team = await GraphHelper.GetAsync(connection, $"v1.0/teams/{groupId}", accessToken, false, true); + var team = GraphHelper.Get(cmdlet, connection, $"v1.0/teams/{groupId}", accessToken, false, true); if (team != null) { team.GroupId = groupId; @@ -147,7 +147,7 @@ private static async Task ParseTeamJsonAsync(string accessToken, PnPConnec } } - public static async Task NewTeamAsync(string accessToken, PnPConnection connection, string groupId, string displayName, string description, string classification, string mailNickname, GroupVisibility visibility, TeamCreationInformation teamCI, string[] owners, string[] members, Guid[] sensitivityLabels, TeamsTemplateType templateType = TeamsTemplateType.None, TeamResourceBehaviorOptions?[] resourceBehaviorOptions = null) + public static Team NewTeam(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId, string displayName, string description, string classification, string mailNickname, GroupVisibility visibility, TeamCreationInformation teamCI, string[] owners, string[] members, Guid[] sensitivityLabels, TeamsTemplateType templateType = TeamsTemplateType.None, TeamResourceBehaviorOptions?[] resourceBehaviorOptions = null) { Group group = null; Team returnTeam = null; @@ -155,7 +155,7 @@ public static async Task NewTeamAsync(string accessToken, PnPConnection co // Create the Group if (string.IsNullOrEmpty(groupId)) { - group = await CreateGroupAsync(accessToken, connection, displayName, description, classification, mailNickname, visibility, owners, sensitivityLabels, templateType, resourceBehaviorOptions); + group = CreateGroup(cmdlet, accessToken, connection, displayName, description, classification, mailNickname, visibility, owners, sensitivityLabels, templateType, resourceBehaviorOptions); bool wait = true; int iterations = 0; while (wait) @@ -164,7 +164,7 @@ public static async Task NewTeamAsync(string accessToken, PnPConnection co try { - var createdGroup = await GraphHelper.GetAsync(connection, $"v1.0/groups/{group.Id}", accessToken); + var createdGroup = GraphHelper.Get(cmdlet, connection, $"v1.0/groups/{group.Id}", accessToken); if (!string.IsNullOrEmpty(createdGroup.DisplayName)) { wait = false; @@ -173,7 +173,7 @@ public static async Task NewTeamAsync(string accessToken, PnPConnection co catch (Exception) { // In case of exception wait for 5 secs - await Task.Delay(TimeSpan.FromSeconds(5)); + Thread.Sleep(TimeSpan.FromSeconds(5)); } // Don't wait more than 1 minute @@ -185,7 +185,7 @@ public static async Task NewTeamAsync(string accessToken, PnPConnection co } else { - group = await GraphHelper.GetAsync(connection, $"v1.0/groups/{groupId}", accessToken); + group = GraphHelper.Get(cmdlet, connection, $"v1.0/groups/{groupId}", accessToken); if (group == null) { throw new PSArgumentException($"Cannot find group with id {groupId}"); @@ -202,22 +202,22 @@ public static async Task NewTeamAsync(string accessToken, PnPConnection co { try { - var teamSettings = await GraphHelper.PutAsync(connection, $"v1.0/groups/{group.Id}/team", team, accessToken); + var teamSettings = GraphHelper.Put(cmdlet, connection, $"v1.0/groups/{group.Id}/team", team, accessToken); if (teamSettings != null) { - returnTeam = await GetTeamAsync(accessToken, connection, group.Id); + returnTeam = GetTeam(cmdlet, accessToken, connection, group.Id); } retry = false; } catch (GraphException ge) when (ge.HttpResponse.StatusCode == System.Net.HttpStatusCode.Conflict) { // Handle conflict exceptions as if it succeeded, as it means a previous request succeeded enabling teams - returnTeam = await GetTeamAsync(accessToken, connection, group.Id); + returnTeam = GetTeam(cmdlet, accessToken, connection, group.Id); retry = false; } catch (Exception) { - await Task.Delay(5000); + Thread.Sleep(5000); iteration++; if (iteration > 10) { @@ -254,7 +254,7 @@ public static async Task NewTeamAsync(string accessToken, PnPConnection co var ownersAndMembers = BatchUtility.Chunk(teamOwnersAndMembers, 200); foreach (var chunk in ownersAndMembers) { - await GraphHelper.PostAsync(connection, $"v1.0/teams/{group.Id}/members/add", new { values = chunk.ToList() }, accessToken); + GraphHelper.Post(cmdlet, connection, $"v1.0/teams/{group.Id}/members/add", new { values = chunk.ToList() }, accessToken); } } } @@ -271,14 +271,14 @@ internal static string GetUserGraphUrlForUPN(string upn) return $"users/{escapedUpn}"; } - private static async Task CreateGroupAsync(string accessToken, PnPConnection connection, string displayName, string description, string classification, string mailNickname, GroupVisibility visibility, string[] owners, Guid[] sensitivityLabels, TeamsTemplateType templateType = TeamsTemplateType.None, TeamResourceBehaviorOptions?[] resourceBehaviorOptions = null) + private static Group CreateGroup(Cmdlet cmdlet, string accessToken, PnPConnection connection, string displayName, string description, string classification, string mailNickname, GroupVisibility visibility, string[] owners, Guid[] sensitivityLabels, TeamsTemplateType templateType = TeamsTemplateType.None, TeamResourceBehaviorOptions?[] resourceBehaviorOptions = null) { // When creating a group, we always need an owner, thus we'll try to define it from the passed in owners array string ownerId = null; if (owners != null && owners.Length > 0) { // Owner(s) have been provided, use the first owner as the initial owner. The other owners will be added later. - var user = await GraphHelper.GetAsync(connection, $"v1.0/{GetUserGraphUrlForUPN(owners[0])}?$select=Id", accessToken); + var user = GraphHelper.Get(cmdlet, connection, $"v1.0/{GetUserGraphUrlForUPN(owners[0])}?$select=Id", accessToken); if (user != null) { @@ -288,7 +288,7 @@ private static async Task CreateGroupAsync(string accessToken, PnPConnect else { // Unable to find the owner by its user principal name, try looking for it on its email address - var collection = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/users?$filter=mail eq '{owners[0]}'&$select=Id", accessToken); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/users?$filter=mail eq '{owners[0]}'&$select=Id", accessToken); if (collection != null && collection.Any()) { // User found on its email address @@ -306,7 +306,7 @@ private static async Task CreateGroupAsync(string accessToken, PnPConnect if (contextSettings.Type != Framework.Utilities.Context.ClientContextType.AzureADCertificate) { // A delegate context is available, make the user part of the delegate token the owner - var user = await GraphHelper.GetAsync(connection, "v1.0/me?$select=Id", accessToken); + var user = GraphHelper.Get(cmdlet, connection, "v1.0/me?$select=Id", accessToken); if (user != null) { @@ -323,7 +323,7 @@ private static async Task CreateGroupAsync(string accessToken, PnPConnect Description = description, Classification = classification, MailEnabled = true, - MailNickname = mailNickname ?? await CreateAliasAsync(connection, accessToken), + MailNickname = mailNickname ?? CreateAlias(cmdlet, connection, accessToken), GroupTypes = new List() { "Unified" }, SecurityEnabled = false, Visibility = visibility == GroupVisibility.NotSpecified ? GroupVisibility.Private : visibility @@ -381,7 +381,7 @@ private static async Task CreateGroupAsync(string accessToken, PnPConnect } try { - return await GraphHelper.PostAsync(connection, "v1.0/groups", group, accessToken); + return GraphHelper.Post(cmdlet, connection, "v1.0/groups", group, accessToken); } catch (GraphException ex) { @@ -396,7 +396,7 @@ private static async Task CreateGroupAsync(string accessToken, PnPConnect } } - private static async Task CreateAliasAsync(PnPConnection connection, string accessToken) + private static string CreateAlias(Cmdlet cmdlet, PnPConnection connection, string accessToken) { var guid = Guid.NewGuid().ToString(); var teamName = string.Empty; @@ -404,7 +404,7 @@ private static async Task CreateAliasAsync(PnPConnection connection, str do { var teamNameTemp = $"msteams_{guid.Substring(0, 8)}{guid.Substring(9, 4)}"; - var collection = await GraphHelper.GetAsync>(connection, $"v1.0/groups?$filter=groupTypes/any(c:c+eq+'Unified') and (mailNickname eq '{teamNameTemp}')", accessToken); + var collection = GraphHelper.Get>(cmdlet, connection, $"v1.0/groups?$filter=groupTypes/any(c:c+eq+'Unified') and (mailNickname eq '{teamNameTemp}')", accessToken); if (collection != null) { if (!collection.Items.Any()) teamName = teamNameTemp; @@ -414,43 +414,43 @@ private static async Task CreateAliasAsync(PnPConnection connection, str return teamName; } - public static async Task UpdateTeamAsync(PnPConnection connection, string accessToken, string groupId, Team team) + public static Team UpdateTeam(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, Team team) { - return await GraphHelper.PatchAsync(connection, accessToken, $"v1.0/teams/{groupId}", team); + return GraphHelper.Patch(cmdlet, connection, accessToken, $"v1.0/teams/{groupId}", team); } - public static async Task UpdateGroupAsync(PnPConnection connection, string accessToken, string groupId, Group group) + public static Group UpdateGroup(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, Group group) { - return await GraphHelper.PatchAsync(connection, accessToken, $"v1.0/groups/{groupId}", group); + return GraphHelper.Patch(cmdlet, connection, accessToken, $"v1.0/groups/{groupId}", group); } - public static async Task SetTeamPictureAsync(PnPConnection connection, string accessToken, string teamId, byte[] bytes, string contentType) + public static void SetTeamPictureAsync(Cmdlet cmdlet, PnPConnection connection, string accessToken, string teamId, byte[] bytes, string contentType) { var byteArrayContent = new ByteArrayContent(bytes); byteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); - await GraphHelper.PutAsync(connection, $"v1.0/teams/{teamId}/photo/$value", accessToken, byteArrayContent); + GraphHelper.Put(cmdlet, connection, $"v1.0/teams/{teamId}/photo/$value", accessToken, byteArrayContent); } - public static async Task SetTeamArchivedStateAsync(PnPConnection connection, string accessToken, string groupId, bool archived, bool? setSiteReadOnly) + public static HttpResponseMessage SetTeamArchivedState(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, bool archived, bool? setSiteReadOnly) { if (archived) { StringContent content = new StringContent(JsonSerializer.Serialize(setSiteReadOnly.HasValue ? new { shouldSetSpoSiteReadOnlyForMembers = setSiteReadOnly } : null)); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - return await GraphHelper.PostAsync(connection, $"v1.0/teams/{groupId}/archive", accessToken, content); + return GraphHelper.Post(cmdlet, connection, $"v1.0/teams/{groupId}/archive", accessToken, content); } else { StringContent content = new StringContent(""); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - return await GraphHelper.PostAsync(connection, $"v1.0/teams/{groupId}/unarchive", accessToken, content); + return GraphHelper.Post(cmdlet, connection, $"v1.0/teams/{groupId}/unarchive", accessToken, content); } } - public static async Task> GetDeletedTeamAsync(string accessToken, PnPConnection connection) + public static IEnumerable GetDeletedTeam(Cmdlet cmdlet, string accessToken, PnPConnection connection) { // get the deleted team - var deletedTeams = await GraphHelper.GetResultCollectionAsync(connection, $"beta/teamwork/deletedTeams", accessToken); + var deletedTeams = GraphHelper.GetResultCollection(cmdlet, connection, $"beta/teamwork/deletedTeams", accessToken); if (deletedTeams != null && deletedTeams.Any()) { return deletedTeams; @@ -460,9 +460,9 @@ public static async Task> GetDeletedTeamAsync(string ac #endregion #region Users - public static async Task AddUserAsync(PnPConnection connection, string accessToken, string groupId, string upn, string role) + public static void AddUser(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string upn, string role) { - var userIdResult = await GraphHelper.GetAsync(connection, $"v1.0/{GetUserGraphUrlForUPN(upn)}?$select=Id", accessToken); + var userIdResult = GraphHelper.Get(cmdlet, connection, $"v1.0/{GetUserGraphUrlForUPN(upn)}?$select=Id", accessToken); var resultElement = JsonSerializer.Deserialize(userIdResult); if (resultElement.TryGetProperty("id", out JsonElement idProperty)) { @@ -474,11 +474,11 @@ public static async Task AddUserAsync(PnPConnection connection, string accessTok var stringContent = new StringContent(JsonSerializer.Serialize(postData)); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - await GraphHelper.PostAsync(connection, $"v1.0/groups/{groupId}/{role.ToLower()}s/$ref", accessToken, stringContent); + GraphHelper.Post(cmdlet, connection, $"v1.0/groups/{groupId}/{role.ToLower()}s/$ref", accessToken, stringContent); } } - public static async Task AddUsersAsync(PnPConnection connection, string accessToken, string groupId, string[] upn, string role) + public static void AddUsers(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string[] upn, string role) { var teamChannelMember = new List(); if (upn != null && upn.Length > 0) @@ -492,13 +492,13 @@ public static async Task AddUsersAsync(PnPConnection connection, string accessTo var chunks = BatchUtility.Chunk(teamChannelMember, 200); foreach (var chunk in chunks.ToList()) { - await GraphHelper.PostAsync(connection, $"v1.0/teams/{groupId}/members/add", new { values = chunk.ToList() }, accessToken); + GraphHelper.Post(cmdlet, connection, $"v1.0/teams/{groupId}/members/add", new { values = chunk.ToList() }, accessToken); } } } } - public static async Task> GetUsersAsync(PnPConnection connection, string accessToken, string groupId, string role) + public static List GetUsers(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string role) { var selectedRole = role != null ? role.ToLower() : null; var owners = new List(); @@ -506,7 +506,7 @@ public static async Task> GetUsersAsync(PnPConnection connection, str var members = new List(); if (selectedRole != "guest") { - owners = (await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/groups/{groupId}/owners?$select=Id,displayName,userPrincipalName,userType", accessToken)).Select(t => new User() + owners = (GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/groups/{groupId}/owners?$select=Id,displayName,userPrincipalName,userType", accessToken)).Select(t => new User() { Id = t.Id, DisplayName = t.DisplayName, @@ -516,7 +516,7 @@ public static async Task> GetUsersAsync(PnPConnection connection, str } if (selectedRole != "owner") { - var users = (await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/groups/{groupId}/members?$select=Id,displayName,userPrincipalName,userType", accessToken)); + var users = (GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/groups/{groupId}/members?$select=Id,displayName,userPrincipalName,userType", accessToken)); HashSet hashSet = new HashSet(owners.Select(u => u.Id)); foreach (var user in users) { @@ -555,12 +555,12 @@ public static async Task> GetUsersAsync(PnPConnection connection, str return finalList; } - public static async Task> GetUsersAsync(PnPConnection connection, string accessToken, string groupId, string channelId, string role) + public static IEnumerable GetUsers(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId, string role) { List users = new List(); var selectedRole = role != null ? role.ToLower() : null; - var collection = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/teams/{groupId}/channels/{channelId}/members", accessToken); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/teams/{groupId}/channels/{channelId}/members", accessToken); if (collection != null && collection.Any()) { users.AddRange(collection.Select(m => new User() { DisplayName = m.DisplayName, Id = m.UserId, UserPrincipalName = m.Email, UserType = m.Roles.Count > 0 ? m.Roles[0].ToLower() : "" })); @@ -576,34 +576,34 @@ public static async Task> GetUsersAsync(PnPConnection connecti } } - public static async Task DeleteUserAsync(PnPConnection connection, string accessToken, string groupId, string upn, string role) + public static void DeleteUser(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string upn, string role) { - var user = await GraphHelper.GetAsync(connection, $"v1.0/{GetUserGraphUrlForUPN(upn)}?$select=Id", accessToken); + var user = GraphHelper.Get(cmdlet, connection, $"v1.0/{GetUserGraphUrlForUPN(upn)}?$select=Id", accessToken); if (user != null) { // check if the user is an owner - var owners = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/groups/{groupId}/owners?$select=Id", accessToken); + var owners = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/groups/{groupId}/owners?$select=Id", accessToken); if (owners.Any() && owners.FirstOrDefault(u => u.Id.Equals(user.Id, StringComparison.OrdinalIgnoreCase)) != null) { if (owners.Count() == 1) { throw new PSInvalidOperationException("Last owner cannot be removed"); } - await GraphHelper.DeleteAsync(connection, $"v1.0/groups/{groupId}/owners/{user.Id}/$ref", accessToken); + GraphHelper.Delete(cmdlet, connection, $"v1.0/groups/{groupId}/owners/{user.Id}/$ref", accessToken); } if (!role.Equals("owner", StringComparison.OrdinalIgnoreCase)) { - await GraphHelper.DeleteAsync(connection, $"v1.0/groups/{groupId}/members/{user.Id}/$ref", accessToken); + GraphHelper.Delete(cmdlet, connection, $"v1.0/groups/{groupId}/members/{user.Id}/$ref", accessToken); } } } - public static async Task> GetTeamUsersWithDisplayNameAsync(PnPConnection connection, string accessToken, string groupId, string userDisplayName) + public static List GetTeamUsersWithDisplayName(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string userDisplayName) { // multiple users can have same display name, so using list var teamUserWithDisplayName = new List(); - teamUserWithDisplayName = (await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/teams/{groupId}/members?$filter=displayname eq '{userDisplayName}'", accessToken)).Select(t => new TeamUser() + teamUserWithDisplayName = (GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/teams/{groupId}/members?$filter=displayname eq '{userDisplayName}'", accessToken)).Select(t => new TeamUser() { Id = t.Id, DisplayName = t.DisplayName, @@ -614,7 +614,7 @@ public static async Task> GetTeamUsersWithDisplayNameAsync(PnPCon return teamUserWithDisplayName; } - public static async Task UpdateTeamUserRole(PnPConnection connection, string accessToken, string groupId, string teamMemberId, string role) + public static TeamUser UpdateTeamUserRole(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string teamMemberId, string role) { var teamUser = new TeamUser { @@ -624,7 +624,7 @@ public static async Task UpdateTeamUserRole(PnPConnection connection, var updateUserEndpoint = $"v1.0/teams/{groupId}/members/{teamMemberId}"; - var result = await GraphHelper.PatchAsync(connection, accessToken, updateUserEndpoint, teamUser); + var result = GraphHelper.Patch(cmdlet, connection, accessToken, updateUserEndpoint, teamUser); return result; } @@ -633,30 +633,30 @@ public static async Task UpdateTeamUserRole(PnPConnection connection, #region Channel - public static async Task GetChannelAsync(string accessToken, PnPConnection connection, string groupId, string channelId, bool useBeta = false) + public static TeamChannel GetChannel(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId, string channelId, bool useBeta = false) { - var channel = await GraphHelper.GetAsync(connection, $"{(useBeta ? "beta" : "v1.0")}/teams/{groupId}/channels/{channelId}", accessToken); + var channel = GraphHelper.Get(cmdlet, connection, $"{(useBeta ? "beta" : "v1.0")}/teams/{groupId}/channels/{channelId}", accessToken); return channel; } - public static async Task> GetChannelsAsync(string accessToken, PnPConnection connection, string groupId, bool useBeta = false) + public static IEnumerable GetChannels(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId, bool useBeta = false) { - var collection = await GraphHelper.GetResultCollectionAsync(connection, $"{(useBeta ? "beta" : "v1.0")}/teams/{groupId}/channels", accessToken); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, $"{(useBeta ? "beta" : "v1.0")}/teams/{groupId}/channels", accessToken); return collection; } - public static async Task GetPrimaryChannelAsync(string accessToken, PnPConnection connection, string groupId, bool useBeta = false) + public static TeamChannel GetPrimaryChannel(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId, bool useBeta = false) { - var collection = await GraphHelper.GetAsync(connection, $"{(useBeta ? "beta" : "v1.0")}/teams/{groupId}/primaryChannel", accessToken); + var collection = GraphHelper.Get(cmdlet, connection, $"{(useBeta ? "beta" : "v1.0")}/teams/{groupId}/primaryChannel", accessToken); return collection; } - public static async Task DeleteChannelAsync(string accessToken, PnPConnection connection, string groupId, string channelId, bool useBeta = false) + public static HttpResponseMessage DeleteChannel(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId, string channelId, bool useBeta = false) { - return await GraphHelper.DeleteAsync(connection, $"{(useBeta ? "beta" : "v1.0")}/teams/{groupId}/channels/{channelId}", accessToken); + return GraphHelper.Delete(cmdlet, connection, $"{(useBeta ? "beta" : "v1.0")}/teams/{groupId}/channels/{channelId}", accessToken); } - public static async Task AddChannelAsync(string accessToken, PnPConnection connection, string groupId, string displayName, string description, TeamsChannelType channelType, string ownerUPN, bool isFavoriteByDefault) + public static TeamChannel AddChannel(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId, string displayName, string description, TeamsChannelType channelType, string ownerUPN, bool isFavoriteByDefault) { var channel = new TeamChannel() { @@ -674,32 +674,32 @@ public static async Task AddChannelAsync(string accessToken, PnPCon if (channelType == TeamsChannelType.Private || channelType == TeamsChannelType.Shared) { channel.Type = "#Microsoft.Graph.channel"; - var user = await GraphHelper.GetAsync(connection, $"v1.0/{GetUserGraphUrlForUPN(ownerUPN)}", accessToken); + var user = GraphHelper.Get(cmdlet, connection, $"v1.0/{GetUserGraphUrlForUPN(ownerUPN)}", accessToken); channel.Members = new List(); channel.Members.Add(new TeamChannelMember() { Roles = new List { "owner" }, UserIdentifier = $"https://{connection.GraphEndPoint}/v1.0/users('{user.Id}')" }); - return await GraphHelper.PostAsync(connection, $"v1.0/teams/{groupId}/channels", channel, accessToken); + return GraphHelper.Post(cmdlet, connection, $"v1.0/teams/{groupId}/channels", channel, accessToken); } else { channel.IsFavoriteByDefault = null; - return await GraphHelper.PostAsync(connection, $"v1.0/teams/{groupId}/channels", channel, accessToken); + return GraphHelper.Post(cmdlet, connection, $"v1.0/teams/{groupId}/channels", channel, accessToken); } } - public static async Task PostMessageAsync(PnPConnection connection, string accessToken, string groupId, string channelId, TeamChannelMessage message) + public static void PostMessage(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId, TeamChannelMessage message) { - await GraphHelper.PostAsync(connection, $"v1.0/teams/{groupId}/channels/{channelId}/messages", message, accessToken); + GraphHelper.Post(cmdlet, connection, $"v1.0/teams/{groupId}/channels/{channelId}/messages", message, accessToken); } - public static async Task GetMessageAsync(PnPConnection connection, string accessToken, string groupId, string channelId, string messageId) + public static TeamChannelMessage GetMessage(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId, string messageId) { - return await GraphHelper.GetAsync(connection, $"v1.0/teams/{groupId}/channels/{channelId}/messages/{messageId}", accessToken); + return GraphHelper.Get(cmdlet, connection, $"v1.0/teams/{groupId}/channels/{channelId}/messages/{messageId}", accessToken); } - public static async Task> GetMessagesAsync(PnPConnection connection, string accessToken, string groupId, string channelId, bool includeDeleted = false) + public static List GetMessages(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId, bool includeDeleted = false) { List messages = new List(); - var collection = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/teams/{groupId}/channels/{channelId}/messages", accessToken); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/teams/{groupId}/channels/{channelId}/messages", accessToken); messages.AddRange(collection); if (includeDeleted) @@ -715,9 +715,9 @@ public static async Task> GetMessagesAsync(PnPConnectio /// /// List all the replies to a message in a channel of a team. /// - public static async Task> GetMessageRepliesAsync(PnPConnection connection, string accessToken, string groupId, string channelId, string messageId, bool includeDeleted = false) + public static List GetMessageReplies(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId, string messageId, bool includeDeleted = false) { - var replies = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/teams/{groupId}/channels/{channelId}/messages/{messageId}/replies", accessToken); + var replies = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/teams/{groupId}/channels/{channelId}/messages/{messageId}/replies", accessToken); return includeDeleted ? replies.ToList() : replies.Where(r => !r.DeletedDateTime.HasValue).ToList(); } @@ -725,17 +725,17 @@ public static async Task> GetMessageRepliesAsync(P /// /// Get a specific reply of a message in a channel of a team. /// - public static async Task GetMessageReplyAsync(PnPConnection connection, string accessToken, string groupId, string channelId, string messageId, string replyId) + public static TeamChannelMessageReply GetMessageReply(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId, string messageId, string replyId) { - return await GraphHelper.GetAsync(connection, $"v1.0/teams/{groupId}/channels/{channelId}/messages/{messageId}/replies/{replyId}", accessToken); + return GraphHelper.Get(cmdlet, connection, $"v1.0/teams/{groupId}/channels/{channelId}/messages/{messageId}/replies/{replyId}", accessToken); } /// /// Updates a Teams Channel /// - public static async Task UpdateChannelAsync(PnPConnection connection, string accessToken, string groupId, string channelId, TeamChannel channel, bool useBeta = false) + public static TeamChannel UpdateChannel(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId, TeamChannel channel, bool useBeta = false) { - return await GraphHelper.PatchAsync(connection, accessToken, $"{(useBeta ? "beta" : "v1.0")}/teams/{groupId}/channels/{channelId}", channel); + return GraphHelper.Patch(cmdlet, connection, accessToken, $"{(useBeta ? "beta" : "v1.0")}/teams/{groupId}/channels/{channelId}", channel); } #endregion @@ -745,12 +745,12 @@ public static async Task UpdateChannelAsync(PnPConnection connectio /// Get specific memberbership of user who has access to a certain Microsoft Teams channel. /// /// User channel membership. - public static async Task GetChannelMemberAsync(PnPConnection connection, string accessToken, string groupId, string channelId, string membershipId) + public static TeamChannelMember GetChannelMember(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId, string membershipId) { // Currently the Graph request to get a membership by id fails (v1.0/teams/{groupId}/channels/{channelId}/members/{membershipId}). // This is why the method below is used. - var memberships = await GetChannelMembersAsync(connection, accessToken, groupId, channelId); + var memberships = GetChannelMembers(cmdlet, connection, accessToken, groupId, channelId); return memberships.FirstOrDefault(m => membershipId.Equals(m.Id)); } @@ -758,9 +758,9 @@ public static async Task GetChannelMemberAsync(PnPConnection /// Get list of all memberships of a certain Microsoft Teams channel. /// /// List of memberships. - public static async Task> GetChannelMembersAsync(PnPConnection connection, string accessToken, string groupId, string channelId, string role = null) + public static IEnumerable GetChannelMembers(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId, string role = null) { - var collection = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/teams/{groupId}/channels/{channelId}/members", accessToken); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/teams/{groupId}/channels/{channelId}/members", accessToken); if (!string.IsNullOrEmpty(role)) { @@ -776,7 +776,7 @@ public static async Task> GetChannelMembersAsync( /// /// User role, valid values: Owner, Member /// Added membership. - public static async Task AddChannelMemberAsync(PnPConnection connection, string accessToken, string groupId, string channelId, string upn, string role) + public static TeamChannelMember AddChannelMember(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId, string upn, string role) { var channelMember = new TeamChannelMember { @@ -787,23 +787,23 @@ public static async Task AddChannelMemberAsync(PnPConnection if (role.Equals("owner", StringComparison.OrdinalIgnoreCase)) channelMember.Roles.Add("owner"); - return await GraphHelper.PostAsync(connection, $"v1.0/teams/{groupId}/channels/{channelId}/members", channelMember, accessToken); + return GraphHelper.Post(cmdlet, connection, $"v1.0/teams/{groupId}/channels/{channelId}/members", channelMember, accessToken); } /// /// Remove specified member of a specified Microsoft Teams channel. /// /// True when removal succeeded, else false. - public static async Task DeleteChannelMemberAsync(PnPConnection connection, string accessToken, string groupId, string channelId, string membershipId) + public static HttpResponseMessage DeleteChannelMember(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId, string membershipId) { - return await GraphHelper.DeleteAsync(connection, $"v1.0/teams/{groupId}/channels/{channelId}/members/{membershipId}", accessToken); + return GraphHelper.Delete(cmdlet, connection, $"v1.0/teams/{groupId}/channels/{channelId}/members/{membershipId}", accessToken); } /// /// Update the role of a specific member of a Microsoft Teams channel. /// /// Updated membership object. - public static async Task UpdateChannelMemberAsync(PnPConnection connection, string accessToken, string groupId, string channelId, string membershipId, string role) + public static TeamChannelMember UpdateChannelMember(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId, string membershipId, string role) { var channelMember = new TeamChannelMember(); @@ -811,41 +811,41 @@ public static async Task UpdateChannelMemberAsync(PnPConnecti if (role.Equals("owner", StringComparison.OrdinalIgnoreCase)) channelMember.Roles.Add("owner"); - return await GraphHelper.PatchAsync(connection, accessToken, $"v1.0/teams/{groupId}/channels/{channelId}/members/{membershipId}", channelMember); + return GraphHelper.Patch(cmdlet, connection, accessToken, $"v1.0/teams/{groupId}/channels/{channelId}/members/{membershipId}", channelMember); } - public static async Task GetChannelsFilesFolderAsync(PnPConnection connection, string accessToken, string groupId, string channelId) + public static TeamsChannelFilesFolder GetChannelsFilesFolder(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId) { - var collection = await GraphHelper.GetAsync(connection, $"v1.0/teams/{groupId}/channels/{channelId}/filesFolder", accessToken); + var collection = GraphHelper.Get(cmdlet, connection, $"v1.0/teams/{groupId}/channels/{channelId}/filesFolder", accessToken); return collection; } #endregion #region Tabs - public static async Task> GetTabsAsync(string accessToken, PnPConnection connection, string groupId, string channelId) + public static IEnumerable GetTabs(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId, string channelId) { - var collection = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/teams/{groupId}/channels/{channelId}/tabs", accessToken); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/teams/{groupId}/channels/{channelId}/tabs", accessToken); return collection; } - public static async Task GetTabAsync(string accessToken, PnPConnection connection, string groupId, string channelId, string tabId) + public static TeamTab GetTab(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId, string channelId, string tabId) { - return await GraphHelper.GetAsync(connection, $"v1.0/teams/{groupId}/channels/{channelId}/tabs/{tabId}?$expand=teamsApp", accessToken, propertyNameCaseInsensitive: true); + return GraphHelper.Get(cmdlet, connection, $"v1.0/teams/{groupId}/channels/{channelId}/tabs/{tabId}?$expand=teamsApp", accessToken, propertyNameCaseInsensitive: true); } - public static async Task DeleteTabAsync(string accessToken, PnPConnection connection, string groupId, string channelId, string tabId) + public static HttpResponseMessage DeleteTab(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId, string channelId, string tabId) { - return await GraphHelper.DeleteAsync(connection, $"v1.0/teams/{groupId}/channels/{channelId}/tabs/{tabId}", accessToken); + return GraphHelper.Delete(cmdlet, connection, $"v1.0/teams/{groupId}/channels/{channelId}/tabs/{tabId}", accessToken); } - public static async Task UpdateTabAsync(PnPConnection connection, string accessToken, string groupId, string channelId, TeamTab tab) + public static void UpdateTab(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId, TeamTab tab) { tab.Configuration = null; - await GraphHelper.PatchAsync(connection, accessToken, $"v1.0/teams/{groupId}/channels/{channelId}/tabs/{tab.Id}", tab); + GraphHelper.Patch(cmdlet, connection, accessToken, $"v1.0/teams/{groupId}/channels/{channelId}/tabs/{tab.Id}", tab); } - public static async Task AddTabAsync(PnPConnection connection, string accessToken, string groupId, string channelId, string displayName, TeamTabType tabType, string teamsAppId, string entityId, string contentUrl, string removeUrl, string websiteUrl) + public static TeamTab AddTab(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string channelId, string displayName, TeamTabType tabType, string teamsAppId, string entityId, string contentUrl, string removeUrl, string websiteUrl) { TeamTab tab = new TeamTab(); switch (tabType) @@ -963,65 +963,64 @@ public static async Task AddTabAsync(PnPConnection connection, string a } tab.DisplayName = displayName; tab.TeamsAppOdataBind = $"https://{connection.GraphEndPoint}/v1.0/appCatalogs/teamsApps/{tab.TeamsAppId}"; - return await GraphHelper.PostAsync(connection, $"v1.0/teams/{groupId}/channels/{channelId}/tabs", tab, accessToken); + return GraphHelper.Post(cmdlet, connection, $"v1.0/teams/{groupId}/channels/{channelId}/tabs", tab, accessToken); } #endregion #region Apps - public static async Task> GetAppsAsync(string accessToken, PnPConnection connection) + public static IEnumerable GetApps(Cmdlet cmdlet, string accessToken, PnPConnection connection) { - var collection = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/appCatalogs/teamsApps", accessToken); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/appCatalogs/teamsApps", accessToken); return collection; } - public static async Task AddAppAsync(PnPConnection connection, string accessToken, byte[] bytes) + public static TeamApp AddApp(Cmdlet cmdlet, PnPConnection connection, string accessToken, byte[] bytes) { var byteArrayContent = new ByteArrayContent(bytes); byteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/zip"); - var response = await GraphHelper.PostAsync(connection, "v1.0/appCatalogs/teamsApps", accessToken, byteArrayContent); + var response = GraphHelper.Post(cmdlet, connection, "v1.0/appCatalogs/teamsApps", accessToken, byteArrayContent); var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); return JsonSerializer.Deserialize(content, new JsonSerializerOptions() { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); } - public static async Task UpdateAppAsync(PnPConnection connection, string accessToken, byte[] bytes, string appId) + public static HttpResponseMessage UpdateApp(Cmdlet cmdlet, PnPConnection connection, string accessToken, byte[] bytes, string appId) { var byteArrayContent = new ByteArrayContent(bytes); byteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/zip"); - return await GraphHelper.PutAsync(connection, $"v1.0/appCatalogs/teamsApps/{appId}", accessToken, byteArrayContent); + return GraphHelper.Put(cmdlet, connection, $"v1.0/appCatalogs/teamsApps/{appId}", accessToken, byteArrayContent); } - public static async Task DeleteAppAsync(PnPConnection connection, string accessToken, string appId) + public static HttpResponseMessage DeleteApp(Cmdlet cmdlet, PnPConnection connection, string accessToken, string appId) { - return await GraphHelper.DeleteAsync(connection, $"v1.0/appCatalogs/teamsApps/{appId}", accessToken); + return GraphHelper.Delete(cmdlet, connection, $"v1.0/appCatalogs/teamsApps/{appId}", accessToken); } #endregion #region Tags - public static async Task> GetTagsAsync(string accessToken, PnPConnection connection, string groupId) + public static IEnumerable GetTags(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId) { - var collection = await GraphHelper.GetResultCollectionAsync(connection, $"v1.0/teams/{groupId}/tags", accessToken); + var collection = GraphHelper.GetResultCollection(cmdlet, connection, $"v1.0/teams/{groupId}/tags", accessToken); return collection; } - public static async Task GetTagsWithIdAsync(string accessToken, PnPConnection connection, string groupId, string tagId) + public static TeamTag GetTagsWithId(Cmdlet cmdlet, string accessToken, PnPConnection connection, string groupId, string tagId) { - var tagInformation = await GraphHelper.GetAsync(connection, $"v1.0/teams/{groupId}/tags/{tagId}", accessToken); + var tagInformation = GraphHelper.Get(cmdlet, connection, $"v1.0/teams/{groupId}/tags/{tagId}", accessToken); return tagInformation; } - public static async Task UpdateTagAsync(PnPConnection connection, string accessToken, string groupId, string tagId, string displayName) + public static void UpdateTag(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string tagId, string displayName) { var body = new { displayName = displayName }; - await GraphHelper.PatchAsync(connection, accessToken, $"v1.0/teams/{groupId}/tags/{tagId}", body); + GraphHelper.Patch(cmdlet, connection, accessToken, $"v1.0/teams/{groupId}/tags/{tagId}", body); } - public static async Task DeleteTagAsync(PnPConnection connection, string accessToken, string groupId, string tagId) + public static HttpResponseMessage DeleteTag(Cmdlet cmdlet, PnPConnection connection, string accessToken, string groupId, string tagId) { - return await GraphHelper.DeleteAsync(connection, $"v1.0/teams/{groupId}/tags/{tagId}", accessToken); + return GraphHelper.Delete(cmdlet, connection, $"v1.0/teams/{groupId}/tags/{tagId}", accessToken); } - #endregion } } \ No newline at end of file diff --git a/src/Commands/Web/SetWebHeader.cs b/src/Commands/Web/SetWebHeader.cs index 1875e796c..b07d8aad8 100644 --- a/src/Commands/Web/SetWebHeader.cs +++ b/src/Commands/Web/SetWebHeader.cs @@ -110,7 +110,7 @@ protected override void ExecuteCmdlet() var stringContent = new StringContent("{" + string.Join(",", setSiteBackgroundImageInstructions) + ",\"type\":2,\"aspect\":0}"); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); CurrentWeb.EnsureProperties(p => p.Url); - var result = GraphHelper.PostAsync(Connection, $"{CurrentWeb.Url.TrimEnd('/')}/_api/siteiconmanager/setsitelogo", AccessToken, stringContent).GetAwaiter().GetResult(); + var result = GraphHelper.Post(this, Connection, $"{CurrentWeb.Url.TrimEnd('/')}/_api/siteiconmanager/setsitelogo", AccessToken, stringContent); WriteVerbose($"Response from setsitelogo request: {result.StatusCode}"); } } @@ -129,7 +129,7 @@ private void SetSiteImage(string imageUrl, string imageType, int aspect) var stringContent = new StringContent($"{{\"relativeLogoUrl\":\"{imageUrl}\",\"type\":0,\"aspect\":{aspect}}}"); stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); CurrentWeb.EnsureProperties(p => p.Url); - var result = GraphHelper.PostAsync(Connection, $"{CurrentWeb.Url.TrimEnd('/')}/_api/siteiconmanager/setsitelogo", AccessToken, stringContent).GetAwaiter().GetResult(); + var result = GraphHelper.Post(this, Connection, $"{CurrentWeb.Url.TrimEnd('/')}/_api/siteiconmanager/setsitelogo", AccessToken, stringContent); WriteVerbose($"Response from {imageType} request: {result.StatusCode}"); } }