コード例 #1
0
        public SearchServiceFixture()
        {
            SearchManagementClient client = 
                TestBase.GetServiceClient<SearchManagementClient>(new CSMTestEnvironmentFactory());

            SearchServiceName = SearchTestUtilities.GenerateServiceName();

            var createServiceParameters =
                new SearchServiceCreateOrUpdateParameters()
                {
                    Location = Location,
                    Properties = new SearchServiceProperties() { Sku = new Sku(SkuType.Free) }
                };

            SearchServiceCreateOrUpdateResponse createServiceResponse =
                client.Services.CreateOrUpdate(ResourceGroupName, SearchServiceName, createServiceParameters);
            Assert.Equal(HttpStatusCode.Created, createServiceResponse.StatusCode);

            AdminKeyResponse adminKeyResponse = client.AdminKeys.List(ResourceGroupName, SearchServiceName);
            Assert.Equal(HttpStatusCode.OK, adminKeyResponse.StatusCode);

            PrimaryApiKey = adminKeyResponse.PrimaryKey;

            ListQueryKeysResponse queryKeyResponse = client.QueryKeys.List(ResourceGroupName, SearchServiceName);
            Assert.Equal(HttpStatusCode.OK, queryKeyResponse.StatusCode);
            Assert.Equal(1, queryKeyResponse.QueryKeys.Count);

            QueryApiKey = queryKeyResponse.QueryKeys[0].Key;
        }
コード例 #2
0
        public SearchServiceFixture()
        {
            SearchManagementClient client =
                TestBase.GetServiceClient <SearchManagementClient>(new CSMTestEnvironmentFactory());

            SearchServiceName = SearchTestUtilities.GenerateServiceName();

            var createServiceParameters =
                new SearchServiceCreateOrUpdateParameters()
            {
                Location   = Location,
                Properties = new SearchServiceProperties()
                {
                    Sku = new Sku(SkuType.Free)
                }
            };

            SearchServiceCreateOrUpdateResponse createServiceResponse =
                client.Services.CreateOrUpdate(ResourceGroupName, SearchServiceName, createServiceParameters);

            Assert.Equal(HttpStatusCode.Created, createServiceResponse.StatusCode);

            AdminKeyResponse adminKeyResponse = client.AdminKeys.List(ResourceGroupName, SearchServiceName);

            Assert.Equal(HttpStatusCode.OK, adminKeyResponse.StatusCode);

            PrimaryApiKey = adminKeyResponse.PrimaryKey;

            ListQueryKeysResponse queryKeyResponse = client.QueryKeys.List(ResourceGroupName, SearchServiceName);

            Assert.Equal(HttpStatusCode.OK, queryKeyResponse.StatusCode);
            Assert.Equal(1, queryKeyResponse.QueryKeys.Count);

            QueryApiKey = queryKeyResponse.QueryKeys[0].Key;
        }
コード例 #3
0
        private string EnsureSearchService(SearchManagementClient client)
        {
            // Ensuring a search service involves creating it, and then waiting until its DNS resolves. The approach
            // we take depends on what kind of test run this is. If it's a Record or Playback run, we need determinism
            // since the mock server has no clue how many times we retried DNS lookup in the original test run. In
            // this case, we can't just delete and re-create the search service if DNS doesn't resolve in a timely
            // manner. However, we do fail fast in the interests of speeding up interactive dev cycles.
            //
            // If we're in None mode (i.e. -- no mock recording or playback), we assume we're running automated tests
            // in batch. In this case, non-determinism is not a problem (because mocks aren't involved), and
            // reliability is paramount. For this reason, we retry the entire sequence several times, deleting and
            // trying to re-create the service each time.
            int maxAttempts = (HttpMockServer.Mode == HttpRecorderMode.None) ? 10 : 1;

            for (int attempt = 0; attempt < maxAttempts; attempt++)
            {
                string searchServiceName = SearchTestUtilities.GenerateServiceName();

                var createServiceParameters =
                    new SearchServiceCreateOrUpdateParameters()
                {
                    Location   = Location,
                    Properties = new SearchServiceProperties()
                    {
                        Sku = new Sku()
                        {
                            Name = SkuType.Free
                        }
                    }
                };

                client.Services.CreateOrUpdate(ResourceGroupName, searchServiceName, createServiceParameters);

                // In the common case, DNS propagation happens in less than 15 seconds. In the uncommon case, it can
                // take many minutes. The timeout we use depends on the mock mode. If we're in Playback, the delay is
                // irrelevant. If we're in Record mode, we can't delete and re-create the service, so we get more
                // reliable results if we wait longer. In "None" mode, we can delete and re-create, which is often
                // faster than waiting a long time for DNS propagation. In that case, rather than force all tests to
                // wait several minutes, we fail fast here.
                TimeSpan maxDelay =
                    (HttpMockServer.Mode == HttpRecorderMode.Record) ?
                    TimeSpan.FromMinutes(1) : TimeSpan.FromSeconds(15);

                if (SearchTestUtilities.WaitForSearchServiceDns(searchServiceName, maxDelay))
                {
                    return(searchServiceName);
                }

                // If the service DNS isn't resolvable in a timely manner, delete it and try to create another one.
                // We need to delete it since there can be only one free service per subscription.
                client.Services.Delete(ResourceGroupName, searchServiceName);
            }

            throw new InvalidOperationException("Failed to provision a search service in a timely manner.");
        }
コード例 #4
0
ファイル: SearchServiceTests.cs プロジェクト: QITIE/ADLSTool
        public void CanListServices()
        {
            Run(() =>
            {
                SearchManagementClient searchMgmt = GetSearchManagementClient();

                string serviceName1 = SearchTestUtilities.GenerateServiceName();
                string serviceName2 = SearchTestUtilities.GenerateServiceName();

                var createServiceParameters =
                    new SearchServiceCreateOrUpdateParameters()
                {
                    Location   = Data.Location,
                    Properties = new SearchServiceProperties()
                    {
                        Sku = new Sku()
                        {
                            Name = SkuType.Free
                        },
                        ReplicaCount   = 1,
                        PartitionCount = 1
                    }
                };

                SearchServiceResource service =
                    searchMgmt.Services.CreateOrUpdate(Data.ResourceGroupName, serviceName1, createServiceParameters);
                Assert.NotNull(service);

                service =
                    searchMgmt.Services.CreateOrUpdate(Data.ResourceGroupName, serviceName2, createServiceParameters);
                Assert.NotNull(service);

                SearchServiceListResult servicesListResult = searchMgmt.Services.List(Data.ResourceGroupName);
                Assert.NotNull(servicesListResult);
                Assert.Equal(2, servicesListResult.Value.Count);
                Assert.Contains(serviceName1, servicesListResult.Value.Select(s => s.Name));
                Assert.Contains(serviceName2, servicesListResult.Value.Select(s => s.Name));
            });
        }
コード例 #5
0
 /// <summary>
 /// Creates or updates a Search service in the given resource group.
 /// If the Search service already exists, all properties will be updated with
 /// the given values.
 /// <see href="https://msdn.microsoft.com/library/azure/dn832687.aspx" />
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group within the current subscription.
 /// </param>
 /// <param name='serviceName'>
 /// The name of the Search service to operate on.
 /// </param>
 /// <param name='parameters'>
 /// The properties to set or update on the Search service.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <SearchServiceResource> CreateOrUpdateAsync(this IServicesOperations operations, string resourceGroupName, string serviceName, SearchServiceCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serviceName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
コード例 #6
0
 /// <summary>
 /// Creates or updates a Search service in the given resource group.
 /// If the Search service already exists, all properties will be updated with
 /// the given values.
 /// <see href="https://msdn.microsoft.com/library/azure/dn832687.aspx" />
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group within the current subscription.
 /// </param>
 /// <param name='serviceName'>
 /// The name of the Search service to operate on.
 /// </param>
 /// <param name='parameters'>
 /// The properties to set or update on the Search service.
 /// </param>
 public static SearchServiceResource CreateOrUpdate(this IServicesOperations operations, string resourceGroupName, string serviceName, SearchServiceCreateOrUpdateParameters parameters)
 {
     return(operations.CreateOrUpdateAsync(resourceGroupName, serviceName, parameters).GetAwaiter().GetResult());
 }
コード例 #7
0
 /// <summary>
 /// Creates or updates a Search service in the given resource group. If the
 /// Search service already exists, all properties will be updated with the
 /// given values.
 /// <see href="https://msdn.microsoft.com/library/azure/dn832687.aspx" />
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group within the current subscription.
 /// </param>
 /// <param name='serviceName'>
 /// The name of the Search service to create or update.
 /// </param>
 /// <param name='parameters'>
 /// The properties to set or update on the Search service.
 /// </param>
 public static SearchServiceResource CreateOrUpdate(this IServicesOperations operations, string resourceGroupName, string serviceName, SearchServiceCreateOrUpdateParameters parameters)
 {
     return(Task.Factory.StartNew(s => ((IServicesOperations)s).CreateOrUpdateAsync(resourceGroupName, serviceName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
コード例 #8
0
        /// <summary>
        /// Creates or updates a Search service in the given resource group.
        /// If the Search service already exists, all properties will be updated with
        /// the given values.
        /// <see href="https://msdn.microsoft.com/library/azure/dn832687.aspx" />
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group within the current subscription.
        /// </param>
        /// <param name='serviceName'>
        /// The name of the Search service to operate on.
        /// </param>
        /// <param name='parameters'>
        /// The properties to set or update on the Search service.
        /// </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 <SearchServiceResource> > CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, SearchServiceCreateOrUpdateParameters parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (serviceName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
            }
            if (parameters == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
            }
            if (parameters != null)
            {
                parameters.Validate();
            }
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("serviceName", serviceName);
                tracingParameters.Add("parameters", parameters);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{serviceName}").ToString();

            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            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("PUT");
            _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 (parameters != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, 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 && (int)_statusCode != 201)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Microsoft.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 <SearchServiceResource>();

            _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <SearchServiceResource>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            // Deserialize Response
            if ((int)_statusCode == 201)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <SearchServiceResource>(_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);
        }