Ejemplo n.º 1
0
 /// <summary>
 /// Imports an application to LUIS, the application's structure is included in
 /// the request body.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='azureRegion'>
 /// Supported Azure regions for Cognitive Services endpoints. Possible values
 /// include: 'westus', 'westeurope', 'southeastasia', 'eastus2',
 /// 'westcentralus', 'westus2', 'eastus', 'southcentralus', 'northeurope',
 /// 'eastasia', 'australiaeast', 'brazilsouth', 'virginia'
 /// </param>
 /// <param name='azureCloud'>
 /// Supported Azure Clouds for Cognitive Services endpoints. Possible values
 /// include: 'com', 'us'
 /// </param>
 /// <param name='luisApp'>
 /// A LUIS application structure.
 /// </param>
 /// <param name='appName'>
 /// The application name to create. If not specified, the application name will
 /// be read from the imported object. If the application name already exists,
 /// an error is returned.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <System.Guid> ImportAsync(this IApps operations, AzureRegions azureRegion, AzureClouds azureCloud, LuisApp luisApp, string appName = default(string), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.ImportWithHttpMessagesAsync(azureRegion, azureCloud, luisApp, appName, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Ejemplo n.º 2
0
 /// <summary>
 /// Creates a new LUIS app.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='azureRegion'>
 /// Supported Azure regions for Cognitive Services endpoints. Possible values
 /// include: 'westus', 'westeurope', 'southeastasia', 'eastus2',
 /// 'westcentralus', 'westus2', 'eastus', 'southcentralus', 'northeurope',
 /// 'eastasia', 'australiaeast', 'brazilsouth', 'virginia'
 /// </param>
 /// <param name='azureCloud'>
 /// Supported Azure Clouds for Cognitive Services endpoints. Possible values
 /// include: 'com', 'us'
 /// </param>
 /// <param name='applicationCreateObject'>
 /// An application containing Name, Description (optional), Culture, Usage
 /// Scenario (optional), Domain (optional) and initial version ID (optional) of
 /// the application. Default value for the version ID is "0.1". Note: the
 /// culture cannot be changed after the app is created.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <System.Guid> AddAsync(this IApps operations, AzureRegions azureRegion, AzureClouds azureCloud, ApplicationCreateObject applicationCreateObject, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.AddWithHttpMessagesAsync(azureRegion, azureCloud, applicationCreateObject, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Exports a LUIS application to JSON format.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='azureRegion'>
 /// Supported Azure regions for Cognitive Services endpoints. Possible values
 /// include: 'westus', 'westeurope', 'southeastasia', 'eastus2',
 /// 'westcentralus', 'westus2', 'eastus', 'southcentralus', 'northeurope',
 /// 'eastasia', 'australiaeast', 'brazilsouth', 'virginia'
 /// </param>
 /// <param name='azureCloud'>
 /// Supported Azure Clouds for Cognitive Services endpoints. Possible values
 /// include: 'com', 'us'
 /// </param>
 /// <param name='appId'>
 /// The application ID.
 /// </param>
 /// <param name='versionId'>
 /// The version ID.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <LuisApp> ExportAsync(this IVersions operations, AzureRegions azureRegion, AzureClouds azureCloud, System.Guid appId, string versionId, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.ExportWithHttpMessagesAsync(azureRegion, azureCloud, appId, versionId, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Creates a new version from the selected version.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='azureRegion'>
 /// Supported Azure regions for Cognitive Services endpoints. Possible values
 /// include: 'westus', 'westeurope', 'southeastasia', 'eastus2',
 /// 'westcentralus', 'westus2', 'eastus', 'southcentralus', 'northeurope',
 /// 'eastasia', 'australiaeast', 'brazilsouth', 'virginia'
 /// </param>
 /// <param name='azureCloud'>
 /// Supported Azure Clouds for Cognitive Services endpoints. Possible values
 /// include: 'com', 'us'
 /// </param>
 /// <param name='appId'>
 /// The application ID.
 /// </param>
 /// <param name='versionId'>
 /// The version ID.
 /// </param>
 /// <param name='versionCloneObject'>
 /// A model containing the new version ID.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <string> CloneAsync(this IVersions operations, AzureRegions azureRegion, AzureClouds azureCloud, System.Guid appId, string versionId, TaskUpdateObject versionCloneObject, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CloneWithHttpMessagesAsync(azureRegion, azureCloud, appId, versionId, versionCloneObject, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Ejemplo n.º 5
0
        public FaceRecognizer(string subscriptionKey, AzureRegions region, string personGroupId)
        {
            this.faceAPI             = new FaceAPI(new ApiKeyServiceClientCredentials(subscriptionKey));
            this.faceAPI.AzureRegion = region;

            this.personGroupId = personGroupId;
        }
Ejemplo n.º 6
0
        static void ReadConfiguration()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");

            Configuration = builder.Build();

            var region = Configuration["LUIS.Region"];

            if (string.IsNullOrWhiteSpace(region))
            {
                throw new ArgumentException("Missing \"LUIS.Region\" in appsettings.json");
            }

            AzureRegion     = (AzureRegions)Enum.Parse(typeof(AzureRegions), region, true);
            SubscriptionKey = Configuration["LUIS.SubscriptionKey"];
            ApplicationId   = Configuration["LUIS.ApplicationId"];

            if (string.IsNullOrWhiteSpace(SubscriptionKey))
            {
                throw new ArgumentException("Missing \"LUIS.SubscriptionKey\" in appsettings.json");
            }

            if (string.IsNullOrWhiteSpace(ApplicationId))
            {
                throw new ArgumentException("Missing \"LUIS.ApplicationId\" in appsettings.json");
            }
        }
Ejemplo n.º 7
0
 public ComputerVisionMain(string key, AzureRegions region)
 {
     _VisionKey          = key;
     _Region             = region;
     _Client             = new ComputerVisionAPI(new ApiKeyServiceClientCredentials(_VisionKey));
     _Client.AzureRegion = _Region;
 }
Ejemplo n.º 8
0
        public static async Task <string> GetImageDetailsAsync(string key, AzureRegions region, string imageUrl)
        {
            StringBuilder      imageDetails = new StringBuilder();
            IComputerVisionAPI client       = new ComputerVisionAPI(new ApiKeyServiceClientCredentials(key));

            client.AzureRegion = region;
            var requiredFeatures = new List <VisualFeatureTypes> {
                VisualFeatureTypes.Adult,
                VisualFeatureTypes.Categories,
                VisualFeatureTypes.Color,
                VisualFeatureTypes.ImageType,
            };

            ImageAnalysis imageAnalysis = await client.AnalyzeImageAsync(imageUrl, requiredFeatures);

            imageDetails.AppendLine($"Dominant Background Color: {imageAnalysis.Color.DominantColorBackground} <br />");
            imageDetails.AppendLine($"Dominant Forground Color: {imageAnalysis.Color.DominantColorForeground} <br />");
            imageDetails.AppendLine($"Is Black & White: {imageAnalysis.Color.IsBWImg} <br />");

            string isLineDraw = imageAnalysis.ImageType.LineDrawingType == 1 ? "Yes" : "No";

            imageDetails.AppendLine($"Is Line drawing: {isLineDraw} <br />");
            imageDetails.AppendLine($"Is Adult content: {imageAnalysis.Adult.IsAdultContent} <br />");

            List <string> categoryList = new List <string>();

            foreach (var category in imageAnalysis.Categories)
            {
                categoryList.Add(category.Name);
            }
            imageDetails.AppendLine($"Categories: {string.Join(", ", categoryList)}");

            return(imageDetails.ToString());
        }
Ejemplo n.º 9
0
 public TextAnalysisMain(string textkey, AzureRegions region)
 {
     _TextKey = textkey;
     _Region  = region;
     _Client  = new TextAnalyticsAPI {
         SubscriptionKey = _TextKey, AzureRegion = _Region
     };
     Results = new TextAnalysisResults();
 }
Ejemplo n.º 10
0
        public static async Task <string> GetImageDescriptionAsync(string key, AzureRegions region, string imageUrl)
        {
            IComputerVisionAPI client = new ComputerVisionAPI(new ApiKeyServiceClientCredentials(key));

            client.AzureRegion = region;

            var result = await client.DescribeImageAsync(imageUrl);

            return(result.Captions[0].Text);
        }
Ejemplo n.º 11
0
        public TextAnalyticsWrapper(string subscriptionKey, AzureRegions region)
        {
            if (string.IsNullOrWhiteSpace(subscriptionKey))
            {
                throw new ArgumentNullException(nameof(subscriptionKey));
            }

            _client             = _client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials(subscriptionKey));
            _client.AzureRegion = region;
        }
Ejemplo n.º 12
0
 public SentimentAnalyzer(ILogger logger,
                          string azureCognitiveServicesSubscriptionKey,
                          AzureRegions azureCognitiveServicesRegion) : base(logger,
                                                                            new AzureSentimentAnalyzer(
                                                                                logger,
                                                                                azureCognitiveServicesSubscriptionKey,
                                                                                azureCognitiveServicesRegion),
                                                                            new RedditSearch.RedditSearch(logger))
 {
 }
Ejemplo n.º 13
0
        internal static string ToSerializedValue(this AzureRegions value)
        {
            switch (value)
            {
            case AzureRegions.Westus:
                return("westus");

            case AzureRegions.Westeurope:
                return("westeurope");
            }
            return(null);
        }
Ejemplo n.º 14
0
        public static async Task <double?> obtainSentiment(string key, AzureRegions region, string text)
        {
            TextAnalyticsAPI client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials());

            client.AzureRegion = region;

            MultiLanguageBatchInput input = new MultiLanguageBatchInput(new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("en", "1", text)
            });
            var result = await client.SentimentAsync(input);

            var score = result.Documents.FirstOrDefault().Score;

            //var tostring = Convert.ToString(score);
            return(score);
        }
        public static async Task <string> ObtainSentiment(string key, AzureRegions region, string text)
        {
            ITextAnalyticsAPI client = new TextAnalyticsAPI();

            client.SubscriptionKey = key;
            client.AzureRegion     = region;

            MultiLanguageBatchInput input = new MultiLanguageBatchInput(new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("en", "1", text)
            });
            var result = await client.SentimentAsync(input);

            var score = result.Documents.FirstOrDefault()?.Score;

            return($"Score for {text} is **{score}**");
        }
Ejemplo n.º 16
0
        internal static string ToSerializedValue(this AzureRegions value)
        {
            switch (value)
            {
            case AzureRegions.Westus:
                return("westus");

            case AzureRegions.Westeurope:
                return("westeurope");

            case AzureRegions.Southeastasia:
                return("southeastasia");

            case AzureRegions.Eastus2:
                return("eastus2");

            case AzureRegions.Westcentralus:
                return("westcentralus");

            case AzureRegions.Westus2:
                return("westus2");

            case AzureRegions.Eastus:
                return("eastus");

            case AzureRegions.Southcentralus:
                return("southcentralus");

            case AzureRegions.Northeurope:
                return("northeurope");

            case AzureRegions.Eastasia:
                return("eastasia");

            case AzureRegions.Australiaeast:
                return("australiaeast");

            case AzureRegions.Brazilsouth:
                return("brazilsouth");

            case AzureRegions.Virginia:
                return("virginia");
            }
            return(null);
        }
Ejemplo n.º 17
0
        public static async Task <string> GetTagsForImageAsync(string key, AzureRegions region, string imageUrl)
        {
            StringBuilder      tagsDetails = new StringBuilder();
            IComputerVisionAPI client      = new ComputerVisionAPI(new ApiKeyServiceClientCredentials(key));

            client.AzureRegion = region;
            var requiredFeatures = new List <VisualFeatureTypes> {
                VisualFeatureTypes.Tags
            };

            ImageAnalysis imageAnalysis = await client.AnalyzeImageAsync(imageUrl, requiredFeatures);

            foreach (var tag in imageAnalysis.Tags)
            {
                tagsDetails.AppendLine($"{tag.Name} ({tag.Confidence}), ");
            }
            return(tagsDetails.ToString().TrimEnd(", ".ToCharArray()));
        }
Ejemplo n.º 18
0
        public static async Task <string> GetFaceWithInImageAsync(string key, AzureRegions region, string imageUrl)
        {
            IComputerVisionAPI client = new ComputerVisionAPI(new ApiKeyServiceClientCredentials(key));

            client.AzureRegion = region;
            var requiredFeatures = new List <VisualFeatureTypes> {
                VisualFeatureTypes.Faces
            };

            ImageAnalysis imageAnalysis = await client.AnalyzeImageAsync(imageUrl, requiredFeatures);

            StringBuilder faceDetails = new StringBuilder();

            faceDetails.Append($"Found total **{imageAnalysis.Faces.Count}** faces in image.");

            foreach (var face in imageAnalysis.Faces)
            {
                faceDetails.Append($"{Environment.NewLine} - Gender: {face.Gender} | Age: {face.Age}");
            }
            return(faceDetails.ToString());
        }
Ejemplo n.º 19
0
        public static async Task <string> obtainLanguage(string key, AzureRegions region, string text)
        {
            TextAnalyticsAPI client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials());

            client.AzureRegion = region;

            BatchInput input = new BatchInput(new List <Input>()
            {
                new Input("1", text)
            });
            var result = await client.DetectLanguageAsync(input);

            var languages = result.Documents.FirstOrDefault()?.DetectedLanguages;

            if (languages.Count > 0)
            {
                return("Language: " + string.Join(", ", languages.Select(x => x.Name)));
            }
            else
            {
                return("Unable to detect language!");
            }
        }
Ejemplo n.º 20
0
        public static async Task <string> obtainKeyPhrase(string key, AzureRegions region, string text)
        {
            TextAnalyticsAPI client = new TextAnalyticsAPI(new ApiKeyServiceClientCredentials());

            client.AzureRegion = region;

            MultiLanguageBatchInput input = new MultiLanguageBatchInput(new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("en", "1", text)
            });
            var result = await client.KeyPhrasesAsync(input);

            var keyphrases = result.Documents.FirstOrDefault().KeyPhrases;

            if (keyphrases.Count > 0)
            {
                return("Keyphrases: " + string.Join(", ", keyphrases));
            }
            else
            {
                return("");
            }
        }
        public static async Task <string> ObtainKeyPhrase(string key, AzureRegions region, string text)
        {
            ITextAnalyticsAPI client = new TextAnalyticsAPI();

            client.SubscriptionKey = key;
            client.AzureRegion     = region;

            MultiLanguageBatchInput input = new MultiLanguageBatchInput(new List <MultiLanguageInput>()
            {
                new MultiLanguageInput("en", "1", text)
            });
            var result = await client.KeyPhrasesAsync(input);

            var keyphrases = result.Documents.FirstOrDefault()?.KeyPhrases;

            if (keyphrases.Count > 0)
            {
                return(string.Join(", ", keyphrases));
            }
            else
            {
                return("Not found any Keyphrases!");
            }
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Gets the training status of all models (intents and entities) for the
 /// specified LUIS app. You must call the train API to train the LUIS app
 /// before you call this API to get training status. "appID" specifies the LUIS
 /// app ID. "versionId" specifies the version number of the LUIS app. For
 /// example, "0.1".
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='azureRegion'>
 /// Supported Azure regions for Cognitive Services endpoints. Possible values
 /// include: 'westus', 'westeurope'
 /// </param>
 /// <param name='appId'>
 /// Format - guid. The application ID.
 /// </param>
 /// <param name='versionId'>
 /// The version ID of the task.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <IList <ModelTrainingInfo> > GetApplicationVersionTrainingStatusAsync(this ITrain operations, AzureRegions azureRegion, string appId, string versionId, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GetApplicationVersionTrainingStatusWithHttpMessagesAsync(azureRegion, appId, versionId, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// apps - Assign a LUIS Azure account to an application
 /// </summary>
 /// <remarks>
 /// Assigns an Azure account to the application.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='azureRegion'>
 /// Supported Azure regions for Cognitive Services endpoints. Possible values
 /// include: 'westus', 'westeurope', 'southeastasia', 'eastus2',
 /// 'westcentralus', 'westus2', 'eastus', 'southcentralus', 'northeurope',
 /// 'eastasia', 'australiaeast', 'brazilsouth', 'virginia'
 /// </param>
 /// <param name='azureCloud'>
 /// Supported Azure Clouds for Cognitive Services endpoints. Possible values
 /// include: 'com', 'us'
 /// </param>
 /// <param name='appId'>
 /// The application ID.
 /// </param>
 /// <param name='azureAccountInfoObject'>
 /// The Azure account information object.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <OperationStatus> AssignToAppAsync(this IAzureAccounts operations, AzureRegions azureRegion, AzureClouds azureCloud, System.Guid appId, AzureAccountInfoObject azureAccountInfoObject = default(AzureAccountInfoObject), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.AssignToAppWithHttpMessagesAsync(azureRegion, azureCloud, appId, azureAccountInfoObject, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Adds a user to the allowed list of users to access this LUIS application.
 /// Users are added using their email address.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='azureRegion'>
 /// Supported Azure regions for Cognitive Services endpoints. Possible values
 /// include: 'westus', 'westeurope', 'southeastasia', 'eastus2',
 /// 'westcentralus', 'westus2', 'eastus', 'southcentralus', 'northeurope',
 /// 'eastasia', 'australiaeast', 'brazilsouth', 'virginia'
 /// </param>
 /// <param name='azureCloud'>
 /// Supported Azure Clouds for Cognitive Services endpoints. Possible values
 /// include: 'com', 'us'
 /// </param>
 /// <param name='appId'>
 /// The application ID.
 /// </param>
 /// <param name='userToAdd'>
 /// A model containing the user's email address.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <OperationStatus> AddAsync(this IPermissions operations, AzureRegions azureRegion, AzureClouds azureCloud, System.Guid appId, UserCollaborator userToAdd, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.AddWithHttpMessagesAsync(azureRegion, azureCloud, appId, userToAdd, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Sends a training request for a version of a specified LUIS app. This POST
 /// request initiates a request asynchronously. To determine whether the
 /// training request is successful, submit a GET request to get training
 /// status. Note: The application version is not fully trained unless all the
 /// models (intents and entities) are trained successfully or are up to date.
 /// To verify training success, get the training status at least once after
 /// training is complete.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='azureRegion'>
 /// Supported Azure regions for Cognitive Services endpoints. Possible values
 /// include: 'westus', 'westeurope'
 /// </param>
 /// <param name='appId'>
 /// Format - guid. The application ID.
 /// </param>
 /// <param name='versionId'>
 /// The version ID of the task.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <EnqueueTrainingResponse> TrainApplicationVersionAsync(this ITrain operations, AzureRegions azureRegion, string appId, string versionId, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.TrainApplicationVersionWithHttpMessagesAsync(azureRegion, appId, versionId, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Gets the list of user emails that have permissions to access your
 /// application.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='azureRegion'>
 /// Supported Azure regions for Cognitive Services endpoints. Possible values
 /// include: 'westus', 'westeurope', 'southeastasia', 'eastus2',
 /// 'westcentralus', 'westus2', 'eastus', 'southcentralus', 'northeurope',
 /// 'eastasia', 'australiaeast', 'brazilsouth', 'virginia'
 /// </param>
 /// <param name='azureCloud'>
 /// Supported Azure Clouds for Cognitive Services endpoints. Possible values
 /// include: 'com', 'us'
 /// </param>
 /// <param name='appId'>
 /// The application ID.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <UserAccessList> ListAsync(this IPermissions operations, AzureRegions azureRegion, AzureClouds azureCloud, System.Guid appId, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.ListWithHttpMessagesAsync(azureRegion, azureCloud, appId, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Sends a training request for a version of a specified LUIS app. This POST
        /// request initiates a request asynchronously. To determine whether the
        /// training request is successful, submit a GET request to get training
        /// status. Note: The application version is not fully trained unless all the
        /// models (intents and entities) are trained successfully or are up to date.
        /// To verify training success, get the training status at least once after
        /// training is complete.
        /// </summary>
        /// <param name='azureRegion'>
        /// Supported Azure regions for Cognitive Services endpoints. Possible values
        /// include: 'westus', 'westeurope'
        /// </param>
        /// <param name='appId'>
        /// Format - guid. The application ID.
        /// </param>
        /// <param name='versionId'>
        /// The version ID of the task.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <EnqueueTrainingResponse> > TrainApplicationVersionWithHttpMessagesAsync(AzureRegions azureRegion, string appId, string versionId, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (appId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "appId");
            }
            if (versionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "versionId");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("azureRegion", azureRegion);
                tracingParameters.Add("appId", appId);
                tracingParameters.Add("versionId", versionId);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "TrainApplicationVersion", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri;
            var _url     = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "apps/{appId}/versions/{versionId}/train";

            _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(azureRegion, Client.SerializationSettings).Trim('"'));
            _url = _url.Replace("{appId}", System.Uri.EscapeDataString(appId));
            _url = _url.Replace("{versionId}", System.Uri.EscapeDataString(versionId));
            // 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;

            // 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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(_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 <EnqueueTrainingResponse>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 202)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <EnqueueTrainingResponse>(_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);
        }
Ejemplo n.º 28
0
 public TextAnalyticsService( string key, AzureRegions region )
 {
     var credentials = new ApiKeyServiceClientCredentials(key);
     _client = new Lazy<TextAnalyticsAPI>(() => new TextAnalyticsAPI(credentials));
     Client.AzureRegion = region;
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Removed a user to the allowed list of users to access this LUIS
 /// application.Users are removed using their email address.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='azureRegion'>
 /// Supported Azure regions for Cognitive Services endpoints. Possible values
 /// include: 'westus', 'westeurope'
 /// </param>
 /// <param name='appId'>
 /// Format - guid. The application ID.
 /// </param>
 /// <param name='body'>
 /// A JSON object containing the user's email address.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task RemoveUserFromAccessListAsync(this IPermissions operations, AzureRegions azureRegion, string appId, object body = default(object), CancellationToken cancellationToken = default(CancellationToken))
 {
     (await operations.RemoveUserFromAccessListWithHttpMessagesAsync(azureRegion, appId, body, null, cancellationToken).ConfigureAwait(false)).Dispose();
 }
 /// <summary>
 /// apps - Get LUIS Azure accounts assigned to the application
 /// </summary>
 /// <remarks>
 /// Gets the LUIS Azure accounts assigned to the application for the user using
 /// his ARM token.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='azureRegion'>
 /// Supported Azure regions for Cognitive Services endpoints. Possible values
 /// include: 'westus', 'westeurope', 'southeastasia', 'eastus2',
 /// 'westcentralus', 'westus2', 'eastus', 'southcentralus', 'northeurope',
 /// 'eastasia', 'australiaeast', 'brazilsouth', 'virginia'
 /// </param>
 /// <param name='azureCloud'>
 /// Supported Azure Clouds for Cognitive Services endpoints. Possible values
 /// include: 'com', 'us'
 /// </param>
 /// <param name='appId'>
 /// The application ID.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <IList <AzureAccountInfoObject> > GetAssignedAsync(this IAzureAccounts operations, AzureRegions azureRegion, AzureClouds azureCloud, System.Guid appId, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GetAssignedWithHttpMessagesAsync(azureRegion, azureCloud, appId, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }