public static async Task Main() { ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build()); try { await RunAsync(config); Console.WriteLine("RunAsync successful"); } catch (Exception exception) { if (exception.Source.Contains("ActiveDirectory")) { Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample."); } Console.Error.WriteLine($"{exception.Message}"); ApiErrorException apiException = exception.GetBaseException() as ApiErrorException; if (apiException != null) { Console.Error.WriteLine( $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'."); } } Console.WriteLine("Press Enter to continue."); }
public async Task ConnectAsync() { try { client = await CreateMediaServicesClientAsync(); Console.WriteLine("connected"); } catch (Exception exception) { if (exception.Source.Contains("ActiveDirectory")) { Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample."); } Console.Error.WriteLine($"{exception.Message}"); ApiErrorException apiException = exception.GetBaseException() as ApiErrorException; if (apiException != null) { Console.Error.WriteLine( $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'."); } } Console.WriteLine("Press Enter to continue."); Console.ReadLine(); }
public static async Task Main(string[] args) { ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build()); try { await RunAsync(config); } catch (Exception exception) { Console.Error.WriteLine($"{exception.Message}"); ApiErrorException apiException = exception.GetBaseException() as ApiErrorException; if (apiException != null) { Console.Error.WriteLine( $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'."); } } Console.WriteLine("Press Enter to continue."); Console.ReadLine(); }
static void Main(string[] args) { ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build()); try { RunApplication(config); } catch (Exception exception) { if (exception.Source.Contains("ActiveDirectory")) { Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample."); } Console.Error.WriteLine($"{exception.Message}"); ApiErrorException apiException = exception.GetBaseException() as ApiErrorException; if (apiException != null) { Console.Error.WriteLine( $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'."); } } }
public static async Task Main(string[] args) { //For secrurity purpose, I just put a dummy one //You will need to create a Media Service account to get all required configrations to access API ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build()); try { await RunAsync(config); } catch (Exception exception) { if (exception.Source.Contains("ActiveDirectory")) { Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample."); } Console.Error.WriteLine($"{exception.Message}"); ApiErrorException apiException = exception.GetBaseException() as ApiErrorException; if (apiException != null) { Console.Error.WriteLine( $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'."); } } Console.WriteLine("Press Enter to continue."); Console.ReadLine(); }
public async Task UploadConvert(string output, string inputMP4FileName) { InputMP4FileName = inputMP4FileName; outputAssetName = output; ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build()); try { await RunAsync(config); } catch (Exception exception) { if (exception.Source.Contains("ActiveDirectory")) { new Exception("TIP: Make sure that you have filled out the appsettings.json file before running this sample."); } new Exception($"{exception.Message}"); ApiErrorException apiException = exception.GetBaseException() as ApiErrorException; if (apiException != null) { new Exception( $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'."); } } }
public async void ResponseListenerTokenExpiredTest() { bool eventDispatched = false; _kuzzle.EventHandler.TokenExpired += delegate() { eventDispatched = true; }; TaskCompletionSource <Response> responseTask = new TaskCompletionSource <Response>(); string requestId = "uniq-id"; JObject apiResponse = new JObject { { "requestId", requestId }, { "room", requestId }, { "status", 401 }, { "error", new JObject { { "message", "Token expired" }, { "stack", "line 42: error" } } } }; _kuzzle.requests[requestId] = responseTask; _kuzzle.ResponsesListener(_kuzzle, apiResponse.ToString()); ApiErrorException ex = await Assert.ThrowsAsync <ApiErrorException>(async() => { await responseTask.Task; }); Assert.True(eventDispatched); Assert.Equal(401, ex.Status); Assert.Equal("Token expired", ex.Message); Assert.Equal("line 42: error", ex.Stack); }
private static string MyStreamingEndpointName = "default"; // Change this to your Endpoint name. public static async Task Main(string[] args) { // Please make sure you have set configuration in appsettings.json.For more information, see // https://docs.microsoft.com/azure/media-services/latest/access-api-cli-how-to. ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build()); try { await RunAsync(config); } catch (Exception exception) { Console.Error.WriteLine($"{exception.Message}"); ApiErrorException apiException = exception.GetBaseException() as ApiErrorException; if (apiException != null) { Console.Error.WriteLine( $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'."); } } Console.WriteLine("Press Enter to continue."); Console.ReadLine(); }
public void ToString_HttpError() { var ex = new ApiErrorException(HttpStatusCode.Forbidden, TEST_MESSAGE); Assert.True(ex.IsHttpError); Assert.Equal($"{HttpStatusCode.Forbidden}: {TEST_MESSAGE}", ex.ToString()); }
public void ToString_HttpError_TruncatesLongMessages() { var ex = new ApiErrorException(HttpStatusCode.Forbidden, LONG_TEST_MESSAGE); Assert.True(ex.IsHttpError); Assert.Equal($"{HttpStatusCode.Forbidden}: {LONG_TEST_MESSAGE.Substring(0, 77)}...", ex.ToString()); }
public async Task <IActionResult> MediaTest( [FromForm(Name = "myFile")] IFormFile myFile) { ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("C:/Users/ALIENWARE.000/Desktop/Front/MusicServer/MusicServer/appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build()); var message = ""; try { var urlStream = await uploadEncodeAndStreamFiles.RunAsync(config, "sample1-0c6fd45a-6cc0-4bb9-92d4-b4815b76612b.mp4"); return(Ok(new { url = urlStream })); } catch (Exception exception) { if (exception.Source.Contains("ActiveDirectory")) { Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample."); } Console.Error.WriteLine($"{exception.Message}"); ApiErrorException apiException = exception.GetBaseException() as ApiErrorException; if (apiException != null) { Console.Error.WriteLine( $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'."); } return(StatusCode(StatusCodes.Status500InternalServerError, apiException)); } }
public void ToString_NotAnHttpError_DoesNotTruncate(string message) { var ex = new ApiErrorException(message); Assert.False(ex.IsHttpError); Assert.Equal($"SnipeSharp.Exceptions.ApiErrorException: {message}", ex.ToString()); }
/// <summary> /// Convert response to stream /// </summary> /// <param name="response">response object</param> /// <returns>Stream with response</returns> public async Task <Stream> BuildSendResponse(HttpResponseMessage response) { var stream = await response.Content.ReadAsStreamAsync(); if (response.IsSuccessStatusCode) { return(stream); } var content = await StreamToStringAsync(stream); ApiErrorException apiError = null; try { apiError = JsonConvert.DeserializeObject <ApiErrorException>(content); } catch (Exception) { throw new ApiException { StatusCode = (int)response.StatusCode, Content = content }; } throw apiError; }
public async Task PostDocument_ShouldFail_WhenDocumentIsInvalid() { var doc = new { test = 123, _key = "Spaces are not allowed in keys" }; ApiErrorException ex = await Assert.ThrowsAsync <ApiErrorException>(async() => await _docClient.PostDocumentAsync("TestCollection", doc)); Assert.NotNull(ex.ApiError.ErrorMessage); }
public void ConstructWith_Message() { var ex = new ApiErrorException(TEST_MESSAGE); Assert.False(ex.IsHttpError); Assert.Null(ex.HttpStatusCode); Assert.Equal(TEST_MESSAGE, ex.Message); }
public void ConstructWith_StatusCodeAndMessage() { var ex = new ApiErrorException(HttpStatusCode.Forbidden, TEST_MESSAGE); Assert.True(ex.IsHttpError); Assert.Equal(HttpStatusCode.Forbidden, ex.HttpStatusCode); Assert.Equal(TEST_MESSAGE, ex.Message); }
public void ConstructWith_StatusCode() { var ex = new ApiErrorException(HttpStatusCode.Forbidden, null); Assert.True(ex.IsHttpError); Assert.Equal(HttpStatusCode.Forbidden, ex.HttpStatusCode); Assert.Equal(HttpStatusCode.Forbidden.ToString(), ex.Message); }
public void ConstructWith_Dictionary() { var ex = new ApiErrorException(new Dictionary <string, string> { ["Key1"] = "Value1", ["Key2"] = "Value2" }); Assert.False(ex.IsHttpError); Assert.Null(ex.HttpStatusCode); Assert.NotNull(ex.Messages); Assert.Equal(@"{""Key1"":""Value1"",""Key2"":""Value2""}", ex.Message); }
private async Task <TResponse> CreateResult <TResponse>(ExecuteRequest <TResponse> info, HttpResponseMessage request) where TResponse : class, IResponseResult { if (request.IsSuccessStatusCode) { var content = await request.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <TResponse>(content)); } var errorContent = await request.Content.ReadAsStringAsync(); throw ApiErrorException.Create(errorContent); }
/// <summary> /// Submits a request to Media Services to apply the specified Transform to a given input video. /// </summary> /// <param name="client">The Media Services client.</param> /// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param> /// <param name="accountName"> The Media Services account name.</param> /// <param name="transformName">The name of the transform.</param> /// <param name="outputAssetName">The (unique) name of the output asset that will store the result of the encoding job. </param> /// <param name="jobName">The (unique) name of the job.</param> /// <returns></returns> private static async Task <Job> SubmitJobAsync(IAzureMediaServicesClient client, string resourceGroup, string accountName, string transformName, string outputAssetName, string jobName) { // This example shows how to encode from any HTTPs source URL - a new feature of the v3 API. // Change the URL to any accessible HTTPs URL or SAS URL from Azure. JobInputHttp jobInput = new JobInputHttp(files: new[] { "https://nimbuscdn-nimbuspm.streaming.mediaservices.windows.net/2b533311-b215-4409-80af-529c3e853622/Ignite-short.mp4" }); JobOutput[] jobOutputs = { new JobOutputAsset(outputAssetName), }; // In this example, we are assuming that the job name is unique. // If you already have a job with the desired name, use the Jobs.Get method // to get the existing job. In Media Services v3, the Get method on entities returns null // if the entity doesn't exist (a case-insensitive check on the name). Job job; try { job = await client.Jobs.CreateAsync( resourceGroup, accountName, transformName, jobName, new Job { Input = jobInput, Outputs = jobOutputs, }); } catch (Exception exception) { ApiErrorException apiException = exception.GetBaseException() as ApiErrorException; if (apiException != null) { Console.Error.WriteLine( $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'."); } throw exception; } return(job); }
/// <summary> /// Create an AzureMediaServicesClient object based on the credentials supplied in appsettings.json /// </summary> /// <returns>Generic asynchronous operation that returns type IAzureMediaServicesClient</returns> private static async Task <IAzureMediaServicesClient> ClientService() { try { if (_configuration == null) { _configuration = new Configuration( new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build() ); } _serviceClientCredentials = await ClientCredentials(); return(new AzureMediaServicesClient(_configuration.ArmEndpoint, _serviceClientCredentials) { SubscriptionId = _configuration.SubscriptionId }); } catch (Exception exception) { if (exception.Source.Contains("ActiveDirectory")) { Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample."); } else if (exception.Source.Contains("Forbidden")) { Console.Error.WriteLine("TIP: Make sure the resource identified in the appsettings.json file has not been deleted or configured with CORS which would require the enclusion of special headers"); } Console.Error.WriteLine($"{ exception.Message }"); ApiErrorException apiException = exception.GetBaseException() as ApiErrorException; if (apiException != null) { Console.Error.WriteLine( $"ERROR: API call failed with error code '{ apiException.Body.Error.Code }' and message '{ apiException.Body.Error.Message }'." ); } return(null); } }
private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Helpers.WriteLine(Environment.NewLine + Environment.NewLine + " ***** Exception occurred! *****", 1); Exception ex = e.ExceptionObject as Exception; if (ex is ApiErrorException) { ApiErrorException apiEx = ex as ApiErrorException; if (apiEx.Body != null && apiEx.Body.Error != null) { Helpers.WriteLine($"API error code '{apiEx.Body.Error.Code}' and message '{apiEx.Body.Error.Message}' {Environment.NewLine}", 1); } } Helpers.WriteLine($"Message: {ex.Message}", 1); Helpers.WriteLine($"Stack trace: {ex.StackTrace}", 1); }
public static async Task Main(string[] args) { // If Visual Studio is used, let's read the .env file which should be in the root folder (same folder than the solution .sln file). // Same code will work in VS Code, but VS Code uses also launch.json to get the .env file. // You can create this ".env" file by saving the "sample.env" file as ".env" file and fill it with the right values. try { DotEnv.Load(".env"); } catch { } ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() // parses the values from the optional .env file at the solution root .Build()); try { await RunAsync(config); } catch (Exception exception) { if (exception.Source.Contains("ActiveDirectory")) { Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample."); } Console.Error.WriteLine($"{exception.Message}"); ApiErrorException apiException = exception.GetBaseException() as ApiErrorException; if (apiException != null) { Console.Error.WriteLine( $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'."); } } Console.WriteLine("Press Enter to exit the sample."); Console.ReadLine(); }
public async Task <IActionResult> DownloadFileEncryptAndUploadMedia([FromForm] DownloadEncryptFileCommand command) { try { var currentDirectory = System.IO.Directory.GetCurrentDirectory(); ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(currentDirectory + "/appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build()); try { uploadMusicService.CopyFileEncryptAndUploadToAzureBlob(command.blobName, command.password, ResourceTypes.Video); var urlStream = await uploadEncodeAndStreamFiles.RunAsync(config, command.blobName); return(Ok(new { url = urlStream })); } catch (Exception exception) { if (exception.Source.Contains("ActiveDirectory")) { Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample."); } Console.Error.WriteLine($"{exception.Message}"); ApiErrorException apiException = exception.GetBaseException() as ApiErrorException; if (apiException != null) { Console.Error.WriteLine( $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'."); } return(StatusCode(StatusCodes.Status500InternalServerError, apiException)); } //return StatusCode(StatusCodes.Status200OK); } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, ex)); } }
/// <summary> /// Helper method to return the error message of an ApiErrorException /// </summary> /// <param name="ex">the ApiErrorException for which to return the message</param> /// <returns> /// Error message of an ApiErrorException /// </returns> public static string ReturnApiErrorMessage(ApiErrorException ex) { string errorContent = null; if (ex.Body != null && ex.Body.Error != null) { errorContent = ex.Body.Error.Message; } if (errorContent == null) { ODataError error = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <ODataError>(ex.Response.Content); if (error != null) { errorContent = error.Message; } } return(errorContent); }
public static async void Run([BlobTrigger("samples-workitems/{name}")] Stream myBlob, string name, ILogger log) { // Function がキックされていることをチェックするためのログ出力 log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes"); // 入力された Blob ファイル名をこの先でも使うので変数に保存 InputMP4FileName = name; // appsettings.json に AMS へログインするための情報が入っている // ここのフォーマットは az コマンドで出力されてくる json そのままコピー&ペースト // az ams account sp create --account-name amsaccount --resource-group amsResourceGroup ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build()); try { await RunAsync(config, myBlob); } catch (Exception exception) { if (exception.Source.Contains("ActiveDirectory")) { Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample."); } Console.Error.WriteLine($"{exception.Message}"); ApiErrorException apiException = exception.GetBaseException() as ApiErrorException; if (apiException != null) { Console.Error.WriteLine( $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'."); } } }
public async Task AnalyseMediaAssets() { try { using (IAzureMediaServicesClient client = await CreateMediaServicesClientAsync()) { WriteLine("connected"); var assets = Directory.EnumerateFiles($"{mediaFolder}", "*.mp4", SearchOption.TopDirectoryOnly) .Where(f => !Directory.Exists($"{mediaOutputFolder}{Path.DirectorySeparatorChar}{Path.GetFileNameWithoutExtension(f)}")); foreach (var asset in assets) { await IndexMediaAsset(client, asset); } WriteLine("Done."); WriteLine("Press Enter to Continue"); ReadLine(); } } catch (Exception exception) { if (exception.Source.Contains("ActiveDirectory")) { Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample."); } Error.WriteLine($"{exception.Message}"); ApiErrorException apiException = exception.GetBaseException() as ApiErrorException; if (apiException != null) { Error.WriteLine( $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'."); } } }
/// <param name='repository'> /// </param> /// <param name='branch'> /// </param> /// <param name='channelId'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ApiErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <IList <DefaultChannel> > > ListWithHttpMessagesAsync(string repository = default(string), string branch = default(string), int?channelId = default(int?), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { string apiVersion = "2018-07-16"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("repository", repository); tracingParameters.Add("branch", branch); tracingParameters.Add("channelId", channelId); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/default-channels").ToString(); List <string> _queryParameters = new List <string>(); if (repository != null) { _queryParameters.Add(string.Format("repository={0}", System.Uri.EscapeDataString(repository))); } if (branch != null) { _queryParameters.Add(string.Format("branch={0}", System.Uri.EscapeDataString(branch))); } if (channelId != null) { _queryParameters.Add(string.Format("channelId={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(channelId, Client.SerializationSettings).Trim('"')))); } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // 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) { var ex = new ApiErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ApiError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ApiError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <IList <DefaultChannel> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <IList <DefaultChannel> >(_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); }
/// <param name='data'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ApiErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse> CreateWithHttpMessagesAsync(PostData data = default(PostData), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (data != null) { data.Validate(); } string apiVersion = "2018-07-16"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("data", data); tracingParameters.Add("apiVersion", apiVersion); 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("/") ? "" : "/")), "api/default-channels").ToString(); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + 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 (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 (data != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(data, 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 != 201) { var ex = new ApiErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ApiError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ApiError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Helper method to throw the appropriate exception based on the error returned by the SDK /// </summary> /// <param name="ex"></param> /// <param name="customMessages"></param> protected void ThrowAppropriateException(ApiErrorException ex, List <string> customObjects = null) { string message = "DMS API Error " + ReturnApiErrorMessage(ex); HttpStatusCode statusCode = ex.Response.StatusCode; switch (statusCode) { case HttpStatusCode.BadRequest: ThrowTerminatingError( new ErrorRecord( new BadRequestException(message, ex), "Bad Request", ErrorCategory.InvalidData, null)); break; case HttpStatusCode.Forbidden: ThrowTerminatingError( new ErrorRecord( ex, "The server refuses to fulfill this request.", ErrorCategory.InvalidOperation, null)); break; case HttpStatusCode.NotFound: ThrowTerminatingError( new ErrorRecord( new NotFoundException(message, ex), "Not found", ErrorCategory.ObjectNotFound, null)); break; //TODO: not sure what this looks like case HttpStatusCode.ServiceUnavailable: ThrowTerminatingError( new ErrorRecord( ex, "The service or resource is not available.", ErrorCategory.ResourceUnavailable, null)); break; //TODO: not sure what this looks like case HttpStatusCode.Unauthorized: ThrowTerminatingError( new ErrorRecord( ex, "You are not authorized to perform this operation.", ErrorCategory.PermissionDenied, null)); break; case HttpStatusCode.PreconditionFailed: ThrowTerminatingError( new ErrorRecord( new PreConditionFailedException(message, ex), "PreConditionFailed", ErrorCategory.InvalidOperation, null)); break; default: ThrowTerminatingError( new ErrorRecord( new DataMigrationServiceExceptionBase(message, ex), "Error", ErrorCategory.InvalidOperation, null)); break; } }