From 028866d272f8ba40a1a365b2fa2260d444f84057 Mon Sep 17 00:00:00 2001 From: Aleksandr Vishniakov Date: Thu, 10 Dec 2020 18:28:34 +0200 Subject: [PATCH] VDS-393: Use user groups from index (#47) * VDS-393: Use usergroups from index * Fix code smells * Check for groups field existance in index document --- .../Customer/Services/IDemoMemberService.cs | 10 + .../DemoCustomerSegmentsModuleModuleApi.cs | 2119 +++++++++++++++++ .../ServiceCollectionExtension.cs | 3 + .../Domain/Customer/DemoMemberService.cs | 67 +- VirtoCommerce.Storefront/Startup.cs | 4 +- 5 files changed, 2199 insertions(+), 4 deletions(-) create mode 100644 VirtoCommerce.Storefront.Model/Customer/Services/IDemoMemberService.cs create mode 100644 VirtoCommerce.Storefront/AutoRestClients/DemoCustomerSegmentsModuleModuleApi.cs diff --git a/VirtoCommerce.Storefront.Model/Customer/Services/IDemoMemberService.cs b/VirtoCommerce.Storefront.Model/Customer/Services/IDemoMemberService.cs new file mode 100644 index 00000000..b6b758a2 --- /dev/null +++ b/VirtoCommerce.Storefront.Model/Customer/Services/IDemoMemberService.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace VirtoCommerce.Storefront.Model.Customer.Services +{ + public interface IDemoMemberService + { + Task> GetMemberIndexByIdAsync(string memberId); + } +} diff --git a/VirtoCommerce.Storefront/AutoRestClients/DemoCustomerSegmentsModuleModuleApi.cs b/VirtoCommerce.Storefront/AutoRestClients/DemoCustomerSegmentsModuleModuleApi.cs new file mode 100644 index 00000000..da97a66b --- /dev/null +++ b/VirtoCommerce.Storefront/AutoRestClients/DemoCustomerSegmentsModuleModuleApi.cs @@ -0,0 +1,2119 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Models; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + public partial class DemoCustomerSegmentsModuleModuleClient : ServiceClient, IDemoCustomerSegmentsModuleModuleClient + { + /// + /// The base URI of the service. + /// + public System.Uri BaseUri { get; set; } + + /// + /// Gets or sets json serialization settings. + /// + public JsonSerializerSettings SerializationSettings { get; private set; } + + /// + /// Gets or sets json deserialization settings. + /// + public JsonSerializerSettings DeserializationSettings { get; private set; } + + /// + /// Subscription credentials which uniquely identify client subscription. + /// + public ServiceClientCredentials Credentials { get; private set; } + + /// + /// Gets the IDemoCustomerSegmentOperations. + /// + public virtual IDemoCustomerSegmentOperations DemoCustomerSegment { get; private set; } + + /// + /// Gets the IDemoSearch. + /// + public virtual IDemoSearch DemoSearch { get; private set; } + + /// + /// Initializes a new instance of the DemoCustomerSegmentsModuleModuleClient class. + /// + /// + /// HttpClient to be used + /// + /// + /// True: will dispose the provided httpClient on calling DemoCustomerSegmentsModuleModuleClient.Dispose(). False: will not dispose provided httpClient + protected DemoCustomerSegmentsModuleModuleClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient) + { + Initialize(); + } + + /// + /// Initializes a new instance of the DemoCustomerSegmentsModuleModuleClient class. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + protected DemoCustomerSegmentsModuleModuleClient(params DelegatingHandler[] handlers) : base(handlers) + { + Initialize(); + } + + /// + /// Initializes a new instance of the DemoCustomerSegmentsModuleModuleClient class. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + protected DemoCustomerSegmentsModuleModuleClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) + { + Initialize(); + } + + /// + /// Initializes a new instance of the DemoCustomerSegmentsModuleModuleClient class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + /// + /// Thrown when a required parameter is null + /// + protected DemoCustomerSegmentsModuleModuleClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) + { + if (baseUri == null) + { + throw new System.ArgumentNullException("baseUri"); + } + BaseUri = baseUri; + } + + /// + /// Initializes a new instance of the DemoCustomerSegmentsModuleModuleClient class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + /// + /// Thrown when a required parameter is null + /// + protected DemoCustomerSegmentsModuleModuleClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) + { + if (baseUri == null) + { + throw new System.ArgumentNullException("baseUri"); + } + BaseUri = baseUri; + } + + /// + /// Initializes a new instance of the DemoCustomerSegmentsModuleModuleClient class. + /// + /// + /// Required. Subscription credentials which uniquely identify client subscription. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + /// + /// Thrown when a required parameter is null + /// + public DemoCustomerSegmentsModuleModuleClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) + { + if (credentials == null) + { + throw new System.ArgumentNullException("credentials"); + } + Credentials = credentials; + if (Credentials != null) + { + Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the DemoCustomerSegmentsModuleModuleClient class. + /// + /// + /// Required. Subscription credentials which uniquely identify client subscription. + /// + /// + /// HttpClient to be used + /// + /// + /// True: will dispose the provided httpClient on calling DemoCustomerSegmentsModuleModuleClient.Dispose(). False: will not dispose provided httpClient + /// + /// Thrown when a required parameter is null + /// + public DemoCustomerSegmentsModuleModuleClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : this(httpClient, disposeHttpClient) + { + if (credentials == null) + { + throw new System.ArgumentNullException("credentials"); + } + Credentials = credentials; + if (Credentials != null) + { + Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the DemoCustomerSegmentsModuleModuleClient class. + /// + /// + /// Required. Subscription credentials which uniquely identify client subscription. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + /// + /// Thrown when a required parameter is null + /// + public DemoCustomerSegmentsModuleModuleClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) + { + if (credentials == null) + { + throw new System.ArgumentNullException("credentials"); + } + Credentials = credentials; + if (Credentials != null) + { + Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the DemoCustomerSegmentsModuleModuleClient class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Required. Subscription credentials which uniquely identify client subscription. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + /// + /// Thrown when a required parameter is null + /// + public DemoCustomerSegmentsModuleModuleClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) + { + if (baseUri == null) + { + throw new System.ArgumentNullException("baseUri"); + } + if (credentials == null) + { + throw new System.ArgumentNullException("credentials"); + } + BaseUri = baseUri; + Credentials = credentials; + if (Credentials != null) + { + Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the DemoCustomerSegmentsModuleModuleClient class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Required. Subscription credentials which uniquely identify client subscription. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + /// + /// Thrown when a required parameter is null + /// + public DemoCustomerSegmentsModuleModuleClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) + { + if (baseUri == null) + { + throw new System.ArgumentNullException("baseUri"); + } + if (credentials == null) + { + throw new System.ArgumentNullException("credentials"); + } + BaseUri = baseUri; + Credentials = credentials; + if (Credentials != null) + { + Credentials.InitializeServiceClient(this); + } + } + + /// + /// An optional partial-method to perform custom initialization. + /// + partial void CustomInitialize(); + /// + /// Initializes client properties. + /// + private void Initialize() + { + DemoCustomerSegment = new DemoCustomerSegmentOperations(this); + DemoSearch = new DemoSearch(this); + BaseUri = new System.Uri("http://localhost"); + SerializationSettings = new JsonSerializerSettings + { + Formatting = Newtonsoft.Json.Formatting.Indented, + DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, + NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, + ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + DeserializationSettings = new JsonSerializerSettings + { + DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, + NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, + ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + CustomInitialize(); + } + } +} +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Models; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + /// + /// + public partial interface IDemoCustomerSegmentsModuleModuleClient : System.IDisposable + { + /// + /// The base URI of the service. + /// + System.Uri BaseUri { get; set; } + + /// + /// Gets or sets json serialization settings. + /// + JsonSerializerSettings SerializationSettings { get; } + + /// + /// Gets or sets json deserialization settings. + /// + JsonSerializerSettings DeserializationSettings { get; } + + /// + /// Subscription credentials which uniquely identify client + /// subscription. + /// + ServiceClientCredentials Credentials { get; } + + + /// + /// Gets the IDemoCustomerSegmentOperations. + /// + IDemoCustomerSegmentOperations DemoCustomerSegment { get; } + + /// + /// Gets the IDemoSearch. + /// + IDemoSearch DemoSearch { get; } + + } +} +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Models; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + /// + /// DemoCustomerSegmentOperations operations. + /// + public partial class DemoCustomerSegmentOperations : IServiceOperations, IDemoCustomerSegmentOperations + { + /// + /// Initializes a new instance of the DemoCustomerSegmentOperations class. + /// + /// + /// Reference to the service client. + /// + /// + /// Thrown when a required parameter is null + /// + public DemoCustomerSegmentOperations(DemoCustomerSegmentsModuleModuleClient client) + { + if (client == null) + { + throw new System.ArgumentNullException("client"); + } + Client = client; + } + + /// + /// Gets a reference to the DemoCustomerSegmentsModuleModuleClient + /// + public DemoCustomerSegmentsModuleModuleClient Client { get; private set; } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetNewCustomerSegmentWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetNewCustomerSegment", tracingParameters); + } + // Construct URL + var _baseUrl = Client.BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/demo/customersegments/new").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + 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; + // 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 != 401 && (int)_statusCode != 403) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + 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; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_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; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetCustomerSegmentByIdWithHttpMessagesAsync(string id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (id == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "id"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetCustomerSegmentById", tracingParameters); + } + // Construct URL + var _baseUrl = Client.BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/demo/customersegments/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(id)); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + 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; + // 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 != 401 && (int)_statusCode != 403) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + 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; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_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; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> SaveCustomerSegmentsWithHttpMessagesAsync(IList body = default(IList), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "SaveCustomerSegments", tracingParameters); + } + // Construct URL + var _baseUrl = Client.BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/demo/customersegments").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + 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 = 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-patch+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 != 401 && (int)_statusCode != 403) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + 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; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_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; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task DeleteCustomerSegmentsWithHttpMessagesAsync(IList ids = default(IList), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("ids", ids); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "DeleteCustomerSegments", tracingParameters); + } + // Construct URL + var _baseUrl = Client.BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/demo/customersegments").ToString(); + List _queryParameters = new List(); + if (ids != null) + { + _queryParameters.Add(string.Format("ids={0}", System.Uri.EscapeDataString(string.Join(",", ids)))); + } + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + 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; + // 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 != 204 && (int)_statusCode != 401 && (int)_statusCode != 403) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + 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; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> SearchCustomerSegmentsWithHttpMessagesAsync(DemoCustomerSegmentSearchCriteria body = default(DemoCustomerSegmentSearchCriteria), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("body", body); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "SearchCustomerSegments", tracingParameters); + } + // Construct URL + var _baseUrl = Client.BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/demo/customersegments/search").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + 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 = 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-patch+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 != 401 && (int)_statusCode != 403) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + 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; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_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; + } + + } +} +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Models; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + /// + /// DemoCustomerSegmentOperations operations. + /// + public partial interface IDemoCustomerSegmentOperations + { + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + Task> GetNewCustomerSegmentWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// Thrown when a required parameter is null + /// + Task> GetCustomerSegmentByIdWithHttpMessagesAsync(string id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + Task>> SaveCustomerSegmentsWithHttpMessagesAsync(IList body = default(IList), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + Task DeleteCustomerSegmentsWithHttpMessagesAsync(IList ids = default(IList), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + Task> SearchCustomerSegmentsWithHttpMessagesAsync(DemoCustomerSegmentSearchCriteria body = default(DemoCustomerSegmentSearchCriteria), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + } +} +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Models; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + /// + /// Extension methods for DemoCustomerSegmentOperations. + /// + public static partial class DemoCustomerSegmentOperationsExtensions + { + /// + /// The operations group for this extension method. + /// + public static DemoCustomerSegment GetNewCustomerSegment(this IDemoCustomerSegmentOperations operations) + { + return operations.GetNewCustomerSegmentAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetNewCustomerSegmentAsync(this IDemoCustomerSegmentOperations operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetNewCustomerSegmentWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static DemoCustomerSegment GetCustomerSegmentById(this IDemoCustomerSegmentOperations operations, string id) + { + return operations.GetCustomerSegmentByIdAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task GetCustomerSegmentByIdAsync(this IDemoCustomerSegmentOperations operations, string id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetCustomerSegmentByIdWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static IList SaveCustomerSegments(this IDemoCustomerSegmentOperations operations, IList body = default(IList)) + { + return operations.SaveCustomerSegmentsAsync(body).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task> SaveCustomerSegmentsAsync(this IDemoCustomerSegmentOperations operations, IList body = default(IList), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.SaveCustomerSegmentsWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static void DeleteCustomerSegments(this IDemoCustomerSegmentOperations operations, IList ids = default(IList)) + { + operations.DeleteCustomerSegmentsAsync(ids).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task DeleteCustomerSegmentsAsync(this IDemoCustomerSegmentOperations operations, IList ids = default(IList), CancellationToken cancellationToken = default(CancellationToken)) + { + (await operations.DeleteCustomerSegmentsWithHttpMessagesAsync(ids, null, cancellationToken).ConfigureAwait(false)).Dispose(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static DemoCustomerSegmentSearchResult SearchCustomerSegments(this IDemoCustomerSegmentOperations operations, DemoCustomerSegmentSearchCriteria body = default(DemoCustomerSegmentSearchCriteria)) + { + return operations.SearchCustomerSegmentsAsync(body).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task SearchCustomerSegmentsAsync(this IDemoCustomerSegmentOperations operations, DemoCustomerSegmentSearchCriteria body = default(DemoCustomerSegmentSearchCriteria), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.SearchCustomerSegmentsWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + } +} +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Models; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + /// + /// DemoSearch operations. + /// + public partial class DemoSearch : IServiceOperations, IDemoSearch + { + /// + /// Initializes a new instance of the DemoSearch class. + /// + /// + /// Reference to the service client. + /// + /// + /// Thrown when a required parameter is null + /// + public DemoSearch(DemoCustomerSegmentsModuleModuleClient client) + { + if (client == null) + { + throw new System.ArgumentNullException("client"); + } + Client = client; + } + + /// + /// Gets a reference to the DemoCustomerSegmentsModuleModuleClient + /// + public DemoCustomerSegmentsModuleModuleClient Client { get; private set; } + + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> GetDocumentIndexAsyncWithHttpMessagesAsync(string documentType, string documentId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (documentType == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "documentType"); + } + if (documentId == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "documentId"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("documentType", documentType); + tracingParameters.Add("documentId", documentId); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetDocumentIndexAsync", tracingParameters); + } + // Construct URL + var _baseUrl = Client.BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/demo/search/index/{documentType}/{documentId}").ToString(); + _url = _url.Replace("{documentType}", System.Uri.EscapeDataString(documentType)); + _url = _url.Replace("{documentId}", System.Uri.EscapeDataString(documentId)); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + 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; + // 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 != 401 && (int)_statusCode != 403) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + 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; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_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; + } + + } +} +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Models; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + /// + /// DemoSearch operations. + /// + public partial interface IDemoSearch + { + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// Thrown when a required parameter is null + /// + Task>> GetDocumentIndexAsyncWithHttpMessagesAsync(string documentType, string documentId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + } +} +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Models; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + /// + /// Extension methods for DemoSearch. + /// + public static partial class DemoSearchExtensions + { + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + public static IDictionary GetDocumentIndexAsync(this IDemoSearch operations, string documentType, string documentId) + { + return operations.GetDocumentIndexAsyncAsync(documentType, documentId).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task> GetDocumentIndexAsyncAsync(this IDemoSearch operations, string documentType, string documentId, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetDocumentIndexAsyncWithHttpMessagesAsync(documentType, documentId, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + } +} +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi.Models +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + public partial class IConditionTree + { + /// + /// Initializes a new instance of the IConditionTree class. + /// + public IConditionTree() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the IConditionTree class. + /// + /// List of all available children for + /// current tree node (is used in expression designer) + public IConditionTree(string id = default(string), IList availableChildren = default(IList), IList children = default(IList)) + { + Id = id; + AvailableChildren = availableChildren; + Children = children; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public string Id { get; private set; } + + /// + /// Gets list of all available children for current tree node (is used + /// in expression designer) + /// + [JsonProperty(PropertyName = "availableChildren")] + public IList AvailableChildren { get; private set; } + + /// + /// + [JsonProperty(PropertyName = "children")] + public IList Children { get; private set; } + + } +} +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi.Models +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + public partial class DemoCustomerSegmentTree + { + /// + /// Initializes a new instance of the DemoCustomerSegmentTree class. + /// + public DemoCustomerSegmentTree() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the DemoCustomerSegmentTree class. + /// + public DemoCustomerSegmentTree(bool? all = default(bool?), bool? not = default(bool?), string id = default(string), IList availableChildren = default(IList), IList children = default(IList)) + { + All = all; + Not = not; + Id = id; + AvailableChildren = availableChildren; + Children = children; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "all")] + public bool? All { get; set; } + + /// + /// + [JsonProperty(PropertyName = "not")] + public bool? Not { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public string Id { get; private set; } + + /// + /// + [JsonProperty(PropertyName = "availableChildren")] + public IList AvailableChildren { get; set; } + + /// + /// + [JsonProperty(PropertyName = "children")] + public IList Children { get; set; } + + } +} +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi.Models +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + public partial class DemoCustomerSegment + { + /// + /// Initializes a new instance of the DemoCustomerSegment class. + /// + public DemoCustomerSegment() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the DemoCustomerSegment class. + /// + public DemoCustomerSegment(string name = default(string), string description = default(string), string userGroup = default(string), bool? isActive = default(bool?), System.DateTime? startDate = default(System.DateTime?), System.DateTime? endDate = default(System.DateTime?), IList storeIds = default(IList), DemoCustomerSegmentTree expressionTree = default(DemoCustomerSegmentTree), System.DateTime? createdDate = default(System.DateTime?), System.DateTime? modifiedDate = default(System.DateTime?), string createdBy = default(string), string modifiedBy = default(string), string id = default(string)) + { + Name = name; + Description = description; + UserGroup = userGroup; + IsActive = isActive; + StartDate = startDate; + EndDate = endDate; + StoreIds = storeIds; + ExpressionTree = expressionTree; + CreatedDate = createdDate; + ModifiedDate = modifiedDate; + CreatedBy = createdBy; + ModifiedBy = modifiedBy; + Id = id; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "userGroup")] + public string UserGroup { get; set; } + + /// + /// + [JsonProperty(PropertyName = "isActive")] + public bool? IsActive { get; set; } + + /// + /// + [JsonProperty(PropertyName = "startDate")] + public System.DateTime? StartDate { get; set; } + + /// + /// + [JsonProperty(PropertyName = "endDate")] + public System.DateTime? EndDate { get; set; } + + /// + /// + [JsonProperty(PropertyName = "storeIds")] + public IList StoreIds { get; set; } + + /// + /// + [JsonProperty(PropertyName = "expressionTree")] + public DemoCustomerSegmentTree ExpressionTree { get; set; } + + /// + /// + [JsonProperty(PropertyName = "createdDate")] + public System.DateTime? CreatedDate { get; set; } + + /// + /// + [JsonProperty(PropertyName = "modifiedDate")] + public System.DateTime? ModifiedDate { get; set; } + + /// + /// + [JsonProperty(PropertyName = "createdBy")] + public string CreatedBy { get; set; } + + /// + /// + [JsonProperty(PropertyName = "modifiedBy")] + public string ModifiedBy { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + } +} +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi.Models +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + public partial class SortInfo + { + /// + /// Initializes a new instance of the SortInfo class. + /// + public SortInfo() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the SortInfo class. + /// + /// Possible values include: 'Ascending', + /// 'Descending' + public SortInfo(string sortColumn = default(string), string sortDirection = default(string)) + { + SortColumn = sortColumn; + SortDirection = sortDirection; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "sortColumn")] + public string SortColumn { get; set; } + + /// + /// Gets or sets possible values include: 'Ascending', 'Descending' + /// + [JsonProperty(PropertyName = "sortDirection")] + public string SortDirection { get; set; } + + } +} +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi.Models +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + public partial class DemoCustomerSegmentSearchCriteria + { + /// + /// Initializes a new instance of the DemoCustomerSegmentSearchCriteria + /// class. + /// + public DemoCustomerSegmentSearchCriteria() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the DemoCustomerSegmentSearchCriteria + /// class. + /// + public DemoCustomerSegmentSearchCriteria(IList storeIds = default(IList), bool? isActive = default(bool?), string responseGroup = default(string), string objectType = default(string), IList objectTypes = default(IList), IList objectIds = default(IList), string keyword = default(string), string searchPhrase = default(string), string languageCode = default(string), string sort = default(string), IList sortInfos = default(IList), int? skip = default(int?), int? take = default(int?)) + { + StoreIds = storeIds; + IsActive = isActive; + ResponseGroup = responseGroup; + ObjectType = objectType; + ObjectTypes = objectTypes; + ObjectIds = objectIds; + Keyword = keyword; + SearchPhrase = searchPhrase; + LanguageCode = languageCode; + Sort = sort; + SortInfos = sortInfos; + Skip = skip; + Take = take; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "storeIds")] + public IList StoreIds { get; set; } + + /// + /// + [JsonProperty(PropertyName = "isActive")] + public bool? IsActive { get; set; } + + /// + /// + [JsonProperty(PropertyName = "responseGroup")] + public string ResponseGroup { get; set; } + + /// + /// + [JsonProperty(PropertyName = "objectType")] + public string ObjectType { get; set; } + + /// + /// + [JsonProperty(PropertyName = "objectTypes")] + public IList ObjectTypes { get; set; } + + /// + /// + [JsonProperty(PropertyName = "objectIds")] + public IList ObjectIds { get; set; } + + /// + /// + [JsonProperty(PropertyName = "keyword")] + public string Keyword { get; set; } + + /// + /// + [JsonProperty(PropertyName = "searchPhrase")] + public string SearchPhrase { get; set; } + + /// + /// + [JsonProperty(PropertyName = "languageCode")] + public string LanguageCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "sort")] + public string Sort { get; set; } + + /// + /// + [JsonProperty(PropertyName = "sortInfos")] + public IList SortInfos { get; private set; } + + /// + /// + [JsonProperty(PropertyName = "skip")] + public int? Skip { get; set; } + + /// + /// + [JsonProperty(PropertyName = "take")] + public int? Take { get; set; } + + } +} +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi.Models +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + public partial class DemoCustomerSegmentSearchResult + { + /// + /// Initializes a new instance of the DemoCustomerSegmentSearchResult + /// class. + /// + public DemoCustomerSegmentSearchResult() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the DemoCustomerSegmentSearchResult + /// class. + /// + public DemoCustomerSegmentSearchResult(int? totalCount = default(int?), IList results = default(IList)) + { + TotalCount = totalCount; + Results = results; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "totalCount")] + public int? TotalCount { get; set; } + + /// + /// + [JsonProperty(PropertyName = "results")] + public IList Results { get; set; } + + } +} diff --git a/VirtoCommerce.Storefront/DependencyInjection/ServiceCollectionExtension.cs b/VirtoCommerce.Storefront/DependencyInjection/ServiceCollectionExtension.cs index f42baafb..db167703 100644 --- a/VirtoCommerce.Storefront/DependencyInjection/ServiceCollectionExtension.cs +++ b/VirtoCommerce.Storefront/DependencyInjection/ServiceCollectionExtension.cs @@ -16,6 +16,7 @@ using VirtoCommerce.Storefront.AutoRestClients.ContentModuleApi; using VirtoCommerce.Storefront.AutoRestClients.CoreModuleApi; using VirtoCommerce.Storefront.AutoRestClients.CustomerModuleApi; +using VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi; using VirtoCommerce.Storefront.AutoRestClients.DynamicAssociationsModuleModuleApi; using VirtoCommerce.Storefront.AutoRestClients.InventoryModuleApi; using VirtoCommerce.Storefront.AutoRestClients.MarketingModuleApi; @@ -120,6 +121,8 @@ public static void AddPlatformEndpoint(this IServiceCollection services, Action< services.AddSingleton(sp => new Notifications(sp.GetRequiredService())); services.AddAutoRestClient((credentials, httpClient, disposeHttpClient, baseUri) => new CustomerModuleClient(credentials, httpClient, disposeHttpClient) { BaseUri = baseUri }); services.AddSingleton(sp => new CustomerModule(sp.GetRequiredService())); + services.AddAutoRestClient((credentials, httpClient, disposeHttpClient, baseUri) => new DemoCustomerSegmentsModuleModuleClient(credentials, httpClient, disposeHttpClient) { BaseUri = baseUri }); + services.AddSingleton(sp => new DemoSearch(sp.GetRequiredService())); services.AddAutoRestClient((credentials, httpClient, disposeHttpClient, baseUri) => new OrdersModuleClient(credentials, httpClient, disposeHttpClient) { BaseUri = baseUri }); services.AddSingleton(sp => new OrderModule(sp.GetRequiredService())); services.AddSingleton(sp => new OrderModulePayments(sp.GetRequiredService())); diff --git a/VirtoCommerce.Storefront/Domain/Customer/DemoMemberService.cs b/VirtoCommerce.Storefront/Domain/Customer/DemoMemberService.cs index 36ac7bb1..5158af2a 100644 --- a/VirtoCommerce.Storefront/Domain/Customer/DemoMemberService.cs +++ b/VirtoCommerce.Storefront/Domain/Customer/DemoMemberService.cs @@ -1,21 +1,74 @@ using System; +using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; +using Microsoft.Extensions.Caching.Memory; using Microsoft.Rest; +using Newtonsoft.Json.Linq; using VirtoCommerce.Storefront.AutoRestClients.CustomerModuleApi; +using VirtoCommerce.Storefront.AutoRestClients.DemoCustomerSegmentsModuleModuleApi; using VirtoCommerce.Storefront.Infrastructure; using VirtoCommerce.Storefront.Model.Caching; +using VirtoCommerce.Storefront.Model.Common.Caching; +using VirtoCommerce.Storefront.Model.Customer; +using VirtoCommerce.Storefront.Model.Customer.Services; namespace VirtoCommerce.Storefront.Domain { - public class DemoMemberService : MemberService + public class DemoMemberService : MemberService, IDemoMemberService { private readonly ICustomerModule _customerApi; + private readonly IDemoSearch _demoSearchApi; + private readonly IStorefrontMemoryCache _memoryCache; + private readonly IApiChangesWatcher _apiChangesWatcher; private readonly string NO_CONTENT = "NoContent"; - public DemoMemberService(ICustomerModule customerApi, IStorefrontMemoryCache memoryCache, IApiChangesWatcher changesWatcher) - : base(customerApi, memoryCache, changesWatcher) + public DemoMemberService(ICustomerModule customerApi, IDemoSearch demoSearchApi, IStorefrontMemoryCache memoryCache, IApiChangesWatcher apiChangesWatcher) + : base(customerApi, memoryCache, apiChangesWatcher) { _customerApi = customerApi; + _demoSearchApi = demoSearchApi; + _memoryCache = memoryCache; + _apiChangesWatcher = apiChangesWatcher; + } + + public async Task> GetMemberIndexByIdAsync(string memberId) + { + ValidateParameters(memberId); + + var cacheKey = CacheKey.With(GetType(), "GetMemberIndexByIdAsync", memberId); + var result = await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) => + { + var indexDto = await _demoSearchApi.GetDocumentIndexAsyncAsync(nameof(Member), memberId); + + cacheEntry.AddExpirationToken(CustomerCacheRegion.CreateChangeToken(memberId)); + cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken()); + return indexDto; + }); + return result; + } + + public override async Task GetContactByIdAsync(string contactId) + { + var result = await base.GetContactByIdAsync(contactId); + var indexDocument = await GetMemberIndexByIdAsync(contactId); + if (indexDocument != null) + { + indexDocument.TryGetValue("groups", out var groupsField); + // This conversion is required because returned IDictionary contains deserialized arrays as JArrays + string[] groups; + if (groupsField is JArray groupsArray) + { + groups = groupsArray.ToObject(); + } + else + { + groups = groupsField != null ? new[] { groupsField as string } : Array.Empty(); + } + + result.UserGroups = result.UserGroups.Concat(groups).Distinct().ToArray(); + } + return result; } public override async Task DeleteContactAsync(string contactId) @@ -39,5 +92,13 @@ public override async Task DeleteContactAsync(string contactId) //Invalidate cache CustomerCacheRegion.ExpireMember(contactId); } + + private static void ValidateParameters(string memberId) + { + if (memberId == null) + { + throw new ArgumentNullException(nameof(memberId)); + } + } } } diff --git a/VirtoCommerce.Storefront/Startup.cs b/VirtoCommerce.Storefront/Startup.cs index 2cfb568c..5abc0624 100644 --- a/VirtoCommerce.Storefront/Startup.cs +++ b/VirtoCommerce.Storefront/Startup.cs @@ -99,7 +99,9 @@ public void ConfigureServices(IServiceCollection services) services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(x => x.GetRequiredService()); + services.AddSingleton(x => x.GetRequiredService()); services.AddSingleton(); services.AddSingleton(x => x.GetRequiredService()); services.AddSingleton(x => x.GetRequiredService());