Ejemplo n.º 1
0
        public void PatchAccount()
        {
            HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler {
                    StatusCodeToReturn = HttpStatusCode.OK
                });

                // create the account
                ResourceUtils.CreateAccount(netAppMgmtClient);

                var dict = new Dictionary <string, string>();
                dict.Add("Tag1", "Value1");

                // Now try and modify it
                var netAppAccountPatch = new NetAppAccountPatch()
                {
                    Tags = dict
                };

                var resource = netAppMgmtClient.Accounts.Update(netAppAccountPatch, ResourceUtils.resourceGroup, ResourceUtils.accountName1);
                Assert.True(resource.Tags.ToString().Contains("Tag1") && resource.Tags.ToString().Contains("Value1"));

                // cleanup - remove the account
                ResourceUtils.DeleteAccount(netAppMgmtClient);
            }
        }
Ejemplo n.º 2
0
        public override void ExecuteCmdlet()
        {
            if (ParameterSetName == ResourceIdParameterSet)
            {
                var resourceIdentifier = new ResourceIdentifier(this.ResourceId);
                ResourceGroupName = resourceIdentifier.ResourceGroupName;
                Name = resourceIdentifier.ResourceName;
            }
            else if (ParameterSetName == ObjectParameterSet)
            {
                ResourceGroupName = InputObject.ResourceGroupName;
                Name = InputObject.Name;
            }

            var netAppAccountBody = new NetAppAccountPatch()
            {
                Location          = Location,
                ActiveDirectories = (ActiveDirectory != null) ? ModelExtensions.ConvertActiveDirectoriesFromPs(ActiveDirectory) : null,
                Tags = Tag,
            };

            if (ShouldProcess(Name, string.Format(PowerShell.Cmdlets.NetAppFiles.Properties.Resources.UpdateResourceMessage, ResourceGroupName)))
            {
                var anfAccount = AzureNetAppFilesManagementClient.Accounts.Update(netAppAccountBody, ResourceGroupName, Name);
                WriteObject(anfAccount.ToPsNetAppFilesAccount());
            }
        }
Ejemplo n.º 3
0
        public void PatchAccount()
        {
            HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler {
                    StatusCodeToReturn = HttpStatusCode.OK
                });

                // create the account
                ResourceUtils.CreateAccount(netAppMgmtClient, activeDirectory: ResourceUtils.activeDirectory);

                var dict = new Dictionary <string, string>();
                dict.Add("Tag2", "Value1");

                // Now try and modify it
                var netAppAccountPatch = new NetAppAccountPatch()
                {
                    Tags = dict
                };

                // tag changes but active directory still present
                var resource = netAppMgmtClient.Accounts.Update(netAppAccountPatch, ResourceUtils.resourceGroup, ResourceUtils.accountName1);
                Assert.True(resource.Tags.ContainsKey("Tag2"));
                Assert.Equal("Value1", resource.Tags["Tag2"]);
                Assert.NotNull(resource.ActiveDirectories);
                Assert.Equal("sdkuser", resource.ActiveDirectories.First().Username);

                // so deleting the active directory requires the put operation
                // but changing an active directory can be done but requires the id

                ResourceUtils.activeDirectory2.ActiveDirectoryId = resource.ActiveDirectories.First().ActiveDirectoryId;
                var activeDirectories = new List <ActiveDirectory> {
                    ResourceUtils.activeDirectory2
                };

                dict.Add("Tag3", "Value3");

                // Now try and modify it
                var netAppAccountPatch2 = new NetAppAccountPatch()
                {
                    ActiveDirectories = activeDirectories,
                    Tags = dict
                };

                var resource2 = netAppMgmtClient.Accounts.Update(netAppAccountPatch2, ResourceUtils.resourceGroup, ResourceUtils.accountName1);
                Assert.True(resource2.Tags.ContainsKey("Tag2"));
                Assert.Equal("Value1", resource2.Tags["Tag2"]);
                Assert.True(resource2.Tags.ContainsKey("Tag3"));
                Assert.Equal("Value3", resource2.Tags["Tag3"]);
                Assert.NotNull(resource2.ActiveDirectories);
                Assert.Equal("sdkuser1", resource2.ActiveDirectories.First().Username);

                // cleanup - remove the account
                ResourceUtils.DeleteAccount(netAppMgmtClient);
            }
        }
        public override void ExecuteCmdlet()
        {
            if (ParameterSetName == ParentObjectParameterSet)
            {
                ResourceGroupName = AccountObject.ResourceGroupName;
                var NameParts = AccountObject.Name.Split('/');
                AccountName = NameParts[0];
            }

            if (ShouldProcess($"{AccountName}.ActiveDirectory", string.Format(PowerShell.Cmdlets.NetAppFiles.Properties.Resources.CreateResourceMessage, ResourceGroupName)))
            {
                var anfAccount = AzureNetAppFilesManagementClient.Accounts.Get(ResourceGroupName, AccountName);
                if (anfAccount == null)
                {
                    throw new ArgumentException($"Specified NetAppAccount with name '{this.AccountName}' does not extist in Resource Group '{this.ResourceGroupName}'");
                }

                var activeDirectory = new Management.NetApp.Models.ActiveDirectory
                {
                    AdName                     = AdName,
                    Dns                        = string.Join(",", Dns),
                    Domain                     = Domain,
                    SmbServerName              = SmbServerName,
                    Username                   = Username,
                    Password                   = Password.ConvertToString(),
                    Site                       = Site,
                    OrganizationalUnit         = OrganizationalUnit,
                    BackupOperators            = BackupOperator,
                    KdcIP                      = KdcIP,
                    ServerRootCACertificate    = ServerRootCACertificate,
                    SecurityOperators          = SecurityOperator,
                    AesEncryption              = AesEncryption,
                    LdapSigning                = LdapSigning,
                    LdapOverTLS                = LdapOverTLS,
                    AllowLocalNfsUsersWithLdap = AllowLocalNfsUsersWithLdap,
                    Administrators             = Administrator,
                    EncryptDCConnections       = EncryptDCConnection
                };
                if (anfAccount.ActiveDirectories == null)
                {
                    anfAccount.ActiveDirectories = new List <Management.NetApp.Models.ActiveDirectory>();
                }
                anfAccount.ActiveDirectories.Add(activeDirectory);
                var netAppAccountBody = new NetAppAccountPatch()
                {
                    ActiveDirectories = anfAccount.ActiveDirectories
                };
                var updatedAnfAccount      = AzureNetAppFilesManagementClient.Accounts.Update(netAppAccountBody, ResourceGroupName, AccountName);
                var updatedActiveDirectory = updatedAnfAccount.ActiveDirectories.FirstOrDefault <Management.NetApp.Models.ActiveDirectory>(e => e.SmbServerName == SmbServerName);
                WriteObject(updatedActiveDirectory.ConvertToPs(ResourceGroupName, AccountName));
            }
        }
Ejemplo n.º 5
0
        public override void ExecuteCmdlet()
        {
            IDictionary <string, string> tagPairs = null;

            if (Tag != null)
            {
                tagPairs = new Dictionary <string, string>();

                foreach (string key in Tag.Keys)
                {
                    tagPairs.Add(key, Tag[key].ToString());
                }
            }

            if (ParameterSetName == ResourceIdParameterSet)
            {
                var resourceIdentifier = new ResourceIdentifier(this.ResourceId);
                ResourceGroupName = resourceIdentifier.ResourceGroupName;
                Name = resourceIdentifier.ResourceName;
            }
            else if (ParameterSetName == ObjectParameterSet)
            {
                ResourceGroupName = InputObject.ResourceGroupName;
                Name = InputObject.Name;
            }

            var netAppAccountBody = new NetAppAccountPatch()
            {
                Location          = Location,
                ActiveDirectories = (ActiveDirectory != null) ? ActiveDirectory.ConvertFromPs() : null,
                Tags = tagPairs,
            };

            if (ShouldProcess(Name, string.Format(PowerShell.Cmdlets.NetAppFiles.Properties.Resources.UpdateResourceMessage, ResourceGroupName)))
            {
                var anfAccount = AzureNetAppFilesManagementClient.Accounts.Update(netAppAccountBody, ResourceGroupName, Name);
                WriteObject(anfAccount.ToPsNetAppFilesAccount());
            }
        }
 /// <summary>
 /// Update a NetApp account
 /// </summary>
 /// <remarks>
 /// Patch the specified NetApp account
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// NetApp Account object supplied in the body of the operation.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='accountName'>
 /// The name of the NetApp account
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <NetAppAccount> UpdateAsync(this IAccountsOperations operations, NetAppAccountPatch body, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.UpdateWithHttpMessagesAsync(body, resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Update a NetApp account
 /// </summary>
 /// <remarks>
 /// Patch the specified NetApp account
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='body'>
 /// NetApp Account object supplied in the body of the operation.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group.
 /// </param>
 /// <param name='accountName'>
 /// The name of the NetApp account
 /// </param>
 public static NetAppAccount Update(this IAccountsOperations operations, NetAppAccountPatch body, string resourceGroupName, string accountName)
 {
     return(operations.UpdateAsync(body, resourceGroupName, accountName).GetAwaiter().GetResult());
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Patch a NetApp account
        /// </summary>
        /// <param name='body'>
        /// NetApp Account object supplied in the body of the operation.
        /// </param>
        /// <param name='resourceGroup'>
        /// The name of the resource group.
        /// </param>
        /// <param name='accountName'>
        /// The name of the NetApp account
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </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 <AzureOperationResponse <NetAppAccount> > UpdateWithHttpMessagesAsync(NetAppAccountPatch body, string resourceGroup, string accountName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (body == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "body");
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (resourceGroup == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroup");
            }
            if (accountName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
            }
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("body", body);
                tracingParameters.Add("resourceGroup", resourceGroup);
                tracingParameters.Add("accountName", accountName);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.NetApp/netAppAccounts/{accountName}").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{resourceGroup}", System.Uri.EscapeDataString(resourceGroup));
            _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // 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);
                }
            }

            // 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");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // 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 != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_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 AzureOperationResponse <NetAppAccount>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <NetAppAccount>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        public override void ExecuteCmdlet()
        {
            if (ParameterSetName == ParentObjectParameterSet)
            {
                ResourceGroupName = AccountObject.ResourceGroupName;
                var NameParts = AccountObject.Name.Split('/');
                AccountName = NameParts[0];
            }
            else if (ParameterSetName == ObjectParameterSet)
            {
                ResourceGroupName = InputObject.ResourceGroupName;
                AccountName       = InputObject.AccountName;
                ActiveDirectoryId = InputObject.ActiveDirectoryId;
            }

            if (ShouldProcess(ActiveDirectoryId, string.Format(PowerShell.Cmdlets.NetAppFiles.Properties.Resources.CreateResourceMessage, ResourceGroupName)))
            {
                var anfAccount = AzureNetAppFilesManagementClient.Accounts.Get(ResourceGroupName, AccountName);
                if (anfAccount == null)
                {
                    throw new ArgumentException($"Specified NetAppAccount with name '{this.AccountName}' does not extist in Resource Group '{this.ResourceGroupName}'");
                }
                string dnsStr = null;
                if (Dns != null)
                {
                    dnsStr = string.Join(",", Dns);
                }
                Management.NetApp.Models.ActiveDirectory anfADConfig = null;
                if (string.IsNullOrWhiteSpace(ActiveDirectoryId))
                {
                    anfADConfig = new Management.NetApp.Models.ActiveDirectory();
                }
                else
                {
                    anfADConfig = anfAccount.ActiveDirectories?.FirstOrDefault(a => a.ActiveDirectoryId == ActiveDirectoryId);
                    if (anfADConfig == null)
                    {
                        throw new ArgumentException($"ActiveDirectory configuration with ID '{this.ActiveDirectoryId}' in account '{this.AccountName}' is not found. Please use New-AzNetAppFilesActiveDirectory to Create a new ActiveDirectory configuration.");
                    }
                }

                anfADConfig.AdName                  = AdName ?? anfADConfig.AdName;
                anfADConfig.Dns                     = dnsStr ?? anfADConfig.Dns;
                anfADConfig.Domain                  = Domain ?? anfADConfig.Domain;
                anfADConfig.SmbServerName           = SmbServerName ?? anfADConfig.SmbServerName;
                anfADConfig.Username                = Username ?? anfADConfig.Username;
                anfADConfig.Password                = Password.ConvertToString();
                anfADConfig.Site                    = Site ?? anfADConfig.Site;
                anfADConfig.OrganizationalUnit      = OrganizationalUnit ?? anfADConfig.Site;
                anfADConfig.BackupOperators         = BackupOperator ?? anfADConfig.BackupOperators;
                anfADConfig.KdcIP                   = KdcIP ?? anfADConfig.KdcIP;
                anfADConfig.ServerRootCACertificate = ServerRootCACertificate ?? anfADConfig.ServerRootCACertificate;
                anfADConfig.SecurityOperators       = SecurityOperator ?? anfADConfig.SecurityOperators;
                if (AesEncryption)
                {
                    anfADConfig.AesEncryption = AesEncryption;
                }
                if (LdapSigning)
                {
                    anfADConfig.LdapSigning = LdapSigning;
                }
                if (LdapOverTLS)
                {
                    anfADConfig.LdapOverTLS = LdapOverTLS;
                }
                if (AllowLocalNfsUsersWithLdap)
                {
                    anfADConfig.AllowLocalNfsUsersWithLdap = AllowLocalNfsUsersWithLdap;
                }
                anfADConfig.Administrators = Administrator ?? anfADConfig.Administrators;
                if (EncryptDCConnection)
                {
                    anfADConfig.EncryptDCConnections = EncryptDCConnection;
                }

                var netAppAccountBody = new NetAppAccountPatch()
                {
                    ActiveDirectories = anfAccount.ActiveDirectories
                };

                var updatedAnfAccount      = AzureNetAppFilesManagementClient.Accounts.Update(netAppAccountBody, ResourceGroupName, AccountName);
                var updatedActiveDirectory = updatedAnfAccount.ActiveDirectories.FirstOrDefault <Management.NetApp.Models.ActiveDirectory>(e => e.ActiveDirectoryId == ActiveDirectoryId);
                WriteObject(updatedActiveDirectory.ConvertToPs(ResourceGroupName, AccountName));
            }
        }