public AllocationProfileResponse ProfileAllocation( ProfileRequestBase request, FundingStreamPeriodProfilePattern profilePattern, decimal fundingValue) { if (profilePattern == null) { throw new InvalidOperationException($"Profile pattern is null, {request}"); } IReadOnlyCollection <DeliveryProfilePeriod> profilePeriods = GetProfiledAllocationPeriodsWithPatternApplied(fundingValue, profilePattern.ProfilePattern, profilePattern.RoundingStrategy); IReadOnlyCollection <DistributionPeriods> distributionPeriods = GetDistributionPeriodWithPatternApplied( profilePeriods); return(new AllocationProfileResponse( profilePeriods.ToArray(), distributionPeriods.ToArray()) { ProfilePatternKey = profilePattern.ProfilePatternKey, ProfilePatternDisplayName = profilePattern.ProfilePatternDisplayName }); }
private string GetProfilePatternCacheKeyByProviderTypes(ProfileRequestBase profileRequest) { string providerTypeIdComponent = string.IsNullOrWhiteSpace(profileRequest.ProviderType) ? null : $"-{profileRequest.ProviderType}"; string providerSubTypeIdComponent = string.IsNullOrWhiteSpace(profileRequest.ProviderSubType) ? null : $"-{profileRequest.ProviderSubType}"; return($"{profileRequest.FundingPeriodId}-{profileRequest.FundingStreamId}-{profileRequest.FundingLineCode}{providerTypeIdComponent}{providerSubTypeIdComponent}"); }
/// <summary> /// Create a Profile. /// </summary> /// <remarks> /// Create a Profile for an Image. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionId'> /// The Azure Subscription ID. /// </param> /// <param name='resourceGroup'> /// The Name of the resource group in which the workspace is located. /// </param> /// <param name='workspace'> /// The name of the workspace. /// </param> /// <param name='imageId'> /// The Image Id. /// </param> /// <param name='inputRequest'> /// The payload that is used to create the Profile. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task CreateAsync(this IProfilesOperations operations, System.Guid subscriptionId, string resourceGroup, string workspace, string imageId, ProfileRequestBase inputRequest, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.CreateWithHttpMessagesAsync(subscriptionId, resourceGroup, workspace, imageId, inputRequest, null, cancellationToken).ConfigureAwait(false)).Dispose(); }
/// <summary> /// Create a Profile. /// </summary> /// <remarks> /// Create a Profile for an Image. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='subscriptionId'> /// The Azure Subscription ID. /// </param> /// <param name='resourceGroup'> /// The Name of the resource group in which the workspace is located. /// </param> /// <param name='workspace'> /// The name of the workspace. /// </param> /// <param name='imageId'> /// The Image Id. /// </param> /// <param name='inputRequest'> /// The payload that is used to create the Profile. /// </param> public static void Create(this IProfilesOperations operations, System.Guid subscriptionId, string resourceGroup, string workspace, string imageId, ProfileRequestBase inputRequest) { operations.CreateAsync(subscriptionId, resourceGroup, workspace, imageId, inputRequest).GetAwaiter().GetResult(); }
private void AndTheProfilingResponse(ProfileRequestBase request, FundingStreamPeriodProfilePattern profilePattern, decimal fundingValue, AllocationProfileResponse allocationProfileResponse) => _fundingValueProfiler.Setup(_ => _.ProfileAllocation(request, profilePattern, fundingValue)) .Returns(allocationProfileResponse);
private void LogError(Exception e, ProfileRequestBase profileRequest) { _logger.Error(e, $"Request resulted in an error of: {e.Message} for {profileRequest}"); }
public AllocationProfileResponse ProfileAllocation( ProfileRequestBase request, FundingStreamPeriodProfilePattern profilePattern, decimal fundingValue) => _fundingValueProfiler.ProfileAllocation(request, profilePattern, fundingValue);
private async Task <FundingStreamPeriodProfilePattern> GetProfilePatternByProviderTypes(ProfileRequestBase profileRequest) { FundingStreamPeriodProfilePattern profilePattern = null; string profilePatternCacheKey = GetProfilePatternCacheKeyByProviderTypes(profileRequest); profilePattern = await _cachingResilience.ExecuteAsync(() => _cacheProvider.GetAsync <FundingStreamPeriodProfilePattern>(profilePatternCacheKey)); if (profilePattern == null) { profilePattern = await _profilePatternRepositoryResilience.ExecuteAsync(() => _profilePatternRepository.GetProfilePattern(profileRequest.FundingPeriodId, profileRequest.FundingStreamId, profileRequest.FundingLineCode, profileRequest.ProviderType, profileRequest.ProviderSubType)); if (profilePattern != null) { await _cachingResilience.ExecuteAsync(() => _cacheProvider.SetAsync(profilePatternCacheKey, profilePattern, DateTimeOffset.Now.AddMinutes(30))); } } return(profilePattern ?? await GetProfilePatternByIdOrDefault(profileRequest)); }
private async Task <FundingStreamPeriodProfilePattern> GetProfilePattern(ProfileRequestBase profileRequest) => !string.IsNullOrWhiteSpace(profileRequest.ProviderType) && !string.IsNullOrWhiteSpace(profileRequest.ProviderSubType) ? await GetProfilePatternByProviderTypes(profileRequest) : await GetProfilePatternByIdOrDefault(profileRequest);
/// <summary> /// Create a Profile. /// </summary> /// <remarks> /// Create a Profile for an Image. /// </remarks> /// <param name='subscriptionId'> /// The Azure Subscription ID. /// </param> /// <param name='resourceGroup'> /// The Name of the resource group in which the workspace is located. /// </param> /// <param name='workspace'> /// The name of the workspace. /// </param> /// <param name='imageId'> /// The Image Id. /// </param> /// <param name='inputRequest'> /// The payload that is used to create the Profile. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ModelErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse> CreateWithHttpMessagesAsync(System.Guid subscriptionId, string resourceGroup, string workspace, string imageId, ProfileRequestBase inputRequest, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroup == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroup"); } if (workspace == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workspace"); } if (imageId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "imageId"); } if (inputRequest == null) { throw new ValidationException(ValidationRules.CannotBeNull, "inputRequest"); } if (inputRequest != null) { inputRequest.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("resourceGroup", resourceGroup); tracingParameters.Add("workspace", workspace); tracingParameters.Add("imageId", imageId); tracingParameters.Add("inputRequest", inputRequest); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "modelmanagement/v1.0/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.MachineLearningServices/workspaces/{workspace}/images/{imageId}/profiles").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(subscriptionId, Client.SerializationSettings).Trim('"'))); _url = _url.Replace("{resourceGroup}", System.Uri.EscapeDataString(resourceGroup)); _url = _url.Replace("{workspace}", System.Uri.EscapeDataString(workspace)); _url = _url.Replace("{imageId}", System.Uri.EscapeDataString(imageId)); List <string> _queryParameters = new List <string>(); 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("POST"); _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 (inputRequest != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(inputRequest, 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 != 202) { var ex = new ModelErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ModelErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ModelErrorResponse>(_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(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }