< Summary

Class:Microsoft.Azure.CognitiveServices.FormRecognizer.FormRecognizerClientExtensions
Assembly:Microsoft.Azure.CognitiveServices.Vision.FormRecognizer
File(s):C:\Git\azure-sdk-for-net\sdk\cognitiveservices\FormRecognizer\src\Customizations\FormRecognizerClient2.cs
C:\Git\azure-sdk-for-net\sdk\cognitiveservices\FormRecognizer\src\Generated\FormRecognizerClientExtensions.cs
Covered lines:0
Uncovered lines:29
Coverable lines:29
Total lines:444
Line coverage:0% (0 of 29)
Covered branches:0
Total branches:0

Metrics

MethodCyclomatic complexity Line coverage Branch coverage
AnalyzeWithCustomModelAsync()-0%100%
TrainCustomModelAsync()-0%100%
GetExtractedKeysAsync()-0%100%
GetCustomModelsAsync()-0%100%
GetCustomModelAsync()-0%100%
DeleteCustomModelAsync()-0%100%
AnalyzeWithCustomModelAsync()-0%100%
BatchReadReceiptAsync()-0%100%
GetReadReceiptResultAsync()-0%100%
BatchReadReceiptInStreamAsync()-0%100%

File(s)

C:\Git\azure-sdk-for-net\sdk\cognitiveservices\FormRecognizer\src\Customizations\FormRecognizerClient2.cs

#LineLine coverage
 1namespace Microsoft.Azure.CognitiveServices.FormRecognizer
 2{
 3    using Microsoft.Rest;
 4    using Microsoft.Rest.Serialization;
 5    using Models;
 6    using Newtonsoft.Json;
 7    using System.Collections;
 8    using System.Collections.Generic;
 9    using System.IO;
 10    using System.Net;
 11    using System.Net.Http;
 12    using System.Net.Http.Headers;
 13    using System.Threading;
 14    using System.Threading.Tasks;
 15
 16    public partial interface IFormRecognizerClient : System.IDisposable
 17    {
 18        Task<HttpOperationResponse<AnalyzeResult>> AnalyzeWithCustomModelWithHttpMessagesAsync2(System.Guid id, Stream f
 19    }
 20
 21    public static partial class FormRecognizerClientExtensions
 22    {
 23        public static async Task<AnalyzeResult> AnalyzeWithCustomModelAsync(this IFormRecognizerClient operations, Syste
 24        {
 025            using (var _result = await operations.AnalyzeWithCustomModelWithHttpMessagesAsync2(id, formStream, keys, nul
 26            {
 027                return _result.Body;
 28            }
 029        }
 30    }
 31
 32    public partial class FormRecognizerClient : ServiceClient<FormRecognizerClient>, IFormRecognizerClient
 33    {
 34        partial void CustomInitialize()
 35        {
 36            // Disable metadata property handling when de/serializing models so we can properly support "$ref" in Elemen
 37            SerializationSettings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
 38            DeserializationSettings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
 39        }
 40
 41        public async Task<HttpOperationResponse<AnalyzeResult>> AnalyzeWithCustomModelWithHttpMessagesAsync2(System.Guid
 42        {
 43            if (Endpoint == null)
 44            {
 45                throw new ValidationException(ValidationRules.CannotBeNull, "this.Endpoint");
 46            }
 47            if (formStream == null)
 48            {
 49                throw new ValidationException(ValidationRules.CannotBeNull, "formStream");
 50            }
 51            // Tracing
 52            bool _shouldTrace = ServiceClientTracing.IsEnabled;
 53            string _invocationId = null;
 54            if (_shouldTrace)
 55            {
 56                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
 57                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
 58                tracingParameters.Add("id", id);
 59                tracingParameters.Add("keys", keys);
 60                tracingParameters.Add("formStream", formStream);
 61                tracingParameters.Add("cancellationToken", cancellationToken);
 62                ServiceClientTracing.Enter(_invocationId, this, "AnalyzeWithCustomModel", tracingParameters);
 63            }
 64            // Construct URL
 65            var _baseUrl = BaseUri;
 66            var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "custom/models/{id}/analyze";
 67            _url = _url.Replace("{Endpoint}", Endpoint);
 68            _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSet
 69            List<string> _queryParameters = new List<string>();
 70            if (keys != null)
 71            {
 72                _queryParameters.Add(string.Format("keys={0}", System.Uri.EscapeDataString(string.Join(",", keys))));
 73            }
 74            if (_queryParameters.Count > 0)
 75            {
 76                _url += "?" + string.Join("&", _queryParameters);
 77            }
 78            // Create HTTP transport objects
 79            var _httpRequest = new HttpRequestMessage();
 80            HttpResponseMessage _httpResponse = null;
 81            _httpRequest.Method = new HttpMethod("POST");
 82            _httpRequest.RequestUri = new System.Uri(_url);
 83            // Set Headers
 84
 85
 86            if (customHeaders != null)
 87            {
 88                foreach (var _header in customHeaders)
 89                {
 90                    if (_httpRequest.Headers.Contains(_header.Key))
 91                    {
 92                        _httpRequest.Headers.Remove(_header.Key);
 93                    }
 94                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
 95                }
 96            }
 97
 98            // Serialize Request
 99            string _requestContent = null;
 100            MultipartFormDataContent _multiPartContent = new MultipartFormDataContent();
 101            if (formStream != null)
 102            {
 103                StreamContent _formStream = new StreamContent(formStream);
 104                FileStream _formStreamAsFileStream = formStream as FileStream;
 105                if (_formStreamAsFileStream != null)
 106                {
 107                    _formStream.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
 108                    {
 109                        Name = "form_stream",
 110                        FileName = _formStreamAsFileStream.Name
 111                    };
 112                    _formStream.Headers.Add("Content-Type", contentType);
 113                }
 114                _multiPartContent.Add(_formStream, "form_stream");
 115            }
 116            _httpRequest.Content = _multiPartContent;
 117            // Set Credentials
 118            if (Credentials != null)
 119            {
 120                cancellationToken.ThrowIfCancellationRequested();
 121                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 122            }
 123            // Send Request
 124            if (_shouldTrace)
 125            {
 126                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
 127            }
 128            cancellationToken.ThrowIfCancellationRequested();
 129
 130            _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
 131            if (_shouldTrace)
 132            {
 133                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
 134            }
 135            HttpStatusCode _statusCode = _httpResponse.StatusCode;
 136            cancellationToken.ThrowIfCancellationRequested();
 137            string _responseContent = null;
 138            if ((int)_statusCode != 200)
 139            {
 140                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _st
 141                try
 142                {
 143                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 144                    ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Deseri
 145                    if (_errorBody != null)
 146                    {
 147                        ex.Body = _errorBody;
 148                    }
 149                }
 150                catch (JsonException)
 151                {
 152                    // Ignore the exception
 153                }
 154                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
 155                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
 156                if (_shouldTrace)
 157                {
 158                    ServiceClientTracing.Error(_invocationId, ex);
 159                }
 160                _httpRequest.Dispose();
 161                if (_httpResponse != null)
 162                {
 163                    _httpResponse.Dispose();
 164                }
 165                throw ex;
 166            }
 167            // Create Result
 168            var _result = new HttpOperationResponse<AnalyzeResult>();
 169            _result.Request = _httpRequest;
 170            _result.Response = _httpResponse;
 171            // Deserialize Response
 172            if ((int)_statusCode == 200)
 173            {
 174                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
 175                try
 176                {
 177                    _result.Body = SafeJsonConvert.DeserializeObject<AnalyzeResult>(_responseContent, DeserializationSet
 178                }
 179                catch (JsonException ex)
 180                {
 181                    _httpRequest.Dispose();
 182                    if (_httpResponse != null)
 183                    {
 184                        _httpResponse.Dispose();
 185                    }
 186                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
 187                }
 188            }
 189            if (_shouldTrace)
 190            {
 191                ServiceClientTracing.Exit(_invocationId, _result);
 192            }
 193            return _result;
 194        }
 195    }
 196}

C:\Git\azure-sdk-for-net\sdk\cognitiveservices\FormRecognizer\src\Generated\FormRecognizerClientExtensions.cs

#LineLine coverage
 1// <auto-generated>
 2// Copyright (c) Microsoft Corporation. All rights reserved.
 3// Licensed under the MIT License. See License.txt in the project root for
 4// license information.
 5//
 6// Code generated by Microsoft (R) AutoRest Code Generator.
 7// Changes may cause incorrect behavior and will be lost if the code is
 8// regenerated.
 9// </auto-generated>
 10
 11namespace Microsoft.Azure.CognitiveServices.FormRecognizer
 12{
 13    using Models;
 14    using System.Collections;
 15    using System.Collections.Generic;
 16    using System.IO;
 17    using System.Threading;
 18    using System.Threading.Tasks;
 19
 20    /// <summary>
 21    /// Extension methods for FormRecognizerClient.
 22    /// </summary>
 23    public static partial class FormRecognizerClientExtensions
 24    {
 25            /// <summary>
 26            /// Train Model
 27            /// </summary>
 28            /// <remarks>
 29            /// Create and train a custom model. The train request must include a source
 30            /// parameter that is either an externally accessible Azure Storage blob
 31            /// container Uri (preferably a Shared Access Signature Uri) or valid path to a
 32            /// data folder in a locally mounted drive. When local paths are specified,
 33            /// they must follow the Linux/Unix path format and be an absolute path rooted
 34            /// to the input mount configuration
 35            /// setting value e.g., if '{Mounts:Input}' configuration setting value is
 36            /// '/input' then a valid source path would be '/input/contosodataset'. All
 37            /// data to be trained is expected to be directly under the source folder.
 38            /// Subfolders are not supported. Models are trained using documents that are
 39            /// of the following content type - 'application/pdf', 'image/jpeg' and
 40            /// 'image/png'."
 41            /// Other type of content is ignored.
 42            /// </remarks>
 43            /// <param name='operations'>
 44            /// The operations group for this extension method.
 45            /// </param>
 46            /// <param name='trainRequest'>
 47            /// Request object for training.
 48            /// </param>
 49            /// <param name='cancellationToken'>
 50            /// The cancellation token.
 51            /// </param>
 52            public static async Task<TrainResult> TrainCustomModelAsync(this IFormRecognizerClient operations, TrainRequ
 53            {
 054                using (var _result = await operations.TrainCustomModelWithHttpMessagesAsync(trainRequest, null, cancella
 55                {
 056                    return _result.Body;
 57                }
 058            }
 59
 60            /// <summary>
 61            /// Get Keys
 62            /// </summary>
 63            /// <remarks>
 64            /// Retrieve the keys that were
 65            /// extracted during the training of the specified model.
 66            /// </remarks>
 67            /// <param name='operations'>
 68            /// The operations group for this extension method.
 69            /// </param>
 70            /// <param name='id'>
 71            /// Model identifier.
 72            /// </param>
 73            /// <param name='cancellationToken'>
 74            /// The cancellation token.
 75            /// </param>
 76            public static async Task<KeysResult> GetExtractedKeysAsync(this IFormRecognizerClient operations, System.Gui
 77            {
 078                using (var _result = await operations.GetExtractedKeysWithHttpMessagesAsync(id, null, cancellationToken)
 79                {
 080                    return _result.Body;
 81                }
 082            }
 83
 84            /// <summary>
 85            /// Get Models
 86            /// </summary>
 87            /// <remarks>
 88            /// Get information about all trained custom models
 89            /// </remarks>
 90            /// <param name='operations'>
 91            /// The operations group for this extension method.
 92            /// </param>
 93            /// <param name='cancellationToken'>
 94            /// The cancellation token.
 95            /// </param>
 96            public static async Task<ModelsResult> GetCustomModelsAsync(this IFormRecognizerClient operations, Cancellat
 97            {
 098                using (var _result = await operations.GetCustomModelsWithHttpMessagesAsync(null, cancellationToken).Conf
 99                {
 0100                    return _result.Body;
 101                }
 0102            }
 103
 104            /// <summary>
 105            /// Get Model
 106            /// </summary>
 107            /// <remarks>
 108            /// Get information about a model.
 109            /// </remarks>
 110            /// <param name='operations'>
 111            /// The operations group for this extension method.
 112            /// </param>
 113            /// <param name='id'>
 114            /// Model identifier.
 115            /// </param>
 116            /// <param name='cancellationToken'>
 117            /// The cancellation token.
 118            /// </param>
 119            public static async Task<ModelResult> GetCustomModelAsync(this IFormRecognizerClient operations, System.Guid
 120            {
 0121                using (var _result = await operations.GetCustomModelWithHttpMessagesAsync(id, null, cancellationToken).C
 122                {
 0123                    return _result.Body;
 124                }
 0125            }
 126
 127            /// <summary>
 128            /// Delete Model
 129            /// </summary>
 130            /// <remarks>
 131            /// Delete model artifacts.
 132            /// </remarks>
 133            /// <param name='operations'>
 134            /// The operations group for this extension method.
 135            /// </param>
 136            /// <param name='id'>
 137            /// The identifier of the model to delete.
 138            /// </param>
 139            /// <param name='cancellationToken'>
 140            /// The cancellation token.
 141            /// </param>
 142            public static async Task DeleteCustomModelAsync(this IFormRecognizerClient operations, System.Guid id, Cance
 143            {
 0144                (await operations.DeleteCustomModelWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(fal
 0145            }
 146
 147            /// <summary>
 148            /// Analyze Form
 149            /// </summary>
 150            /// <remarks>
 151            /// Extract key-value pairs from a given document. The input document must be
 152            /// of one of the supported content types - 'application/pdf', 'image/jpeg' or
 153            /// 'image/png'. A success response is returned in JSON.
 154            /// </remarks>
 155            /// <param name='operations'>
 156            /// The operations group for this extension method.
 157            /// </param>
 158            /// <param name='id'>
 159            /// Model Identifier to analyze the document with.
 160            /// </param>
 161            /// <param name='formStream'>
 162            /// A pdf document or image (jpg,png) file to analyze.
 163            /// </param>
 164            /// <param name='keys'>
 165            /// An optional list of known keys to extract the values for.
 166            /// </param>
 167            /// <param name='cancellationToken'>
 168            /// The cancellation token.
 169            /// </param>
 170            public static async Task<AnalyzeResult> AnalyzeWithCustomModelAsync(this IFormRecognizerClient operations, S
 171            {
 0172                using (var _result = await operations.AnalyzeWithCustomModelWithHttpMessagesAsync(id, formStream, keys, 
 173                {
 0174                    return _result.Body;
 175                }
 0176            }
 177
 178            /// <summary>
 179            /// Batch Read Receipt operation. The response contains a field called
 180            /// 'Operation-Location', which contains the URL that you must use for your
 181            /// 'Get Read Receipt Result' operation.
 182            /// </summary>
 183            /// <param name='operations'>
 184            /// The operations group for this extension method.
 185            /// </param>
 186            /// <param name='url'>
 187            /// Publicly reachable URL of an image.
 188            /// </param>
 189            /// <param name='cancellationToken'>
 190            /// The cancellation token.
 191            /// </param>
 192            public static async Task<BatchReadReceiptHeaders> BatchReadReceiptAsync(this IFormRecognizerClient operation
 193            {
 0194                using (var _result = await operations.BatchReadReceiptWithHttpMessagesAsync(url, null, cancellationToken
 195                {
 0196                    return _result.Headers;
 197                }
 0198            }
 199
 200            /// <summary>
 201            /// This interface is used for getting the analysis results of a 'Batch Read
 202            /// Receipt' operation. The URL to this interface should be retrieved from the
 203            /// 'Operation-Location' field returned from the 'Batch Read Receipt'
 204            /// operation.
 205            /// </summary>
 206            /// <param name='operations'>
 207            /// The operations group for this extension method.
 208            /// </param>
 209            /// <param name='operationId'>
 210            /// Id of read operation returned in the response of a 'Batch Read Receipt'
 211            /// operation.
 212            /// </param>
 213            /// <param name='cancellationToken'>
 214            /// The cancellation token.
 215            /// </param>
 216            public static async Task<ReadReceiptResult> GetReadReceiptResultAsync(this IFormRecognizerClient operations,
 217            {
 0218                using (var _result = await operations.GetReadReceiptResultWithHttpMessagesAsync(operationId, null, cance
 219                {
 0220                    return _result.Body;
 221                }
 0222            }
 223
 224            /// <summary>
 225            /// Read Receipt operation. When you use the 'Batch Read Receipt' interface,
 226            /// the response contains a field called 'Operation-Location'. The
 227            /// 'Operation-Location' field contains the URL that you must use for your 'Get
 228            /// Read Receipt Result' operation.
 229            /// </summary>
 230            /// <param name='operations'>
 231            /// The operations group for this extension method.
 232            /// </param>
 233            /// <param name='image'>
 234            /// An image stream.
 235            /// </param>
 236            /// <param name='cancellationToken'>
 237            /// The cancellation token.
 238            /// </param>
 239            public static async Task<BatchReadReceiptInStreamHeaders> BatchReadReceiptInStreamAsync(this IFormRecognizer
 240            {
 0241                using (var _result = await operations.BatchReadReceiptInStreamWithHttpMessagesAsync(image, null, cancell
 242                {
 0243                    return _result.Headers;
 244                }
 0245            }
 246
 247    }
 248}