// Get ApplicationId of Service Principal if user doesn't provide this parameter private Guid GetApplicationId(Guid applicationId) { if (applicationId != Guid.Empty) { return(applicationId); } MicrosoftGraphClient graphClient = AzureSession.Instance.ClientFactory.CreateArmClient <MicrosoftGraphClient>( DefaultProfile.DefaultContext, AzureEnvironment.ExtendedEndpoint.MicrosoftGraphUrl); graphClient.TenantID = DefaultProfile.DefaultContext.Tenant.Id.ToString(); MicrosoftGraphServicePrincipal sp = null; try { sp = graphClient.ServicePrincipals.GetServicePrincipal(ObjectId.ToString()); } catch (Exception e) { string errorMessage = $"Can not find service princaipl per the parameter ObjectId:{ObjectId}, the error message is '{e.Message}'." + " Please specify Application Id explicitly by providing ApplicationId parameter and retry."; throw new AzPSArgumentException(errorMessage, nameof(ObjectId)); } var spApplicationId = Guid.Empty; Guid.TryParse(sp.AppId, out spApplicationId); Debug.Assert(spApplicationId != Guid.Empty); return(spApplicationId); }
public void TestSetRemoveAccessPolicyBySPN() { MicrosoftGraphApplication app = null; MicrosoftGraphServicePrincipal principal = null; KeyVaultManagementController controller = KeyVaultManagementController.NewInstance; controller.RunPsTestWorkflow( _logger, //script builder () => { app = CreateNewAdApp(controller); principal = CreateNewAdServicePrincipal(controller, app.AppId); return(new[] { string.Format("{0} {1} {2} {3}", "Test-SetRemoveAccessPolicyBySPN", _data.PreCreatedVault, _data.ResourceGroupName, principal.ServicePrincipalNames.Where(s => s.StartsWith("http")).FirstOrDefault()) }); }, // cleanup () => { DeleteAdServicePrincipal(controller, principal); DeleteAdApp(controller, app); }, MethodBase.GetCurrentMethod().ReflectedType?.ToString(), MethodBase.GetCurrentMethod().Name ); }
private MicrosoftGraphServicePrincipal CreateNewAdServicePrincipal(KeyVaultManagementController controllerAdmin, string appId) { var sp = new MicrosoftGraphServicePrincipal { AppId = appId, AccountEnabled = true }; return(controllerAdmin.GraphClient.ServicePrincipals.CreateServicePrincipal(sp)); }
/// <summary> /// Ensures the role assignment. /// </summary> /// <param name="serverPrincipal">The server principal.</param> /// <param name="storageAccountSubscriptionId">The storage account subscription identifier.</param> /// <param name="storageAccountResourceId">The storage account resource identifier.</param> /// <returns>RoleAssignment.</returns> public RoleAssignment EnsureRoleAssignment(MicrosoftGraphServicePrincipal serverPrincipal, string storageAccountSubscriptionId, string storageAccountResourceId) { string currentSubscriptionId = AuthorizationManagementClient.SubscriptionId; bool hasMismatchSubscription = currentSubscriptionId != storageAccountSubscriptionId; try { if (hasMismatchSubscription) { AuthorizationManagementClient.SubscriptionId = storageAccountSubscriptionId; } var resourceIdentifier = new ResourceIdentifier(storageAccountResourceId); string roleDefinitionScope = "/"; RoleDefinition roleDefinition = AuthorizationManagementClient.RoleDefinitions.Get(roleDefinitionScope, BuiltInRoleDefinitionId); var serverPrincipalId = serverPrincipal.Id.ToString(); var roleAssignments = AuthorizationManagementClient.RoleAssignments .ListForResource( resourceIdentifier.ResourceGroupName, ResourceIdentifier.GetProviderFromResourceType(resourceIdentifier.ResourceType), resourceIdentifier.ParentResource ?? "/", ResourceIdentifier.GetTypeFromResourceType(resourceIdentifier.ResourceType), resourceIdentifier.ResourceName, odataQuery: new ODataQuery <RoleAssignmentFilter>(f => f.AssignedTo(serverPrincipalId))); var roleAssignmentScope = storageAccountResourceId; Guid roleAssignmentId = StorageSyncResourceManager.GetGuid(); RoleAssignment roleAssignment = roleAssignments.FirstOrDefault(); if (roleAssignment == null) { VerboseLogger.Invoke(StorageSyncResources.CreateRoleAssignmentMessage); var createParameters = new RoleAssignmentCreateParameters { Properties = new RoleAssignmentProperties { PrincipalId = serverPrincipalId, RoleDefinitionId = AuthorizationHelper.ConstructFullyQualifiedRoleDefinitionIdFromSubscriptionAndIdAsGuid(resourceIdentifier.Subscription, BuiltInRoleDefinitionId) } }; roleAssignment = AuthorizationManagementClient.RoleAssignments.Create(roleAssignmentScope, roleAssignmentId.ToString(), createParameters); StorageSyncResourceManager.Wait(); } return(roleAssignment); } finally { if (hasMismatchSubscription) { AuthorizationManagementClient.SubscriptionId = currentSubscriptionId; } } }
public static PSADServicePrincipal ToPSADServicePrincipal(this MicrosoftGraphServicePrincipal servicePrincipal) { return(new PSADServicePrincipal() { DisplayName = servicePrincipal.DisplayName, Id = servicePrincipal.Id, DeletionTimestamp = servicePrincipal.DeletedDateTime, ApplicationId = Guid.Parse(servicePrincipal.AppId), Type = "ServicePrincipal", ServicePrincipalNames = servicePrincipal.ServicePrincipalNames.ToArray(), AdditionalProperties = servicePrincipal.AdditionalProperties }); }
/// <summary> /// Ensures the service principal. /// </summary> /// <returns>PSADServicePrincipal.</returns> public MicrosoftGraphServicePrincipal GetServicePrincipalOrNull() { string applicationId = CurrentApplicationId.ToString(); // TODO: Remove this call once Az Powershell supports MSGraphClient in Test framework. MicrosoftGraphServicePrincipal servicePrincipal = this.StorageSyncResourceManager.GetServicePrincipalOrNull(); if (servicePrincipal == null) { var oDataQuery = new ODataQuery <MicrosoftGraphServicePrincipal>(sp => sp.AppId == applicationId); servicePrincipal = MicrosoftGraphClient.FilterServicePrincipals(oDataQuery).FirstOrDefault(); } return(servicePrincipal); }
public IEnumerable <PSADServicePrincipal> FilterServicePrincipals(ADObjectFilterOptions options, int first = int.MaxValue, int skip = 0) { List <PSADServicePrincipal> servicePrincipals = new List <PSADServicePrincipal>(); MicrosoftGraphServicePrincipal servicePrincipal = null; if (!string.IsNullOrEmpty(options.Id)) { try { servicePrincipal = GraphClient.ServicePrincipals.GetServicePrincipal(options.Id); } catch { /* The user does not exist, ignore the exception. */ } if (servicePrincipal != null) { servicePrincipals.Add(servicePrincipal.ToPSADServicePrincipal()); } } else if (!string.IsNullOrEmpty(options.SPN)) { try { var odataQuery = new Rest.Azure.OData.ODataQuery <MicrosoftGraphServicePrincipal>(s => s.ServicePrincipalNames.Contains(options.SPN)); // todo: doesn't support paging servicePrincipal = GraphClient.ServicePrincipals.ListServicePrincipal(filter: OdataHelper.GetFilterString(odataQuery)).Value.FirstOrDefault(); } catch { /* The user does not exist, ignore the exception. */ } if (servicePrincipal != null) { servicePrincipals.Add(servicePrincipal.ToPSADServicePrincipal()); } } else { Rest.Azure.OData.ODataQuery <MicrosoftGraphServicePrincipal> odataQuery = null; if (!string.IsNullOrEmpty(options.SearchString) && options.SearchString.EndsWith("*")) { options.SearchString = options.SearchString.TrimEnd('*'); odataQuery = new Rest.Azure.OData.ODataQuery <MicrosoftGraphServicePrincipal>(s => s.DisplayName != null && s.DisplayName.StartsWith(options.SearchString)); } else { odataQuery = new Rest.Azure.OData.ODataQuery <MicrosoftGraphServicePrincipal>(s => s.DisplayName == options.SearchString); } return(FilterServicePrincipals(odataQuery, first, skip)); } return(servicePrincipals); }
public static IEnumerable <MicrosoftGraphServicePrincipal> FilterServicePrincipals(this IMicrosoftGraphClient client, MicrosoftObjectFilterOptions options) { List <MicrosoftGraphServicePrincipal> servicePrincipals = new List <MicrosoftGraphServicePrincipal>(); MicrosoftGraphServicePrincipal servicePrincipal = null; if (!string.IsNullOrEmpty(options.Id)) { try { servicePrincipal = client.ServicePrincipals.GetServicePrincipal(options.Id); } catch { /* The user does not exist, ignore the exception. */ } if (servicePrincipal != null) { servicePrincipals.Add(servicePrincipal); } } else if (!string.IsNullOrEmpty(options.SPN)) { try { var odataQuery = new ODataQuery <MicrosoftGraphServicePrincipal>(s => s.ServicePrincipalNames.Contains(options.SPN)); servicePrincipal = client.ServicePrincipals.ListServicePrincipal(filter: FormatFilterString(odataQuery)).Value.FirstOrDefault(); } catch { /* The user does not exist, ignore the exception. */ } if (servicePrincipal != null) { servicePrincipals.Add(servicePrincipal); } } else { ODataQuery <MicrosoftGraphServicePrincipal> odataQuery = null; if (!string.IsNullOrEmpty(options.SearchString) && options.SearchString.EndsWith("*")) { options.SearchString = options.SearchString.TrimEnd('*'); odataQuery = new ODataQuery <MicrosoftGraphServicePrincipal>(s => s.DisplayName.StartsWith(options.SearchString)); } else { odataQuery = new ODataQuery <MicrosoftGraphServicePrincipal>(s => s.DisplayName == options.SearchString); } return(client.ServicePrincipals.ListServicePrincipal(filter: FormatFilterString(odataQuery)).Value); } return(servicePrincipals); }
private AcsServicePrincipal BuildServicePrincipal(string name, string clientSecret) { var keyCredentials = new List <MicrosoftGraphKeyCredential> { new MicrosoftGraphKeyCredential { EndDateTime = DateTime.UtcNow.AddYears(2), StartDateTime = DateTime.UtcNow, Key = clientSecret, Type = "Symmetric", Usage = "Verify" } }; var appCreateParameters = new MicrosoftGraphApplication { DisplayName = name, KeyCredentials = keyCredentials }; var app = GraphClient.Applications.CreateApplication(appCreateParameters); MicrosoftGraphServicePrincipal sp = null; var success = RetryAction(() => { var servicePrincipalCreateParams = new MicrosoftGraphServicePrincipal { AppId = app.AppId, AccountEnabled = true, KeyCredentials = keyCredentials }; sp = GraphClient.ServicePrincipals.CreateServicePrincipal(servicePrincipalCreateParams); }, Resources.ServicePrincipalCreate); if (!success) { throw new AzPSInvalidOperationException( Resources.CouldNotCreateAServicePrincipalWithTheRightPermissionsAreYouAnOwner, desensitizedMessage: Resources.CouldNotCreateAServicePrincipalWithTheRightPermissionsAreYouAnOwner); } AddSubscriptionRoleAssignment("Contributor", sp.Id); return(new AcsServicePrincipal { SpId = app.AppId, ClientSecret = clientSecret, ObjectId = sp.Id }); }
/// <summary> /// Executes the cmdlet. /// </summary> public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ExecuteClientAction(() => { // Validate Storage Account Resource Id var storageAccountResourceIdentifier = new ResourceIdentifier(StorageAccountResourceId); if (string.IsNullOrEmpty(storageAccountResourceIdentifier?.ResourceName)) { throw new PSArgumentException(nameof(StorageAccountResourceId)); } if (this.IsParameterBound(c => c.StorageAccountTenantId)) { if (StorageAccountTenantId != AzureContext.Tenant.Id) { throw new PSArgumentException(string.Format(StorageSyncResources.NewCloudEndpointCrossTenantErrorFormat, StorageAccountTenantId, AzureContext.Tenant.Id)); } } if (storageAccountResourceIdentifier.Subscription != AzureContext.Subscription.Id) { WriteWarning(string.Format(StorageSyncResources.NewCloudEndpointCrossSubscriptionWarningFormat, storageAccountResourceIdentifier.Subscription, AzureContext.Subscription.Id)); if (!StorageSyncClientWrapper.TryRegisterProvider(AzureContext.Subscription.Id, StorageSyncConstants.ResourceProvider, storageAccountResourceIdentifier.Subscription)) { WriteWarning(string.Format(StorageSyncResources.NewCloudEndpointUnableToRegisterErrorFormat, storageAccountResourceIdentifier.Subscription)); } } MicrosoftGraphServicePrincipal servicePrincipal = StorageSyncClientWrapper.GetServicePrincipalOrNull(); if (servicePrincipal == null) { throw new PSArgumentException(StorageSyncResources.MissingServicePrincipalResourceIdErrorMessage); } RoleAssignment roleAssignment = StorageSyncClientWrapper.EnsureRoleAssignment(servicePrincipal, storageAccountResourceIdentifier.Subscription, StorageAccountResourceId); var parentResourceIdentifier = default(ResourceIdentifier); if (this.IsParameterBound(c => c.ParentResourceId)) { parentResourceIdentifier = new ResourceIdentifier(ParentResourceId); if (!string.Equals(StorageSyncConstants.SyncGroupType, parentResourceIdentifier.ResourceType, System.StringComparison.OrdinalIgnoreCase)) { throw new PSArgumentException(StorageSyncResources.MissingParentResourceIdErrorMessage); } } var createParameters = new CloudEndpointCreateParameters() { StorageAccountResourceId = StorageAccountResourceId, AzureFileShareName = AzureFileShareName, StorageAccountTenantId = (StorageAccountTenantId ?? AzureContext.Tenant.Id) }; string resourceGroupName = ResourceGroupName ?? ParentObject?.ResourceGroupName ?? parentResourceIdentifier.ResourceGroupName; string storageSyncServiceName = StorageSyncServiceName ?? ParentObject?.StorageSyncServiceName ?? parentResourceIdentifier.GetParentResourceName(StorageSyncConstants.StorageSyncServiceTypeName, 0); string syncGroupName = SyncGroupName ?? ParentObject?.SyncGroupName ?? parentResourceIdentifier.ResourceName; Target = string.Join("/", resourceGroupName, storageSyncServiceName, syncGroupName, Name); if (ShouldProcess(Target, ActionMessage)) { StorageSyncModels.CloudEndpoint resource = StorageSyncClientWrapper.StorageSyncManagementClient.CloudEndpoints.Create( resourceGroupName, storageSyncServiceName, syncGroupName, Name, createParameters); WriteObject(resource); } }); }
/// <summary> /// Verifies that the Azure Active Directory user or group exists, and will get the object id if it is not set. /// </summary> /// <param name="displayName">Azure Active Directory user or group display name</param> /// <param name="objectId">Azure Active Directory user or group object id</param> /// <returns></returns> protected ManagedInstanceAdministrator GetActiveDirectoryInformation(string displayName, Guid objectId) { // Gets the default Tenant id for the subscriptions Guid tenantId = GetTenantId(); // Check for a Azure Active Directory group. Recommended to always use group. IEnumerable <MicrosoftGraphGroup> groupList = null; MicrosoftGraphGroup group = null; var filter = new MicrosoftObjectFilterOptions() { Id = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null, SearchString = displayName, Paging = true, }; // Get a list of groups from Azure Active Directory groupList = MicrosoftGraphClient.FilterGroups(filter).Where(gr => string.Equals(gr.DisplayName, displayName, StringComparison.OrdinalIgnoreCase)); if (groupList != null && groupList.Count() > 1) { // More than one group was found with that display name. throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADGroupMoreThanOneFound, displayName)); } else if (groupList != null && groupList.Count() == 1) { // Only one group was found. Get the group display name and object id group = groupList.First(); // Only support Security Groups if (group.SecurityEnabled.HasValue && !group.SecurityEnabled.Value) { throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.InvalidADGroupNotSecurity, displayName)); } } // Lookup for serviceprincipals ODataQuery <MicrosoftGraphServicePrincipal> odataQueryFilter; if ((objectId != null && objectId != Guid.Empty)) { var applicationIdString = objectId.ToString(); odataQueryFilter = new Rest.Azure.OData.ODataQuery <MicrosoftGraphServicePrincipal>(a => a.AppId == applicationIdString); } else { odataQueryFilter = new Rest.Azure.OData.ODataQuery <MicrosoftGraphServicePrincipal>(a => a.DisplayName == displayName); } var servicePrincipalList = MicrosoftGraphClient.FilterServicePrincipals(odataQueryFilter); if (servicePrincipalList != null && servicePrincipalList.Count() > 1) { // More than one service principal was found. throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADApplicationMoreThanOneFound, displayName)); } else if (servicePrincipalList != null && servicePrincipalList.Count() == 1) { // Only one user was found. Get the user display name and object id MicrosoftGraphServicePrincipal app = servicePrincipalList.First(); if (displayName != null && string.CompareOrdinal(displayName, app.DisplayName) != 0) { throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADApplicationDisplayNameMismatch, displayName, app.DisplayName)); } if (group != null) { throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADDuplicateGroupAndApplicationFound, displayName)); } return(new ManagedInstanceAdministrator() { Login = displayName, Sid = new Guid(app.AppId), TenantId = tenantId }); } if (group != null) { return(new ManagedInstanceAdministrator() { Login = group.DisplayName, Sid = new Guid(group.Id), TenantId = tenantId }); } // No group or service principal was found. Check for a user filter = new MicrosoftObjectFilterOptions() { Id = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null, SearchString = displayName, Paging = true, }; // Get a list of user from Azure Active Directory var userList = MicrosoftGraphClient.FilterUsers(filter).Where(gr => string.Equals(gr.DisplayName, displayName, StringComparison.OrdinalIgnoreCase)); // No user was found. Check if the display name is a UPN if (userList == null || userList.Count() == 0) { // Check if the display name is the UPN filter = new MicrosoftObjectFilterOptions() { Id = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null, UPN = displayName, Paging = true, }; userList = MicrosoftGraphClient.FilterUsers(filter).Where(gr => string.Equals(gr.UserPrincipalName, displayName, StringComparison.OrdinalIgnoreCase)); } // No user was found. Check if the display name is a guest user. if (userList == null || userList.Count() == 0) { // Check if the display name is the UPN filter = new MicrosoftObjectFilterOptions() { Id = (objectId != null && objectId != Guid.Empty) ? objectId.ToString() : null, Mail = displayName, Paging = true, }; userList = MicrosoftGraphClient.FilterUsers(filter); } // No user was found if (userList == null || userList.Count() == 0) { throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADObjectNotFound, displayName)); } else if (userList.Count() > 1) { // More than one user was found. throw new ArgumentException(string.Format(Microsoft.Azure.Commands.Sql.Properties.Resources.ADUserMoreThanOneFound, displayName)); } else { // Only one user was found. Get the user display name and object id var obj = userList.First(); return(new ManagedInstanceAdministrator() { Login = displayName, Sid = new Guid(obj.Id), TenantId = tenantId }); } }
/// <summary> /// Update entity in servicePrincipals /// </summary> /// <remarks> /// Represents an Azure Active Directory object. The directoryObject type is /// the base type for many other directory entity types. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='servicePrincipalId'> /// key: id of servicePrincipal /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateServicePrincipalAsync(this IServicePrincipalsOperations operations, string servicePrincipalId, MicrosoftGraphServicePrincipal body, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateServicePrincipalWithHttpMessagesAsync(servicePrincipalId, body, null, cancellationToken).ConfigureAwait(false)).Dispose(); }
/// <summary> /// Update entity in servicePrincipals /// </summary> /// <remarks> /// Represents an Azure Active Directory object. The directoryObject type is /// the base type for many other directory entity types. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='servicePrincipalId'> /// key: id of servicePrincipal /// </param> /// <param name='body'> /// New property values /// </param> public static void UpdateServicePrincipal(this IServicePrincipalsOperations operations, string servicePrincipalId, MicrosoftGraphServicePrincipal body) { operations.UpdateServicePrincipalAsync(servicePrincipalId, body).GetAwaiter().GetResult(); }
/// <summary> /// Add new entity to servicePrincipals /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <MicrosoftGraphServicePrincipal> CreateServicePrincipalAsync(this IServicePrincipalsOperations operations, MicrosoftGraphServicePrincipal body, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateServicePrincipalWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Add new entity to servicePrincipals /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> public static MicrosoftGraphServicePrincipal CreateServicePrincipal(this IServicePrincipalsOperations operations, MicrosoftGraphServicePrincipal body) { return(operations.CreateServicePrincipalAsync(body).GetAwaiter().GetResult()); }
/// <summary> /// Update entity in servicePrincipals /// </summary> /// <remarks> /// Represents an Azure Active Directory object. The directoryObject type is /// the base type for many other directory entity types. /// </remarks> /// <param name='servicePrincipalId'> /// key: id of servicePrincipal /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="OdataErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse> UpdateServicePrincipalWithHttpMessagesAsync(string servicePrincipalId, MicrosoftGraphServicePrincipal body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (servicePrincipalId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "servicePrincipalId"); } if (body == null) { throw new ValidationException(ValidationRules.CannotBeNull, "body"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("servicePrincipalId", servicePrincipalId); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "UpdateServicePrincipal", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + Client.ApiVersion + "/"), "servicePrincipals/{servicePrincipal-id}").ToString(); _url = _url.Replace("{servicePrincipal-id}", System.Uri.EscapeDataString(servicePrincipalId)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Serialize Request string _requestContent = null; if (body != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new OdataErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); OdataError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <OdataError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
private void DeleteAdServicePrincipal(KeyVaultManagementController controllerAdmin, MicrosoftGraphServicePrincipal newServicePrincipal) { if (newServicePrincipal != null) { controllerAdmin.GraphClient.ServicePrincipals.DeleteServicePrincipal(newServicePrincipal.Id); } }